Codebase list eclipse-platform-text / 282d544
New upstream version 4.8 Emmanuel Bourg 5 years ago
425 changed file(s) with 12832 addition(s) and 2997 deletion(s). Raw diff Collapse all Expand all
0 <?xml version="1.0" encoding="UTF-8"?>
1 <projectDescription>
2 <name>eclipse.platform.text</name>
3 <comment></comment>
4 <projects>
5 </projects>
6 <buildSpec>
7 </buildSpec>
8 <natures>
9 </natures>
10 </projectDescription>
11 Bundle-ManifestVersion: 2
22 Bundle-Name: %pluginName
33 Bundle-SymbolicName: org.eclipse.core.filebuffers; singleton:=true
4 Bundle-Version: 3.6.100.qualifier
4 Bundle-Version: 3.6.200.qualifier
55 Bundle-Activator: org.eclipse.core.internal.filebuffers.FileBuffersPlugin
66 Bundle-ActivationPolicy: lazy
77 Bundle-Vendor: %providerName
1717 org.eclipse.core.filesystem;bundle-version="[1.2.0,2.0.0)"
1818 Bundle-RequiredExecutionEnvironment: JavaSE-1.8
1919 Import-Package: com.ibm.icu.text
20 Automatic-Module-Name: org.eclipse.core.filebuffers
0 Bug 534597 - Unanticipated comparator errors in I20180511-2000
1313 <parent>
1414 <artifactId>eclipse.platform.text</artifactId>
1515 <groupId>eclipse.platform.text</groupId>
16 <version>4.7.3-SNAPSHOT</version>
16 <version>4.8.0-SNAPSHOT</version>
1717 </parent>
1818 <groupId>org.eclipse.core</groupId>
1919 <artifactId>org.eclipse.core.filebuffers</artifactId>
20 <version>3.6.100-SNAPSHOT</version>
20 <version>3.6.200-SNAPSHOT</version>
2121 <packaging>eclipse-plugin</packaging>
2222 </project>
531531 }
532532
533533 in= new BufferedReader(new InputStreamReader(contentStream, encoding), BUFFER_SIZE);
534 StringBuffer buffer= new StringBuffer(BUFFER_SIZE);
534 StringBuilder buffer= new StringBuilder(BUFFER_SIZE);
535535 char[] readBuffer= new char[READER_CHUNK_SIZE];
536536 int n= in.read(readBuffer);
537537 while (n > 0) {
520520 }
521521
522522 in= new BufferedReader(new InputStreamReader(contentStream, encoding), BUFFER_SIZE);
523 StringBuffer buffer= new StringBuffer(BUFFER_SIZE);
523 StringBuilder buffer= new StringBuilder(BUFFER_SIZE);
524524 char[] readBuffer= new char[READER_CHUNK_SIZE];
525525 int n= in.read(readBuffer);
526526 while (n > 0) {
11 Bundle-ManifestVersion: 2
22 Bundle-Name: %Plugin.name
33 Bundle-SymbolicName: org.eclipse.core.filebuffers.tests;singleton:=true
4 Bundle-Version: 3.11.100.qualifier
4 Bundle-Version: 3.11.200.qualifier
55 Bundle-Activator: org.eclipse.core.filebuffers.tests.FileBuffersTestPlugin
66 Bundle-ActivationPolicy: lazy
77 Bundle-Vendor: %Plugin.providerName
1616 org.junit;bundle-version="4.12.0"
1717 Bundle-RequiredExecutionEnvironment: JavaSE-1.8
1818 Eclipse-BundleShape: dir
19 Automatic-Module-Name: org.eclipse.core.filebuffers.tests
1313 <parent>
1414 <artifactId>tests-pom</artifactId>
1515 <groupId>eclipse.platform.text</groupId>
16 <version>4.7.3-SNAPSHOT</version>
16 <version>4.8.0-SNAPSHOT</version>
1717 <relativePath>../tests-pom/</relativePath>
1818 </parent>
1919 <groupId>org.eclipse.core</groupId>
2020 <artifactId>org.eclipse.core.filebuffers.tests</artifactId>
21 <version>3.11.100-SNAPSHOT</version>
21 <version>3.11.200-SNAPSHOT</version>
2222 <packaging>eclipse-test-plugin</packaging>
2323 <properties>
2424 <testSuite>${project.artifactId}</testSuite>
6868
6969 private IPath createLinkedFile(String linkedFileName, String linkedFileTarget) throws CoreException {
7070 IFile linkedFile= ResourceHelper.createLinkedFile(fProject, new Path(linkedFileName), FileBuffersTestPlugin.getDefault(), new Path(linkedFileTarget));
71 return linkedFile != null ? linkedFile.getFullPath() : null;
71 return linkedFile.getFullPath();
7272 }
7373
7474 private IPath createLinkedFolder(String linkedFolderName, String linkedFolderTarget) throws CoreException {
7575 IFolder linkedFolder= ResourceHelper.createLinkedFolder(fProject, new Path(linkedFolderName), FileBuffersTestPlugin.getDefault(), new Path(linkedFolderTarget));
76 return linkedFolder != null ? linkedFolder.getFullPath() : null;
76 return linkedFolder.getFullPath();
7777 }
7878
7979 /*
861861 IPath newLocation= moveUnderlyingFile();
862862 if (newLocation != null) {
863863 if (listener.count != 1 || listener.buffer != fileBuffer || !newLocation.equals(listener.newLocation)) {
864 StringBuffer buf= new StringBuffer();
864 StringBuilder buf= new StringBuilder();
865865 buf.append("Wrong listener notifcation in " + getClass().getName() + ":\n");
866866 buf.append("listener.count: " + listener.count + " (expected: 1)\n");
867867 if (newLocation.equals(listener.newLocation))
1212 import static org.junit.Assert.assertFalse;
1313 import static org.junit.Assert.assertNotNull;
1414 import static org.junit.Assert.assertTrue;
15
16 import java.io.IOException;
1517
1618 import org.junit.After;
1719 import org.junit.Test;
6769
6870 @Test
6971 public void testBug118199_fixed() throws Exception {
70 IFile file= getProject().getWorkspace().getRoot().getFileForLocation(getPath());
72 IPath location= getPath();
73 IFile file= getProject().getWorkspace().getRoot().getFileForLocation(location);
74 if (file == null) {
75 throw new IOException("File '" + location + "' can not be found."); //$NON-NLS-1$ //$NON-NLS-2$
76 }
7177 IPath path= file.getFullPath();
7278 assertFalse(file.exists());
7379 fManager.connect(path, LocationKind.IFILE, null);
1010 package org.eclipse.core.filebuffers.tests;
1111
1212 import static org.junit.Assert.*;
13
14 import java.io.IOException;
1315
1416 import org.junit.After;
1517 import org.junit.Test;
6567
6668 @Test
6769 public void testBug118199_fixed() throws Exception {
68 IFile file= getProject().getWorkspace().getRoot().getFileForLocation(getPath());
70 IPath location= getPath();
71 IFile file= getProject().getWorkspace().getRoot().getFileForLocation(location);
72 if (file == null) {
73 throw new IOException("File '" + location + "' can not be found."); //$NON-NLS-1$ //$NON-NLS-2$
74 }
6975 IPath path= file.getFullPath();
7076 assertFalse(file.exists());
7177 fManager.connect(path, LocationKind.IFILE, null);
6363 String entryName = entry.getName();
6464 File file = new File(dstDir, changeSeparator(entryName, '/', File.separatorChar));
6565 file.getParentFile().mkdirs();
66 InputStream src = null;
67 OutputStream dst = null;
68 try {
69 src = zipFile.getInputStream(entry);
70 dst = new FileOutputStream(file);
66 try (InputStream src= zipFile.getInputStream(entry); OutputStream dst= new FileOutputStream(file)) {
7167 transferData(src, dst);
72 } finally {
73 if(dst != null){
74 try {
75 dst.close();
76 } catch(IOException e){
77 }
78 }
79 if(src != null){
80 try {
81 src.close();
82 } catch(IOException e){
83 }
84 }
8568 }
8669 }
8770 } finally {
161144 public static void copy(File src, File dst) throws IOException {
162145 if(src.isDirectory()){
163146 String[] srcChildren = src.list();
147 if (srcChildren == null) {
148 throw new IOException("Content from directory '" + src.getAbsolutePath() + "' can not be listed."); //$NON-NLS-1$ //$NON-NLS-2$
149 }
164150 for(int i = 0; i < srcChildren.length; ++i){
165151 File srcChild= new File(src, srcChildren[i]);
166152 File dstChild= new File(dst, srcChildren[i]);
5757 @Override
5858 public void setup(IDocument document, IPath location, LocationKind locationKind) {
5959 if (locationKind == LocationKind.IFILE)
60 append(document, new StringBuffer(location.toPortableString()).reverse().toString());
60 append(document, new StringBuilder(location.toPortableString()).reverse().toString());
6161 }
6262 }
6363
6565 @Override
6666 public void setup(IDocument document, IPath location, LocationKind locationKind) {
6767 if (locationKind == LocationKind.LOCATION)
68 append(document, new StringBuffer(location.toPortableString()).reverse().toString());
68 append(document, new StringBuilder(location.toPortableString()).reverse().toString());
6969 }
7070 }
7171
7373 @Override
7474 public void setup(IDocument document, IPath location, LocationKind locationKind) {
7575 if (locationKind == LocationKind.NORMALIZE)
76 append(document, new StringBuffer(location.toPortableString()).reverse().toString());
76 append(document, new StringBuilder(location.toPortableString()).reverse().toString());
7777 }
7878 }
7979
132132 org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
133133 org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
134134 org.eclipse.jdt.core.compiler.source=1.8
135 org.eclipse.jdt.core.formatter.align_fields_grouping_blank_lines=2147483647
135136 org.eclipse.jdt.core.formatter.align_type_members_on_columns=false
136137 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16
137138 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation=0
145146 org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=48
146147 org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0
147148 org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16
149 org.eclipse.jdt.core.formatter.alignment_for_expressions_in_for_loop_header=0
148150 org.eclipse.jdt.core.formatter.alignment_for_method_declaration=0
151 org.eclipse.jdt.core.formatter.alignment_for_module_statements=16
149152 org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16
153 org.eclipse.jdt.core.formatter.alignment_for_parameterized_type_references=0
150154 org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16
151155 org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16
152156 org.eclipse.jdt.core.formatter.alignment_for_resources_in_try=80
156160 org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16
157161 org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16
158162 org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16
163 org.eclipse.jdt.core.formatter.alignment_for_type_arguments=0
164 org.eclipse.jdt.core.formatter.alignment_for_type_parameters=0
159165 org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch=16
160166 org.eclipse.jdt.core.formatter.blank_lines_after_imports=1
161167 org.eclipse.jdt.core.formatter.blank_lines_after_package=1
182188 org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line
183189 org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false
184190 org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=false
191 org.eclipse.jdt.core.formatter.comment.count_line_length_from_starting_position=false
185192 org.eclipse.jdt.core.formatter.comment.format_block_comments=false
186193 org.eclipse.jdt.core.formatter.comment.format_header=false
187194 org.eclipse.jdt.core.formatter.comment.format_html=true
214221 org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true
215222 org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true
216223 org.eclipse.jdt.core.formatter.indentation.size=4
224 org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_enum_constant=insert
217225 org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field=insert
218226 org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert
219227 org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method=insert
408416 org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=true
409417 org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0
410418 org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=3
419 org.eclipse.jdt.core.formatter.parentheses_positions_in_annotation=common_lines
420 org.eclipse.jdt.core.formatter.parentheses_positions_in_catch_clause=common_lines
421 org.eclipse.jdt.core.formatter.parentheses_positions_in_enum_constant_declaration=common_lines
422 org.eclipse.jdt.core.formatter.parentheses_positions_in_for_statment=common_lines
423 org.eclipse.jdt.core.formatter.parentheses_positions_in_if_while_statement=common_lines
424 org.eclipse.jdt.core.formatter.parentheses_positions_in_lambda_declaration=common_lines
425 org.eclipse.jdt.core.formatter.parentheses_positions_in_method_delcaration=common_lines
426 org.eclipse.jdt.core.formatter.parentheses_positions_in_method_invocation=common_lines
427 org.eclipse.jdt.core.formatter.parentheses_positions_in_switch_statement=common_lines
428 org.eclipse.jdt.core.formatter.parentheses_positions_in_try_clause=common_lines
411429 org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true
412430 org.eclipse.jdt.core.formatter.tabulation.char=tab
413431 org.eclipse.jdt.core.formatter.tabulation.size=4
414432 org.eclipse.jdt.core.formatter.use_on_off_tags=false
415433 org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false
434 org.eclipse.jdt.core.formatter.wrap_before_assignment_operator=false
416435 org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true
436 org.eclipse.jdt.core.formatter.wrap_before_conditional_operator=true
417437 org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch=true
418438 org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested=true
419439 org.eclipse.jdt.core.incompatibleJDKLevel=ignore
00 eclipse.preferences.version=1
1 editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true
12 formatter_profile=_JDT UI Code Style Conventions
2 formatter_settings_version=12
3 formatter_settings_version=13
34 org.eclipse.jdt.ui.exception.name=e
45 org.eclipse.jdt.ui.gettersetter.use.is=true
56 org.eclipse.jdt.ui.ignorelowercasenames=true
89 org.eclipse.jdt.ui.ondemandthreshold=99
910 org.eclipse.jdt.ui.overrideannotation=true
1011 org.eclipse.jdt.ui.staticondemandthreshold=99
12 sp_cleanup.add_default_serial_version_id=false
13 sp_cleanup.add_generated_serial_version_id=false
14 sp_cleanup.add_missing_annotations=false
15 sp_cleanup.add_missing_deprecated_annotations=true
16 sp_cleanup.add_missing_methods=false
17 sp_cleanup.add_missing_nls_tags=false
18 sp_cleanup.add_missing_override_annotations=true
19 sp_cleanup.add_missing_override_annotations_interface_methods=true
20 sp_cleanup.add_serial_version_id=false
21 sp_cleanup.always_use_blocks=false
22 sp_cleanup.always_use_parentheses_in_expressions=false
23 sp_cleanup.always_use_this_for_non_static_field_access=false
24 sp_cleanup.always_use_this_for_non_static_method_access=false
25 sp_cleanup.convert_functional_interfaces=false
26 sp_cleanup.convert_to_enhanced_for_loop=false
27 sp_cleanup.correct_indentation=false
28 sp_cleanup.format_source_code=true
29 sp_cleanup.format_source_code_changes_only=true
30 sp_cleanup.insert_inferred_type_arguments=false
31 sp_cleanup.make_local_variable_final=false
32 sp_cleanup.make_parameters_final=false
33 sp_cleanup.make_private_fields_final=false
34 sp_cleanup.make_type_abstract_if_missing_method=false
35 sp_cleanup.make_variable_declarations_final=false
36 sp_cleanup.never_use_blocks=false
37 sp_cleanup.never_use_parentheses_in_expressions=false
38 sp_cleanup.on_save_use_additional_actions=true
39 sp_cleanup.organize_imports=true
40 sp_cleanup.qualify_static_field_accesses_with_declaring_class=false
41 sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=false
42 sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=false
43 sp_cleanup.qualify_static_member_accesses_with_declaring_class=false
44 sp_cleanup.qualify_static_method_accesses_with_declaring_class=false
45 sp_cleanup.remove_private_constructors=false
46 sp_cleanup.remove_redundant_type_arguments=false
47 sp_cleanup.remove_trailing_whitespaces=true
48 sp_cleanup.remove_trailing_whitespaces_all=true
49 sp_cleanup.remove_trailing_whitespaces_ignore_empty=false
50 sp_cleanup.remove_unnecessary_casts=false
51 sp_cleanup.remove_unnecessary_nls_tags=false
52 sp_cleanup.remove_unused_imports=false
53 sp_cleanup.remove_unused_local_variables=false
54 sp_cleanup.remove_unused_private_fields=false
55 sp_cleanup.remove_unused_private_members=false
56 sp_cleanup.remove_unused_private_methods=false
57 sp_cleanup.remove_unused_private_types=false
58 sp_cleanup.sort_members=false
59 sp_cleanup.sort_members_all=false
60 sp_cleanup.use_anonymous_class_creation=false
61 sp_cleanup.use_blocks=false
62 sp_cleanup.use_blocks_only_for_return_and_throw=false
63 sp_cleanup.use_lambda=false
64 sp_cleanup.use_parentheses_in_expressions=false
65 sp_cleanup.use_this_for_non_static_field_access=false
66 sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=false
67 sp_cleanup.use_this_for_non_static_method_access=false
68 sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=false
11 Bundle-ManifestVersion: 2
22 Bundle-Name: %pluginName
33 Bundle-SymbolicName: org.eclipse.jface.text
4 Bundle-Version: 3.12.2.qualifier
4 Bundle-Version: 3.13.0.qualifier
55 Bundle-Vendor: %providerName
66 Bundle-Localization: plugin
77 Export-Package:
88 org.eclipse.jface.contentassist,
99 org.eclipse.jface.contentassist.images,
1010 org.eclipse.jface.internal.text;x-internal:=true,
11 org.eclipse.jface.internal.text.html;x-friends:="org.eclipse.ui.workbench.texteditor, org.eclipse.ui.editors, org.eclipse.jdt.debug.ui, org.eclipse.jdt.ui, org.eclipse.ant.ui, org.eclipse.ltk.ui.refactoring, org.eclipse.pde.ui",
11 org.eclipse.jface.internal.text.codemining;x-internal:=true,
12 org.eclipse.jface.internal.text.html;x-friends:="org.eclipse.ui.workbench.texteditor, org.eclipse.ui.editors, org.eclipse.jdt.debug.ui, org.eclipse.jdt.ui, org.eclipse.ant.ui, org.eclipse.ltk.ui.refactoring, org.eclipse.pde.ui, org.eclipse.xtext.ui",
1213 org.eclipse.jface.internal.text.link.contentassist;x-internal:=true,
1314 org.eclipse.jface.internal.text.revisions;x-internal:=true,
1415 org.eclipse.jface.internal.text.source;x-internal:=true,
1516 org.eclipse.jface.text,
17 org.eclipse.jface.text.codemining,
1618 org.eclipse.jface.text.contentassist,
1719 org.eclipse.jface.text.formatter,
1820 org.eclipse.jface.text.hyperlink,
2426 org.eclipse.jface.text.revisions,
2527 org.eclipse.jface.text.rules,
2628 org.eclipse.jface.text.source,
29 org.eclipse.jface.text.source.inlined,
2730 org.eclipse.jface.text.source.projection,
2831 org.eclipse.jface.text.source.projection.images,
2932 org.eclipse.jface.text.templates,
3134 Require-Bundle:
3235 org.eclipse.core.runtime;bundle-version="[3.5.0,4.0.0)",
3336 org.eclipse.text;bundle-version="[3.5.0,4.0.0)";visibility:=reexport,
34 org.eclipse.swt;bundle-version="[3.103.0,4.0.0)",
37 org.eclipse.swt;bundle-version="[3.107.0,4.0.0)",
3538 org.eclipse.jface;bundle-version="[3.5.0,4.0.0)"
3639 Bundle-RequiredExecutionEnvironment: JavaSE-1.8
3740 Import-Package: com.ibm.icu.text
41 Automatic-Module-Name: org.eclipse.jface.text
00 Bug 510796 - Comparator errors in I20170120-2000
1 Bug 511251 - Comparator errors in I20170127-2200
1 Bug 511251 - Comparator errors in I20170127-2200
2 Bug 521182 - [compiler] method reference on null object should throw NPE at runtime (JLS compliance)
1313 <parent>
1414 <artifactId>eclipse.platform.text</artifactId>
1515 <groupId>eclipse.platform.text</groupId>
16 <version>4.7.3-SNAPSHOT</version>
16 <version>4.8.0-SNAPSHOT</version>
1717 </parent>
1818 <groupId>org.eclipse.jface</groupId>
1919 <artifactId>org.eclipse.jface.text</artifactId>
20 <version>3.12.2-SNAPSHOT</version>
20 <version>3.13.0-SNAPSHOT</version>
2121 <packaging>eclipse-plugin</packaging>
2222 </project>
1414 import java.util.Iterator;
1515 import java.util.List;
1616 import java.util.Map;
17 import java.util.Map.Entry;
1718
1819 import org.eclipse.core.runtime.IProgressMonitor;
1920 import org.eclipse.core.runtime.NullProgressMonitor;
221222 if (!isCanceled(monitor))
222223 extension.replaceAnnotations(null, additions);
223224 } else {
224 Iterator<Annotation> e1= additions.keySet().iterator();
225 while (e1.hasNext()) {
226 AnnotationBag bag= (AnnotationBag) e1.next();
227 Position position= additions.get(bag);
225 for (Entry<Annotation, Position> entry : additions.entrySet()) {
226 AnnotationBag bag= (AnnotationBag) entry.getKey();
227 Position position= entry.getValue();
228228 if (isCanceled(monitor))
229229 return;
230230 visualAnnotationModel.addAnnotation(bag, position);
237237 * @param ve the verify event
238238 */
239239 private void dump(String who, Event e, VerifyEvent ve) {
240 StringBuffer sb= new StringBuffer("--- [AbstractControlContentAssistSubjectAdapter]\n"); //$NON-NLS-1$
240 StringBuilder sb= new StringBuilder("--- [AbstractControlContentAssistSubjectAdapter]\n"); //$NON-NLS-1$
241241 sb.append(who);
242242 sb.append(" - e: keyCode="+e.keyCode+hex(e.keyCode)); //$NON-NLS-1$
243243 sb.append("; character="+e.character+hex(e.character)); //$NON-NLS-1$
179179 @Override
180180 public void removeSelectionListener(SelectionListener selectionListener) {
181181 fCombo.removeSelectionListener(selectionListener);
182 Object listener= fModifyListeners.get(selectionListener);
183 if (listener instanceof Listener)
184 fCombo.removeListener(SWT.Modify, (Listener)listener);
182 Listener listener= fModifyListeners.get(selectionListener);
183 if (listener != null)
184 fCombo.removeListener(SWT.Modify, listener);
185185 }
186186 }
159159 @Override
160160 public void removeSelectionListener(SelectionListener selectionListener) {
161161 fText.removeSelectionListener(selectionListener);
162 Object listener= fModifyListeners.get(selectionListener);
163 if (listener instanceof Listener)
164 fText.removeListener(SWT.Modify, (Listener)listener);
162 Listener listener= fModifyListeners.get(selectionListener);
163 if (listener != null)
164 fText.removeListener(SWT.Modify, listener);
165165 }
166166 }
301301 @Override
302302 String getText(ISelection selection) throws BadLocationException {
303303 IBlockTextSelection cts= (IBlockTextSelection)selection;
304 StringBuffer buf= new StringBuffer(cts.getLength());
304 StringBuilder buf= new StringBuilder(cts.getLength());
305305 int startLine= cts.getStartLine();
306306 int endLine= cts.getEndLine();
307307 int startColumn= cts.getStartColumn();
470470 return new ReplaceEdit(info.getOffset() + startColumn, endColumn - startColumn, replacement);
471471 }
472472
473 private void appendColumnRange(StringBuffer buf, int line, int visualStartColumn, int visualEndColumn) throws BadLocationException {
473 private void appendColumnRange(StringBuilder buf, int line, int visualStartColumn, int visualEndColumn) throws BadLocationException {
474474 IRegion info= fDocument.getLineInformation(line);
475475 int lineLength= info.getLength();
476476 String content= fDocument.get(info.getOffset(), lineLength);
542542 gc= new GC(fStyledText);
543543 int charWidth= gc.stringExtent(new String(Character.toString(character))).x;
544544 int singleCharWidth= gc.stringExtent(" ").x; //$NON-NLS-1$
545 return (int)Math.ceil(charWidth / singleCharWidth);
545 return (int) Math.ceil((double) charWidth / singleCharWidth);
546546 } finally {
547547 if (gc != null)
548548 gc.dispose();
0 /**
1 * Copyright (c) 2017 Angelo ZERR.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Provide CodeMining support with CodeMiningManager - Bug 527720
9 */
10 package org.eclipse.jface.internal.text.codemining;
11
12 import java.util.concurrent.CancellationException;
13
14 import org.eclipse.core.runtime.IProgressMonitor;
15 import org.eclipse.core.runtime.NullProgressMonitor;
16
17 /**
18 * {@link IProgressMonitor} which throws a {@link CancellationException} when
19 * {@link IProgressMonitor#isCanceled()} returns true.
20 *
21 * @since 3.13
22 */
23 class CancellationExceptionMonitor extends NullProgressMonitor {
24
25 @Override
26 public boolean isCanceled() {
27 boolean canceled= super.isCanceled();
28 if (canceled) {
29 throw new CancellationException();
30 }
31 return canceled;
32 }
33 }
0 /**
1 * Copyright (c) 2017 Angelo ZERR.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Provide CodeMining support with CodeMiningManager - Bug 527720
9 */
10 package org.eclipse.jface.internal.text.codemining;
11
12 import java.util.ArrayList;
13 import java.util.List;
14 import java.util.function.Consumer;
15
16 import org.eclipse.swt.custom.StyledText;
17 import org.eclipse.swt.events.MouseEvent;
18 import org.eclipse.swt.graphics.Color;
19 import org.eclipse.swt.graphics.GC;
20 import org.eclipse.swt.graphics.Point;
21 import org.eclipse.swt.graphics.Rectangle;
22
23 import org.eclipse.core.runtime.IProgressMonitor;
24
25 import org.eclipse.jface.text.Position;
26 import org.eclipse.jface.text.codemining.ICodeMining;
27 import org.eclipse.jface.text.source.ISourceViewer;
28 import org.eclipse.jface.text.source.inlined.LineContentAnnotation;
29
30 /**
31 * Code Mining annotation in line content.
32 *
33 * @since 3.13
34 */
35 public class CodeMiningLineContentAnnotation extends LineContentAnnotation implements ICodeMiningAnnotation {
36
37 private static final String SEPARATOR= " | "; //$NON-NLS-1$
38
39 /**
40 * List of resolved minings which contains current resolved minings and last resolved minings
41 * and null if mining is not resolved.
42 */
43 private ICodeMining[] fResolvedMinings;
44
45 /**
46 * List of current resolved/unresolved minings
47 */
48 private final List<ICodeMining> fMinings;
49
50 /**
51 * List of bounds minings
52 */
53 private final List<Rectangle> fBounds;
54
55 /**
56 * The current progress monitor
57 */
58 private IProgressMonitor fMonitor;
59
60 /**
61 * Code mining annotation constructor.
62 *
63 * @param position the position
64 * @param viewer the viewer
65 */
66 public CodeMiningLineContentAnnotation(Position position, ISourceViewer viewer) {
67 super(position, viewer);
68 fResolvedMinings= null;
69 fMinings= new ArrayList<>();
70 fBounds= new ArrayList<>();
71 }
72
73 @Override
74 public void update(List<ICodeMining> minings, IProgressMonitor monitor) {
75 if (fResolvedMinings == null || (fResolvedMinings.length != minings.size())) {
76 // size of resolved minings are different from size of minings to update, initialize it with size of minings to update
77 fResolvedMinings= new ICodeMining[minings.size()];
78 }
79 // fill valid resolved minings with old minings.
80 int length= Math.min(fMinings.size(), minings.size());
81 for (int i= 0; i < length; i++) {
82 ICodeMining mining= fMinings.get(i);
83 if (mining.getLabel() != null) {
84 // mining was resolved without an error.
85 fResolvedMinings[i]= mining;
86 }
87 }
88 disposeMinings();
89 fMonitor= monitor;
90 fMinings.addAll(minings);
91 }
92
93 @Override
94 public void markDeleted(boolean deleted) {
95 super.markDeleted(deleted);
96 if (deleted) {
97 disposeMinings();
98 fResolvedMinings= null;
99 }
100 }
101
102 private void disposeMinings() {
103 fMinings.stream().forEach(ICodeMining::dispose);
104 fMinings.clear();
105 }
106
107 @Override
108 protected int drawAndComputeWidth(GC gc, StyledText textWidget, int offset, int length, Color color, int x, int y) {
109 List<ICodeMining> minings= new ArrayList<>(fMinings);
110 int nbDraw= 0;
111 int originalX= x;
112 int separatorWidth= -1;
113 boolean redrawn= false;
114 fBounds.clear();
115 for (int i= 0; i < minings.size(); i++) {
116 ICodeMining mining= minings.get(i);
117 // try to get the last resolved mining.
118 ICodeMining lastResolvedMining= (fResolvedMinings != null && fResolvedMinings.length > i) ? fResolvedMinings[i] : null;
119 if (mining.getLabel() != null) {
120 // mining is resolved without error, update the resolved mining list
121 fResolvedMinings[i]= mining;
122 } else if (!mining.isResolved()) {
123 // the mining is not resolved, draw the last resolved mining
124 mining= lastResolvedMining;
125 if (!redrawn) {
126 // redraw the annotation when mining is resolved.
127 redraw();
128 redrawn= true;
129 }
130 } else {
131 // the mining is resolved with error, draw the last resolved mining
132 mining= lastResolvedMining;
133 }
134 if (!CodeMiningManager.isValidMining(mining)) {
135 // ignore the draw of mining
136 continue;
137 }
138 // draw the mining
139 if (nbDraw > 0) {
140 initGC(textWidget, color, gc);
141 gc.drawText(SEPARATOR, x, y);
142 if (separatorWidth == -1) {
143 separatorWidth= gc.stringExtent(SEPARATOR).x;
144 }
145 x+= separatorWidth;
146 }
147 initGC(textWidget, color, gc);
148 @SuppressWarnings("null")
149 Point loc= mining.draw(gc, textWidget, color, x, y);
150 fBounds.add(new Rectangle(x, y, loc.x, loc.y));
151 x+= loc.x;
152 nbDraw++;
153 }
154 return x - originalX;
155 }
156
157 /**
158 * Initialize GC with given color and styled text background color and font.
159 *
160 * @param textWidget the text widget
161 * @param color the color
162 * @param gc the gc to initialize
163 */
164 private void initGC(StyledText textWidget, Color color, GC gc) {
165 gc.setForeground(color);
166 gc.setBackground(textWidget.getBackground());
167 gc.setFont(textWidget.getFont());
168 }
169
170 @Override
171 public void redraw() {
172 // redraw codemining annotation is done only if all current minings are resolved.
173 List<ICodeMining> minings= new ArrayList<>(fMinings);
174 for (ICodeMining mining : minings) {
175 if (!mining.isResolved()) {
176 // one of mining is not resolved, resolve it and then redraw the annotation.
177 mining.resolve(getViewer(), fMonitor).thenRunAsync(() -> {
178 this.redraw();
179 });
180 return;
181 }
182 }
183 // all minings are resolved, redraw the annotation
184 super.redraw();
185 }
186
187 @Override
188 public Consumer<MouseEvent> getAction(MouseEvent e) {
189 ICodeMining mining= CodeMiningManager.getValidCodeMiningAtLocation(fResolvedMinings, fBounds, e.x, e.y);
190 return mining != null ? mining.getAction() : null;
191 }
192
193 @Override
194 public boolean isInVisibleLines() {
195 return super.isInVisibleLines();
196 }
197 }
0 /**
1 * Copyright (c) 2017 Angelo ZERR.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Provide CodeMining support with CodeMiningManager - Bug 527720
9 */
10 package org.eclipse.jface.internal.text.codemining;
11
12 import java.util.ArrayList;
13 import java.util.List;
14 import java.util.function.Consumer;
15 import java.util.stream.Stream;
16
17 import org.eclipse.swt.custom.StyledText;
18 import org.eclipse.swt.events.MouseEvent;
19 import org.eclipse.swt.graphics.Color;
20 import org.eclipse.swt.graphics.GC;
21 import org.eclipse.swt.graphics.Point;
22 import org.eclipse.swt.graphics.Rectangle;
23
24 import org.eclipse.core.runtime.IProgressMonitor;
25
26 import org.eclipse.jface.text.Position;
27 import org.eclipse.jface.text.codemining.ICodeMining;
28 import org.eclipse.jface.text.source.ISourceViewer;
29 import org.eclipse.jface.text.source.inlined.LineHeaderAnnotation;
30
31 /**
32 * Code Mining annotation in line header.
33 *
34 * @since 3.13
35 */
36 public class CodeMiningLineHeaderAnnotation extends LineHeaderAnnotation implements ICodeMiningAnnotation {
37
38 private static final String SEPARATOR= " | "; //$NON-NLS-1$
39
40 /**
41 * List of resolved minings which contains current resolved minings and last resolved minings
42 * and null if mining is not resolved.
43 */
44 private ICodeMining[] fResolvedMinings;
45
46 /**
47 * List of current resolved/unresolved minings
48 */
49 private final List<ICodeMining> fMinings;
50
51 /**
52 * List of bounds minings
53 */
54 private final List<Rectangle> fBounds;
55
56 /**
57 * The current progress monitor
58 */
59 private IProgressMonitor fMonitor;
60
61 /**
62 * Code mining annotation constructor.
63 *
64 * @param position the position
65 * @param viewer the viewer
66 */
67 public CodeMiningLineHeaderAnnotation(Position position, ISourceViewer viewer) {
68 super(position, viewer);
69 fResolvedMinings= null;
70 fMinings= new ArrayList<>();
71 fBounds= new ArrayList<>();
72 }
73
74 @Override
75 public int getHeight() {
76 return hasAtLeastOneResolvedMiningNotEmpty() ? super.getHeight() : 0;
77 }
78
79 /**
80 * Returns <code>true</code> if the annotation has at least one resolved mining which have a
81 * label and <code>false</code> otherwise.
82 *
83 * @return <code>true</code> if the annotation has at least one resolved mining which have a
84 * label and <code>false</code> otherwise.
85 */
86 private boolean hasAtLeastOneResolvedMiningNotEmpty() {
87 if (fResolvedMinings == null || fResolvedMinings.length == 0) {
88 return false;
89 }
90 return Stream.of(fResolvedMinings).anyMatch(m -> CodeMiningManager.isValidMining(m));
91 }
92
93 @Override
94 public void update(List<ICodeMining> minings, IProgressMonitor monitor) {
95 if (fResolvedMinings == null || (fResolvedMinings.length != minings.size())) {
96 // size of resolved minings are different from size of minings to update, initialize it with size of minings to update
97 fResolvedMinings= new ICodeMining[minings.size()];
98 }
99 // fill valid resolved minings with old minings.
100 int length= Math.min(fMinings.size(), minings.size());
101 for (int i= 0; i < length; i++) {
102 ICodeMining mining= fMinings.get(i);
103 if (mining.getLabel() != null) {
104 fResolvedMinings[i]= mining;
105 }
106 }
107 disposeMinings();
108 fMonitor= monitor;
109 fMinings.addAll(minings);
110 }
111
112 @Override
113 public void markDeleted(boolean deleted) {
114 super.markDeleted(deleted);
115 if (deleted) {
116 disposeMinings();
117 fResolvedMinings= null;
118 }
119 }
120
121 private void disposeMinings() {
122 fMinings.stream().forEach(ICodeMining::dispose);
123 fMinings.clear();
124 }
125
126 @Override
127 public void draw(GC gc, StyledText textWidget, int offset, int length, Color color, int x, int y) {
128 List<ICodeMining> minings= new ArrayList<>(fMinings);
129 int nbDraw= 0;
130 int separatorWidth= -1;
131 boolean redrawn= false;
132 fBounds.clear();
133 for (int i= 0; i < minings.size(); i++) {
134 ICodeMining mining= minings.get(i);
135 // try to get the last resolved mining.
136 ICodeMining lastResolvedMining= (fResolvedMinings != null && fResolvedMinings.length > i) ? fResolvedMinings[i] : null;
137 if (mining.getLabel() != null) {
138 // mining is resolved without error, update the resolved mining list
139 fResolvedMinings[i]= mining;
140 } else if (!mining.isResolved()) {
141 // the mining is not resolved, draw the last resolved mining
142 mining= lastResolvedMining;
143 if (!redrawn) {
144 // redraw the annotation when mining is resolved.
145 redraw();
146 redrawn= true;
147 }
148 } else {
149 // the mining is resolved with error, draw the last resolved mining
150 mining= lastResolvedMining;
151 }
152 if (!CodeMiningManager.isValidMining(mining)) {
153 // ignore the draw of mining
154 continue;
155 }
156 // draw the mining
157 if (nbDraw > 0) {
158 initGC(textWidget, color, gc);
159 gc.drawText(SEPARATOR, x, y);
160 if (separatorWidth == -1) {
161 separatorWidth= gc.stringExtent(SEPARATOR).x;
162 }
163 x+= separatorWidth;
164 }
165 initGC(textWidget, color, gc);
166 @SuppressWarnings("null")
167 Point loc= mining.draw(gc, textWidget, color, x, y);
168 fBounds.add(new Rectangle(x, y, loc.x, loc.y));
169 x+= loc.x;
170 nbDraw++;
171 }
172 }
173
174 /**
175 * Initialize GC with given color and styled text background color and font.
176 *
177 * @param textWidget the text widget
178 * @param color the color
179 * @param gc the gc to initialize
180 */
181 private void initGC(StyledText textWidget, Color color, GC gc) {
182 gc.setForeground(color);
183 gc.setBackground(textWidget.getBackground());
184 gc.setFont(textWidget.getFont());
185 }
186
187 @Override
188 public void redraw() {
189 // redraw codemining annotation is done only if all current minings are resolved.
190 List<ICodeMining> minings= new ArrayList<>(fMinings);
191 for (ICodeMining mining : minings) {
192 if (!mining.isResolved()) {
193 // one of mining is not resolved, resolve it and then redraw the annotation.
194 mining.resolve(getViewer(), fMonitor).thenRunAsync(() -> {
195 this.redraw();
196 });
197 return;
198 }
199 }
200 // all minings are resolved, redraw the annotation
201 super.redraw();
202 }
203
204 @Override
205 public Consumer<MouseEvent> getAction(MouseEvent e) {
206 ICodeMining mining= CodeMiningManager.getValidCodeMiningAtLocation(fResolvedMinings, fBounds, e.x, e.y);
207 return mining != null ? mining.getAction() : null;
208 }
209
210 @Override
211 public boolean isInVisibleLines() {
212 return super.isInVisibleLines();
213 }
214 }
0 /**
1 * Copyright (c) 2017 Angelo ZERR.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Provide CodeMining support with CodeMiningManager - Bug 527720
9 */
10 package org.eclipse.jface.internal.text.codemining;
11
12 import java.util.Arrays;
13 import java.util.Collections;
14 import java.util.HashSet;
15 import java.util.LinkedHashMap;
16 import java.util.List;
17 import java.util.Map;
18 import java.util.Set;
19 import java.util.concurrent.CompletableFuture;
20 import java.util.function.Function;
21 import java.util.stream.Collectors;
22
23 import org.eclipse.swt.graphics.Rectangle;
24
25 import org.eclipse.core.runtime.Assert;
26 import org.eclipse.core.runtime.IProgressMonitor;
27
28 import org.eclipse.jface.text.IDocument;
29 import org.eclipse.jface.text.ITextViewer;
30 import org.eclipse.jface.text.Position;
31 import org.eclipse.jface.text.codemining.ICodeMining;
32 import org.eclipse.jface.text.codemining.ICodeMiningProvider;
33 import org.eclipse.jface.text.codemining.LineHeaderCodeMining;
34 import org.eclipse.jface.text.source.ISourceViewer;
35 import org.eclipse.jface.text.source.inlined.AbstractInlinedAnnotation;
36 import org.eclipse.jface.text.source.inlined.InlinedAnnotationSupport;
37
38 /**
39 * Code Mining manager implementation.
40 *
41 * @since 3.13
42 */
43 public class CodeMiningManager implements Runnable {
44
45 /**
46 * The source viewer
47 */
48 private final ISourceViewer fViewer;
49
50 /**
51 * The inlined annotation support used to draw CodeMining in the line spacing.
52 */
53 private final InlinedAnnotationSupport fInlinedAnnotationSupport;
54
55 /**
56 * The list of codemining providers.
57 */
58 private List<ICodeMiningProvider> fCodeMiningProviders;
59
60 /**
61 * The current progress monitor.
62 */
63 private IProgressMonitor fMonitor;
64
65 /**
66 * Constructor of codemining manager with the given arguments.
67 *
68 * @param viewer the source viewer
69 * @param inlinedAnnotationSupport the inlined annotation support used to draw code minings
70 * @param codeMiningProviders the array of codemining providers, must not be empty
71 */
72 public CodeMiningManager(ISourceViewer viewer, InlinedAnnotationSupport inlinedAnnotationSupport,
73 ICodeMiningProvider[] codeMiningProviders) {
74 Assert.isNotNull(viewer);
75 Assert.isNotNull(inlinedAnnotationSupport);
76 Assert.isNotNull(codeMiningProviders);
77 fViewer= viewer;
78 fInlinedAnnotationSupport= inlinedAnnotationSupport;
79 setCodeMiningProviders(codeMiningProviders);
80 }
81
82 /**
83 * Set the codemining providers.
84 *
85 * @param codeMiningProviders the codemining providers.
86 */
87 public void setCodeMiningProviders(ICodeMiningProvider[] codeMiningProviders) {
88 fCodeMiningProviders= Arrays.asList(codeMiningProviders);
89 }
90
91 /**
92 * Uninstalls this codemining manager.
93 */
94 public void uninstall() {
95 cancel();
96 }
97
98 /**
99 * Collect, resolve and render the code minings of the viewer.
100 */
101 @Override
102 public void run() {
103 if (fViewer == null || fInlinedAnnotationSupport == null || fCodeMiningProviders == null
104 || fCodeMiningProviders.size() == 0 || fViewer.getAnnotationModel() == null) {
105 return;
106 }
107 // Cancel the last progress monitor to cancel last resolve and render of code
108 // minings
109 cancel();
110 // Update the code minings
111 updateCodeMinings();
112 }
113
114 /**
115 * Update the code minings.
116 */
117 private void updateCodeMinings() {
118 // Refresh the code minings by using the new progress monitor.
119 fMonitor= new CancellationExceptionMonitor();
120 IProgressMonitor monitor= fMonitor;
121 // Collect the code minings for the viewer
122 getCodeMinings(fViewer, fCodeMiningProviders, monitor).thenAccept(symbols -> {
123 // check if request was canceled.
124 monitor.isCanceled();
125 // then group code minings by lines position
126 Map<Position, List<ICodeMining>> groups= groupByLines(symbols, fCodeMiningProviders);
127 // resolve and render code minings
128 renderCodeMinings(groups, fViewer, monitor);
129 });
130 }
131
132 /**
133 * Cancel the codemining process.
134 */
135 private void cancel() {
136 // Cancel the last progress monitor.
137 if (fMonitor != null) {
138 fMonitor.setCanceled(true);
139 }
140 }
141
142 /**
143 * Return the list of {@link CompletableFuture} which provides the list of {@link ICodeMining}
144 * for the given <code>viewer</code> by using the given providers.
145 *
146 * @param viewer the text viewer.
147 * @param providers the CodeMining list providers.
148 * @param monitor the progress monitor.
149 * @return the list of {@link CompletableFuture} which provides the list of {@link ICodeMining}
150 * for the given <code>viewer</code> by using the given providers.
151 */
152 private static CompletableFuture<List<? extends ICodeMining>> getCodeMinings(ITextViewer viewer,
153 List<ICodeMiningProvider> providers, IProgressMonitor monitor) {
154 List<CompletableFuture<List<? extends ICodeMining>>> com= providers.stream()
155 .map(provider -> provider.provideCodeMinings(viewer, monitor)).filter(c -> c != null)
156 .collect(Collectors.toList());
157 return CompletableFuture.allOf(com.toArray(new CompletableFuture[com.size()])).thenApply(
158 v -> com.stream().map(CompletableFuture::join).flatMap(l -> l.stream()).collect(Collectors.toList()));
159 }
160
161 /**
162 * Returns a sorted Map which groups the given code minings by same position line.
163 *
164 * @param codeMinings list of code minings to group.
165 * @param providers CodeMining providers used to retrieve code minings.
166 * @return a sorted Map which groups the given code minings by same position line.
167 */
168 private static Map<Position, List<ICodeMining>> groupByLines(List<? extends ICodeMining> codeMinings,
169 List<ICodeMiningProvider> providers) {
170 // sort code minings by lineNumber and provider-rank if
171 Collections.sort(codeMinings, (a, b) -> {
172 if (a.getPosition().offset < b.getPosition().offset) {
173 return -1;
174 } else if (a.getPosition().offset > b.getPosition().offset) {
175 return 1;
176 } else if (providers.indexOf(a.getProvider()) < providers.indexOf(b.getProvider())) {
177 return -1;
178 } else if (providers.indexOf(a.getProvider()) > providers.indexOf(b.getProvider())) {
179 return 1;
180 } else {
181 return 0;
182 }
183 });
184 return codeMinings.stream().collect(Collectors.groupingBy(ICodeMining::getPosition, LinkedHashMap::new,
185 Collectors.mapping(Function.identity(), Collectors.toList())));
186 }
187
188 /**
189 * Render the codemining grouped by line position.
190 *
191 * @param groups code minings grouped by lines position
192 * @param viewer the viewer
193 * @param monitor the progress monitor
194 */
195 private void renderCodeMinings(Map<Position, List<ICodeMining>> groups, ISourceViewer viewer,
196 IProgressMonitor monitor) {
197 // check if request was canceled.
198 monitor.isCanceled();
199 IDocument document= viewer != null ? viewer.getDocument() : null;
200 if (document == null) {
201 // this case comes from when editor is closed before codemining rendered is
202 // done.
203 return;
204 }
205 Set<ICodeMiningAnnotation> annotationsToRedraw= new HashSet<>();
206 Set<AbstractInlinedAnnotation> currentAnnotations= new HashSet<>();
207 // Loop for grouped code minings
208 groups.entrySet().stream().forEach(g -> {
209 // check if request was canceled.
210 monitor.isCanceled();
211
212 Position pos= new Position(g.getKey().offset, g.getKey().length);
213 List<ICodeMining> minings= g.getValue();
214 boolean inLineHeader= minings.size() > 0 ? (minings.get(0) instanceof LineHeaderCodeMining) : true;
215 // Try to find existing annotation
216 AbstractInlinedAnnotation ann= fInlinedAnnotationSupport.findExistingAnnotation(pos);
217 if (ann == null) {
218 // The annotation doesn't exists, create it.
219 ann= inLineHeader ? new CodeMiningLineHeaderAnnotation(pos, viewer) : new CodeMiningLineContentAnnotation(pos, viewer);
220 } else if (ann instanceof ICodeMiningAnnotation && ((ICodeMiningAnnotation) ann).isInVisibleLines()) {
221 // annotation is in visible lines
222 annotationsToRedraw.add((ICodeMiningAnnotation) ann);
223 }
224 ((ICodeMiningAnnotation) ann).update(minings, monitor);
225 currentAnnotations.add(ann);
226 });
227 // check if request was canceled.
228 monitor.isCanceled();
229 fInlinedAnnotationSupport.updateAnnotations(currentAnnotations);
230 // redraw the existing codemining annotations since their content can change
231 annotationsToRedraw.stream().forEach(ann -> ann.redraw());
232 }
233
234 /**
235 * Returns <code>true</code> if the given mining has a non empty label and <code>false</code>
236 * otherwise.
237 *
238 * @param mining the mining to check
239 * @return <code>true</code> if the given mining has a non empty label and <code>false</code>
240 * otherwise.
241 */
242 static boolean isValidMining(ICodeMining mining) {
243 return mining != null && mining.getLabel() != null && !mining.getLabel().isEmpty();
244 }
245
246 /**
247 * Returns the valid code mining at the given location by using the bounds of codemining
248 * annotations which stores only the valid code mining.
249 *
250 * @param minings the list of mining of the codemining annotation.
251 * @param bounds the bounds of the valid minings of the codemining annotation.
252 * @param x the x location
253 * @param y the y location
254 * @return the valid code mining at the given location by using the bounds of codemining
255 * annotations which stores only the valid code mining.
256 */
257 static ICodeMining getValidCodeMiningAtLocation(ICodeMining[] minings, List<Rectangle> bounds, int x, int y) {
258 for (int i= 0; i < bounds.size(); i++) {
259 Rectangle bound= bounds.get(i);
260 if (bound.contains(x, y)) {
261 return getCodeValidMiningAtIndex(minings, i);
262 }
263 }
264 return null;
265 }
266
267 /**
268 * Returns the valid code mining at the given index.
269 *
270 * @param minings the list of minings
271 * @param index the index
272 * @return the valid code mining at the given index.
273 */
274 private static ICodeMining getCodeValidMiningAtIndex(ICodeMining[] minings, int index) {
275 int validIndex= 0;
276 for (ICodeMining mining : minings) {
277 if (isValidMining(mining)) {
278 if (validIndex == index) {
279 return mining;
280 }
281 validIndex++;
282 }
283 }
284 return null;
285 }
286 }
0 /**
1 * Copyright (c) 2018, Angelo ZERR and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] CodeMining should support line header/content annotation type both - Bug 529115
9 */
10 package org.eclipse.jface.internal.text.codemining;
11
12 import java.util.List;
13
14 import org.eclipse.core.runtime.IProgressMonitor;
15
16 import org.eclipse.jface.text.codemining.ICodeMining;
17
18 /**
19 * Internal Code Mining annotation API used by the {@link CodeMiningManager}.
20 *
21 * @since 3.13
22 */
23 public interface ICodeMiningAnnotation {
24
25 /**
26 * Update code minings.
27 *
28 * @param minings the minings to update.
29 * @param monitor the monitor
30 */
31 void update(List<ICodeMining> minings, IProgressMonitor monitor);
32
33 /**
34 * Redraw the codemining annotation.
35 */
36 void redraw();
37
38 /**
39 * Return whether the annotation is in visible lines.
40 *
41 * @return <code>true</code> if the annotation is in visible lines and <code>false</code>
42 * otherwise.
43 */
44 boolean isInVisibleLines();
45 }
270270 */
271271 @Override
272272 public void setInput(Object input) {
273 Assert.isLegal(input == null || input instanceof String || input instanceof BrowserInformationControlInput);
273 Assert.isLegal(input == null || input instanceof String || input instanceof BrowserInformationControlInput, input != null ? input.getClass().getName() : "null"); //$NON-NLS-1$
274274
275275 if (input instanceof String) {
276276 setInformation((String)input);
305305 else
306306 styles= new String[] { "overflow:scroll;" }; //$NON-NLS-1$
307307
308 StringBuffer buffer= new StringBuffer(content);
308 StringBuilder buffer= new StringBuilder(content);
309309 HTMLPrinter.insertStyles(buffer, styles);
310310 content= buffer.toString();
311311
589589 return null;
590590
591591 GC gc= new GC(fBrowser);
592 Font font= fSymbolicFontName == null ? JFaceResources.getDialogFont() : JFaceResources.getFont(fSymbolicFontName);
592 Font font= JFaceResources.getFont(fSymbolicFontName);
593593 gc.setFont(font);
594594 int width= gc.getFontMetrics().getAverageCharWidth();
595595 int height= gc.getFontMetrics().getHeight();
152152 fCurrentStyleRange.strikeout= false;
153153 }
154154 }
155
155
156156 private void finishAndReinitializeCurrentStyle(int offset) {
157157 if (fTextPresentation != null && offset != fCurrentStyleRange.start && !isDefaultStyleRange(fCurrentStyleRange)) {
158158 fCurrentStyleRange.length= offset - fCurrentStyleRange.start;
218218 startItalic();
219219 return EMPTY_STRING;
220220 }
221
221
222222 if ("/i".equals(html) || "/em".equals(html)) { //$NON-NLS-1$ //$NON-NLS-2$
223223 stopItalic();
224224 return EMPTY_STRING;
225225 }
226
226
227227 if ("b".equals(html) || "strong".equals(html)) { //$NON-NLS-1$ //$NON-NLS-2$
228228 startBold();
229229 return EMPTY_STRING;
300300 */
301301 private String processHTMLTag() throws IOException {
302302
303 StringBuffer buf= new StringBuffer();
303 StringBuilder buf= new StringBuilder();
304304 int ch;
305305 do {
306306
336336 return html2Text(buf.toString());
337337 }
338338
339 private static boolean isInComment(StringBuffer buf) {
339 private static boolean isInComment(StringBuilder buf) {
340340 return buf.length() >= 3 && "!--".equals(buf.substring(0, 3)); //$NON-NLS-1$
341341 }
342342
343 private static boolean isCommentEnd(StringBuffer buf) {
343 private static boolean isCommentEnd(StringBuilder buf) {
344344 int tagLen= buf.length();
345345 return tagLen >= 5 && "--".equals(buf.substring(tagLen - 2)); //$NON-NLS-1$
346346 }
374374 * A '&' has been read. Process a entity
375375 */
376376 private String processEntity() throws IOException {
377 StringBuffer buf= new StringBuffer();
377 StringBuilder buf= new StringBuilder();
378378 int ch= nextChar();
379379 while (Character.isLetterOrDigit((char)ch) || ch == '#') {
380380 buf.append((char) ch);
1515
1616 import org.eclipse.swt.SWT;
1717 import org.eclipse.swt.SWTError;
18 import org.eclipse.swt.graphics.Color;
1819 import org.eclipse.swt.graphics.FontData;
1920 import org.eclipse.swt.graphics.RGB;
2021 import org.eclipse.swt.widgets.Display;
21 import org.eclipse.swt.widgets.Event;
22 import org.eclipse.swt.widgets.Listener;
2322
2423 import org.eclipse.jface.resource.JFaceColors;
24 import org.eclipse.jface.resource.JFaceResources;
2525 import org.eclipse.jface.util.Util;
2626
2727 import org.eclipse.jface.text.DefaultInformationControl;
3535
3636 private static volatile RGB BG_COLOR_RGB= new RGB(255, 255, 225); // RGB value of info bg color on WindowsXP
3737 private static volatile RGB FG_COLOR_RGB= new RGB(0, 0, 0); // RGB value of info fg color on WindowsXP
38 private static volatile RGB LINK_COLOR_RGB= new RGB(0, 0, 255); // dark blue
39 private static volatile RGB ACTIVE_LINK_COLOR_RGB= new RGB(0, 0, 128); // light blue
3840
3941 private static final String UNIT; // See https://bugs.eclipse.org/bugs/show_bug.cgi?id=155993
4042 static {
6769 private static void cacheColors(Display display) {
6870 BG_COLOR_RGB= JFaceColors.getInformationViewerBackgroundColor(display).getRGB();
6971 FG_COLOR_RGB= JFaceColors.getInformationViewerForegroundColor(display).getRGB();
72 Color hyperlinkText= JFaceColors.getHyperlinkText(display);
73 if (hyperlinkText != null) {
74 LINK_COLOR_RGB= hyperlinkText.getRGB();
75 }
76 Color activeHyperlinkText= JFaceColors.getActiveHyperlinkText(display);
77 if (activeHyperlinkText != null) {
78 ACTIVE_LINK_COLOR_RGB= activeHyperlinkText.getRGB();
79 }
7080 }
7181
7282 private static void installColorUpdater(final Display display) {
73 display.addListener(SWT.Settings, new Listener() {
74 @Override
75 public void handleEvent(Event event) {
76 cacheColors(display);
77 }
78 });
83 display.addListener(SWT.Settings, event -> cacheColors(display));
84 JFaceResources.getColorRegistry().addListener(event -> cacheColors(display));
7985 }
8086
8187 private static String replace(String text, char c, String s) {
8692 if (current == -1)
8793 return text;
8894
89 StringBuffer buffer= new StringBuffer();
95 StringBuilder buffer= new StringBuilder();
9096 while (current > -1) {
9197 buffer.append(text.substring(previous, current));
9298 buffer.append(s);
107113 * @return the string with escaped characters
108114 *
109115 * @see #convertToHTMLContentWithWhitespace(String) for use in browsers
110 * @see #addPreFormatted(StringBuffer, String) for rendering with an {@link HTML2TextReader}
116 * @see #addPreFormatted(StringBuilder, String) for rendering with an {@link HTML2TextReader}
111117 */
112118 public static String convertToHTMLContent(String content) {
113119 content= replace(content, '&', "&amp;"); //$NON-NLS-1$
117123 }
118124
119125 /**
120 * Escapes reserved HTML characters in the given string
121 * and returns them in a way that preserves whitespace in a browser.
126 * Escapes reserved HTML characters in the given string and returns them in a way that preserves
127 * whitespace in a browser.
122128 * <p>
123 * <b>Warning:</b> Whitespace will not be preserved when rendered with an {@link HTML2TextReader}
124 * (e.g. in a {@link DefaultInformationControl} that renders simple HTML).
125
129 * <b>Warning:</b> Whitespace will not be preserved when rendered with an
130 * {@link HTML2TextReader} (e.g. in a {@link DefaultInformationControl} that renders simple
131 * HTML).
132 *
126133 * @param content the input string
127134 * @return the processed string
128135 *
129 * @see #addPreFormatted(StringBuffer, String)
136 * @see #addPreFormatted(StringBuilder, String)
130137 * @see #convertToHTMLContent(String)
131138 * @since 3.7
132139 */
140147
141148 public static String read(Reader rd) {
142149
143 StringBuffer buffer= new StringBuffer();
150 StringBuilder buffer= new StringBuilder();
144151 char[] readBuffer= new char[2048];
145152
146153 try {
156163 return null;
157164 }
158165
166 /**
167 *
168 * @deprecated migrate to new StringBuilder API
169 *
170 * @param buffer the output StringBuilder
171 * @param position offset where the prolog is placed
172 * @param fgRGB Foreground-Color
173 * @param bgRGB Background-Color
174 * @param styleSheet Stylesheet
175 */
176 @Deprecated
159177 public static void insertPageProlog(StringBuffer buffer, int position, RGB fgRGB, RGB bgRGB, String styleSheet) {
160178 if (fgRGB == null)
161179 fgRGB= FG_COLOR_RGB;
170188
171189 appendColors(pageProlog, fgRGB, bgRGB);
172190
191 buffer.insert(position, pageProlog.toString());
192 }
193
194 /**
195 *
196 * @param buffer the output StringBuilder
197 * @param position offset where the prolog is placed
198 * @param fgRGB Foreground-Color
199 * @param bgRGB Background-Color
200 * @param styleSheet Stylesheet
201 */
202 public static void insertPageProlog(StringBuilder buffer, int position, RGB fgRGB, RGB bgRGB, String styleSheet) {
203 if (fgRGB == null)
204 fgRGB= FG_COLOR_RGB;
205 if (bgRGB == null)
206 bgRGB= BG_COLOR_RGB;
207
208 StringBuilder pageProlog= new StringBuilder(300);
209
210 pageProlog.append("<html>"); //$NON-NLS-1$
211
212 appendStyleSheet(pageProlog, styleSheet, fgRGB, bgRGB);
213
214 appendColors(pageProlog, fgRGB, bgRGB);
215
173216 buffer.insert(position, pageProlog.toString());
174217 }
175218
219 /**
220 *
221 *
222 * @param pageProlog The Pageprolog where the color has to be set
223 * @param fgRGB Foreground-Color
224 * @param bgRGB Background-Color
225 *
226 */
227 private static void appendColors(StringBuilder pageProlog, RGB fgRGB, RGB bgRGB) {
228 pageProlog.append("<body text=\""); //$NON-NLS-1$
229 appendColor(pageProlog, fgRGB);
230 pageProlog.append("\" bgcolor=\""); //$NON-NLS-1$
231 appendColor(pageProlog, bgRGB);
232 pageProlog.append("\">"); //$NON-NLS-1$
233 }
234
235 /**
236 *
237 *
238 * @param pageProlog The Pageprolog where the color has to be set
239 * @param fgRGB Foreground-Color
240 * @param bgRGB Background-Color
241 *
242 * @deprecated migrate to new StringBuilder API
243 */
244 @Deprecated
176245 private static void appendColors(StringBuffer pageProlog, RGB fgRGB, RGB bgRGB) {
177246 pageProlog.append("<body text=\""); //$NON-NLS-1$
178247 appendColor(pageProlog, fgRGB);
181250 pageProlog.append("\">"); //$NON-NLS-1$
182251 }
183252
253 /**
254 *
255 *
256 * @param buffer The Output buffer
257 * @param rgb RGB-Value
258 *
259 */
260 private static void appendColor(StringBuilder buffer, RGB rgb) {
261 buffer.append('#');
262 appendAsHexString(buffer, rgb.red);
263 appendAsHexString(buffer, rgb.green);
264 appendAsHexString(buffer, rgb.blue);
265 }
266
267 /**
268 *
269 *
270 * @param buffer The Output buffer
271 * @param rgb RGB-Value
272 *
273 * @deprecated migrate to new StringBuilder API
274 */
275 @Deprecated
184276 private static void appendColor(StringBuffer buffer, RGB rgb) {
185277 buffer.append('#');
186278 appendAsHexString(buffer, rgb.red);
188280 appendAsHexString(buffer, rgb.blue);
189281 }
190282
283 /**
284 *
285 * @param buffer the output buffer
286 * @param intValue the intValue will be converted to hex and appended
287 *
288 */
289 private static void appendAsHexString(StringBuilder buffer, int intValue) {
290 String hexValue= Integer.toHexString(intValue);
291 if (hexValue.length() == 1)
292 buffer.append('0');
293 buffer.append(hexValue);
294 }
295
296 /**
297 *
298 * @param buffer the output buffer
299 * @param intValue the intValue will be converted to hex and appended
300 *
301 * @deprecated migrate to new StringBuilder API
302 */
303 @Deprecated
191304 private static void appendAsHexString(StringBuffer buffer, int intValue) {
192305 String hexValue= Integer.toHexString(intValue);
193306 if (hexValue.length() == 1)
195308 buffer.append(hexValue);
196309 }
197310
311 /**
312 *
313 * @param buffer the output buffer
314 * @param styles array with styles to be appended
315 *
316 */
317 public static void insertStyles(StringBuilder buffer, String[] styles) {
318 if (styles == null || styles.length == 0)
319 return;
320
321 StringBuilder styleBuf= new StringBuilder(10 * styles.length);
322 for (String style : styles) {
323 styleBuf.append(" style=\""); //$NON-NLS-1$
324 styleBuf.append(style);
325 styleBuf.append('"');
326 }
327
328 // Find insertion index
329 // a) within existing body tag with trailing space
330 int index= buffer.indexOf("<body "); //$NON-NLS-1$
331 if (index != -1) {
332 buffer.insert(index+5, styleBuf);
333 return;
334 }
335
336 // b) within existing body tag without attributes
337 index= buffer.indexOf("<body>"); //$NON-NLS-1$
338 if (index != -1) {
339 buffer.insert(index+5, ' ');
340 buffer.insert(index+6, styleBuf);
341 return;
342 }
343 }
344
345
346 /**
347 *
348 * @param buffer the output buffer
349 * @param styles array with styles to be appended
350 *
351 * @deprecated As of 3.13, replaced by {@link #insertStyles(StringBuilder, String[])}
352 */
353 @Deprecated
198354 public static void insertStyles(StringBuffer buffer, String[] styles) {
199355 if (styles == null || styles.length == 0)
200356 return;
223379 }
224380 }
225381
226 private static void appendStyleSheet(StringBuffer buffer, String styleSheet, RGB fgRGB, RGB bgRGB) {
382 /**
383 *
384 * @param buffer the output buffer
385 * @param styleSheet the stylesheet
386 * @param fgRGB Foreground-Color
387 * @param bgRGB Background-Color
388 *
389 */
390 private static void appendStyleSheet(StringBuilder buffer, String styleSheet, RGB fgRGB, RGB bgRGB) {
227391 if (styleSheet == null)
228392 return;
229393
230394 // workaround for https://bugs.eclipse.org/318243
231 StringBuffer fg= new StringBuffer();
395 StringBuilder fg= new StringBuilder();
232396 appendColor(fg, fgRGB);
233397 styleSheet= styleSheet.replaceAll("InfoText", fg.toString()); //$NON-NLS-1$
234 StringBuffer bg= new StringBuffer();
398 StringBuilder bg= new StringBuilder();
235399 appendColor(bg, bgRGB);
236400 styleSheet= styleSheet.replaceAll("InfoBackground", bg.toString()); //$NON-NLS-1$
401
402 // replace link colors with colors from preferences
403 StringBuilder linkColor= new StringBuilder();
404 appendColor(linkColor, LINK_COLOR_RGB);
405 styleSheet= styleSheet.replaceAll("hyperlinkColor", linkColor.toString()); //$NON-NLS-1$
406 StringBuilder activeLinkColor= new StringBuilder();
407 appendColor(activeLinkColor, ACTIVE_LINK_COLOR_RGB);
408 styleSheet= styleSheet.replaceAll("activeHyperlinkColor", activeLinkColor.toString()); //$NON-NLS-1$
237409
238410 buffer.append("<head><style CHARSET=\"ISO-8859-1\" TYPE=\"text/css\">"); //$NON-NLS-1$
239411 buffer.append(styleSheet);
240412 buffer.append("</style></head>"); //$NON-NLS-1$
241413 }
242414
243 private static void appendStyleSheetURL(StringBuffer buffer, URL styleSheetURL) {
415 /**
416 *
417 * @param buffer the output buffer
418 * @param styleSheet the stylesheet
419 * @param fgRGB Foreground-Color
420 * @param bgRGB Background-Color
421 *
422 * @deprecated migrate to new StringBuilder API
423 */
424 @Deprecated
425 private static void appendStyleSheet(StringBuffer buffer, String styleSheet, RGB fgRGB, RGB bgRGB) {
426 if (styleSheet == null)
427 return;
428
429 // workaround for https://bugs.eclipse.org/318243
430 StringBuilder fg= new StringBuilder();
431 appendColor(fg, fgRGB);
432 styleSheet= styleSheet.replaceAll("InfoText", fg.toString()); //$NON-NLS-1$
433 StringBuilder bg= new StringBuilder();
434 appendColor(bg, bgRGB);
435 styleSheet= styleSheet.replaceAll("InfoBackground", bg.toString()); //$NON-NLS-1$
436
437 // replace link colors with colors from preferences
438 StringBuilder linkColor= new StringBuilder();
439 appendColor(linkColor, LINK_COLOR_RGB);
440 styleSheet= styleSheet.replaceAll("hyperlinkColor", linkColor.toString()); //$NON-NLS-1$
441 StringBuilder activeLinkColor= new StringBuilder();
442 appendColor(activeLinkColor, ACTIVE_LINK_COLOR_RGB);
443 styleSheet= styleSheet.replaceAll("activeHyperlinkColor", activeLinkColor.toString()); //$NON-NLS-1$
444
445 buffer.append("<head><style CHARSET=\"ISO-8859-1\" TYPE=\"text/css\">"); //$NON-NLS-1$
446 buffer.append(styleSheet);
447 buffer.append("</style></head>"); //$NON-NLS-1$
448 }
449
450 /**
451 *
452 * @param buffer the output buffer
453 * @param styleSheetURL the URL to the Stylesheet
454 *
455 */
456 private static void appendStyleSheetURL(StringBuilder buffer, URL styleSheetURL) {
244457 if (styleSheetURL == null)
245458 return;
246459
253466 buffer.append("</head>"); //$NON-NLS-1$
254467 }
255468
469 /**
470 *
471 * @param buffer the output buffer
472 * @param styleSheetURL the URL to the Stylesheet
473 *
474 * @deprecated migrate to new StringBuilder API
475 */
476 @Deprecated
477 private static void appendStyleSheetURL(StringBuffer buffer, URL styleSheetURL) {
478 if (styleSheetURL == null)
479 return;
480
481 buffer.append("<head>"); //$NON-NLS-1$
482
483 buffer.append("<LINK REL=\"stylesheet\" HREF= \""); //$NON-NLS-1$
484 buffer.append(styleSheetURL);
485 buffer.append("\" CHARSET=\"ISO-8859-1\" TYPE=\"text/css\">"); //$NON-NLS-1$
486
487 buffer.append("</head>"); //$NON-NLS-1$
488 }
489
490
491 /**
492 *
493 * @param buffer the output buffer
494 * @param position the offset
495 *
496 */
497 public static void insertPageProlog(StringBuilder buffer, int position) {
498 StringBuilder pageProlog= new StringBuilder(60);
499 pageProlog.append("<html>"); //$NON-NLS-1$
500 appendColors(pageProlog, FG_COLOR_RGB, BG_COLOR_RGB);
501 buffer.insert(position, pageProlog.toString());
502 }
503
504 /**
505 *
506 * @param buffer the output buffer
507 * @param position the offset
508 *
509 * @deprecated migrate to new StringBuilder API
510 */
511 @Deprecated
256512 public static void insertPageProlog(StringBuffer buffer, int position) {
257513 StringBuffer pageProlog= new StringBuffer(60);
258514 pageProlog.append("<html>"); //$NON-NLS-1$
260516 buffer.insert(position, pageProlog.toString());
261517 }
262518
519 /**
520 *
521 * @param buffer the output buffer
522 * @param position the offset
523 * @param styleSheetURL URL to the Stylesheet
524 *
525 * @deprecated migrate to new StringBuilder API
526 */
527 @Deprecated
263528 public static void insertPageProlog(StringBuffer buffer, int position, URL styleSheetURL) {
264529 StringBuffer pageProlog= new StringBuffer(300);
265530 pageProlog.append("<html>"); //$NON-NLS-1$
268533 buffer.insert(position, pageProlog.toString());
269534 }
270535
536 /**
537 *
538 * @param buffer the output buffer
539 * @param position the offset
540 * @param styleSheetURL URL to the Stylesheet
541 *
542 */
543 public static void insertPageProlog(StringBuilder buffer, int position, URL styleSheetURL) {
544 StringBuilder pageProlog= new StringBuilder(300);
545 pageProlog.append("<html>"); //$NON-NLS-1$
546 appendStyleSheetURL(pageProlog, styleSheetURL);
547 appendColors(pageProlog, FG_COLOR_RGB, BG_COLOR_RGB);
548 buffer.insert(position, pageProlog.toString());
549 }
550
551 /**
552 *
553 * @param buffer the output buffer
554 * @param position the offset
555 * @param styleSheet Stylesheet
556 *
557 */
558 public static void insertPageProlog(StringBuilder buffer, int position, String styleSheet) {
559 insertPageProlog(buffer, position, null, null, styleSheet);
560 }
561
562 /**
563 *
564 * @param buffer the output buffer
565 * @param position the offset
566 * @param styleSheet Stylesheet
567 *
568 * @deprecated migrate to new StringBuilder API
569 */
570 @Deprecated
271571 public static void insertPageProlog(StringBuffer buffer, int position, String styleSheet) {
272572 insertPageProlog(buffer, position, null, null, styleSheet);
273573 }
274574
575 /**
576 *
577 * @param buffer the output buffer
578 *
579 */
580 public static void addPageProlog(StringBuilder buffer) {
581 insertPageProlog(buffer, buffer.length());
582 }
583
584 /**
585 *
586 * @param buffer the output buffer
587 *
588 * @deprecated migrate to new StringBuilder API
589 */
590 @Deprecated
275591 public static void addPageProlog(StringBuffer buffer) {
276592 insertPageProlog(buffer, buffer.length());
277593 }
278594
595 public static void addPageEpilog(StringBuilder buffer) {
596 buffer.append("</body></html>"); //$NON-NLS-1$
597 }
598
599 /**
600 *
601 * @param buffer the output buffer
602 *
603 * @deprecated migrate to new StringBuilder API
604 */
605 @Deprecated
279606 public static void addPageEpilog(StringBuffer buffer) {
280607 buffer.append("</body></html>"); //$NON-NLS-1$
281608 }
282609
610 /**
611 *
612 * @param buffer the output buffer
613 *
614 */
615 public static void startBulletList(StringBuilder buffer) {
616 buffer.append("<ul>"); //$NON-NLS-1$
617 }
618
619 /**
620 *
621 * @param buffer the output buffer
622 *
623 * @deprecated migrate to new StringBuilder API
624 */
625 @Deprecated
283626 public static void startBulletList(StringBuffer buffer) {
284627 buffer.append("<ul>"); //$NON-NLS-1$
285628 }
286629
630 /**
631 * ends the bulletpointlist
632 *
633 * @param buffer the output buffer
634 *
635 */
636 public static void endBulletList(StringBuilder buffer) {
637 buffer.append("</ul>"); //$NON-NLS-1$
638 }
639
640 /**
641 * ends the bulletpointlist
642 *
643 * @param buffer the output buffer
644 *
645 * @deprecated migrate to new StringBuilder API
646 */
647 @Deprecated
287648 public static void endBulletList(StringBuffer buffer) {
288649 buffer.append("</ul>"); //$NON-NLS-1$
289650 }
290651
652 /**
653 * Adds bulletpoint
654 *
655 * @param buffer the output buffer
656 * @param bullet the bulletpoint
657 *
658 */
659 public static void addBullet(StringBuilder buffer, String bullet) {
660 if (bullet != null) {
661 buffer.append("<li>"); //$NON-NLS-1$
662 buffer.append(bullet);
663 buffer.append("</li>"); //$NON-NLS-1$
664 }
665 }
666
667 /**
668 * Adds bulletpoint
669 *
670 * @param buffer the output buffer
671 * @param bullet the bulletpoint
672 *
673 * @deprecated migrate to new StringBuilder API
674 */
675 @Deprecated
291676 public static void addBullet(StringBuffer buffer, String bullet) {
292677 if (bullet != null) {
293678 buffer.append("<li>"); //$NON-NLS-1$
296681 }
297682 }
298683
684 /**
685 *
686 * Adds h5 headline
687 *
688 * @param buffer the output buffer
689 * @param header of h5 headline
690 *
691 */
692 public static void addSmallHeader(StringBuilder buffer, String header) {
693 if (header != null) {
694 buffer.append("<h5>"); //$NON-NLS-1$
695 buffer.append(header);
696 buffer.append("</h5>"); //$NON-NLS-1$
697 }
698 }
699
700 /**
701 *
702 * Adds h5 headline
703 *
704 * @param buffer the output buffer
705 * @param header of h5 headline
706 *
707 * @deprecated migrate to new StringBuilder API
708 */
709 @Deprecated
299710 public static void addSmallHeader(StringBuffer buffer, String header) {
300711 if (header != null) {
301712 buffer.append("<h5>"); //$NON-NLS-1$
304715 }
305716 }
306717
718 /**
719 *
720 * @param buffer the output buffer
721 * @param paragraph the content of the paragraph
722 *
723 */
724 public static void addParagraph(StringBuilder buffer, String paragraph) {
725 if (paragraph != null) {
726 buffer.append("<p>"); //$NON-NLS-1$
727 buffer.append(paragraph);
728 }
729 }
730
731 /**
732 *
733 * @param buffer the output buffer
734 * @param paragraph the content of the paragraph
735 *
736 * @deprecated migrate to new StringBuilder API
737 */
738 @Deprecated
307739 public static void addParagraph(StringBuffer buffer, String paragraph) {
308740 if (paragraph != null) {
309741 buffer.append("<p>"); //$NON-NLS-1$
318750 * it doesn't starts a new paragraph when rendered with a {@link HTML2TextReader}
319751 * (e.g. in a {@link DefaultInformationControl} that renders simple HTML).
320752 *
321 * @param buffer the output buffer
753 * @param buffer the output StringBuilder
322754 * @param preFormatted the string that should be rendered with whitespace preserved
323755 *
324756 * @see #convertToHTMLContent(String)
325757 * @see #convertToHTMLContentWithWhitespace(String)
326758 * @since 3.7
327759 */
760 public static void addPreFormatted(StringBuilder buffer, String preFormatted) {
761 if (preFormatted != null) {
762 buffer.append("<pre>"); //$NON-NLS-1$
763 buffer.append(preFormatted);
764 buffer.append("</pre>"); //$NON-NLS-1$
765 }
766 }
767
768 /**
769 * Appends a string and keeps its whitespace and newlines.
770 * <p>
771 * <b>Warning:</b> This starts a new paragraph when rendered in a browser, but
772 * it doesn't starts a new paragraph when rendered with a {@link HTML2TextReader}
773 * (e.g. in a {@link DefaultInformationControl} that renders simple HTML).
774 *
775 * @param buffer the output buffer
776 * @param preFormatted the string that should be rendered with whitespace preserved
777 *
778 * @deprecated migrate to new StringBuilder API
779 *
780 * @see #convertToHTMLContent(String)
781 * @see #convertToHTMLContentWithWhitespace(String)
782 * @since 3.7
783 */
784 @Deprecated
328785 public static void addPreFormatted(StringBuffer buffer, String preFormatted) {
329786 if (preFormatted != null) {
330787 buffer.append("<pre>"); //$NON-NLS-1$
333790 }
334791 }
335792
793 /**
794 *
795 * @param buffer the output buffer
796 * @param paragraphReader The content of the Read will be added to output buffer
797 *
798 */
799 public static void addParagraph(StringBuilder buffer, Reader paragraphReader) {
800 if (paragraphReader != null)
801 addParagraph(buffer, read(paragraphReader));
802 }
803
804 /**
805 *
806 * @param buffer the output buffer
807 * @param paragraphReader The content of the Read will be added to output buffer
808 *
809 * @deprecated migrate to new StringBuilder API
810 */
811 @Deprecated
336812 public static void addParagraph(StringBuffer buffer, Reader paragraphReader) {
337813 if (paragraphReader != null)
338814 addParagraph(buffer, read(paragraphReader));
7575 }
7676 }
7777
78 private void append(StringBuffer buffer, String string, TextPresentation presentation) {
78 private void append(StringBuilder buffer, String string, TextPresentation presentation) {
7979
8080 int length= string.length();
8181 buffer.append(string);
118118 GC gc= new GC(drawable);
119119 try {
120120
121 StringBuffer buffer= new StringBuffer();
122 int maxNumberOfLines= Math.round(maxHeight / gc.getFontMetrics().getHeight());
121 StringBuilder buffer= new StringBuilder();
122 int maxNumberOfLines= (int) Math.round((double) maxHeight / gc.getFontMetrics().getHeight());
123123
124124 fCounter= 0;
125125 LineBreakingReader reader= new LineBreakingReader(createReader(hoverInfo, presentation), hoverInfo.length(), gc, maxWidth);
178178 }
179179 }
180180
181 private String trim(StringBuffer buffer, TextPresentation presentation) {
181 private String trim(StringBuilder buffer, TextPresentation presentation) {
182182
183183 int length= buffer.length();
184184
5757 * @exception IOException in case reading fails
5858 */
5959 public String getString() throws IOException {
60 StringBuffer buf= new StringBuffer();
60 StringBuilder buf= new StringBuilder();
6161 int ch;
6262 while ((ch= read()) != -1) {
6363 buf.append((char)ch);
3434 private boolean fSkipWhiteSpace= true;
3535
3636 private boolean fReadFromBuffer;
37 private StringBuffer fBuffer;
37 private StringBuilder fBuffer;
3838 private int fIndex;
3939
4040
4141 protected SubstitutionTextReader(Reader reader) {
4242 fReader= reader;
43 fBuffer= new StringBuffer();
43 fBuffer= new StringBuilder();
4444 fIndex= 0;
4545 fReadFromBuffer= false;
4646 fCharAfterWhiteSpace= -1;
3030 import org.eclipse.swt.layout.GridData;
3131 import org.eclipse.swt.layout.GridLayout;
3232 import org.eclipse.swt.widgets.Control;
33 import org.eclipse.swt.widgets.Display;
3334 import org.eclipse.swt.widgets.Shell;
3435 import org.eclipse.swt.widgets.Table;
3536 import org.eclipse.swt.widgets.TableItem;
3637
3738 import org.eclipse.jface.internal.text.TableOwnerDrawSupport;
39 import org.eclipse.jface.preference.JFacePreferences;
40 import org.eclipse.jface.resource.ColorRegistry;
41 import org.eclipse.jface.resource.JFaceColors;
3842 import org.eclipse.jface.resource.JFaceResources;
3943 import org.eclipse.jface.viewers.StyledString;
4044
310314 });
311315 }
312316
313 fProposalShell.setBackground(control.getDisplay().getSystemColor(SWT.COLOR_BLACK));
314
315 Color c= control.getDisplay().getSystemColor(SWT.COLOR_INFO_BACKGROUND);
316 fProposalTable.setBackground(c);
317
318 c= control.getDisplay().getSystemColor(SWT.COLOR_INFO_FOREGROUND);
319 fProposalTable.setForeground(c);
317 ColorRegistry colorRegistry= JFaceResources.getColorRegistry();
318 Color background= colorRegistry.get(JFacePreferences.CONTENT_ASSIST_BACKGROUND_COLOR);
319 if (background == null) {
320 background= JFaceColors.getInformationViewerBackgroundColor(Display.getDefault());
321 }
322
323 Color foreground= colorRegistry.get(JFacePreferences.CONTENT_ASSIST_FOREGROUND_COLOR);
324 if (foreground == null) {
325 foreground= JFaceColors.getInformationViewerBackgroundColor(Display.getDefault());
326 }
327
328 fProposalShell.setBackground(background);
329 fProposalTable.setBackground(background);
330 fProposalTable.setForeground(foreground);
320331
321332 fProposalTable.addSelectionListener(new SelectionListener() {
322333
160160 return;
161161 List<Long> revisions= new ArrayList<>();
162162 for (Revision revision : info.getRevisions()) {
163 revisions.add(new Long(computeAge(revision)));
163 revisions.add(Long.valueOf(computeAge(revision)));
164164 }
165165 Collections.sort(revisions);
166166 fRevisions= revisions;
204204
205205 private int computeAgeIndex(Revision revision) {
206206 long age= computeAge(revision);
207 int index= fRevisions.indexOf(new Long(age));
207 int index= fRevisions.indexOf(Long.valueOf(age));
208208 return index;
209209 }
210210
375375 // there is already a header
376376 return html;
377377
378 StringBuffer info= new StringBuffer(512 + html.length());
378 StringBuilder info= new StringBuilder(512 + html.length());
379379 HTMLPrinter.insertPageProlog(info, 0, fgStyleSheet);
380380 info.append(html);
381381 HTMLPrinter.addPageEpilog(info);
416416 "dd { margin-top: 0; margin-bottom: 0 }\n" + //$NON-NLS-1$
417417 "\n" + //$NON-NLS-1$
418418 "/* Styles and colors */\n" + //$NON-NLS-1$
419 "a:link { color: #0000FF }\n" + //$NON-NLS-1$
420 "a:hover { color: #000080 }\n" + //$NON-NLS-1$
419 "a:link { color: hyperlinkColor }\n" + //$NON-NLS-1$
420 "a:hover { color: activeHyperlinkColor; }\n" + //$NON-NLS-1$
421421 "a:visited { text-decoration: underline }\n" + //$NON-NLS-1$
422422 "h4 { font-style: italic }\n" + //$NON-NLS-1$
423423 "strong { font-weight: bold }\n" + //$NON-NLS-1$
663663
664664 /**
665665 * Sets the zoom level for the current painting operation. Workaround for bug 516293.
666 *
666 *
667667 * @param zoom the zoom to set
668668 * @since 3.12
669669 */
140140
141141 /**
142142 * Sets the zoom level for the current painting operation. Workaround for bug 516293.
143 *
143 *
144144 * @param zoom the zoom to set
145145 * @since 3.12
146146 */
368368 if (fLineDiffer != null)
369369 ((IAnnotationModel) fLineDiffer).removeAnnotationModelListener(fAnnotationListener);
370370 fLineDiffer= (ILineDiffer) differ;
371 if (fLineDiffer != null)
372 ((IAnnotationModel) fLineDiffer).addAnnotationModelListener(fAnnotationListener);
371 ((IAnnotationModel) fLineDiffer).addAnnotationModelListener(fAnnotationListener);
373372 }
374373 }
375374 }
433433 * The shell of the popup window.
434434 *
435435 * @return the shell used for the popup window
436 */
437 protected final Shell getShell() {
436 * @since 3.13
437 */
438 public final Shell getShell() {
438439 return fShell;
439440 }
440441
645646 setStatusLabelColors(fStatusLabel.getForeground(), background);
646647 }
647648 }
648
649
649650 private void setStatusLabelColors(Color foreground, Color background) {
650651 if (foreground == null || background == null) return;
651652 if (fStatusLabelForeground != null) {
6868 // find white spaces
6969 int end= findEndOfWhiteSpace(d, start, c.offset);
7070
71 StringBuffer buf= new StringBuffer(c.text);
71 StringBuilder buf= new StringBuilder(c.text);
7272 if (end > start) {
7373 // append to input
7474 buf.append(d.get(start, end - start));
372372 @Override
373373 public String toString() {
374374 String delimiter= ", "; //$NON-NLS-1$
375 StringBuffer text= new StringBuffer(super.toString());
375 StringBuilder text= new StringBuilder(super.toString());
376376 text.append("\n"); //$NON-NLS-1$
377377 text.append(this.getClass().getName());
378378 text.append(" undo modification stamp: "); //$NON-NLS-1$
767767 }
768768
769769 /** Text buffer to collect text which is inserted into the viewer */
770 private StringBuffer fTextBuffer;
770 private StringBuilder fTextBuffer;
771771 /** Text buffer to collect viewer content which has been replaced */
772 private StringBuffer fPreservedTextBuffer;
772 private StringBuilder fPreservedTextBuffer;
773773 /** The document modification stamp for undo. */
774774 protected long fPreservedUndoModificationStamp= IDocumentExtension4.UNKNOWN_MODIFICATION_STAMP;
775775 /** The document modification stamp for redo. */
11981198 public void connect(ITextViewer textViewer) {
11991199 if (!isConnected() && textViewer != null) {
12001200 fTextViewer= textViewer;
1201 fTextBuffer= new StringBuffer();
1202 fPreservedTextBuffer= new StringBuffer();
1201 fTextBuffer= new StringBuilder();
1202 fPreservedTextBuffer= new StringBuilder();
12031203 if (fUndoContext == null)
12041204 fUndoContext= new ObjectUndoContext(this);
12051205
00 /*******************************************************************************
1 * Copyright (c) 2006, 2016 IBM Corporation and others.
1 * Copyright (c) 2006, 2018 IBM Corporation and others.
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
419419 * @since 3.5
420420 */
421421 public static int getOffsetForCursorLocation(ITextViewer viewer) {
422
423422 try {
424423 StyledText text= viewer.getTextWidget();
425 if (text == null || text.isDisposed())
424 if (text == null || text.isDisposed()) {
426425 return -1;
426 }
427427
428428 Display display= text.getDisplay();
429429 Point absolutePosition= display.getCursorLocation();
430430 Point relativePosition= text.toControl(absolutePosition);
431431
432 int widgetOffset= text.getOffsetAtLocation(relativePosition);
432 int widgetOffset= text.getOffsetAtPoint(relativePosition);
433 if (widgetOffset == -1) {
434 return -1;
435 }
433436 Point p= text.getLocationAtOffset(widgetOffset);
434 if (p.x > relativePosition.x)
437 if (p.x > relativePosition.x) {
435438 widgetOffset--;
439 }
436440
437441 if (viewer instanceof ITextViewerExtension5) {
438442 ITextViewerExtension5 extension= (ITextViewerExtension5)viewer;
440444 }
441445
442446 return widgetOffset + viewer.getVisibleRegion().getOffset();
443
444447 } catch (IllegalArgumentException e) {
445448 return -1;
446449 }
00 /*******************************************************************************
1 * Copyright (c) 2000, 2008 IBM Corporation and others.
1 * Copyright (c) 2000, 2017 IBM Corporation and others.
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
4545 /** The line width of the line to be painted, default value <code>1</code> */
4646 private int fLineWidth= 0; // NOTE: 0 means width is 1 but with optimized performance
4747 /** The cached x-offset of the <code>fMarginWidth</code> for the current font */
48 private int fCachedWidgetX= -1;
48 private int fCachedWidgetX= -1;
4949 private Font fFontForCachedWidgetX;
5050 /** The active state of this painter */
5151 private boolean fIsActive= false;
9999 }
100100
101101 /**
102 * Initializes this painter, by flushing and recomputing all caches and causing
103 * the widget to be redrawn. Must be called explicitly when font of text widget changes.
102 * Initializes this painter, by flushing and recomputing all caches and causing the widget to be
103 * redrawn.
104104 */
105105 public void initialize() {
106106 computeWidgetX();
114114 private void computeWidgetX() {
115115 GC gc= new GC(fTextWidget);
116116 fFontForCachedWidgetX= fTextWidget.getFont();
117 int pixels= gc.getFontMetrics().getAverageCharWidth();
117 double pixels= gc.getFontMetrics().getAverageCharacterWidth();
118118 gc.dispose();
119119
120 fCachedWidgetX= pixels * fMarginWidth;
120 fCachedWidgetX= (int) (pixels * fMarginWidth + 0.5);
121121 }
122122
123123 @Override
146146 */
147147 @Override
148148 public void managePosition(Position position) {
149 if (fDocument == null) {
150 return;
151 }
149152 try {
150153 fDocument.addPosition(fCategory, position);
151154 } catch (BadPositionCategoryException x) {
1313
1414 import org.eclipse.swt.graphics.FontData;
1515 import org.eclipse.swt.widgets.Composite;
16 import org.eclipse.swt.widgets.Control;
1716 import org.eclipse.swt.widgets.Label;
1817
1918 import org.eclipse.jface.preference.FontFieldEditor;
7877 */
7978 private void checkForDefault() {
8079 if (presentsDefaultValue()) {
81 Control c= getValueControl(fParent);
82 if (c instanceof Label)
83 ((Label) c).setText(fDefaultFontLabel);
80 Label label= getValueControl(fParent);
81 label.setText(fDefaultFontLabel);
8482 }
8583 }
8684
3333 fLineTracker= lineTracker;
3434 }
3535
36 private int insertTabString(StringBuffer buffer, int offsetInLine) {
36 private int insertTabString(StringBuilder buffer, int offsetInLine) {
3737
3838 if (fTabRatio == 0)
3939 return 0;
5454 int index= text.indexOf('\t');
5555 if (index > -1) {
5656
57 StringBuffer buffer= new StringBuffer();
57 StringBuilder buffer= new StringBuilder();
5858
5959 fLineTracker.set(command.text);
6060 int lines= fLineTracker.getNumberOfLines();
37383738 } else {
37393739 int lines= processor.getCoveredLines(selection);
37403740 String delim= fDocument.getLegalLineDelimiters()[0];
3741 StringBuffer text= new StringBuffer(lines * length + (lines - 1) * delim.length());
3741 StringBuilder text= new StringBuilder(lines * length + (lines - 1) * delim.length());
37423742 text.append(e.text);
37433743 for (int i= 0; i < lines - 1; i++) {
37443744 text.append(delim);
39613961 int length= contents.length();
39623962 int lines= processor.getCoveredLines(selection);
39633963 String delim= fDocument.getLegalLineDelimiters()[0];
3964 StringBuffer text= new StringBuffer(lines * length + (lines - 1) * delim.length());
3964 StringBuilder text= new StringBuilder(lines * length + (lines - 1) * delim.length());
39653965 text.append(contents);
39663966 for (int i= 0; i < lines - 1; i++) {
39673967 text.append(delim);
00 /*******************************************************************************
1 * Copyright (c) 2000, 2012 IBM Corporation and others.
1 * Copyright (c) 2000, 2018 IBM Corporation and others.
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
221221 */
222222 @Override
223223 protected void presentInformation() {
224 if (fTextViewer == null)
225 return;
224 if (fTextViewer == null) {
225 return;
226 }
226227
227228 StyledText textWidget= fTextViewer.getTextWidget();
228229 if (textWidget != null && !textWidget.isDisposed()) {
229230 Display display= textWidget.getDisplay();
230 if (display == null)
231 if (display == null) {
231232 return;
232
233 display.asyncExec(new Runnable() {
234 @Override
235 public void run() {
233 }
234
235 display.asyncExec(() -> {
236 if (!textWidget.isDisposed()) {
236237 doPresentInformation();
237238 }
238239 });
257258 * @return the document offset corresponding to the given point
258259 */
259260 private int computeOffsetAtLocation(int x, int y) {
260
261261 try {
262
263262 StyledText styledText= fTextViewer.getTextWidget();
264 int widgetOffset= styledText.getOffsetAtLocation(new Point(x, y));
263 int widgetOffset= styledText.getOffsetAtPoint(new Point(x, y));
264 if (widgetOffset == -1) {
265 return -1;
266 }
265267 Point p= styledText.getLocationAtOffset(widgetOffset);
266 if (p.x > x)
268 if (p.x > x) {
267269 widgetOffset--;
270 }
268271
269272 if (fTextViewer instanceof ITextViewerExtension5) {
270273 ITextViewerExtension5 extension= (ITextViewerExtension5) fTextViewer;
272275 }
273276
274277 return widgetOffset + fTextViewer._getVisibleRegionOffset();
275
276278 } catch (IllegalArgumentException e) {
277279 return -1;
278280 }
00 /*******************************************************************************
1 * Copyright (c) 2006, 2017 Wind River Systems, Inc., IBM Corporation and others.
1 * Copyright (c) 2006, 2018 Wind River Systems, Inc., IBM Corporation and others.
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
249249 // Y-coordinate of line
250250 int y= fTextWidget.getLinePixel(line);
251251 // compute first visible char offset
252 int startOffset;
253 try {
254 startOffset= fTextWidget.getOffsetAtLocation(new Point(x, y)) - 1;
255 if (startOffset - 2 <= lineOffset) {
256 startOffset= lineOffset;
257 }
258 } catch (IllegalArgumentException iae) {
252 int startOffset = fTextWidget.getOffsetAtPoint(new Point(x, y)) - 1;
253 if (startOffset == -1) {
254 startOffset= lineOffset;
255 } else if (startOffset - 2 <= lineOffset) {
259256 startOffset= lineOffset;
260257 }
261258 // compute last visible char offset
264261 // line end is visible
265262 endOffset= lineEndOffset;
266263 } else {
267 try {
268 endOffset= fTextWidget.getOffsetAtLocation(new Point(x + w - 1, y)) + 1;
269 if (endOffset + 2 >= lineEndOffset) {
270 endOffset= lineEndOffset;
271 }
272 } catch (IllegalArgumentException iae) {
264 endOffset= fTextWidget.getOffsetAtPoint(new Point(x + w - 1, y)) + 1;
265 if (endOffset == -1) {
266 endOffset= lineEndOffset;
267 } else if (endOffset + 2 >= lineEndOffset) {
273268 endOffset= lineEndOffset;
274269 }
275270 }
0 /**
1 * Copyright (c) 2017 Angelo ZERR.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Provide CodeMining support with CodeMiningManager - Bug 527720
9 */
10 package org.eclipse.jface.text.codemining;
11
12 import java.util.concurrent.CompletableFuture;
13 import java.util.function.Consumer;
14
15 import org.eclipse.swt.custom.StyledText;
16 import org.eclipse.swt.events.MouseEvent;
17 import org.eclipse.swt.graphics.Color;
18 import org.eclipse.swt.graphics.GC;
19 import org.eclipse.swt.graphics.Point;
20
21 import org.eclipse.core.runtime.IProgressMonitor;
22
23 import org.eclipse.jface.text.ITextViewer;
24 import org.eclipse.jface.text.Position;
25
26 /**
27 * Abstract class for {@link ICodeMining}.
28 *
29 * @since 3.13
30 */
31 public abstract class AbstractCodeMining implements ICodeMining {
32
33 /**
34 * The position where codemining must be drawn
35 */
36 private final Position position;
37
38 /**
39 * The owner codemining provider which creates this mining.
40 */
41 private final ICodeMiningProvider provider;
42
43 /**
44 * The future used to resolve mining.
45 */
46 private CompletableFuture<Void> resolveFuture;
47
48 /**
49 * The label of the resolved codemining.
50 */
51 private String label;
52
53 /**
54 * The action to execute when mining is clicked and null otherwise.
55 */
56 private final Consumer<MouseEvent> action;
57
58 /**
59 * CodeMining constructor to locate the code mining in a given position.
60 *
61 * @param position the position where the mining must be drawn.
62 * @param provider the owner codemining provider which creates this mining.
63 * @param action the action to execute when mining is clicked and null otherwise.
64 */
65 protected AbstractCodeMining(Position position, ICodeMiningProvider provider, Consumer<MouseEvent> action) {
66 this.position= position;
67 this.provider= provider;
68 this.action= action;
69 }
70
71 @Override
72 public Position getPosition() {
73 return position;
74 }
75
76 @Override
77 public ICodeMiningProvider getProvider() {
78 return provider;
79 }
80
81 @Override
82 public String getLabel() {
83 return label;
84 }
85
86 /**
87 * Set the label mining.
88 *
89 * @param label the label mining.
90 */
91 public void setLabel(String label) {
92 this.label= label;
93 }
94
95 @Override
96 public final CompletableFuture<Void> resolve(ITextViewer viewer, IProgressMonitor monitor) {
97 if (resolveFuture == null) {
98 resolveFuture= doResolve(viewer, monitor);
99 }
100 return resolveFuture;
101 }
102
103 /**
104 * Returns the future which resolved the content of mining and null otherwise. By default, the
105 * resolve do nothing.
106 *
107 * @param viewer the viewer
108 * @param monitor the monitor
109 * @return the future which resolved the content of mining and null otherwise.
110 */
111 protected CompletableFuture<Void> doResolve(ITextViewer viewer, IProgressMonitor monitor) {
112 return CompletableFuture.completedFuture(null);
113 }
114
115 @Override
116 public boolean isResolved() {
117 return (resolveFuture != null && resolveFuture.isDone());
118 }
119
120 @Override
121 public void dispose() {
122 if (resolveFuture != null) {
123 resolveFuture.cancel(true);
124 resolveFuture= null;
125 }
126 }
127
128 /**
129 * Draw the {@link #getLabel()} of mining with gray color. User can override this method to draw
130 * anything.
131 *
132 * @param gc the graphics context
133 * @param textWidget the text widget to draw on
134 * @param color the color of the line
135 * @param x the x position of the annotation
136 * @param y the y position of the annotation
137 * @return the size of the draw of mining.
138 */
139 @Override
140 public Point draw(GC gc, StyledText textWidget, Color color, int x, int y) {
141 String title= getLabel() != null ? getLabel() : "no command"; //$NON-NLS-1$
142 gc.drawString(title, x, y, true);
143 return gc.stringExtent(title);
144 }
145
146 @Override
147 public Consumer<MouseEvent> getAction() {
148 return action;
149 }
150 }
0 /**
1 * Copyright (c) 2017 Angelo ZERR.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Provide CodeMining support with CodeMiningManager - Bug 527720
9 */
10 package org.eclipse.jface.text.codemining;
11
12 import org.eclipse.core.runtime.Assert;
13 import org.eclipse.core.runtime.IAdaptable;
14
15 /**
16 * A codemining provider that can provide adapters through a context that can be set by the creator
17 * of this codemining provider.
18 * <p>
19 * Clients may subclass.
20 * </p>
21 *
22 * @since 3.13
23 */
24 public abstract class AbstractCodeMiningProvider implements ICodeMiningProvider {
25
26 /**
27 * The context of this codemining provider.
28 */
29 private IAdaptable context;
30
31 /**
32 * Sets this codemining provider's context which is responsible to provide the adapters.
33 *
34 * @param context the context for this codemining provider
35 * @throws IllegalArgumentException if the context is <code>null</code>
36 * @throws IllegalStateException if this method is called more than once
37 */
38 public final void setContext(IAdaptable context) throws IllegalStateException, IllegalArgumentException {
39 Assert.isLegal(context != null);
40 if (this.context != null)
41 throw new IllegalStateException();
42 this.context= context;
43 }
44
45 @Override
46 public void dispose() {
47 context= null;
48 }
49
50 /**
51 * Returns an object which is an instance of the given class and provides additional context for
52 * this codemining provider.
53 *
54 * @param adapterClass the adapter class to look up
55 * @return an instance that can be cast to the given class, or <code>null</code> if this object
56 * does not have an adapter for the given class
57 */
58 protected final <T> T getAdapter(Class<T> adapterClass) {
59 Assert.isLegal(adapterClass != null);
60 if (context != null)
61 return context.getAdapter(adapterClass);
62 return null;
63 }
64 }
0 /**
1 * Copyright (c) 2017 Angelo ZERR.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Provide extension point for CodeMining - Bug 528419
9 */
10 package org.eclipse.jface.text.codemining;
11
12 import org.eclipse.jface.text.IDocument;
13 import org.eclipse.jface.text.ITextViewer;
14 import org.eclipse.jface.text.reconciler.Reconciler;
15
16 /**
17 * A reconciler which update code minings.
18 *
19 * @since 3.13
20 */
21 public class CodeMiningReconciler extends Reconciler {
22
23 private CodeMiningStrategy fStrategy;
24
25 public CodeMiningReconciler() {
26 super.setIsIncrementalReconciler(false);
27 fStrategy= new CodeMiningStrategy();
28 this.setReconcilingStrategy(fStrategy, IDocument.DEFAULT_CONTENT_TYPE);
29 }
30
31 @Override
32 public void install(ITextViewer textViewer) {
33 super.install(textViewer);
34 fStrategy.install(textViewer);
35 }
36
37 @Override
38 public void uninstall() {
39 super.uninstall();
40 fStrategy.uninstall();
41 }
42
43 }
0 /**
1 * Copyright (c) 2017 Angelo ZERR.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Provide extension point for CodeMining - Bug 528419
9 */
10 package org.eclipse.jface.text.codemining;
11
12 import org.eclipse.core.runtime.IProgressMonitor;
13
14 import org.eclipse.jface.text.IDocument;
15 import org.eclipse.jface.text.IRegion;
16 import org.eclipse.jface.text.ITextViewer;
17 import org.eclipse.jface.text.reconciler.DirtyRegion;
18 import org.eclipse.jface.text.reconciler.IReconcilingStrategy;
19 import org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension;
20 import org.eclipse.jface.text.source.ISourceViewerExtension5;
21
22 /**
23 * A reconciling strategy which updates code minings.
24 *
25 * @since 3.13
26 */
27 class CodeMiningStrategy implements IReconcilingStrategy, IReconcilingStrategyExtension {
28
29 private ISourceViewerExtension5 fViewer;
30
31 public void install(ITextViewer viewer) {
32 if (viewer instanceof ISourceViewerExtension5) {
33 fViewer= (ISourceViewerExtension5) viewer;
34 }
35 }
36
37 @Override
38 public void initialReconcile() {
39 // Do nothing
40 // Initial reconcilation will happen when the SourceViewer
41 // has initialized the code mining provider
42 // see SourceViewer#ensureCodeMiningManagerInstalled
43 }
44
45 @Override
46 public void reconcile(IRegion partition) {
47 if (fViewer != null) {
48 fViewer.updateCodeMinings();
49 }
50 }
51
52 public void uninstall() {
53 fViewer= null;
54 }
55
56 @Override
57 public void setProgressMonitor(IProgressMonitor monitor) {
58 // Do nothing
59 }
60
61 @Override
62 public void setDocument(IDocument document) {
63 // Do nothing
64 }
65
66 @Override
67 public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) {
68 // Do nothing
69 }
70
71 }
0 /**
1 * Copyright (c) 2017 Angelo ZERR.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Provide CodeMining support with CodeMiningManager - Bug 527720
9 */
10 package org.eclipse.jface.text.codemining;
11
12 import java.util.concurrent.CompletableFuture;
13 import java.util.function.Consumer;
14
15 import org.eclipse.swt.custom.StyledText;
16 import org.eclipse.swt.events.MouseEvent;
17 import org.eclipse.swt.graphics.Color;
18 import org.eclipse.swt.graphics.GC;
19 import org.eclipse.swt.graphics.Point;
20
21 import org.eclipse.core.runtime.IProgressMonitor;
22
23 import org.eclipse.jface.text.ITextViewer;
24 import org.eclipse.jface.text.Position;
25
26 /**
27 * A code mining represents a content (ex: label, icons) that should be shown along with source
28 * text, like the number of references, a way to run tests (with run/debug icons), etc.
29 *
30 * A code mining is unresolved when no content (ex: label, icons) is associated to it. For
31 * performance reasons the creation of a code mining and resolving should be done to two stages.
32 *
33 * @since 3.13
34 */
35 public interface ICodeMining {
36
37 /**
38 * Returns the line position where code mining must be displayed in the line spacing area.
39 *
40 * @return the line position where code mining must be displayed in the line spacing area.
41 */
42 Position getPosition();
43
44 /**
45 * Returns the owner provider which has created this mining.
46 *
47 * @return the owner provider which has created this mining.
48 */
49 ICodeMiningProvider getProvider();
50
51 /**
52 * Returns the label may be set early in the class lifecycle, or upon completion of the future
53 * provided by {@link #resolve(ITextViewer, IProgressMonitor)} operation.
54 *
55 * <p>
56 * The returned label can have several values:
57 * <ul>
58 * <li><code>null</code> when mining is not resolved</li>
59 * <li><code>null</code> when mining is resolved means that mining was resolved with an error and it will not
60 * be displayed.</li>
61 * <li>empty when mining is resolved means that mining will not be displayed</li>
62 * <li>non empty when mining must be displayed</li>
63 * </ul>
64 * </p>
65 *
66 * @return the label may be set early in the class lifecycle, or upon completion of the future
67 * provided by {@link #resolve(ITextViewer, IProgressMonitor)} operation.
68 */
69 String getLabel();
70
71 /**
72 * Returns the future to resolve the content of mining, or
73 * {@link CompletableFuture#completedFuture(Object)} if no such resolution is necessary (in
74 * which case {#isResolved()} is expected to return <code>true</code>).
75 *
76 * @param viewer the viewer.
77 * @param monitor the monitor.
78 * @return the future to resolve the content of mining, or
79 * {@link CompletableFuture#completedFuture(Object)} if no such resolution is necessary
80 * (in which case {#isResolved()} is expected to return <code>true</code>).
81 */
82 CompletableFuture<Void> resolve(ITextViewer viewer, IProgressMonitor monitor);
83
84 /**
85 * Returns whether the content mining is resolved. If it is not resolved,
86 * {{@link #resolve(ITextViewer, IProgressMonitor)}} will be invoked later, triggering the
87 * future to resolve content.
88 *
89 * @return whether the content mining is resolved. If it is not resolved,
90 * {{@link #resolve(ITextViewer, IProgressMonitor)}} will be invoked later, triggering
91 * the future to resolve content.
92 */
93 boolean isResolved();
94
95 /**
96 * Draw the code mining.
97 *
98 * @param gc the graphics context
99 * @param textWidget the text widget to draw on
100 * @param color the color of the line
101 * @param x the x position of the annotation
102 * @param y the y position of the annotation
103 * @return the size of the draw of mining.
104 */
105 Point draw(GC gc, StyledText textWidget, Color color, int x, int y);
106
107 /**
108 * Returns the action to execute when mining is clicked and null otherwise.
109 *
110 * @return the action to execute when mining is clicked and null otherwise.
111 */
112 Consumer<MouseEvent> getAction();
113
114 /**
115 * Dispose the mining. Typically shuts down or cancels all related asynchronous operations.
116 */
117 void dispose();
118 }
0 /**
1 * Copyright (c) 2017 Angelo ZERR.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Provide CodeMining support with CodeMiningManager - Bug 527720
9 */
10 package org.eclipse.jface.text.codemining;
11
12 import java.util.List;
13 import java.util.concurrent.CompletableFuture;
14
15 import org.eclipse.core.runtime.IProgressMonitor;
16
17 import org.eclipse.jface.text.ITextViewer;
18
19 /**
20 * A code mining provider adds minings {@link ICodeMining} to source text. The mining will be shown
21 * as dedicated horizontal lines in between the source text.
22 *
23 * @since 3.13
24 */
25 public interface ICodeMiningProvider {
26
27 /**
28 * Compute a list of code minings {@link ICodeMining}. This call should return as fast as
29 * possible and if computing the content of {@link ICodeMining} is expensive implementors should
30 * only return code mining objects with the position and implement resolve
31 * {@link ICodeMining#resolve(ITextViewer, IProgressMonitor)}.
32 *
33 * @param viewer the viewer in which the command was invoked.
34 * @param monitor A progress monitor.
35 * @return An array of future of code minings that resolves to such. The lack of a result can be
36 * signaled by returning null, or an empty array.
37 */
38 CompletableFuture<List<? extends ICodeMining>> provideCodeMinings(ITextViewer viewer, IProgressMonitor monitor);
39
40 /**
41 * Dispose code mining provider.
42 */
43 void dispose();
44 }
0 /**
1 * Copyright (c) 2018, Angelo ZERR and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] CodeMining should support line header/content annotation type both - Bug 529115
9 */
10 package org.eclipse.jface.text.codemining;
11
12 import java.util.function.Consumer;
13
14 import org.eclipse.swt.events.MouseEvent;
15
16 import org.eclipse.jface.text.Position;
17
18 /**
19 * Abstract class for line content code mining.
20 *
21 * @since 3.13
22 *
23 */
24 public abstract class LineContentCodeMining extends AbstractCodeMining {
25
26 /**
27 * CodeMining constructor to locate the code mining in a given position.
28 *
29 * @param position the position where the mining must be drawn.
30 * @param provider the owner codemining provider which creates this mining.
31 */
32 public LineContentCodeMining(Position position, ICodeMiningProvider provider) {
33 this(position, provider, null);
34 }
35
36 /**
37 * CodeMining constructor to locate the code mining in a given position.
38 *
39 * @param position the position where the mining must be drawn.
40 * @param provider the owner codemining provider which creates this mining.
41 * @param action the action to execute when mining is clicked and null otherwise.
42 */
43 public LineContentCodeMining(Position position, ICodeMiningProvider provider, Consumer<MouseEvent> action) {
44 super(position, provider, action);
45 }
46
47 }
0 /**
1 * Copyright (c) 2018, Angelo ZERR and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] CodeMining should support line header/content annotation type both - Bug 529115
9 */
10 package org.eclipse.jface.text.codemining;
11
12 import java.util.function.Consumer;
13
14 import org.eclipse.swt.events.MouseEvent;
15
16 import org.eclipse.jface.text.BadLocationException;
17 import org.eclipse.jface.text.IDocument;
18 import org.eclipse.jface.text.source.inlined.Positions;
19
20 /**
21 * Abstract class for line header code mining.
22 *
23 * @since 3.13
24 *
25 */
26 public abstract class LineHeaderCodeMining extends AbstractCodeMining {
27
28 /**
29 * CodeMining constructor to locate the code mining before the given line number.
30 *
31 * @param beforeLineNumber the line number where codemining must be drawn. Use 0 if you wish to
32 * locate the code mining before the first line number (1).
33 * @param document the document.
34 * @param provider the owner codemining provider which creates this mining.
35 * @throws BadLocationException when line number doesn't exists
36 */
37 public LineHeaderCodeMining(int beforeLineNumber, IDocument document, ICodeMiningProvider provider) throws BadLocationException {
38 this(beforeLineNumber, document, provider, null);
39 }
40
41 /**
42 * CodeMining constructor to locate the code mining before the given line number.
43 *
44 * @param beforeLineNumber the line number where codemining must be drawn. Use 0 if you wish to
45 * locate the code mining before the first line number (1).
46 * @param document the document.
47 * @param provider the owner codemining provider which creates this mining.
48 * @param action the action to execute when mining is clicked and null otherwise.
49 * @throws BadLocationException when line number doesn't exists
50 */
51 public LineHeaderCodeMining(int beforeLineNumber, IDocument document, ICodeMiningProvider provider, Consumer<MouseEvent> action)
52 throws BadLocationException {
53 super(Positions.of(beforeLineNumber, document, true), provider, action);
54 }
55
56 }
2020 import java.util.concurrent.Future;
2121 import java.util.concurrent.TimeUnit;
2222 import java.util.concurrent.TimeoutException;
23 import java.util.function.Consumer;
2324
2425 import org.eclipse.osgi.util.NLS;
2526
3132 import org.eclipse.jface.contentassist.IContentAssistSubjectControl;
3233
3334 import org.eclipse.jface.text.BadLocationException;
35 import org.eclipse.jface.text.DocumentEvent;
3436 import org.eclipse.jface.text.IDocument;
3537 import org.eclipse.jface.text.ITextViewer;
3638 import org.eclipse.jface.text.TextUtilities;
3941 * This class is used to present proposals asynchronously to the user. If additional information
4042 * exists for a proposal, then selecting that proposal will result in the information being
4143 * displayed in a secondary window.
42 *
44 *
4345 * @since 3.12
4446 */
4547 class AsyncCompletionProposalPopup extends CompletionProposalPopup {
5254 private final int fOffset;
5355 private final int fSize;
5456 private int fRemaining;
55
57
5658 public ComputingProposal(int offset, int size) {
5759 fSize= size;
5860 fRemaining = size;
146148 fFilterOffset= fInvocationOffset;
147149 fLastCompletionOffset= fFilterOffset;
148150 // start invocation of processors as Futures, and make them populate the proposals upon completion
149 List<ICompletionProposal> computedProposals = Collections.synchronizedList(new ArrayList<>());
150151 fFutures= buildCompletionFuturesOrJobs(fInvocationOffset);
151 List<CompletableFuture<Void>> populateFutures = new ArrayList<>(fFutures.size());
152 for (CompletableFuture<List<ICompletionProposal>> future : fFutures) {
153 populateFutures.add(future.thenAccept(proposals ->
154 computedProposals.addAll(proposals)
155 ));
156 }
157
158 long requestBeginningTimestamp = System.currentTimeMillis();
159 long stillRemainingThreeshold = MAX_WAIT_IN_MS;
160 for (CompletableFuture<?> future : populateFutures) {
161 try {
162 future.get(stillRemainingThreeshold, TimeUnit.MILLISECONDS);
163 } catch (TimeoutException | ExecutionException | InterruptedException ex) {
164 // future failed or took more time than we want to wait
152 runFutures(fInvocationOffset, null, true, autoActivated, true);
153 } else {
154 fLastCompletionOffset= fFilterOffset;
155 handleRepeatedInvocation();
156 }
157
158 return getErrorMessage();
159 }
160
161 @Override
162 void handleRepeatedInvocation() {
163 cancelFutures();
164 fFutures= buildCompletionFuturesOrJobs(fInvocationOffset);
165 runFutures(fInvocationOffset, null, false, false, false);
166 }
167
168 private List<ICompletionProposal> runFutures(int offset, Consumer<List<ICompletionProposal>> callback, boolean createSelector, boolean autoActivated, boolean autoInsert) {
169 List<ICompletionProposal> computedProposals= Collections.synchronizedList(new ArrayList<>());
170 List<CompletableFuture<Void>> populateFutures= new ArrayList<>(fFutures.size());
171 for (CompletableFuture<List<ICompletionProposal>> future : fFutures) {
172 populateFutures.add(future.thenAccept(proposals -> computedProposals.addAll(proposals)));
173 }
174
175 long requestBeginningTimestamp= System.currentTimeMillis();
176 long stillRemainingThreeshold= MAX_WAIT_IN_MS;
177 for (CompletableFuture<?> future : populateFutures) {
178 try {
179 future.get(stillRemainingThreeshold, TimeUnit.MILLISECONDS);
180 } catch (TimeoutException | ExecutionException | InterruptedException ex) {
181 // future failed or took more time than we want to wait
182 }
183 stillRemainingThreeshold= MAX_WAIT_IN_MS - (System.currentTimeMillis() - requestBeginningTimestamp);
184 if (stillRemainingThreeshold < 0) {
185 // we already spent too much time (more than MAX_WAIT_IN_MS), stop waiting.
186 break;
187 }
188 }
189 fComputedProposals= computedProposals;
190 if (stillRemainingThreeshold > 0) { // everything ready in time, go synchronous
191 int count= computedProposals.size();
192 if (count == 0 && hideWhenNoProposals(autoActivated))
193 return computedProposals;
194
195 if (autoInsert && count == 1 && !autoActivated && canAutoInsert(computedProposals.get(0))) {
196 insertProposal(computedProposals.get(0), (char) 0, 0, offset);
197 hide();
198 } else {
199 if (createSelector) {
200 createProposalSelector();
165201 }
166 stillRemainingThreeshold = MAX_WAIT_IN_MS - (System.currentTimeMillis() - requestBeginningTimestamp);
167 if (stillRemainingThreeshold < 0) {
168 // we already spent too much time (more than MAX_WAIT_IN_MS), stop waiting.
169 break;
170 }
171 }
172 fComputedProposals = computedProposals;
173 if (stillRemainingThreeshold > 0) { // everything ready in time, go synchronous
174 int count= (computedProposals == null ? 0 : computedProposals.size());
175 if (count == 0 && hideWhenNoProposals(autoActivated))
176 return null;
177
178 if (count == 1 && !autoActivated && canAutoInsert(computedProposals.get(0))) {
179 insertProposal(computedProposals.get(0), (char) 0, 0, fInvocationOffset);
180 hide();
202 if (callback != null) {
203 callback.accept(computedProposals);
181204 } else {
182 createProposalSelector();
183205 setProposals(computedProposals, false);
184206 displayProposals();
185207 }
186 } else { // processors took too much time, go asynchronous
208 }
209 } else { // processors took too much time, go asynchronous
210 if (createSelector) {
187211 createProposalSelector();
188 ComputingProposal computingProposal= new ComputingProposal(fInvocationOffset, fFutures.size());
189 computedProposals.add(0, computingProposal);
190 fComputedProposals = computedProposals;
191 setProposals(fComputedProposals, false);
192 Set<CompletableFuture<Void>> remaining = Collections.synchronizedSet(new HashSet<>(populateFutures));
193 for (CompletableFuture<Void> populateFuture : populateFutures) {
194 populateFuture.thenRun(() -> {
195 remaining.removeIf(CompletableFuture::isDone);
196 computingProposal.setRemaining(remaining.size());
197 if (remaining.isEmpty()) {
198 computedProposals.remove(computingProposal);
212 }
213 ComputingProposal computingProposal= new ComputingProposal(offset, fFutures.size());
214 computedProposals.add(0, computingProposal);
215 setProposals(fComputedProposals, false);
216 Set<CompletableFuture<Void>> remaining= Collections.synchronizedSet(new HashSet<>(populateFutures));
217 for (CompletableFuture<Void> populateFuture : populateFutures) {
218 populateFuture.thenRun(() -> {
219 remaining.removeIf(CompletableFuture::isDone);
220 computingProposal.setRemaining(remaining.size());
221 if (remaining.isEmpty()) {
222 computedProposals.remove(computingProposal);
223 }
224 List<ICompletionProposal> newProposals= new ArrayList<>(computedProposals);
225 fComputedProposals= newProposals;
226 Display.getDefault().asyncExec(() -> {
227 if (autoInsert && !autoActivated && remaining.isEmpty() && newProposals.size() == 1 && canAutoInsert(newProposals.get(0))) {
228 if (Helper.okToUse(fProposalShell)) {
229 insertProposal(newProposals.get(0), (char) 0, 0, offset);
230 hide();
231 }
232 return;
199233 }
200 List<ICompletionProposal> newProposals = new ArrayList<>(computedProposals);
201 fComputedProposals = newProposals;
202 Display.getDefault().asyncExec(() -> {
234 if (remaining.isEmpty() && callback != null) {
235 callback.accept(newProposals);
236 } else {
203237 setProposals(newProposals, false);
204238 displayProposals();
205 });
239 }
206240 });
207 }
241 });
242 }
243 displayProposals();
244 }
245 return computedProposals;
246 }
247
248 @Override
249 public String incrementalComplete() {
250 cancelFutures();
251 if (Helper.okToUse(fProposalShell) && fFilteredProposals != null) {
252 return super.incrementalComplete();
253 }
254 final Control control= fContentAssistSubjectControlAdapter.getControl();
255
256 if (fKeyListener == null)
257 fKeyListener= new ProposalSelectionListener();
258
259 if (!Helper.okToUse(fProposalShell) && !control.isDisposed())
260 fContentAssistSubjectControlAdapter.addKeyListener(fKeyListener);
261
262 fInvocationOffset= fContentAssistSubjectControlAdapter.getSelectedRange().x;
263 fFilterOffset= fInvocationOffset;
264 fLastCompletionOffset= fFilterOffset;
265
266 fFutures= buildCompletionFuturesOrJobs(fInvocationOffset);
267 fFilteredProposals= runFutures(fInvocationOffset, (List<ICompletionProposal> proposals) -> {
268 ensureDocumentListenerInstalled();
269 if (proposals.size() > 0 && completeCommonPrefix()) {
270 hide();
271 } else {
272 fFilteredProposals= proposals;
273 setProposals(proposals, false);
208274 displayProposals();
209275 }
210 } else {
211 fLastCompletionOffset= fFilterOffset;
212 handleRepeatedInvocation();
213 }
214
276 }, true, false, true);
215277 return getErrorMessage();
216278 }
217
218 @Override
219 public void hide() {
220 super.hide();
279
280 @Override
281 List<ICompletionProposal> computeProposals(int offset) {
282 if (fProposalShell != null) {
283 fProposalShell.dispose();
284 }
285 showProposals(true);
286 return fComputedProposals;
287 }
288
289 @Override
290 void createProposalSelector() {
291 super.createProposalSelector();
292 fProposalShell.addDisposeListener(e -> cancelFutures());
293 }
294
295 void cancelFutures() {
221296 if (fFutures != null) {
222297 for (Future<?> future : fFutures) {
223298 future.cancel(true);
224299 }
225 }
300 fFutures= null;
301 }
302 }
303
304 @Override
305 protected List<ICompletionProposal> computeFilteredProposals(int offset, DocumentEvent event) {
306 if(fComputedProposals != null && fComputedProposals.size() > 0 && fComputedProposals.get(0) instanceof ComputingProposal) {
307 Set<CompletableFuture<List<ICompletionProposal>>> remaining = Collections.synchronizedSet(new HashSet<>(fFutures));
308 for (CompletableFuture<List<ICompletionProposal>> future : fFutures) {
309 future.thenRun(() -> {
310 remaining.removeIf(CompletableFuture::isDone);
311 if (remaining.isEmpty()) {
312 filterProposals();
313 }
314 });
315 }
316 return fComputedProposals;
317 }
318 return super.computeFilteredProposals(offset, event);
319 }
320
321 @Override
322 public void hide() {
323 super.hide();
324 cancelFutures();
226325 }
227326
228327 protected List<CompletableFuture<List<ICompletionProposal>>> buildCompletionFuturesOrJobs(int invocationOffset) {
237336 }
238337 List<CompletableFuture<List<ICompletionProposal>>> futures = new ArrayList<>(processors.size());
239338 for (IContentAssistProcessor processor : processors) {
240 futures.add(CompletableFuture.supplyAsync(() ->
241 Arrays.asList(processor.computeCompletionProposals(fViewer, invocationOffset))
242 ));
339 futures.add(CompletableFuture.supplyAsync(() -> {
340 ICompletionProposal[] proposals= processor.computeCompletionProposals(fViewer, invocationOffset);
341 if (proposals == null) {
342 return Collections.emptyList();
343 }
344 return Arrays.asList(proposals);
345 }));
243346 }
244347 return futures;
245348 }
255358 }
256359 return IDocument.DEFAULT_CONTENT_TYPE;
257360 }
361
258362 }
7474 import org.eclipse.jface.internal.text.InformationControlReplacer;
7575 import org.eclipse.jface.internal.text.TableOwnerDrawSupport;
7676 import org.eclipse.jface.preference.JFacePreferences;
77 import org.eclipse.jface.resource.JFaceColors;
7778 import org.eclipse.jface.resource.JFaceResources;
7879 import org.eclipse.jface.util.Geometry;
7980 import org.eclipse.jface.viewers.StyledString;
288289 /** Listener filling the document event queue. */
289290 private IDocumentListener fDocumentListener;
290291 /** The filter list of proposals. */
291 private List<ICompletionProposal> fFilteredProposals;
292 List<ICompletionProposal> fFilteredProposals;
292293 /** The computed list of proposals. */
293294 List<ICompletionProposal> fComputedProposals;
294295 /** The offset for which the proposals have been computed. */
551552 * @param offset the offset
552553 * @return the completion proposals available at this offset, never null
553554 */
554 private List<ICompletionProposal> computeProposals(int offset) {
555 List<ICompletionProposal> computeProposals(int offset) {
555556 ICompletionProposal[] completionProposals;
556557 if (fContentAssistSubjectControl != null) {
557558 completionProposals= fContentAssistant.computeCompletionProposals(fContentAssistSubjectControl, offset);
653654 }
654655 });
655656
656 fProposalShell.setBackground(control.getDisplay().getSystemColor(SWT.COLOR_GRAY));
657
658 Color c= getBackgroundColor(control);
659 fProposalTable.setBackground(c);
660
661 c= getForegroundColor(control);
662 fProposalTable.setForeground(c);
657 Color background= getBackgroundColor(control);
658 if (background == null) {
659 background= JFaceColors.getInformationViewerBackgroundColor(Display.getDefault());
660 }
661
662 Color foreground= getForegroundColor(control);
663 if (foreground == null) {
664 foreground= JFaceColors.getInformationViewerBackgroundColor(Display.getDefault());
665 }
666
667 fProposalShell.setBackground(background);
668 fProposalTable.setBackground(background);
669 fProposalTable.setForeground(foreground);
663670
664671 fProposalTable.addSelectionListener(new SelectionListener() {
665672
12591266 *
12601267 * @since 3.2
12611268 */
1262 private void ensureDocumentListenerInstalled() {
1269 void ensureDocumentListenerInstalled() {
12631270 if (fDocumentListener == null) {
12641271 fDocumentListener= new IDocumentListener() {
12651272 @Override
14591466 * Filters the displayed proposal based on the given cursor position and the
14601467 * offset of the original invocation of the content assistant.
14611468 */
1462 private void filterProposals() {
1469 void filterProposals() {
14631470 if (!fIsFilterPending) {
14641471 fIsFilterPending= true;
14651472 Control control= fContentAssistSubjectControlAdapter.getControl();
14761483 * @return the set of filtered proposals
14771484 * @since 3.0
14781485 */
1479 private List<ICompletionProposal> computeFilteredProposals(int offset, DocumentEvent event) {
1486 List<ICompletionProposal> computeFilteredProposals(int offset, DocumentEvent event) {
14801487
14811488 if (offset == fInvocationOffset && event == null) {
14821489 fIsFilteredSubset= false;
16111618
16121619 if (count == 1 && canAutoInsert(fFilteredProposals.get(0))) {
16131620 insertProposal(fFilteredProposals.get(0), (char) 0, 0, fInvocationOffset);
1614 hide();
1621 hide();
16151622 } else {
16161623 ensureDocumentListenerInstalled();
16171624 if (count > 0 && completeCommonPrefix())
16221629 setProposals(fComputedProposals, false);
16231630 displayProposals();
16241631 }
1632 }
16251633 }
1626 }
16271634 });
16281635 }
16291636 return getErrorMessage();
16391646 * selector can be closed, <code>false</code> otherwise
16401647 * @since 3.0
16411648 */
1642 private boolean completeCommonPrefix() {
1649 boolean completeCommonPrefix() {
16431650
16441651 // 0: insert single proposals
16451652 if (fFilteredProposals.size() == 1) {
16551662 IDocument document= fContentAssistSubjectControlAdapter.getDocument();
16561663
16571664 // contains the common postfix in the case that there are any proposals matching our LHS
1658 StringBuffer rightCasePostfix= null;
1665 StringBuilder rightCasePostfix= null;
16591666 List<ICompletionProposal> rightCase= new ArrayList<>();
16601667
16611668 boolean isWrongCaseMatch= false;
16651672 CharSequence wrongCasePrefix= null;
16661673 int wrongCasePrefixStart= 0;
16671674 // contains the common postfix of all case-insensitive matches
1668 StringBuffer wrongCasePostfix= null;
1675 StringBuilder wrongCasePostfix= null;
16691676 List<ICompletionProposal> wrongCase= new ArrayList<>();
16701677
16711678 boolean hasMixedProposals= hasMixedProposals();
16881695 rightCase.add(proposal);
16891696 CharSequence newPostfix= insertion.subSequence(relativeCompletionOffset, insertion.length());
16901697 if (rightCasePostfix == null)
1691 rightCasePostfix= new StringBuffer(newPostfix.toString());
1698 rightCasePostfix= new StringBuilder(newPostfix.toString());
16921699 else
16931700 truncatePostfix(rightCasePostfix, newPostfix, false);
16941701 } else if (i == 0 || isWrongCaseMatch) {
17201727 newPostfix= insertion.subSequence(relativeCompletionOffset, insertion.length());
17211728 }
17221729 if (wrongCasePostfix == null)
1723 wrongCasePostfix= new StringBuffer(newPostfix.toString());
1730 wrongCasePostfix= new StringBuilder(newPostfix.toString());
17241731 else
17251732 truncatePostfix(wrongCasePostfix, newPostfix, hasMixedProposals);
17261733 wrongCase.add(proposal);
17781785 try {
17791786 // 4: check if parts of the postfix are already in the document
17801787 int to= Math.min(document.getLength(), fFilterOffset + postfix.length());
1781 StringBuffer inDocument= new StringBuffer(document.get(fFilterOffset, to - fFilterOffset));
1788 StringBuilder inDocument= new StringBuilder(document.get(fFilterOffset, to - fFilterOffset));
17821789 truncatePostfix(inDocument, postfix, hasMixedProposals);
17831790
17841791 // 5: replace and reveal
18631870 * @param sequence the characters to truncate with
18641871 * @param ignoreCase <code>true</code> to ignore case while comparing
18651872 */
1866 private void truncatePostfix(StringBuffer buffer, CharSequence sequence, boolean ignoreCase) {
1873 private void truncatePostfix(StringBuilder buffer, CharSequence sequence, boolean ignoreCase) {
18671874 // find common prefix
18681875 int min= Math.min(buffer.length(), sequence.length());
18691876 for (int c= 0; c < min; c++) {
18921899 */
18931900 void setMessage(String message) {
18941901 Assert.isNotNull(message);
1895 if (isActive() && fMessageText != null)
1902 if (isActive() && fMessageText != null && !fMessageText.isDisposed())
18961903 fMessageText.setText(message + " "); //$NON-NLS-1$
18971904 }
18981905
19151922 * @since 3.2
19161923 */
19171924 public void setStatusLineVisible(boolean show) {
1918 if (!isActive() || show == (fMessageText != null))
1925 if (!isActive() || show == (fMessageText != null && !fMessageText.isDisposed()))
19191926 return; // nothing to do
19201927
19211928 if (show) {
77 * Contributors:
88 * IBM Corporation - initial API and implementation
99 * Mickael Istria (Red Hat Inc.) - [251156] Allow multiple contentAssitProviders internally & inheritance
10 * Stephan Wahlbrink <sw@wahlbrink.eu> - Bug 512251 - Fix IllegalArgumentException in ContextInformationPopup
1011 *******************************************************************************/
1112 package org.eclipse.jface.text.contentassist;
1213
117118 if (fContentAssistSubjectControl != null)
118119 return fContentAssistSubjectControl.getLineDelimiter();
119120 return fViewer.getTextWidget().getLineDelimiter();
121 }
122
123 public boolean isValidWidgetOffset(int widgetOffset) {
124 if (fContentAssistSubjectControl != null) {
125 IDocument document= fContentAssistSubjectControl.getDocument();
126 return (widgetOffset >= 0 && widgetOffset <= document.getLength());
127 }
128 return (widgetOffset >= 0 && widgetOffset <= fViewer.getTextWidget().getCharCount());
120129 }
121130
122131 @Override
1414 *******************************************************************************/
1515 package org.eclipse.jface.text.contentassist;
1616
17 import java.util.ArrayList;
18 import java.util.Arrays;
19 import java.util.Collection;
1720 import java.util.Collections;
1821 import java.util.HashMap;
1922 import java.util.LinkedHashSet;
23 import java.util.List;
2024 import java.util.Map;
25 import java.util.Objects;
2126 import java.util.Set;
27 import java.util.function.Function;
2228
2329 import org.eclipse.swt.SWT;
2430 import org.eclipse.swt.SWTError;
8288 /**
8389 * The standard implementation of the {@link IContentAssistant} interface. Usually, clients
8490 * instantiate this class and configure it before using it.
85 *
91 *
8692 * Since 3.12, it can compute and display the proposals asynchronously when invoking
8793 * {@link #ContentAssistant(boolean)} with <code>true</code>.
8894 */
10471053
10481054 /**
10491055 * Tells whether this content assistant allows to run asynchronous
1050 *
1056 *
10511057 * @since 3.12
10521058 */
10531059 private boolean fAsynchronous;
10691075 * context information above the location at which it was activated. If auto activation will be
10701076 * enabled, without further configuration steps, this content assistant is activated after a 500
10711077 * milliseconds delay. It uses the default partitioning.
1072 *
1078 *
10731079 * @param asynchronous <true> if this content assistant should present the proposals
10741080 * asynchronously, <code>false</code> otherwise
10751081 * @since 3.12
11151121 else
11161122 fProcessors.put(contentType, Collections.singleton(processor));
11171123 }
1118
1124
11191125 /**
11201126 * Registers a given content assist processor for a particular content type. If there is already
11211127 * a processor registered for this type, it is kept and the new processor is appended to the list
11871193 if (fProcessors == null)
11881194 return ""; //$NON-NLS-1$
11891195
1190 StringBuffer buf= new StringBuffer(5);
1196 StringBuilder buf= new StringBuilder(5);
11911197 for (Set<IContentAssistProcessor> processorsForContentType : fProcessors.values()) {
11921198 for (IContentAssistProcessor processor : processorsForContentType) {
11931199 char[] triggers= processor.getCompletionProposalAutoActivationCharacters();
19081914 *
19091915 * @param viewer the text viewer
19101916 * @param offset a offset within the document
1911 * @return a content-assist processor or <code>null</code> if none exists
1912 * @since 3.0
1913 */
1914 private IContentAssistProcessor getProcessor(ITextViewer viewer, int offset) {
1917 * @return the content-assist processors or <code>null</code> if none exists
1918 * @since 3.13
1919 */
1920 private Set<IContentAssistProcessor> getProcessors(ITextViewer viewer, int offset) {
19151921 try {
19161922
19171923 IDocument document= viewer.getDocument();
19181924 String type= TextUtilities.getContentType(document, getDocumentPartitioning(), offset, true);
19191925
1920 return getContentAssistProcessor(type);
1926 return getContentAssistProcessors(type);
19211927
19221928 } catch (BadLocationException x) {
19231929 }
19261932 }
19271933
19281934 /**
1929 * Returns the content assist processor for the content type of the specified document position.
1935 * Returns the content assist processors for the content type of the specified document position.
19301936 *
19311937 * @param contentAssistSubjectControl the content assist subject control
19321938 * @param offset a offset within the document
1933 * @return a content-assist processor or <code>null</code> if none exists
1934 * @since 3.0
1935 */
1936 private IContentAssistProcessor getProcessor(IContentAssistSubjectControl contentAssistSubjectControl, int offset) {
1939 * @return the content-assist processors or <code>null</code> if none exists
1940 * @since 3.13
1941 */
1942 private Set<IContentAssistProcessor> getProcessors(IContentAssistSubjectControl contentAssistSubjectControl, int offset) {
19371943 try {
19381944
19391945 IDocument document= contentAssistSubjectControl.getDocument();
19431949 else
19441950 type= IDocument.DEFAULT_CONTENT_TYPE;
19451951
1946 return getContentAssistProcessor(type);
1952 return getContentAssistProcessors(type);
19471953
19481954 } catch (BadLocationException x) {
19491955 }
19651971 final IContentAssistSubjectControl contentAssistSubjectControl, final int offset) {
19661972 fLastErrorMessage= null;
19671973
1968 final ICompletionProposal[][] result= { null };
1969
1970 final IContentAssistProcessor p= getProcessor(contentAssistSubjectControl, offset);
1971 if (p instanceof ISubjectControlContentAssistProcessor) {
1974 final List<ICompletionProposal> result= new ArrayList<>();
1975 final Set<IContentAssistProcessor> processors= getProcessors(contentAssistSubjectControl, offset);
1976 if (processors != null) {
1977 processors.forEach(p -> {
1978 if (p instanceof ISubjectControlContentAssistProcessor) {
1979 // Ensure that the assist session ends cleanly even if the processor throws an exception.
1980 SafeRunner.run(new ExceptionLoggingSafeRunnable(COMPLETION_ERROR_MESSAGE_KEY) {
1981 @Override
1982 public void run() throws Exception {
1983 result.addAll(Arrays.asList( ((ISubjectControlContentAssistProcessor) p)
1984 .computeCompletionProposals(contentAssistSubjectControl, offset)));
1985 fLastErrorMessage= p.getErrorMessage();
1986 }
1987 });
1988 }
1989 });
1990 }
1991
1992 return result.isEmpty() ? null : result.toArray(new ICompletionProposal[result.size()]);
1993 }
1994
1995 /**
1996 * Returns an array of completion proposals computed based on the specified document position.
1997 * The position is used to determine the appropriate content assist processor to invoke.
1998 *
1999 * @param viewer the viewer for which to compute the proposals
2000 * @param offset a document offset
2001 * @return an array of completion proposals or <code>null</code> if no proposals are possible
2002 * @see IContentAssistProcessor#computeCompletionProposals(ITextViewer, int)
2003 */
2004 ICompletionProposal[] computeCompletionProposals(final ITextViewer viewer, final int offset) {
2005 fLastErrorMessage= null;
2006
2007 final Set<IContentAssistProcessor> processors= getProcessors(viewer, offset);
2008 final List<ICompletionProposal> res = new ArrayList<>();
2009 if (processors != null && !processors.isEmpty()) {
19722010 // Ensure that the assist session ends cleanly even if the processor throws an exception.
19732011 SafeRunner.run(new ExceptionLoggingSafeRunnable(COMPLETION_ERROR_MESSAGE_KEY) {
19742012 @Override
19752013 public void run() throws Exception {
1976 result[0]= ((ISubjectControlContentAssistProcessor) p)
1977 .computeCompletionProposals(contentAssistSubjectControl, offset);
1978 fLastErrorMessage= p.getErrorMessage();
2014 processors.forEach(p -> {
2015 ICompletionProposal[] proposals= p.computeCompletionProposals(viewer, offset);
2016 if (proposals != null) {
2017 res.addAll(Arrays.asList(proposals));
2018 }
2019 fLastErrorMessage= p.getErrorMessage();
2020 });
19792021 }
19802022 });
19812023 }
19822024
1983 return result[0];
1984 }
1985
1986 /**
1987 * Returns an array of completion proposals computed based on the specified document position.
1988 * The position is used to determine the appropriate content assist processor to invoke.
1989 *
1990 * @param viewer the viewer for which to compute the proposals
1991 * @param offset a document offset
1992 * @return an array of completion proposals or <code>null</code> if no proposals are possible
1993 * @see IContentAssistProcessor#computeCompletionProposals(ITextViewer, int)
1994 */
1995 ICompletionProposal[] computeCompletionProposals(final ITextViewer viewer, final int offset) {
1996 fLastErrorMessage= null;
1997
1998 final ICompletionProposal[][] result= { null };
1999
2000 final IContentAssistProcessor p= getProcessor(viewer, offset);
2001 if (p != null) {
2002 // Ensure that the assist session ends cleanly even if the processor throws an exception.
2003 SafeRunner.run(new ExceptionLoggingSafeRunnable(COMPLETION_ERROR_MESSAGE_KEY) {
2004 @Override
2005 public void run() throws Exception {
2006 result[0]= p.computeCompletionProposals(viewer, offset);
2007 fLastErrorMessage= p.getErrorMessage();
2008 }
2009 });
2010 }
2011
2012 return result[0];
2025 return res.isEmpty() ? null : res.toArray(new ICompletionProposal[res.size()]);
20132026 }
20142027
20152028 /**
20252038 IContextInformation[] computeContextInformation(final ITextViewer viewer, final int offset) {
20262039 fLastErrorMessage= null;
20272040
2028 final IContextInformation[][] result= { null };
2029
2030 final IContentAssistProcessor p= getProcessor(viewer, offset);
2031 if (p != null) {
2041 final List<IContextInformation> result= new ArrayList<>();
2042 final Set<IContentAssistProcessor> processors= getProcessors(viewer, offset);
2043 if (processors != null && !processors.isEmpty()) {
20322044 // Ensure that the assist session ends cleanly even if the processor throws an exception.
20332045 SafeRunner.run(new ExceptionLoggingSafeRunnable(CONTEXT_ERROR_MESSAGE_KEY) {
20342046 @Override
20352047 public void run() throws Exception {
2036 result[0]= p.computeContextInformation(viewer, offset);
2037 fLastErrorMessage= p.getErrorMessage();
2048 processors.forEach(p -> {
2049 result.addAll(Arrays.asList(p.computeContextInformation(viewer, offset)));
2050 fLastErrorMessage= p.getErrorMessage();
2051 });
20382052 }
20392053 });
20402054 }
20412055
2042 return result[0];
2056 return result.isEmpty() ? null : result.toArray(new IContextInformation[result.size()]);
20432057 }
20442058
20452059 /**
20572071 final IContentAssistSubjectControl contentAssistSubjectControl, final int offset) {
20582072 fLastErrorMessage= null;
20592073
2060 final IContextInformation[][] result= { null };
2061
2062 final IContentAssistProcessor p= getProcessor(contentAssistSubjectControl, offset);
2063 if (p instanceof ISubjectControlContentAssistProcessor) {
2064 // Ensure that the assist session ends cleanly even if the processor throws an exception.
2065 SafeRunner.run(new ExceptionLoggingSafeRunnable(CONTEXT_ERROR_MESSAGE_KEY) {
2066 @Override
2067 public void run() throws Exception {
2068 result[0]= ((ISubjectControlContentAssistProcessor) p)
2069 .computeContextInformation(contentAssistSubjectControl, offset);
2070 fLastErrorMessage= p.getErrorMessage();
2074 final List<IContextInformation> result= new ArrayList<>();
2075 final Set<IContentAssistProcessor> processors = getProcessors(contentAssistSubjectControl, offset);
2076 if (processors != null) {
2077 processors.forEach(p -> {
2078 if (p instanceof ISubjectControlContentAssistProcessor) {
2079 // Ensure that the assist session ends cleanly even if the processor throws an exception.
2080 SafeRunner.run(new ExceptionLoggingSafeRunnable(CONTEXT_ERROR_MESSAGE_KEY) {
2081 @Override
2082 public void run() throws Exception {
2083 result.addAll(Arrays.asList( ((ISubjectControlContentAssistProcessor) p)
2084 .computeContextInformation(contentAssistSubjectControl, offset)));
2085 fLastErrorMessage= p.getErrorMessage();
2086 }
2087 });
20712088 }
20722089 });
20732090 }
20742091
2075 return result[0];
2092 return result.isEmpty() ? null : result.toArray(new IContextInformation[result.size()]);
20762093 }
20772094
20782095 /**
20872104 * @since 3.0
20882105 */
20892106 IContextInformationValidator getContextInformationValidator(ITextViewer viewer, int offset) {
2090 IContentAssistProcessor p= getProcessor(viewer, offset);
2107 Set<IContentAssistProcessor> processors= getProcessors(viewer, offset);
2108 if (processors == null || processors.isEmpty()) {
2109 return null;
2110 }
2111 // pick first one, arbitrary
2112 IContentAssistProcessor p = processors.iterator().next();
20912113 return p != null ? p.getContextInformationValidator() : null;
20922114 }
20932115
21032125 * @since 3.0
21042126 */
21052127 IContextInformationValidator getContextInformationValidator(IContentAssistSubjectControl contentAssistSubjectControl, int offset) {
2106 IContentAssistProcessor p= getProcessor(contentAssistSubjectControl, offset);
2128 Set<IContentAssistProcessor> processors= getProcessors(contentAssistSubjectControl, offset);
2129 if (processors == null || processors.isEmpty()) {
2130 return null;
2131 }
2132 // pick first one, arbitrary
2133 IContentAssistProcessor p = processors.iterator().next();
21072134 return p != null ? p.getContextInformationValidator() : null;
21082135 }
21092136
21512178 * @since 3.0
21522179 */
21532180 char[] getCompletionProposalAutoActivationCharacters(IContentAssistSubjectControl contentAssistSubjectControl, int offset) {
2154 IContentAssistProcessor p= getProcessor(contentAssistSubjectControl, offset);
2155 return p != null ? p.getCompletionProposalAutoActivationCharacters() : null;
2181 return mergeResults(getProcessors(contentAssistSubjectControl, offset), IContentAssistProcessor::getCompletionProposalAutoActivationCharacters);
21562182 }
21572183
21582184 /**
21662192 * @see IContentAssistProcessor#getCompletionProposalAutoActivationCharacters()
21672193 */
21682194 char[] getCompletionProposalAutoActivationCharacters(ITextViewer viewer, int offset) {
2169 IContentAssistProcessor p= getProcessor(viewer, offset);
2170 return p != null ? p.getCompletionProposalAutoActivationCharacters() : null;
2195 return mergeResults(getProcessors(viewer, offset), IContentAssistProcessor::getCompletionProposalAutoActivationCharacters);
21712196 }
21722197
21732198 /**
21822207 * @since 3.0
21832208 */
21842209 char[] getContextInformationAutoActivationCharacters(ITextViewer viewer, int offset) {
2185 IContentAssistProcessor p= getProcessor(viewer, offset);
2186 return p != null ? p.getContextInformationAutoActivationCharacters() : null;
2210 return mergeResults(getProcessors(viewer, offset), IContentAssistProcessor::getContextInformationAutoActivationCharacters);
21872211 }
21882212
21892213 /**
21982222 * @since 3.0
21992223 */
22002224 char[] getContextInformationAutoActivationCharacters(IContentAssistSubjectControl contentAssistSubjectControl, int offset) {
2201 IContentAssistProcessor p= getProcessor(contentAssistSubjectControl, offset);
2202 return p != null ? p.getContextInformationAutoActivationCharacters() : null;
2225 return mergeResults(getProcessors(contentAssistSubjectControl, offset), IContentAssistProcessor::getContextInformationAutoActivationCharacters);
2226 }
2227
2228 private char[] mergeResults(Collection<IContentAssistProcessor> processors, Function<IContentAssistProcessor, char[]> f) {
2229 if (processors == null) {
2230 return null;
2231 }
2232 char[][] arrays = processors.stream()
2233 .map(f)
2234 .filter(Objects::nonNull)
2235 .filter(array -> array.length > 0)
2236 .toArray(char[][]::new);
2237 if (arrays.length == 0) {
2238 return null;
2239 } else if (arrays.length == 1) {
2240 return arrays[0];
2241 } else {
2242 LinkedHashSet<Character> res = new LinkedHashSet<>();
2243 for (char[] current : arrays) {
2244 for (char c : current) {
2245 res.add(Character.valueOf(c));
2246 }
2247 }
2248 char[] array = new char[res.size()];
2249 int index = 0;
2250 for (Character c : res) {
2251 array[index] = c.charValue();
2252 index++;
2253 }
2254 return array;
2255 }
22032256 }
22042257
22052258 @Override
24422495 */
24432496 void fireSessionBeginEvent(boolean isAutoActivated) {
24442497 if (fContentAssistSubjectControlAdapter != null && !isProposalPopupActive()) {
2445 IContentAssistProcessor processor= getProcessor(fContentAssistSubjectControlAdapter, fContentAssistSubjectControlAdapter.getSelectedRange().x);
2446 ContentAssistEvent event= new ContentAssistEvent(this, processor, isAutoActivated);
2447 for (ICompletionListener listener : fCompletionListeners) {
2448 listener.assistSessionStarted(event);
2498 Set<IContentAssistProcessor> processors= getProcessors(fContentAssistSubjectControlAdapter, fContentAssistSubjectControlAdapter.getSelectedRange().x);
2499 if (processors != null) {
2500 processors.forEach(processor -> {
2501 ContentAssistEvent event= new ContentAssistEvent(this, processor, isAutoActivated);
2502 for (ICompletionListener listener : fCompletionListeners) {
2503 listener.assistSessionStarted(event);
2504 }
2505 });
24492506 }
24502507 }
24512508 }
24572514 */
24582515 void fireSessionRestartEvent() {
24592516 if (fContentAssistSubjectControlAdapter != null) {
2460 IContentAssistProcessor processor= getProcessor(fContentAssistSubjectControlAdapter, fContentAssistSubjectControlAdapter.getSelectedRange().x);
2461 ContentAssistEvent event= new ContentAssistEvent(this, processor);
2462 for (ICompletionListener listener : fCompletionListeners) {
2463 if (listener instanceof ICompletionListenerExtension)
2464 ((ICompletionListenerExtension)listener).assistSessionRestarted(event);
2517 Set<IContentAssistProcessor> processors= getProcessors(fContentAssistSubjectControlAdapter, fContentAssistSubjectControlAdapter.getSelectedRange().x);
2518 if (processors != null) {
2519 processors.forEach(processor -> {
2520 ContentAssistEvent event= new ContentAssistEvent(this, processor);
2521 for (ICompletionListener listener : fCompletionListeners) {
2522 if (listener instanceof ICompletionListenerExtension)
2523 ((ICompletionListenerExtension)listener).assistSessionRestarted(event);
2524 }
2525 });
24652526 }
24662527 }
24672528 }
24732534 */
24742535 void fireSessionEndEvent() {
24752536 if (fContentAssistSubjectControlAdapter != null) {
2476 IContentAssistProcessor processor= getProcessor(fContentAssistSubjectControlAdapter, fContentAssistSubjectControlAdapter.getSelectedRange().x);
2477 ContentAssistEvent event= new ContentAssistEvent(this, processor);
2478 for (ICompletionListener listener : fCompletionListeners) {
2479 listener.assistSessionEnded(event);
2537 Set<IContentAssistProcessor> processors= getProcessors(fContentAssistSubjectControlAdapter, fContentAssistSubjectControlAdapter.getSelectedRange().x);
2538 if (processors != null) {
2539 processors.forEach(processor -> {
2540 ContentAssistEvent event= new ContentAssistEvent(this, processor);
2541 for (ICompletionListener listener : fCompletionListeners) {
2542 listener.assistSessionEnded(event);
2543 }
2544 });
24802545 }
24812546 }
24822547 }
66 *
77 * Contributors:
88 * IBM Corporation - initial API and implementation
9 * Stephan Wahlbrink <sw@wahlbrink.eu> - Bug 512251 - Fix IllegalArgumentException in ContextInformationPopup
910 *******************************************************************************/
1011 package org.eclipse.jface.text.contentassist;
1112
273274 * @since 3.0
274275 */
275276 private void internalShowContextInfo(ContextFrame frame) {
276 if (frame != null) {
277 if (frame != null && canShowFrame(frame)) {
277278 fContextFrameStack.push(frame);
278279 if (fContextFrameStack.size() == 1)
279280 fLastContext= null;
332333 */
333334 private boolean isLastFrame(ContextFrame frame) {
334335 return frame != null && frame.equals(fLastContext);
336 }
337
338 /**
339 * Pre-checks if the given context frame can be (re)shown.
340 *
341 * The function checks if the frame has valid position data. It does not call the context
342 * information validator.
343 *
344 * @param frame the frame to check
345 * @return <code>true</code> if the context frame OK to use, otherwise <code>false</code>
346 */
347 private boolean canShowFrame(ContextFrame frame) {
348 return fContentAssistSubjectControlAdapter.isValidWidgetOffset(frame.fVisibleOffset);
335349 }
336350
337351 /**
456470 if (Helper.okToUse(fContextInfoPopup)) {
457471
458472 int size= fContextFrameStack.size();
459 if (size > 0) {
473 while (size > 0) {
460474 fLastContext= fContextFrameStack.pop();
461475 -- size;
462 }
463
464 if (size > 0) {
465 ContextFrame current= fContextFrameStack.peek();
466 internalShowContextFrame(current, false);
467 } else {
468
476
477 if (size > 0) {
478 ContextFrame current= fContextFrameStack.peek();
479 if (canShowFrame(current)) {
480 internalShowContextFrame(current, false);
481 return;
482 }
483 // continue - try next
484 }
485 else {
486 break;
487 }
488 }
489 {
469490 fContentAssistant.removeContentAssistListener(this, ContentAssistant.CONTEXT_INFO_POPUP);
470491
471492 if (fContentAssistSubjectControlAdapter.getControl() != null)
271271 @Override
272272 public void mouseMove(MouseEvent e) {
273273 if (fTable.equals(e.getSource())) {
274 Object o= fTable.getItem(new Point(e.x, e.y));
275 if (fLastItem == null ^ o == null) {
276 fTable.setCursor(o == null ? null : fTable.getDisplay().getSystemCursor(SWT.CURSOR_HAND));
274 TableItem item= fTable.getItem(new Point(e.x, e.y));
275 if (fLastItem == null ^ item == null) {
276 fTable.setCursor(item == null ? null : fTable.getDisplay().getSystemCursor(SWT.CURSOR_HAND));
277277 }
278 if (o instanceof TableItem) {
279 TableItem item= (TableItem) o;
280 if (!o.equals(fLastItem)) {
281 fLastItem= (TableItem) o;
278 if (item != null) {
279 if (!item.equals(fLastItem)) {
280 fLastItem= item;
282281 fTable.setSelection(new TableItem[] { fLastItem });
283282 } else if (e.y < fTable.getItemHeight() / 4) {
284283 // Scroll up
295294 fTable.setSelection(new TableItem[] { fLastItem });
296295 }
297296 }
298 } else if (o == null) {
297 } else {
299298 fLastItem= null;
300299 }
301300 }
2525 /** The word detector used by this rule */
2626 protected IWordDetector fDetector;
2727 /** The internal buffer used for pattern detection */
28 private StringBuffer fBuffer= new StringBuffer();
28 private StringBuilder fBuffer= new StringBuilder();
2929
3030 /**
3131 * Creates a rule for the given starting and ending word
3838 /** The table of predefined words and token for this rule. */
3939 protected Map<String, IToken> fWords= new HashMap<>();
4040 /** Buffer used for pattern detection. */
41 private StringBuffer fBuffer= new StringBuffer();
41 private StringBuilder fBuffer= new StringBuilder();
4242 /**
4343 * Tells whether this rule is case sensitive.
4444 * @since 3.3
00 /*******************************************************************************
1 * Copyright (c) 2000, 2015 IBM Corporation and others.
1 * Copyright (c) 2000, 2018 IBM Corporation and others.
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
14541454 return new Region(vOffset, vLength);
14551455 }
14561456
1457 int widgetOffset;
1458 try {
1459 int widgetClippingStartOffset= fTextWidget.getOffsetAtLocation(new Point(0, event.y));
1460 int firstWidgetLine= fTextWidget.getLineAtOffset(widgetClippingStartOffset);
1461 widgetOffset= fTextWidget.getOffsetAtLine(firstWidgetLine);
1462 } catch (IllegalArgumentException ex1) {
1457 int widgetOffset= -1;
1458 int widgetClippingStartOffset= fTextWidget.getOffsetAtPoint(new Point(0, event.y));
1459 if (widgetClippingStartOffset != -1) {
1460 try {
1461 int firstWidgetLine= fTextWidget.getLineAtOffset(widgetClippingStartOffset);
1462 widgetOffset= fTextWidget.getOffsetAtLine(firstWidgetLine);
1463 } catch (IllegalArgumentException ex) {
1464 /* ignore; keep widgetOffset at -1 */
1465 }
1466 }
1467 if (widgetOffset == -1) {
14631468 try {
14641469 int firstVisibleLine= JFaceTextUtil.getPartialTopIndex(fTextWidget);
14651470 widgetOffset= fTextWidget.getOffsetAtLine(firstVisibleLine);
1466 } catch (IllegalArgumentException ex2) { // above try code might fail too
1471 } catch (IllegalArgumentException ex) { // above try code might fail
14671472 widgetOffset= 0;
14681473 }
14691474 }
14701475
1471 int widgetEndOffset;
1472 try {
1473 int widgetClippingEndOffset= fTextWidget.getOffsetAtLocation(new Point(0, event.y + event.height));
1474 int lastWidgetLine= fTextWidget.getLineAtOffset(widgetClippingEndOffset);
1475 widgetEndOffset= fTextWidget.getOffsetAtLine(lastWidgetLine + 1);
1476 } catch (IllegalArgumentException ex1) {
1476 int widgetEndOffset= -1;
1477 int widgetClippingEndOffset= fTextWidget.getOffsetAtPoint(new Point(0, event.y + event.height));
1478 if (widgetClippingEndOffset != -1) {
1479 try {
1480 int lastWidgetLine= fTextWidget.getLineAtOffset(widgetClippingEndOffset);
1481 widgetEndOffset= fTextWidget.getOffsetAtLine(lastWidgetLine + 1);
1482 } catch (IllegalArgumentException ex1) {
1483 /* ignore; keep widgetEndOffset at -1 */
1484 }
1485 }
1486 if (widgetEndOffset == -1) {
14771487 // happens if the editor is not "full", e.g. the last line of the document is visible in the editor
14781488 try {
14791489 int lastVisibleLine= JFaceTextUtil.getPartialBottomIndex(fTextWidget);
1480 if (lastVisibleLine == fTextWidget.getLineCount() - 1)
1490 if (lastVisibleLine == fTextWidget.getLineCount() - 1) {
14811491 // last line
14821492 widgetEndOffset= fTextWidget.getCharCount();
1483 else
1493 } else {
14841494 widgetEndOffset= fTextWidget.getOffsetAtLine(lastVisibleLine + 1) - 1;
1485 } catch (IllegalArgumentException ex2) { // above try code might fail too
1495 }
1496 } catch (IllegalArgumentException ex) { // above try code might fail too
14861497 widgetEndOffset= fTextWidget.getCharCount();
14871498 }
14881499 }
1919 import java.util.List;
2020 import java.util.Map;
2121 import java.util.Set;
22 import java.util.function.Consumer;
2223
2324 import org.eclipse.swt.SWT;
2425 import org.eclipse.swt.custom.StyledText;
4950 import org.eclipse.jface.text.ITextListener;
5051 import org.eclipse.jface.text.ITextViewer;
5152 import org.eclipse.jface.text.ITextViewerExtension5;
52 import org.eclipse.jface.text.IViewportListener;
5353 import org.eclipse.jface.text.JFaceTextUtil;
5454 import org.eclipse.jface.text.Position;
5555 import org.eclipse.jface.text.TextEvent;
6969 /**
7070 * Internal listener class.
7171 */
72 class InternalListener implements IViewportListener, IAnnotationModelListener, ITextListener {
73
74 @Override
75 public void viewportChanged(int verticalPosition) {
76 if (verticalPosition != fScrollPos)
77 redraw();
78 }
79
72 class AnnotationsListener implements IAnnotationModelListener {
8073 @Override
8174 public void modelChanged(IAnnotationModel model) {
8275 postRedraw();
83 }
84
85 @Override
86 public void textChanged(TextEvent e) {
87 if (e.getViewerRedrawState())
88 postRedraw();
8976 }
9077 }
9178
138125 /** The buffer for double buffering */
139126 private Image fBuffer;
140127 /** The internal listener */
141 private InternalListener fInternalListener= new InternalListener();
128 private AnnotationsListener fAnnotationListener= new AnnotationsListener();
142129 /** The width of this vertical ruler */
143130 private int fWidth;
144131 /** Switch for enabling/disabling the setModel method. */
191178 */
192179 private MouseListener fMouseListener;
193180
181 private Consumer<StyledText> lineHeightChangeHandler= (t) -> postRedraw();
182
183 private ITextListener fLineListener = new ITextListener() {
184 private int previousLineCount = -1;
185
186 @Override
187 public void textChanged(TextEvent event) {
188 if (event.getViewerRedrawState() && fCachedTextWidget.getLineCount() != previousLineCount) {
189 previousLineCount= fCachedTextWidget.getLineCount();
190 postRedraw();
191 }
192 }
193 };
194
194195 /**
195196 * Constructs this column with the given arguments.
196197 *
203204 this(width, annotationAccess);
204205 fAllowSetModel= false;
205206 fModel= model;
206 fModel.addAnnotationModelListener(fInternalListener);
207 fModel.addAnnotationModelListener(fAnnotationListener);
207208 }
208209
209210 /**
229230 fWidth= width;
230231 fAllowSetModel= false;
231232 fModel= model;
232 fModel.addAnnotationModelListener(fInternalListener);
233 fModel.addAnnotationModelListener(fAnnotationListener);
233234 }
234235
235236 /**
336337 });
337338
338339 if (fCachedTextViewer != null) {
339 fCachedTextViewer.addViewportListener(fInternalListener);
340 fCachedTextViewer.addTextListener(fInternalListener);
340 VisibleLinesTracker.track(fCachedTextViewer, lineHeightChangeHandler);
341 fCachedTextViewer.addTextListener(fLineListener);
341342 // on word wrap toggle a "resized" ControlEvent is fired: suggest a redraw of the ruler
342343 fCachedTextWidget.addControlListener(new ControlAdapter() {
343344 @Override
505506 private void handleDispose() {
506507
507508 if (fCachedTextViewer != null) {
508 fCachedTextViewer.removeViewportListener(fInternalListener);
509 fCachedTextViewer.removeTextListener(fInternalListener);
509 VisibleLinesTracker.untrack(fCachedTextViewer, lineHeightChangeHandler);
510 fCachedTextViewer.removeTextListener(fLineListener);
510511 }
511512
512513 if (fModel != null)
513 fModel.removeAnnotationModelListener(fInternalListener);
514 fModel.removeAnnotationModelListener(fAnnotationListener);
514515
515516 if (fBuffer != null) {
516517 fBuffer.dispose();
520521 fConfiguredAnnotationTypes.clear();
521522 fAllowedAnnotationTypes.clear();
522523 fAnnotationAccessExtension= null;
524
523525 }
524526
525527 /**
818820 r.height= textBounds.height;
819821 r.y = textBounds.y;
820822 }
821
823 // adjust the annotation position at the bottom of the line if line height has custom line height
824 int defaultLineHeight= fCachedTextWidget.getLineHeight();
825 int lineHeight= fCachedTextWidget.getLineHeight(offset);
826 if (lineHeight > defaultLineHeight) {
827 int adjust= lineHeight - defaultLineHeight;
828 r.y+= adjust;
829 r.height-= adjust;
830 }
822831 if (r.y < dimension.y && fAnnotationAccessExtension != null) // annotation within visible area
823832 fAnnotationAccessExtension.paint(annotation, gc, fCanvas, r);
824833 }
866875 if (fAllowSetModel && model != fModel) {
867876
868877 if (fModel != null)
869 fModel.removeAnnotationModelListener(fInternalListener);
878 fModel.removeAnnotationModelListener(fAnnotationListener);
870879
871880 fModel= model;
872881
873882 if (fModel != null)
874 fModel.addAnnotationModelListener(fInternalListener);
883 fModel.addAnnotationModelListener(fAnnotationListener);
875884
876885 postRedraw();
877886 }
8989 }
9090
9191 if (fShowLineNumber && lineNumber > -1)
92 return JFaceTextMessages.getFormattedString("DefaultAnnotationHover.lineNumber", new String[] { Integer.toString(lineNumber + 1) }); //$NON-NLS-1$
92 return JFaceTextMessages.getFormattedString("DefaultAnnotationHover.lineNumber", Integer.toString(lineNumber + 1)); //$NON-NLS-1$
9393
9494 return null;
9595 }
130130 * @return the formatted message
131131 */
132132 protected String formatMultipleMessages(List<String> messages) {
133 StringBuffer buffer= new StringBuffer();
133 StringBuilder buffer= new StringBuilder();
134134 buffer.append(JFaceTextMessages.getString("DefaultAnnotationHover.multipleMarkers")); //$NON-NLS-1$
135135
136136 Iterator<String> e= messages.iterator();
137137 while (e.hasNext()) {
138138 buffer.append('\n');
139139 String listItemText= e.next();
140 buffer.append(JFaceTextMessages.getFormattedString("DefaultAnnotationHover.listItem", new String[] { listItemText })); //$NON-NLS-1$
140 buffer.append(JFaceTextMessages.getFormattedString("DefaultAnnotationHover.listItem", listItemText)); //$NON-NLS-1$
141141 }
142142 return buffer.toString();
143143 }
169169 if (value instanceof List) {
170170 @SuppressWarnings("unchecked")
171171 List<Object> messages= (List<Object>) value;
172 if (messages.contains(message))
172 if (messages.contains(message))
173173 return true;
174174
175175 messages.add(message);
66 *
77 * Contributors:
88 * IBM Corporation - initial API and implementation
9 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Add CodeMining support in SourceViewer - Bug 527515
910 *******************************************************************************/
1011 package org.eclipse.jface.text.source;
1112
4546 * to the quick assist invocation context as well as the current annotation hover.</li>
4647 * <li>{@link org.eclipse.jface.text.source.ISourceViewerExtension4} since version 3.4
4748 * introducing API to access a minimal set of content assistant APIs.</li>
49 * <li>{@link org.eclipse.jface.text.source.ISourceViewerExtension5} since version 3.13
50 * introducing API to access minimal set of code mining APIs.</li>
4851 * </ul></p>
4952 * <p>
5053 * Clients may implement this interface and its extension interfaces or use the
0 /*******************************************************************************
1 * Copyright (c) 2017, 2018 Angelo ZERR.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Add CodeMining support in SourceViewer - Bug 527515
9 *******************************************************************************/
10 package org.eclipse.jface.text.source;
11
12 import org.eclipse.jface.text.codemining.ICodeMining;
13 import org.eclipse.jface.text.codemining.ICodeMiningProvider;
14
15 /**
16 * Extension interface for {@link org.eclipse.jface.text.source.ISourceViewer}.
17 * <p>
18 * It introduces API to access a minimal set of code mining APIs.</li>
19 * </p>
20 *
21 * @see ICodeMining
22 * @see ICodeMiningProvider
23 * @since 3.13
24 */
25 public interface ISourceViewerExtension5 {
26
27 /**
28 * Set the {@link AnnotationPainter} to use to draw code minings.
29 *
30 * @param painter the {@link AnnotationPainter} to use to draw code minings.
31 */
32 void setCodeMiningAnnotationPainter(AnnotationPainter painter);
33
34 /**
35 * Register the code mining providers.
36 *
37 * @param codeMiningProviders the code mining providers to register.
38 */
39 void setCodeMiningProviders(ICodeMiningProvider[] codeMiningProviders);
40
41 /**
42 * Returns <code>true</code> if there are code mining providers and <code>false</code>
43 * otherwise.
44 *
45 * @return <code>true</code> if there are code mining providers and <code>false</code>
46 * otherwise.
47 */
48 boolean hasCodeMiningProviders();
49
50 /**
51 * Update the code minings.
52 *
53 * Clients and implementors are responsible of calling this method when needed. A typical
54 * use-case can be to run it upon completion of a reconcilier and after a job that would compute
55 * all the necessary pre-requisites to insert code mining annotations.
56 */
57 void updateCodeMinings();
58
59 }
5656 * @return the formatted string
5757 * @since 3.0
5858 */
59 public static String getFormattedString(String key, Object[] args) {
59 public static String getFormattedString(String key, Object... args) {
6060 String format= null;
6161 try {
6262 format= fgResourceBundle.getString(key);
4646 */
4747 protected String formatSource(String content) {
4848 if (content != null) {
49 StringBuffer sb= new StringBuffer(content);
49 StringBuilder sb= new StringBuilder(content);
5050 final String tabReplacement= getTabReplacement();
5151 for (int pos= 0; pos < sb.length(); pos++) {
5252 if (sb.charAt(pos) == '\t')
113113 * the viewer).
114114 * added controls how many lines are added - added lines are
115115 */
116 StringBuffer text = new StringBuffer();
116 StringBuilder text = new StringBuilder();
117117 int added= 0;
118118 for (ILineDiffInfo info : diffInfos) {
119119 String[] original= info.getOriginalText();
137137 }
138138 }
139139
140 text = new StringBuffer(text.toString().trim());
140 text = new StringBuilder(text.toString().trim());
141141 if (text.length() == 0 && added-- > 0 && maxLines-- > 0) {
142142 text.append("+ ");//$NON-NLS-1$
143143 }
124124
125125 @Override
126126 protected String createDisplayString(int line) {
127 StringBuffer buffer= new StringBuffer();
127 StringBuilder buffer= new StringBuilder();
128128 if (fShowNumbers)
129129 buffer.append(super.createDisplayString(line));
130130 if (fCharacterDisplay && getModel() != null)
1616
1717 import java.lang.ref.WeakReference;
1818 import java.util.Arrays;
19 import java.util.function.Consumer;
1920
2021 import org.eclipse.swt.SWT;
2122 import org.eclipse.swt.custom.StyledText;
5455 import org.eclipse.jface.text.ITextViewer;
5556 import org.eclipse.jface.text.ITextViewerExtension;
5657 import org.eclipse.jface.text.ITextViewerExtension5;
57 import org.eclipse.jface.text.IViewportListener;
5858 import org.eclipse.jface.text.JFaceTextUtil;
5959 import org.eclipse.jface.text.TextEvent;
6060
8181 /**
8282 * Internal listener class.
8383 */
84 class InternalListener implements IViewportListener, ITextListener {
84 class InternalListener implements ITextListener {
8585
8686 /**
8787 * @since 3.1
8989 private boolean fCachedRedrawState= true;
9090
9191 @Override
92 public void viewportChanged(int verticalPosition) {
93 if (fCachedRedrawState && verticalPosition != fScrollPos)
94 redraw();
95 }
96
97 @Override
9892 public void textChanged(TextEvent event) {
9993
10094 fCachedRedrawState= event.getViewerRedrawState();
106100 layout(event.getViewerRedrawState());
107101 return;
108102 }
109
110 boolean viewerCompletelyShown= isViewerCompletelyShown();
111 if (viewerCompletelyShown || fSensitiveToTextChanges || event.getDocumentEvent() == null)
112 postRedraw();
113 fSensitiveToTextChanges= viewerCompletelyShown;
114103 }
115104 }
116105
242231 if (relativePosition.x < 0)
243232 offset= lineInfo.getOffset();
244233 else {
245 try {
246 int widgetOffset= fCachedTextWidget.getOffsetAtLocation(relativePosition);
234 int widgetOffset= fCachedTextWidget.getOffsetAtPoint(relativePosition);
235 if (widgetOffset != -1) {
247236 Point p= fCachedTextWidget.getLocationAtOffset(widgetOffset);
248 if (p.x > relativePosition.x)
237 if (p.x > relativePosition.x) {
249238 widgetOffset--;
239 }
250240
251241 // Convert to model offset
252242 if (fCachedTextViewer instanceof ITextViewerExtension5) {
253243 ITextViewerExtension5 extension= (ITextViewerExtension5)fCachedTextViewer;
254244 offset= extension.widgetOffset2ModelOffset(widgetOffset);
255 } else
245 } else {
256246 offset= widgetOffset + fCachedTextViewer.getVisibleRegion().getOffset();
257
258 } catch (IllegalArgumentException ex) {
247 }
248 } else {
259249 int lineEndOffset= lineInfo.getOffset() + lineInfo.getLength();
260250
261251 // Convert to widget offset
392382 private StyledText fCachedTextWidget;
393383 /** The columns canvas */
394384 private Canvas fCanvas;
395 /** Cache for the actual scroll position in pixels */
396 private int fScrollPos;
397385 /** The drawable for double buffering */
398386 private Image fBuffer;
399387 /** The internal listener */
400 private InternalListener fInternalListener= new InternalListener();
388 private ITextListener fInternalListener= new InternalListener();
401389 /** The font of this column */
402390 private Font fFont;
403391 /** The indentation cache */
404392 private int[] fIndentation;
405 /** Indicates whether this column reacts on text change events */
406 private boolean fSensitiveToTextChanges= false;
407393 /** The foreground color */
408394 private Color fForeground;
409395 /** The background color */
445431 private WeakReference<Font> fLastFont;
446432 private Font fLastZoomedFont;
447433
434 /**
435 * Redraw the ruler handler called when a line height change.
436 *
437 * @since 3.13
438 */
439 private Consumer<StyledText> lineHeightChangeHandler= (t) -> postRedraw();
448440
449441 /**
450442 * Constructs a new vertical ruler column.
617609 }
618610 }
619611 });
612
613 // track when StyledText is redrawn to check if some line height changed. In this case, the ruler must be redrawn
614 // to draw line number with well height.
615 VisibleLinesTracker.track(fCachedTextViewer, lineHeightChangeHandler);
620616
621617 fCanvas= new Canvas(parentControl, SWT.NO_FOCUS ) {
622618 @Override
658654 fCanvas.addMouseWheelListener(fMouseHandler);
659655
660656 if (fCachedTextViewer != null) {
661
662 fCachedTextViewer.addViewportListener(fInternalListener);
657 VisibleLinesTracker.track(fCachedTextViewer, lineHeightChangeHandler);
663658 fCachedTextViewer.addTextListener(fInternalListener);
659
664660
665661 if (fFont == null) {
666662 if (fCachedTextWidget != null && !fCachedTextWidget.isDisposed())
682678 protected void handleDispose() {
683679
684680 if (fCachedTextViewer != null) {
685 fCachedTextViewer.removeViewportListener(fInternalListener);
686 fCachedTextViewer.removeTextListener(fInternalListener);
681 VisibleLinesTracker.untrack(fCachedTextViewer, lineHeightChangeHandler);
687682 }
688683
689684 if (fBuffer != null) {
712707
713708 if (fBuffer != null) {
714709 Rectangle r= fBuffer.getBounds();
715 if (r.width != size.x || r.height != size.y) {
710 if (IS_MAC_BUG_516293 || r.width != size.x || r.height != size.y) {
716711 fBuffer.dispose();
717712 fBuffer= null;
718713 }
755750 gc.setBackground(getBackground(fCanvas.getDisplay()));
756751 gc.fillRectangle(0, 0, width, height);
757752
758 fScrollPos= fCachedTextWidget.getTopPixel();
759753 doPaint(gc, visibleLines);
760754 } finally {
761755 gc.dispose();
766760 gcImage.dispose();
767761 return imageData;
768762 });
769
763
770764 } else {
771765 if (fBuffer == null)
772766 fBuffer= new Image(fCanvas.getDisplay(), size.x, size.y);
780774 gc.setBackground(getBackground(fCanvas.getDisplay()));
781775 gc.fillRectangle(0, 0, size.x, size.y);
782776
783 fScrollPos= fCachedTextWidget.getTopPixel();
784777 doPaint(gc, visibleLines);
785778 } finally {
786779 gc.dispose();
794787 * This method is not API and it is expected to disappear in Eclipse 4.8.
795788 * Subclasses that want to take advantage of the unsupported workaround for bug 516258
796789 * can re-implement this method and return true.
797 *
790 *
798791 * @return true iff this class supports the workaround for bug 516258
799 *
792 *
800793 * @nooverride This method is not intended to be re-implemented or extended by clients.
801794 * @noreference This method is not intended to be referenced by clients.
802795 * @since 3.12
809802 * This method is not API and it is expected to disappear in Eclipse 4.8.
810803 * Subclasses that want to take advantage of the unsupported workaround for bug 516258
811804 * can override this method and store the given zoom level for later use.
812 *
805 *
813806 * @param zoom the zoom level to use for drawing operations
814 *
807 *
815808 * @nooverride This method is not intended to be re-implemented or extended by clients.
816809 * @noreference This method is not intended to be referenced by clients.
817810 * @since 3.12
819812 protected void internalSetZoom(int zoom) {
820813 // callback for subclasses
821814 }
822
815
823816 /**
824817 * Returns the view port height in lines.
825818 *
248248 gc.setForeground(fColor);
249249
250250 Rectangle bounds= fTextWidget.getTextBounds(offset, offset + length - 1);
251 int height= fTextWidget.getCaret().getSize().y;
251252
252253 // draw box around line segment
253 gc.drawRectangle(bounds.x, bounds.y, bounds.width - 1, bounds.height - 1);
254 gc.drawRectangle(bounds.x, bounds.y + bounds.height - height, bounds.width - 1, height - 1);
254255
255256 // draw box around character area
256257 // int widgetBaseline= fTextWidget.getBaseline();
15011501 if (fHeader.getToolTipText() != null)
15021502 return;
15031503
1504 StringBuffer overview = new StringBuffer();
1504 StringBuilder overview = new StringBuilder();
15051505
15061506 for (int i= fAnnotationsSortedByLayer.size() -1; i >= 0; i--) {
15071507
15271527 if (overview.length() > 0) {
15281528 overview.append("\n"); //$NON-NLS-1$
15291529 }
1530 overview.append(JFaceTextMessages.getFormattedString("OverviewRulerHeader.toolTipTextEntry", new Object[] {annotationTypeLabel, Integer.valueOf(count)})); //$NON-NLS-1$
1530 overview.append(JFaceTextMessages.getFormattedString("OverviewRulerHeader.toolTipTextEntry", annotationTypeLabel, Integer.valueOf(count))); //$NON-NLS-1$
15311531 }
15321532 }
15331533
99 * Tom Eicher (Avaloq Evolution AG) - block selection mode
1010 * Tom Hofmann (Perspectix AG) - bug 297572
1111 * Sergey Prigogin (Google) - bug 441448
12 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Add CodeMining support in SourceViewer - Bug 527515
1213 *******************************************************************************/
1314 package org.eclipse.jface.text.source;
1415
2728
2829 import org.eclipse.jface.internal.text.NonDeletingPositionUpdater;
2930 import org.eclipse.jface.internal.text.StickyHoverManager;
31 import org.eclipse.jface.internal.text.codemining.CodeMiningManager;
3032
3133 import org.eclipse.jface.text.AbstractHoverInformationControlManager;
3234 import org.eclipse.jface.text.BadLocationException;
4850 import org.eclipse.jface.text.Position;
4951 import org.eclipse.jface.text.Region;
5052 import org.eclipse.jface.text.TextViewer;
53 import org.eclipse.jface.text.codemining.ICodeMiningProvider;
5154 import org.eclipse.jface.text.contentassist.IContentAssistant;
5255 import org.eclipse.jface.text.contentassist.IContentAssistantExtension2;
5356 import org.eclipse.jface.text.contentassist.IContentAssistantExtension4;
6366 import org.eclipse.jface.text.quickassist.IQuickAssistAssistant;
6467 import org.eclipse.jface.text.quickassist.IQuickAssistInvocationContext;
6568 import org.eclipse.jface.text.reconciler.IReconciler;
69 import org.eclipse.jface.text.source.inlined.InlinedAnnotationSupport;
6670
6771 /**
6872 * SWT based implementation of
8185 * <p>
8286 * Clients may subclass this class but should expect some breakage by future releases.</p>
8387 */
84 public class SourceViewer extends TextViewer implements ISourceViewer, ISourceViewerExtension, ISourceViewerExtension2, ISourceViewerExtension3, ISourceViewerExtension4 {
88 public class SourceViewer extends TextViewer implements ISourceViewer, ISourceViewerExtension, ISourceViewerExtension2, ISourceViewerExtension3, ISourceViewerExtension4, ISourceViewerExtension5 {
8589
8690
8791 /**
347351
348352 /**
349353 * The overview ruler.
354 *
350355 * @since 2.1
351356 */
352357 private IOverviewRuler fOverviewRuler;
355360 * @since 2.1
356361 */
357362 private boolean fIsOverviewRulerVisible;
358
363 /**
364 * The inlined annotation support used by code mining manager.
365 *
366 * @since 3.13
367 */
368 private InlinedAnnotationSupport fInlinedAnnotationSupport;
369 /**
370 * The text viewer's code mining providers.
371 *
372 * @since 3.13
373 */
374 private ICodeMiningProvider[] fCodeMiningProviders;
375 /**
376 * The text viewer's annotation painter to draw code mining annotations.
377 *
378 * @since 3.13
379 */
380 private AnnotationPainter fAnnotationPainter;
381 /**
382 * The text viewer's code mining manager.
383 *
384 * @since 3.13
385 */
386 private CodeMiningManager fCodeMiningManager;
359387
360388 /**
361389 * Constructs a new source viewer. The vertical ruler is initially visible.
523551 if (prefixes != null && prefixes.length > 0)
524552 setDefaultPrefixes(prefixes, t);
525553 }
554 setCodeMiningProviders(configuration.getCodeMiningProviders(this));
526555
527556 activatePlugins();
528557 }
730759 }
731760
732761 setHyperlinkDetectors(null, SWT.NONE);
762
763 if (hasCodeMiningProviders()) {
764 fCodeMiningManager.uninstall();
765 fCodeMiningManager= null;
766 }
767 setCodeMiningProviders(null);
768 if (fInlinedAnnotationSupport != null) {
769 fInlinedAnnotationSupport.uninstall();
770 fInlinedAnnotationSupport= null;
771 }
733772 }
734773
735774 @Override
12221261 return fVerticalRulerHoveringController.getCurrentAnnotationHover();
12231262 }
12241263
1264 @Override
1265 public void setCodeMiningProviders(ICodeMiningProvider[] codeMiningProviders) {
1266 if (fCodeMiningProviders != null) {
1267 for (ICodeMiningProvider contentMiningProvider : fCodeMiningProviders) {
1268 contentMiningProvider.dispose();
1269 }
1270 }
1271 boolean enable= codeMiningProviders != null && codeMiningProviders.length > 0;
1272 fCodeMiningProviders= codeMiningProviders;
1273 if (enable) {
1274 if (fCodeMiningManager != null) {
1275 fCodeMiningManager.setCodeMiningProviders(fCodeMiningProviders);
1276 }
1277 ensureCodeMiningManagerInstalled();
1278 } else {
1279 if (fCodeMiningManager != null) {
1280 fCodeMiningManager.uninstall();
1281 }
1282 fCodeMiningManager= null;
1283 }
1284 }
1285
1286 /**
1287 * Ensures that the code mining manager has been
1288 * installed if a content mining provider is available.
1289 *
1290 * @since 3.13
1291 */
1292 private void ensureCodeMiningManagerInstalled() {
1293 if (fCodeMiningProviders != null && fCodeMiningProviders.length > 0 && fAnnotationPainter != null) {
1294 if (fInlinedAnnotationSupport == null) {
1295 fInlinedAnnotationSupport= new InlinedAnnotationSupport();
1296 fInlinedAnnotationSupport.install(this, fAnnotationPainter);
1297 }
1298 fCodeMiningManager= new CodeMiningManager(this, fInlinedAnnotationSupport, fCodeMiningProviders);
1299 // now trigger an update
1300 updateCodeMinings();
1301 }
1302 }
1303
1304 @Override
1305 public boolean hasCodeMiningProviders() {
1306 return fCodeMiningManager != null; // manager always has at least one provider
1307 }
1308
1309 @Override
1310 public void updateCodeMinings() {
1311 if (hasCodeMiningProviders()) {
1312 fCodeMiningManager.run();
1313 }
1314 }
1315
1316 @Override
1317 public void setCodeMiningAnnotationPainter(AnnotationPainter painter) {
1318 fAnnotationPainter= painter;
1319 ensureCodeMiningManagerInstalled();
1320 }
1321
12251322 }
00 /*******************************************************************************
1 * Copyright (c) 2000, 2008 IBM Corporation and others.
1 * Copyright (c) 2000, 2017 IBM Corporation and others.
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
66 *
77 * Contributors:
88 * IBM Corporation - initial API and implementation
9 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Add CodeMining support in SourceViewer - Bug 527515
910 *******************************************************************************/
1011 package org.eclipse.jface.text.source;
1112
2829 import org.eclipse.jface.text.ITextViewerExtension2;
2930 import org.eclipse.jface.text.IUndoManager;
3031 import org.eclipse.jface.text.TextViewerUndoManager;
32 import org.eclipse.jface.text.codemining.ICodeMiningProvider;
3133 import org.eclipse.jface.text.contentassist.IContentAssistant;
3234 import org.eclipse.jface.text.formatter.IContentFormatter;
3335 import org.eclipse.jface.text.hyperlink.DefaultHyperlinkPresenter;
416418 public int getHyperlinkStateMask(ISourceViewer sourceViewer) {
417419 return SWT.MOD1;
418420 }
421
422 /**
423 * Returns the code mining providers which be used to draw code minings in the given source
424 * viewer. This implementation always returns <code>null</code>.
425 *
426 * @param sourceViewer the source viewer to be configured by this configuration
427 * @return an array with code mining providers or <code>null</code> if no code mining support
428 * should be installed
429 * @since 3.13
430 */
431 public ICodeMiningProvider[] getCodeMiningProviders(ISourceViewer sourceViewer) {
432 return null;
433 }
419434 }
0 /**
1 * Copyright (c) 2018 Angelo ZERR.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Angelo Zerr <angelo.zerr@gmail.com> - Bug 527720 - [CodeMining] Line number in vertical ruler can be not synchronized with line header annotation
9 */
10 package org.eclipse.jface.text.source;
11
12 import java.util.ArrayList;
13 import java.util.Collection;
14 import java.util.function.Consumer;
15
16 import org.eclipse.swt.custom.StyledText;
17 import org.eclipse.swt.events.PaintEvent;
18 import org.eclipse.swt.events.PaintListener;
19
20 import org.eclipse.jface.text.ITextViewer;
21 import org.eclipse.jface.text.JFaceTextUtil;
22
23 /**
24 * Class to track line height change of visible lines of a given {@link StyledText}.
25 *
26 */
27 class VisibleLinesTracker implements PaintListener {
28
29 private static final String DATA_KEY= VisibleLinesTracker.class.getName();
30
31 /**
32 * The viewer to track.
33 */
34 private final ITextViewer viewer;
35
36 /**
37 * The previous bottom line index.
38 */
39 private int oldBottom= -1;
40
41 /**
42 * The previous bottom line pixel.
43 */
44 private int oldBottomPixel;
45
46 /**
47 *
48 * List of handler to call when a visible line height change.
49 */
50 private final Collection<Consumer<StyledText>> handlers;
51
52 /**
53 * Constructor to track line height change of visible lines of the {@link StyledText} of the
54 * given viewer.
55 *
56 * @param viewer the viewer to track
57 */
58 private VisibleLinesTracker(ITextViewer viewer) {
59 this.viewer= viewer;
60 this.handlers= new ArrayList<>();
61 }
62
63 @Override
64 public void paintControl(PaintEvent e) {
65 StyledText textWidget= viewer.getTextWidget();
66 // track if bottom line index or bottom line pixel changed.
67 if (oldBottom == -1) {
68 oldBottom= JFaceTextUtil.getPartialBottomIndex(viewer);
69 oldBottomPixel= JFaceTextUtil.getLinePixel(textWidget, oldBottom);
70 return;
71 }
72 int newBottom= JFaceTextUtil.getPartialBottomIndex(viewer);
73 if (newBottom != oldBottom) {
74 oldBottom= newBottom;
75 oldBottomPixel= JFaceTextUtil.getLinePixel(textWidget, oldBottom);
76 handlers.forEach(handler -> handler.accept(textWidget));
77 return;
78 }
79 int newBottomPixel= JFaceTextUtil.getLinePixel(textWidget, newBottom);
80 if (newBottomPixel != oldBottomPixel) {
81 oldBottomPixel= newBottomPixel;
82 handlers.forEach(handler -> handler.accept(textWidget));
83 return;
84 }
85 }
86
87 /**
88 * Track the line height change of the {@link StyledText} of the given handler an call the given
89 * handler.
90 *
91 * @param viewer the viewer to track
92 * @param handler the handler to call when line height change.
93 */
94 static void track(ITextViewer viewer, Consumer<StyledText> handler) {
95 StyledText textWidget= viewer != null ? viewer.getTextWidget() : null;
96 if (textWidget == null) {
97 return;
98 }
99 VisibleLinesTracker tracker= (VisibleLinesTracker) textWidget.getData(DATA_KEY);
100 if (tracker == null) {
101 tracker= new VisibleLinesTracker(viewer);
102 textWidget.setData(DATA_KEY, tracker);
103 }
104 tracker.addHandler(handler);
105 }
106
107 /**
108 * Untrack the line height change of the {@link StyledText} of the given handler an call the
109 * given handler.
110 *
111 * @param viewer the viewer to track
112 * @param handler the handler to call when line height change.
113 */
114 static void untrack(ITextViewer viewer, Consumer<StyledText> handler) {
115 StyledText textWidget= viewer != null ? viewer.getTextWidget() : null;
116 if (textWidget == null) {
117 return;
118 }
119 VisibleLinesTracker tracker= (VisibleLinesTracker) textWidget.getData(DATA_KEY);
120 if (tracker != null) {
121 tracker.removeHandler(handler);
122 }
123 }
124
125 /**
126 * Add the given handler.
127 *
128 * @param handler the handler to call when a visible line height change.
129 */
130 private void addHandler(Consumer<StyledText> handler) {
131 if (handlers.isEmpty()) {
132 viewer.getTextWidget().addPaintListener(this);
133 }
134 handlers.add(handler);
135 }
136
137 /**
138 * Remove the given handler.
139 *
140 * @param handler the handler to call when a visible line height change.
141 */
142 private void removeHandler(Consumer<StyledText> handler) {
143 handlers.remove(handler);
144 if (handlers.isEmpty()) {
145 viewer.getTextWidget().removePaintListener(this);
146 }
147 }
148 }
0 /**
1 * Copyright (c) 2017, 2018 Angelo ZERR.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Provide inline annotations support - Bug 527675
9 */
10 package org.eclipse.jface.text.source.inlined;
11
12 import java.util.function.Consumer;
13
14 import org.eclipse.swt.SWT;
15 import org.eclipse.swt.custom.StyledText;
16 import org.eclipse.swt.events.MouseEvent;
17 import org.eclipse.swt.graphics.Color;
18 import org.eclipse.swt.graphics.Font;
19 import org.eclipse.swt.graphics.GC;
20
21 import org.eclipse.jface.text.ITextViewerExtension5;
22 import org.eclipse.jface.text.Position;
23 import org.eclipse.jface.text.source.Annotation;
24 import org.eclipse.jface.text.source.ISourceViewer;
25
26 /**
27 * Abstract class for inlined annotation.
28 *
29 * @since 3.13
30 * @noimplement This interface is not intended to be implemented by clients.
31 */
32 public abstract class AbstractInlinedAnnotation extends Annotation {
33
34 /**
35 * The type of inlined annotations.
36 */
37 public static final String TYPE= "org.eclipse.jface.text.source.inlined"; //$NON-NLS-1$
38
39 /**
40 * The position where the annotation must be drawn.
41 */
42 private final Position position;
43
44 /**
45 * The {@link ISourceViewer} where the annotation must be drawn.
46 */
47 private ISourceViewer fViewer;
48
49 /**
50 * The {@link InlinedAnnotationSupport} which manages the annotation.
51 */
52 private InlinedAnnotationSupport support;
53
54 int fX;
55
56 int fY;
57
58 /**
59 * Inlined annotation constructor.
60 *
61 * @param position the position where the annotation must be drawn.
62 * @param viewer the {@link ISourceViewer} where the annotation must be drawn.
63 */
64 protected AbstractInlinedAnnotation(Position position, ISourceViewer viewer) {
65 super(TYPE, false, ""); //$NON-NLS-1$
66 this.position= position;
67 fViewer= viewer;
68 }
69
70 /**
71 * Returns the position where the annotation must be drawn.
72 *
73 * @return the position where the annotation must be drawn.
74 */
75 public Position getPosition() {
76 return position;
77 }
78
79 /**
80 * Returns the {@link StyledText} widget where the annotation must be drawn.
81 *
82 * @return the {@link StyledText} widget where the annotation must be drawn.
83 */
84 public StyledText getTextWidget() {
85 return fViewer.getTextWidget();
86 }
87
88 /**
89 * Returns the {@link ISourceViewer} where the annotation must be drawn.
90 *
91 * @return the {@link ISourceViewer} where the annotation must be drawn.
92 */
93 public ISourceViewer getViewer() {
94 return fViewer;
95 }
96
97 /**
98 * Redraw the inlined annotation.
99 */
100 public void redraw() {
101 StyledText text= getTextWidget();
102 InlinedAnnotationSupport.runInUIThread(text, (t) -> {
103 Position pos= getPosition();
104 int offset= pos.getOffset();
105 ISourceViewer viewer= getViewer();
106 if (viewer instanceof ITextViewerExtension5) {
107 // adjust offset according folded content
108 offset= ((ITextViewerExtension5) viewer).modelOffset2WidgetOffset(offset);
109 }
110 InlinedAnnotationDrawingStrategy.draw(this, null, t, offset, pos.getLength(), null);
111 });
112 }
113
114 /**
115 * Draw the inlined annotation. By default it draw the text of the annotation with gray color.
116 * User can override this method to draw anything.
117 *
118 * @param gc the graphics context
119 * @param textWidget the text widget to draw on
120 * @param offset the offset of the line
121 * @param length the length of the line
122 * @param color the color of the line
123 * @param x the x position of the annotation
124 * @param y the y position of the annotation
125 */
126 public void draw(GC gc, StyledText textWidget, int offset, int length, Color color, int x, int y) {
127 gc.setForeground(color);
128 gc.setBackground(textWidget.getBackground());
129 gc.drawString(getText(), x, y, true);
130 }
131
132 /**
133 * Called when mouse over the inlined annotation.
134 *
135 * @param e the mouse event
136 */
137 public void onMouseHover(MouseEvent e) {
138 StyledText styledText= (StyledText) e.widget;
139 styledText.setCursor(styledText.getDisplay().getSystemCursor(SWT.CURSOR_HAND));
140 }
141
142 /**
143 * Called when mouse out the inlined annotation.
144 *
145 * @param e the mouse event
146 */
147 public void onMouseOut(MouseEvent e) {
148 StyledText styledText= (StyledText) e.widget;
149 styledText.setCursor(null);
150 }
151
152 public Consumer<MouseEvent> getAction(MouseEvent e) {
153 return null;
154 }
155
156 /**
157 * Set the inlined annotation support which manages this annotation.
158 *
159 * @param support the inlined annotation support which manages this annotation.
160 */
161 void setSupport(InlinedAnnotationSupport support) {
162 this.support= support;
163 }
164
165 /**
166 * Return whether the annotation is in visible lines.
167 *
168 * @return <code>true</code> if the annotation is in visible lines and <code>false</code>
169 * otherwise.
170 */
171 protected boolean isInVisibleLines() {
172 return support.isInVisibleLines(getPosition().getOffset());
173 }
174
175 /**
176 * Return whether the given offset is in visible lines.
177 *
178 * @param offset the offset
179 * @return <code>true</code> if the given offset is in visible lines and <code>false</code>
180 * otherwise.
181 */
182 protected boolean isInVisibleLines(int offset) {
183 return support.isInVisibleLines(offset);
184 }
185
186 /**
187 * Returns the font according the specified <code>style</code> that the receiver will use to
188 * paint textual information.
189 *
190 * @param style the style of Font widget to get.
191 * @return the receiver's font according the specified <code>style</code>
192 *
193 */
194 Font getFont(int style) {
195 return support.getFont(style);
196 }
197
198 /**
199 * Set the location where the annotation is drawn.
200 *
201 * @param x the x coordinate where draw of annotation starts.
202 * @param y the y coordinate where draw of annotation starts.
203 */
204 void setLocation(int x, int y) {
205 this.fX= x;
206 this.fY= y;
207 }
208
209 /**
210 * Returns <code>true</code> if the point specified by the arguments is inside the annotation
211 * specified by the receiver, and <code>false</code> otherwise.
212 *
213 * @param x the x coordinate of the point to test for containment
214 * @param y the y coordinate of the point to test for containment
215 * @return <code>true</code> if the annotation contains the point and <code>false</code>
216 * otherwise
217 */
218 boolean contains(int x, int y) {
219 StyledText styledText= getTextWidget();
220 GC gc= null;
221 try {
222 gc= new GC(styledText);
223 return x >= fX && y >= fY && y <= fY + styledText.getLineHeight(position.getOffset()) && x <= fX + gc.stringExtent(getText()).x + 2 * gc.getFontMetrics().getAverageCharacterWidth();
224 } finally {
225 if (gc != null) {
226 gc.dispose();
227 }
228 }
229 }
230 }
0 /**
1 * Copyright (c) 2017 Angelo ZERR.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Provide inline annotations support - Bug 527675
9 */
10 package org.eclipse.jface.text.source.inlined;
11
12 import org.eclipse.swt.custom.StyleRange;
13 import org.eclipse.swt.custom.StyledText;
14 import org.eclipse.swt.graphics.Color;
15 import org.eclipse.swt.graphics.GC;
16 import org.eclipse.swt.graphics.GlyphMetrics;
17 import org.eclipse.swt.graphics.Point;
18 import org.eclipse.swt.graphics.Rectangle;
19
20 import org.eclipse.jface.text.Position;
21 import org.eclipse.jface.text.source.Annotation;
22 import org.eclipse.jface.text.source.AnnotationPainter.IDrawingStrategy;
23
24 /**
25 * {@link IDrawingStrategy} implementation to render {@link AbstractInlinedAnnotation}.
26 *
27 * @since 3.13
28 */
29 class InlinedAnnotationDrawingStrategy implements IDrawingStrategy {
30
31 @Override
32 public void draw(Annotation annotation, GC gc, StyledText textWidget, int offset, int length, Color color) {
33 if (!(annotation instanceof AbstractInlinedAnnotation)) {
34 return;
35 }
36 if (!((AbstractInlinedAnnotation) annotation).isInVisibleLines()) {
37 // The annotation is not in visible lines, don't draw it.
38 return;
39 }
40 InlinedAnnotationDrawingStrategy.draw((AbstractInlinedAnnotation) annotation, gc, textWidget, offset, length,
41 color);
42 }
43
44 /**
45 * Draw the inlined annotation.
46 *
47 * @param annotation the annotation to be drawn
48 * @param gc the graphics context, <code>null</code> when in clearing mode
49 * @param textWidget the text widget to draw on
50 * @param offset the offset of the line
51 * @param length the length of the line
52 * @param color the color of the line
53 */
54 public static void draw(AbstractInlinedAnnotation annotation, GC gc, StyledText textWidget, int offset, int length,
55 Color color) {
56 if (annotation instanceof LineHeaderAnnotation) {
57 draw((LineHeaderAnnotation) annotation, gc, textWidget, offset, length, color);
58 } else {
59 draw((LineContentAnnotation) annotation, gc, textWidget, offset, length, color);
60 }
61 }
62
63 /**
64 * Draw the line header annotation in the line spacing of the previous line.
65 *
66 * @param annotation the annotation to be drawn
67 * @param gc the graphics context, <code>null</code> when in clearing mode
68 * @param textWidget the text widget to draw on
69 * @param offset the offset of the line
70 * @param length the length of the line
71 * @param color the color of the line
72 */
73 private static void draw(LineHeaderAnnotation annotation, GC gc, StyledText textWidget, int offset, int length,
74 Color color) {
75 StyleRange style= null;
76 try {
77 style= textWidget.getStyleRangeAtOffset(offset);
78 } catch (Exception e) {
79 return;
80 }
81 if (annotation.isMarkedDeleted() || annotation.getPosition().isDeleted()) {
82 // When annotation is deleted, update metrics to null to remove extra spaces of the line header annotation.
83 if (style != null) {
84 style.metrics= null;
85 textWidget.setStyleRange(style);
86 }
87 return;
88 }
89 if (gc != null) {
90 // Compute the location of the annotation
91 Rectangle bounds= textWidget.getTextBounds(offset, offset);
92 int x= bounds.x;
93 int y= bounds.y;
94
95 // Colorize line spacing area with the background of StyledText to avoid having highlighted line color
96 gc.setBackground(textWidget.getBackground());
97 Rectangle client= textWidget.getClientArea();
98 gc.fillRectangle(0, y, client.width, annotation.getHeight());
99
100 // Draw the line header annotation
101 annotation.setLocation(x, y);
102 annotation.draw(gc, textWidget, offset, length, color, x, y);
103 int height= annotation.getHeight();
104 if (height != 0) {
105 // The inline annotation replaces one character by taking a place width
106 // GlyphMetrics
107 // Here we need to redraw this first character because GlyphMetrics clip this
108 // character.
109
110 // FIXME: remove this code when we need not redraw the character (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=531769)
111 // START TO REMOVE
112 String s= textWidget.getText(offset, offset);
113 Point charBounds= gc.stringExtent(s);
114 int charWidth= charBounds.x;
115 int charHeight= charBounds.y;
116 annotation.setRedrawnCharacterWidth(charWidth);
117 annotation.setRedrawnCharacterHeight(charHeight);
118 // END TO REMOVE
119
120 StyleRange newStyle= updateStyle(annotation, style);
121 if (newStyle != null) {
122 textWidget.setStyleRange(newStyle);
123 return;
124 }
125
126 // FIXME: remove this code when we need not redraw the character (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=531769)
127 // START TO REMOVE
128 int charX= x + bounds.width - charWidth;
129 int charY= y + bounds.height - textWidget.getLineHeight();
130 if (style != null) {
131 if (style.background != null) {
132 gc.setBackground(style.background);
133 gc.fillRectangle(charX, charY, charWidth + 1, bounds.height);
134 }
135 if (style.foreground != null) {
136 gc.setForeground(style.foreground);
137 } else {
138 gc.setForeground(textWidget.getForeground());
139 }
140 gc.setFont(annotation.getFont(style.fontStyle));
141 }
142 gc.drawString(s, charX, charY, true);
143 // END TO REMOVE
144 } else if (style != null && style.metrics != null && style.metrics.ascent != 0) {
145 // line header annotation had an height, reset it
146 style.metrics= null;
147 textWidget.setStyleRange(style);
148 }
149 } else {
150 if (style != null && style.metrics != null) {
151 // Here GlyphMetrics ascent is done, the redraw of the full line width is done to avoid annotation clipping
152 Rectangle bounds= textWidget.getTextBounds(offset, offset);
153 Rectangle client= textWidget.getClientArea();
154 textWidget.redraw(0, bounds.y, client.width, bounds.height, false);
155 } else {
156 textWidget.redrawRange(offset, length, true);
157 }
158 }
159 }
160
161 /**
162 * Returns the style to apply with GlyphMetrics ascent only if needed.
163 *
164 * @param annotation the line header annotation
165 * @param style the current style and null otherwise.
166 * @return the style to apply with GlyphMetrics ascent only if needed.
167 */
168 static StyleRange updateStyle(LineHeaderAnnotation annotation, StyleRange style) {
169 int width= annotation.getRedrawnCharacterWidth();
170 if (width == 0) {
171 // Update GlyphMetrics only when mining was already drawn
172 return null;
173 }
174 int height= annotation.getHeight();
175 if (height == 0) {
176 return null;
177 }
178 int fullHeight= height + annotation.getRedrawnCharacterHeight();
179 if (style == null) {
180 style= new StyleRange();
181 Position position= annotation.getPosition();
182 style.start= position.getOffset();
183 style.length= 1;
184 }
185 GlyphMetrics metrics= style.metrics;
186 if (!annotation.isMarkedDeleted()) {
187 if (metrics == null) {
188 metrics= new GlyphMetrics(fullHeight, 0, width);
189 } else {
190 if (metrics.ascent == fullHeight) {
191 return null;
192 }
193 /**
194 * We must create a new GlyphMetrics instance because comparison with similarTo used
195 * later in StyledText#setStyleRange will compare the same (modified) and won't
196 * realize an update happened.
197 */
198 metrics= new GlyphMetrics(fullHeight, 0, width);
199 }
200 } else {
201 metrics= null;
202 }
203 style.metrics= metrics;
204 return style;
205 }
206
207 /**
208 * Draw the line content annotation inside line in the empty area computed by
209 * {@link GlyphMetrics}.
210 *
211 * @param annotation the annotation to be drawn
212 * @param gc the graphics context, <code>null</code> when in clearing mode
213 * @param textWidget the text widget to draw on
214 * @param offset the offset of the line
215 * @param length the length of the line
216 * @param color the color of the line
217 */
218 private static void draw(LineContentAnnotation annotation, GC gc, StyledText textWidget, int offset, int length,
219 Color color) {
220 StyleRange style= null;
221 try {
222 style= textWidget.getStyleRangeAtOffset(offset);
223 } catch (Exception e) {
224 return;
225 }
226 if (annotation.isMarkedDeleted() || annotation.getPosition().isDeleted()) {
227 // When annotation is deleted, update metrics to null to remove extra spaces of the line content annotation.
228 if (style != null) {
229 style.metrics= null;
230 textWidget.setStyleRange(style);
231 }
232 return;
233 }
234 if (gc != null) {
235 // Compute the location of the annotation
236 Rectangle bounds= textWidget.getTextBounds(offset, offset);
237 int x= bounds.x;
238 int y= bounds.y;
239
240 // Get size of the character where GlyphMetrics width is added
241 String s= textWidget.getText(offset, offset);
242 Point charBounds= gc.stringExtent(s);
243 int charWidth= charBounds.x;
244 int charHeight= charBounds.y;
245
246 // When line text has line header annotation, there is a space on the top, adjust the y by using char height
247 y+= bounds.height - charHeight;
248
249 // Draw the line content annotation
250 annotation.setLocation(x, y);
251 annotation.draw(gc, textWidget, offset, length, color, x, y);
252 int width= annotation.getWidth();
253 if (width != 0) {
254 // FIXME: remove this code when we need not redraw the character (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=531769)
255 // START TO REMOVE
256 annotation.setRedrawnCharacterWidth(charWidth);
257 // END TO REMOVE
258
259 // Annotation takes place, add GlyphMetrics width to the style
260 StyleRange newStyle= updateStyle(annotation, style);
261 if (newStyle != null) {
262 textWidget.setStyleRange(newStyle);
263 return;
264 }
265
266 // FIXME: remove this code when we need not redraw the character (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=531769)
267 // START TO REMOVE
268 // The inline annotation replaces one character by taking a place width
269 // GlyphMetrics
270 // Here we need to redraw this first character (if it's not a line delimiter) because GlyphMetrics clip this
271 // character.
272 if (!("\r".equals(s) || "\n".equals(s))) { //$NON-NLS-1$ //$NON-NLS-2$
273 int charX= x + bounds.width - charWidth;
274 int charY= y;
275 if (style != null) {
276 if (style.background != null) {
277 gc.setBackground(style.background);
278 gc.fillRectangle(charX, charY, charWidth + 1, bounds.height);
279 }
280 if (style.foreground != null) {
281 gc.setForeground(style.foreground);
282 } else {
283 gc.setForeground(textWidget.getForeground());
284 }
285 gc.setFont(annotation.getFont(style.fontStyle));
286 }
287 gc.drawString(s, charX, charY, true);
288 }
289 // END TO REMOVE
290 } else if (style != null && style.metrics != null && style.metrics.width != 0) {
291 // line content annotation had an , reset it
292 style.metrics= null;
293 textWidget.setStyleRange(style);
294 }
295 } else {
296 textWidget.redrawRange(offset, length, true);
297 }
298 }
299
300 /**
301 * Returns the style to apply with GlyphMetrics width only if needed.
302 *
303 * @param annotation the line content annotation
304 * @param style the current style and null otherwise.
305 * @return the style to apply with GlyphMetrics width only if needed.
306 */
307 static StyleRange updateStyle(LineContentAnnotation annotation, StyleRange style) {
308 int width= annotation.getWidth();
309 if (width == 0) {
310 return null;
311 }
312 int fullWidth= width + annotation.getRedrawnCharacterWidth();
313 if (style == null) {
314 style= new StyleRange();
315 Position position= annotation.getPosition();
316 style.start= position.getOffset();
317 style.length= 1;
318 }
319 GlyphMetrics metrics= style.metrics;
320 if (!annotation.isMarkedDeleted()) {
321 if (metrics == null) {
322 metrics= new GlyphMetrics(0, 0, fullWidth);
323 } else {
324 if (metrics.width == fullWidth) {
325 return null;
326 }
327 /**
328 * We must create a new GlyphMetrics instance because comparison with similarTo used
329 * later in StyledText#setStyleRange will compare the same (modified) and won't
330 * realize an update happened.
331 */
332 metrics= new GlyphMetrics(0, 0, fullWidth);
333 }
334 } else {
335 metrics= null;
336 }
337 style.metrics= metrics;
338 return style;
339 }
340 }
0 /**
1 * Copyright (c) 2017, 2018 Angelo ZERR.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Provide inline annotations support - Bug 527675
9 */
10 package org.eclipse.jface.text.source.inlined;
11
12 import java.util.ArrayList;
13 import java.util.Collections;
14 import java.util.HashMap;
15 import java.util.Iterator;
16 import java.util.List;
17 import java.util.Map;
18 import java.util.Map.Entry;
19 import java.util.Set;
20 import java.util.function.Consumer;
21
22 import org.eclipse.swt.SWT;
23 import org.eclipse.swt.custom.StyleRange;
24 import org.eclipse.swt.custom.StyledText;
25 import org.eclipse.swt.events.ControlEvent;
26 import org.eclipse.swt.events.ControlListener;
27 import org.eclipse.swt.events.MouseEvent;
28 import org.eclipse.swt.events.MouseListener;
29 import org.eclipse.swt.events.MouseMoveListener;
30 import org.eclipse.swt.graphics.Color;
31 import org.eclipse.swt.graphics.Device;
32 import org.eclipse.swt.graphics.Font;
33 import org.eclipse.swt.graphics.FontData;
34 import org.eclipse.swt.graphics.GlyphMetrics;
35 import org.eclipse.swt.widgets.Display;
36
37 import org.eclipse.core.runtime.Assert;
38
39 import org.eclipse.jface.text.BadLocationException;
40 import org.eclipse.jface.text.DocumentEvent;
41 import org.eclipse.jface.text.IDocument;
42 import org.eclipse.jface.text.IDocumentListener;
43 import org.eclipse.jface.text.IRegion;
44 import org.eclipse.jface.text.ISynchronizable;
45 import org.eclipse.jface.text.ITextPresentationListener;
46 import org.eclipse.jface.text.ITextViewerExtension4;
47 import org.eclipse.jface.text.IViewportListener;
48 import org.eclipse.jface.text.JFaceTextUtil;
49 import org.eclipse.jface.text.Position;
50 import org.eclipse.jface.text.TextPresentation;
51 import org.eclipse.jface.text.source.Annotation;
52 import org.eclipse.jface.text.source.AnnotationPainter;
53 import org.eclipse.jface.text.source.AnnotationPainter.IDrawingStrategy;
54 import org.eclipse.jface.text.source.IAnnotationModel;
55 import org.eclipse.jface.text.source.IAnnotationModelExtension;
56 import org.eclipse.jface.text.source.IAnnotationModelExtension2;
57 import org.eclipse.jface.text.source.ISourceViewer;
58
59 /**
60 * Support to draw inlined annotations:
61 *
62 * <ul>
63 * <li>line header annotation with {@link LineHeaderAnnotation}.</li>
64 * <li>line content annotation with {@link LineContentAnnotation}.</li>
65 * </ul>
66 *
67 * @since 3.13
68 */
69 public class InlinedAnnotationSupport {
70
71 /**
72 * The annotation inlined strategy singleton.
73 */
74 private static final IDrawingStrategy INLINED_STRATEGY= new InlinedAnnotationDrawingStrategy();
75
76 /**
77 * The annotation inlined strategy ID.
78 */
79 private static final String INLINED_STRATEGY_ID= "inlined"; //$NON-NLS-1$
80
81 /**
82 * The StyledText font normal, bold, italic and bold itlaic both.
83 */
84 private Font regularFont, boldFont, italicFont, boldItalicFont;
85
86 /**
87 * Listener used to update {@link GlyphMetrics} width style for {@link LineContentAnnotation}.
88 */
89 private ITextPresentationListener updateStylesWidth;
90
91 /**
92 * Class to update {@link GlyphMetrics} width style for {@link LineContentAnnotation}.
93 *
94 */
95 private class UpdateStylesWidth implements ITextPresentationListener {
96
97 @Override
98 public void applyTextPresentation(TextPresentation textPresentation) {
99 IAnnotationModel annotationModel= fViewer.getAnnotationModel();
100 IRegion region= textPresentation.getExtent();
101 ((IAnnotationModelExtension2) annotationModel)
102 .getAnnotationIterator(region.getOffset(), region.getLength(), true, true)
103 .forEachRemaining(annotation -> {
104 if (annotation instanceof LineContentAnnotation) {
105 LineContentAnnotation ann= (LineContentAnnotation) annotation;
106 StyleRange style= InlinedAnnotationDrawingStrategy.updateStyle(ann, null);
107 if (style != null) {
108 textPresentation.mergeStyleRange(style);
109 }
110 } else if (annotation instanceof LineHeaderAnnotation) {
111 LineHeaderAnnotation ann= (LineHeaderAnnotation) annotation;
112 StyleRange style= InlinedAnnotationDrawingStrategy.updateStyle(ann, null);
113 if (style != null) {
114 textPresentation.mergeStyleRange(style);
115 }
116 }
117 });
118 }
119 }
120
121 /**
122 * Tracker of start/end offset of visible lines.
123 */
124 private VisibleLines visibleLines;
125
126 /**
127 * Class to track start/end offset of visible lines.
128 *
129 */
130 private class VisibleLines implements IViewportListener, IDocumentListener, ControlListener {
131
132 private int startOffset;
133
134 private Integer endOffset;
135
136 public VisibleLines() {
137 install();
138 fViewer.getTextWidget().getDisplay().asyncExec(() -> {
139 compute();
140 });
141 }
142
143 @Override
144 public void viewportChanged(int verticalOffset) {
145 compute();
146 }
147
148 @Override
149 public void documentAboutToBeChanged(DocumentEvent event) {
150 endOffset= null;
151 }
152
153 @Override
154 public void documentChanged(DocumentEvent event) {
155 // Do nothing
156 }
157
158 @Override
159 public void controlMoved(ControlEvent e) {
160 // Do nothing
161 }
162
163 @Override
164 public void controlResized(ControlEvent e) {
165 compute();
166 }
167
168 @SuppressWarnings("boxing")
169 private void compute() {
170 startOffset= getInclusiveTopIndexStartOffset();
171 endOffset= getExclusiveBottomIndexEndOffset();
172 }
173
174 /**
175 * Returns the document offset of the upper left corner of the source viewer's view port,
176 * possibly including partially visible lines.
177 *
178 * @return the document offset if the upper left corner of the view port
179 */
180 private int getInclusiveTopIndexStartOffset() {
181 if (fViewer != null && fViewer.getTextWidget() != null && !fViewer.getTextWidget().isDisposed()) {
182 int top= JFaceTextUtil.getPartialTopIndex(fViewer);
183 try {
184 IDocument document= fViewer.getDocument();
185 return document.getLineOffset(top);
186 } catch (BadLocationException x) {
187 // Do nothing
188 }
189 }
190 return -1;
191 }
192
193 /**
194 * Returns the first invisible document offset of the lower right corner of the source
195 * viewer's view port, possibly including partially visible lines.
196 *
197 * @return the first invisible document offset of the lower right corner of the view port
198 */
199 private int getExclusiveBottomIndexEndOffset() {
200 if (fViewer != null && fViewer.getTextWidget() != null && !fViewer.getTextWidget().isDisposed()) {
201 int bottom= JFaceTextUtil.getPartialBottomIndex(fViewer);
202 try {
203 IDocument document= fViewer.getDocument();
204 if (bottom >= document.getNumberOfLines()) {
205 bottom= document.getNumberOfLines() - 1;
206 }
207 return document.getLineOffset(bottom) + document.getLineLength(bottom);
208 } catch (BadLocationException x) {
209 // Do nothing
210 }
211 }
212 return -1;
213 }
214
215 /**
216 * Return whether the given offset is in visible lines.
217 *
218 * @param offset the offset
219 * @return <code>true</code> if the given offset is in visible lines and <code>false</code>
220 * otherwise.
221 */
222 @SuppressWarnings("boxing")
223 boolean isInVisibleLines(int offset) {
224 if (endOffset == null) {
225 Display display= fViewer.getTextWidget().getDisplay();
226 if (display.getThread() == Thread.currentThread()) {
227 endOffset= getExclusiveBottomIndexEndOffset();
228 } else {
229 display.syncExec(() -> endOffset= getExclusiveBottomIndexEndOffset());
230 }
231 }
232 return offset >= startOffset && offset <= endOffset;
233 }
234
235 /**
236 * Uninstall visible lines
237 */
238 void uninstall() {
239 if (fViewer != null) {
240 fViewer.removeViewportListener(this);
241 if (fViewer.getDocument() != null) {
242 fViewer.getDocument().removeDocumentListener(this);
243 }
244 if (fViewer.getTextWidget() != null) {
245 fViewer.getTextWidget().removeControlListener(this);
246 }
247 }
248 }
249
250 void install() {
251 fViewer.addViewportListener(this);
252 fViewer.getDocument().addDocumentListener(this);
253 fViewer.getTextWidget().addControlListener(this);
254 }
255 }
256
257 private class MouseTracker implements MouseMoveListener, MouseListener {
258
259 private AbstractInlinedAnnotation fAnnotation;
260
261 private Consumer<MouseEvent> fAction;
262
263 private void update(MouseEvent e) {
264 fAnnotation= null;
265 fAction= null;
266 AbstractInlinedAnnotation annotation= getInlinedAnnotationAtPoint(fViewer, e.x, e.y);
267 if (annotation != null) {
268 Consumer<MouseEvent> action= annotation.getAction(e);
269 if (action != null) {
270 fAnnotation= annotation;
271 fAction= action;
272 }
273 }
274 }
275
276 @Override
277 public void mouseMove(MouseEvent e) {
278 AbstractInlinedAnnotation oldAnnotation= fAnnotation;
279 update(e);
280 if (oldAnnotation != null) {
281 if (oldAnnotation.equals(fAnnotation)) {
282 // Same annotations which was hovered, do nothing.
283 return;
284 } else {
285 oldAnnotation.onMouseOut(e);
286 }
287 }
288 if (fAnnotation != null) {
289 fAnnotation.onMouseHover(e);
290 }
291 }
292
293 @Override
294 public void mouseDoubleClick(MouseEvent e) {
295 // Do nothing
296 }
297
298 @Override
299 public void mouseDown(MouseEvent e) {
300 // Do nothing
301 }
302
303 @Override
304 public void mouseUp(MouseEvent e) {
305 if (e.button != 1) {
306 return;
307 }
308 if (fAction != null) {
309 fAction.accept(e);
310 }
311 }
312 }
313
314 /**
315 * The source viewer
316 */
317 private ISourceViewer fViewer;
318
319 /**
320 * The annotation painter to use to draw the inlined annotations.
321 */
322 private AnnotationPainter fPainter;
323
324 /**
325 * Holds the current inlined annotations.
326 */
327 private Set<AbstractInlinedAnnotation> fInlinedAnnotations;
328
329 /**
330 * The mouse tracker used to support hover, click on inlined annotation.
331 */
332 private final MouseTracker fMouseTracker= new MouseTracker();
333
334 /**
335 * Install the inlined annotation support for the given viewer.
336 *
337 * @param viewer the source viewer
338 * @param painter the annotation painter to use to draw the inlined annotations.
339 */
340 public void install(ISourceViewer viewer, AnnotationPainter painter) {
341 Assert.isNotNull(viewer);
342 Assert.isNotNull(painter);
343 fViewer= viewer;
344 fPainter= painter;
345 initPainter();
346 StyledText text= fViewer.getTextWidget();
347 if (text == null || text.isDisposed()) {
348 return;
349 }
350 if (fViewer instanceof ITextViewerExtension4) {
351 updateStylesWidth= new UpdateStylesWidth();
352 ((ITextViewerExtension4) fViewer).addTextPresentationListener(updateStylesWidth);
353 }
354 visibleLines= new VisibleLines();
355 text.addMouseListener(fMouseTracker);
356 text.addMouseMoveListener(fMouseTracker);
357 setColor(text.getDisplay().getSystemColor(SWT.COLOR_DARK_GRAY));
358 }
359
360 /**
361 * Initialize painter with inlined drawing strategy.
362 */
363 private void initPainter() {
364 fPainter.addDrawingStrategy(INLINED_STRATEGY_ID, INLINED_STRATEGY);
365 fPainter.addAnnotationType(AbstractInlinedAnnotation.TYPE, INLINED_STRATEGY_ID);
366 }
367
368 /**
369 * Set the color to use to draw the inlined annotations.
370 *
371 * @param color the color to use to draw the inlined annotations.
372 */
373 public void setColor(Color color) {
374 fPainter.setAnnotationTypeColor(AbstractInlinedAnnotation.TYPE, color);
375 }
376
377 /**
378 * Unisntall the inlined annotation support
379 */
380 public void uninstall() {
381 StyledText text= this.fViewer.getTextWidget();
382 if (text != null && !text.isDisposed()) {
383 text.removeMouseListener(this.fMouseTracker);
384 text.removeMouseMoveListener(this.fMouseTracker);
385 }
386 if (fViewer != null) {
387 if (fViewer instanceof ITextViewerExtension4) {
388 ((ITextViewerExtension4) fViewer).removeTextPresentationListener(updateStylesWidth);
389 }
390 }
391 if (visibleLines != null) {
392 visibleLines.uninstall();
393 visibleLines= null;
394 }
395 removeInlinedAnnotations();
396 disposeFont();
397 fViewer= null;
398 fPainter= null;
399 }
400
401 /**
402 * Update the given inlined annotation.
403 *
404 * @param annotations the inlined annotation.
405 */
406 public void updateAnnotations(Set<AbstractInlinedAnnotation> annotations) {
407 IDocument document= fViewer != null ? fViewer.getDocument() : null;
408 if (document == null) {
409 // this case comes from when editor is closed before rendered is done.
410 return;
411 }
412 IAnnotationModel annotationModel= fViewer.getAnnotationModel();
413 if (annotationModel == null) {
414 return;
415 }
416 Map<AbstractInlinedAnnotation, Position> annotationsToAdd= new HashMap<>();
417 List<AbstractInlinedAnnotation> annotationsToRemove= fInlinedAnnotations != null
418 ? new ArrayList<>(fInlinedAnnotations)
419 : Collections.emptyList();
420 // Loop for annotations to update
421 for (AbstractInlinedAnnotation ann : annotations) {
422 if (!annotationsToRemove.remove(ann)) {
423 // The annotation was not created, add it
424 annotationsToAdd.put(ann, ann.getPosition());
425 }
426 }
427 // Process annotations to remove
428 for (AbstractInlinedAnnotation ann : annotationsToRemove) {
429 // Mark annotation as deleted to ignore the draw
430 ann.markDeleted(true);
431 }
432 // Update annotation model
433 synchronized (getLockObject(annotationModel)) {
434 // Update annotations with this inlined annotation support.
435 for (AbstractInlinedAnnotation ann : annotations) {
436 ann.setSupport(this);
437 }
438 if (annotationsToAdd.size() == 0 && annotationsToRemove.size() == 0) {
439 // None change, do nothing. Here the user could change position of codemining
440 // range
441 // (ex: user key press
442 // "Enter"), but we don't need to redraw the viewer because change of position
443 // is done by AnnotationPainter.
444 } else {
445 if (annotationModel instanceof IAnnotationModelExtension) {
446 ((IAnnotationModelExtension) annotationModel).replaceAnnotations(
447 annotationsToRemove.toArray(new Annotation[annotationsToRemove.size()]), annotationsToAdd);
448 } else {
449 removeInlinedAnnotations();
450 Iterator<Entry<AbstractInlinedAnnotation, Position>> iter= annotationsToAdd.entrySet().iterator();
451 while (iter.hasNext()) {
452 Entry<AbstractInlinedAnnotation, Position> mapEntry= iter.next();
453 annotationModel.addAnnotation(mapEntry.getKey(), mapEntry.getValue());
454 }
455 }
456 }
457 fInlinedAnnotations= annotations;
458 }
459 }
460
461 /**
462 * Returns the existing codemining annotation with the given position information and null
463 * otherwise.
464 *
465 * @param pos the position
466 * @return the existing codemining annotation with the given position information and null
467 * otherwise.
468 */
469 @SuppressWarnings("unchecked")
470 public <T extends AbstractInlinedAnnotation> T findExistingAnnotation(Position pos) {
471 if (fInlinedAnnotations == null) {
472 return null;
473 }
474 for (AbstractInlinedAnnotation ann : fInlinedAnnotations) {
475 if (pos.equals(ann.getPosition()) && !ann.getPosition().isDeleted()) {
476 try {
477 return (T) ann;
478 } catch (ClassCastException e) {
479 // Do nothing
480 }
481 }
482 }
483 return null;
484 }
485
486 /**
487 * Returns the lock object for the given annotation model.
488 *
489 * @param annotationModel the annotation model
490 * @return the annotation model's lock object
491 */
492 private Object getLockObject(IAnnotationModel annotationModel) {
493 if (annotationModel instanceof ISynchronizable) {
494 Object lock= ((ISynchronizable) annotationModel).getLockObject();
495 if (lock != null)
496 return lock;
497 }
498 return annotationModel;
499 }
500
501 /**
502 * Remove the inlined annotations.
503 */
504 private void removeInlinedAnnotations() {
505
506 IAnnotationModel annotationModel= fViewer.getAnnotationModel();
507 if (annotationModel == null || fInlinedAnnotations == null)
508 return;
509
510 synchronized (getLockObject(annotationModel)) {
511 if (annotationModel instanceof IAnnotationModelExtension) {
512 ((IAnnotationModelExtension) annotationModel).replaceAnnotations(
513 fInlinedAnnotations.toArray(new Annotation[fInlinedAnnotations.size()]), null);
514 } else {
515 for (AbstractInlinedAnnotation annotation : fInlinedAnnotations)
516 annotationModel.removeAnnotation(annotation);
517 }
518 fInlinedAnnotations= null;
519 }
520 }
521
522 /**
523 * Returns the {@link AbstractInlinedAnnotation} from the given point and null otherwise.
524 *
525 * @param viewer the source viewer
526 * @param x the x coordinate of the point
527 * @param y the y coordinate of the point
528 * @return the {@link AbstractInlinedAnnotation} from the given point and null otherwise.
529 */
530 private AbstractInlinedAnnotation getInlinedAnnotationAtPoint(ISourceViewer viewer, int x, int y) {
531 if (fInlinedAnnotations != null) {
532 for (AbstractInlinedAnnotation ann : fInlinedAnnotations) {
533 if (ann.contains(x, y) && isInVisibleLines(ann.getPosition().getOffset())) {
534 return ann;
535 }
536 }
537 }
538 return null;
539 }
540
541 /**
542 * Execute UI {@link StyledText} function which requires UI Thread.
543 *
544 * @param text the styled text
545 * @param fn the function to execute.
546 */
547 static void runInUIThread(StyledText text, Consumer<StyledText> fn) {
548 if (text == null || text.isDisposed()) {
549 return;
550 }
551 Display display= text.getDisplay();
552 if (display.getThread() == Thread.currentThread()) {
553 try {
554 fn.accept(text);
555 } catch (Exception e) {
556 // Ignore UI error
557 }
558 } else {
559 display.asyncExec(() -> {
560 if (text.isDisposed()) {
561 return;
562 }
563 try {
564 fn.accept(text);
565 } catch (Exception e) {
566 // Ignore UI error
567 }
568 });
569 }
570 }
571
572 /**
573 * Return whether the given offset is in visible lines.
574 *
575 * @param offset the offset
576 * @return <code>true</code> if the given offset is in visible lines and <code>false</code>
577 * otherwise.
578 */
579 boolean isInVisibleLines(int offset) {
580 if (visibleLines == null) {
581 // case of support has been uninstalled and mining must be drawn.
582 return false;
583 }
584 return visibleLines.isInVisibleLines(offset);
585 }
586
587 /**
588 * Returns the font according the specified <code>style</code> that the receiver will use to
589 * paint textual information.
590 *
591 * @param style the style of Font widget to get.
592 * @return the receiver's font according the specified <code>style</code>
593 *
594 */
595 Font getFont(int style) {
596 StyledText styledText= fViewer != null ? fViewer.getTextWidget() : null;
597 if (styledText == null) {
598 return null;
599 }
600 if (!styledText.getFont().equals(regularFont)) {
601 disposeFont();
602 regularFont= styledText.getFont();
603 }
604 Device device= styledText.getDisplay();
605 switch (style) {
606 case SWT.BOLD:
607 if (boldFont != null)
608 return boldFont;
609 return boldFont= new Font(device, getFontData(style));
610 case SWT.ITALIC:
611 if (italicFont != null)
612 return italicFont;
613 return italicFont= new Font(device, getFontData(style));
614 case SWT.BOLD | SWT.ITALIC:
615 if (boldItalicFont != null)
616 return boldItalicFont;
617 return boldItalicFont= new Font(device, getFontData(style));
618 default:
619 return regularFont;
620 }
621 }
622
623 /**
624 * Returns the font data array according the given style.
625 *
626 * @param style the style
627 * @return the font data array according the given style.
628 */
629 FontData[] getFontData(int style) {
630 FontData[] fontDatas= regularFont.getFontData();
631 for (int i= 0; i < fontDatas.length; i++) {
632 fontDatas[i].setStyle(style);
633 }
634 return fontDatas;
635 }
636
637 /**
638 * Dispose the font.
639 */
640 void disposeFont() {
641 if (boldFont != null)
642 boldFont.dispose();
643 if (italicFont != null)
644 italicFont.dispose();
645 if (boldItalicFont != null)
646 boldItalicFont.dispose();
647 boldFont= italicFont= boldItalicFont= null;
648 }
649 }
0 /**
1 * Copyright (c) 2017 Angelo ZERR.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Provide inline annotations support - Bug 527675
9 */
10 package org.eclipse.jface.text.source.inlined;
11
12 import org.eclipse.swt.custom.StyledText;
13 import org.eclipse.swt.graphics.Color;
14 import org.eclipse.swt.graphics.GC;
15
16 import org.eclipse.jface.text.Position;
17 import org.eclipse.jface.text.source.ISourceViewer;
18
19 /**
20 * Inlined annotation which is drawn in the line content and which takes some place with a given
21 * width.
22 *
23 * @since 3.13
24 */
25 public class LineContentAnnotation extends AbstractInlinedAnnotation {
26
27 /**
28 * The annotation width
29 */
30 private int width;
31
32 private int redrawnCharacterWidth;
33
34 /**
35 * Line content annotation constructor.
36 *
37 * @param position the position where the annotation must be drawn.
38 * @param viewer the {@link ISourceViewer} where the annotation must be drawn.
39 */
40 public LineContentAnnotation(Position position, ISourceViewer viewer) {
41 super(position, viewer);
42 }
43
44 /**
45 * Returns the annotation width. By default it computes the well width for the text annotation.
46 *
47 * @return the annotation width.
48 */
49 public final int getWidth() {
50 return width;
51 }
52
53 /**
54 * {@inheritDoc}
55 * <p>
56 * After drawn, compute the text width and update it.
57 * </p>
58 */
59 @Override
60 public final void draw(GC gc, StyledText textWidget, int offset, int length, Color color, int x, int y) {
61 width= drawAndComputeWidth(gc, textWidget, offset, length, color, x, y);
62 }
63
64 /**
65 * Draw the inlined annotation. By default it draws the text of the annotation with gray color.
66 * User can override this method to draw anything.
67 *
68 * @param gc the graphics context
69 * @param textWidget the text widget to draw on
70 * @param offset the offset of the line
71 * @param length the length of the line
72 * @param color the color of the line
73 * @param x the x position of the annotation
74 * @param y the y position of the annotation
75 * @return the text width.
76 */
77 protected int drawAndComputeWidth(GC gc, StyledText textWidget, int offset, int length, Color color, int x, int y) {
78 // Draw the text annotation and returns the width
79 super.draw(gc, textWidget, offset, length, color, x, y);
80 return gc.stringExtent(getText()).x + 2 * gc.getFontMetrics().getAverageCharWidth();
81 }
82
83 int getRedrawnCharacterWidth() {
84 return redrawnCharacterWidth;
85 }
86
87 void setRedrawnCharacterWidth(int redrawnCharacterWidth) {
88 this.redrawnCharacterWidth= redrawnCharacterWidth;
89 }
90
91 @Override
92 boolean contains(int x, int y) {
93 return (x >= this.fX && x <= this.fX + width && y >= this.fY && y <= this.fY + getTextWidget().getLineHeight());
94 }
95
96 }
0 /**
1 * Copyright (c) 2017, 2018 Angelo ZERR.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Provide inline annotations support - Bug 527675
9 */
10 package org.eclipse.jface.text.source.inlined;
11
12 import org.eclipse.swt.custom.StyledText;
13
14 import org.eclipse.jface.text.Position;
15 import org.eclipse.jface.text.source.ISourceViewer;
16
17 /**
18 * Inlined annotation which is drawn before a line and which takes some place with a given height.
19 *
20 * @since 3.13
21 */
22 public class LineHeaderAnnotation extends AbstractInlinedAnnotation {
23
24 private int redrawnCharacterHeight;
25
26 private int redrawnCharacterWidth;
27
28 /**
29 * Line header annotation constructor.
30 *
31 * @param position the position where the annotation must be drawn.
32 * @param viewer the {@link ISourceViewer} where the annotation must be drawn.
33 */
34 public LineHeaderAnnotation(Position position, ISourceViewer viewer) {
35 super(position, viewer);
36 }
37
38 /**
39 * Returns the annotation height. By default, returns the {@link StyledText#getLineHeight()}.
40 *
41 * @return the annotation height.
42 */
43 public int getHeight() {
44 StyledText styledText= super.getTextWidget();
45 return styledText.getLineHeight();
46 }
47
48 int getRedrawnCharacterHeight() {
49 return redrawnCharacterHeight;
50 }
51
52 void setRedrawnCharacterHeight(int redrawnCharacterHeight) {
53 this.redrawnCharacterHeight= redrawnCharacterHeight;
54 }
55
56 int getRedrawnCharacterWidth() {
57 return redrawnCharacterWidth;
58 }
59
60 void setRedrawnCharacterWidth(int redrawnCharacterWidth) {
61 this.redrawnCharacterWidth= redrawnCharacterWidth;
62 }
63
64 @Override
65 boolean contains(int x, int y) {
66 return (x >= this.fX && y >= this.fY && y <= this.fY + getHeight());
67 }
68 }
0 /**
1 * Copyright (c) 2017 Angelo ZERR.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Provide inline annotations support - Bug 527675
9 */
10 package org.eclipse.jface.text.source.inlined;
11
12 import org.eclipse.jface.text.BadLocationException;
13 import org.eclipse.jface.text.IDocument;
14 import org.eclipse.jface.text.Position;
15
16 /**
17 * Utilities class to retrieve position.
18 *
19 * @since 3.13
20 */
21 public class Positions {
22
23 /**
24 * Returns the line position by taking care or not of of leading spaces.
25 *
26 * @param lineIndex the line index
27 * @param document the document
28 * @param leadingSpaces true if line spacing must take care of and not otherwise.
29 * @return the line position by taking care of leading spaces.
30 * @throws BadLocationException if the line number is invalid in this document
31 */
32 public static Position of(int lineIndex, IDocument document, boolean leadingSpaces) throws BadLocationException {
33 int offset= document.getLineOffset(lineIndex);
34 int lineLength= document.getLineLength(lineIndex);
35 String line= document.get(offset, lineLength);
36 if (leadingSpaces) {
37 offset+= getLeadingSpaces(line);
38 }
39 return new Position(offset, 1);
40 }
41
42 /**
43 * Returns the leading spaces of the given line text.
44 *
45 * @param line the line text.
46 * @return the leading spaces of the given line text.
47 */
48 private static int getLeadingSpaces(String line) {
49 int counter= 0;
50 char[] chars= line.toCharArray();
51 for (char c : chars) {
52 if (c == '\t')
53 counter++;
54 else if (c == ' ')
55 counter++;
56 else
57 break;
58 }
59 return counter;
60 }
61 }
197197 boolean enabled = getBooleanValue(attributes, ENABLED_ATTRIBUTE, true);
198198 boolean autoInsertable= getBooleanValue(attributes, AUTO_INSERTABLE_ATTRIBUTE, true);
199199
200 StringBuffer buffer= new StringBuffer();
200 StringBuilder buffer= new StringBuilder();
201201 NodeList children= node.getChildNodes();
202202 for (int j= 0; j != children.getLength(); j++) {
203203 String value= children.item(j).getNodeValue();
385385 if (idx == -1) {
386386 return str;
387387 }
388 StringBuffer buf= new StringBuffer();
388 StringBuilder buf= new StringBuilder();
389389 int k= 0;
390390 while (idx != -1) {
391391 buf.append(str.substring(k, idx));
0 <?xml version="1.0" encoding="UTF-8"?>
1 <classpath>
2 <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
3 <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
4 <classpathentry kind="src" path="src"/>
5 <classpathentry kind="output" path="bin"/>
6 </classpath>
0 <?xml version="1.0" encoding="UTF-8"?>
1 <projectDescription>
2 <name>org.eclipse.jface.text.examples</name>
3 <comment></comment>
4 <projects>
5 </projects>
6 <buildSpec>
7 <buildCommand>
8 <name>org.eclipse.jdt.core.javabuilder</name>
9 <arguments>
10 </arguments>
11 </buildCommand>
12 <buildCommand>
13 <name>org.eclipse.pde.ManifestBuilder</name>
14 <arguments>
15 </arguments>
16 </buildCommand>
17 <buildCommand>
18 <name>org.eclipse.pde.SchemaBuilder</name>
19 <arguments>
20 </arguments>
21 </buildCommand>
22 </buildSpec>
23 <natures>
24 <nature>org.eclipse.pde.PluginNature</nature>
25 <nature>org.eclipse.jdt.core.javanature</nature>
26 </natures>
27 </projectDescription>
0 eclipse.preferences.version=1
1 org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
2 org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
3 org.eclipse.jdt.core.compiler.compliance=1.8
4 org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
5 org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
6 org.eclipse.jdt.core.compiler.source=1.8
0 eclipse.preferences.version=1
1 pluginProject.extensions=false
2 resolve.requirebundle=false
0 Manifest-Version: 1.0
1 Bundle-ManifestVersion: 2
2 Bundle-Name: CodeMinig Examples
3 Bundle-SymbolicName: org.eclipse.jface.text.examples
4 Bundle-Version: 1.0.0.qualifier
5 Bundle-RequiredExecutionEnvironment: JavaSE-1.8
6 Require-Bundle: org.eclipse.jface.text,
7 org.eclipse.core.runtime,
8 org.eclipse.swt,
9 org.eclipse.jface;bundle-version="3.14.0"
10 Automatic-Module-Name: org.eclipse.jface.text.examples
0 source.. = src/
1 output.. = bin/
2 bin.includes = META-INF/,\
3 .
0 <?xml version="1.0" encoding="UTF-8"?>
1 <!--
2 Copyright (c) 2012, 2014 Eclipse Foundation and others.
3 All rights reserved. This program and the accompanying materials
4 are made available under the terms of the Eclipse Distribution License v1.0
5 which accompanies this distribution, and is available at
6 http://www.eclipse.org/org/documents/edl-v10.php
7
8 Contributors:
9 Igor Fedorenko - initial implementation
10 -->
11 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
12 <modelVersion>4.0.0</modelVersion>
13 <parent>
14 <artifactId>eclipse.platform.text</artifactId>
15 <groupId>eclipse.platform.text</groupId>
16 <version>4.8.0-SNAPSHOT</version>
17 </parent>
18 <groupId>org.eclipse.core</groupId>
19 <artifactId>org.eclipse.jface.text.examples</artifactId>
20 <version>1.0.0-SNAPSHOT</version>
21 <packaging>eclipse-plugin</packaging>
22 </project>
0 /**
1 * Copyright (c) 2017 Angelo ZERR.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Add CodeMining support in SourceViewer - Bug 527515
9 */
10 package org.eclipse.jface.text.examples.codemining;
11
12 import org.eclipse.jface.text.BadLocationException;
13 import org.eclipse.jface.text.IDocument;
14 import org.eclipse.jface.text.codemining.ICodeMiningProvider;
15 import org.eclipse.jface.text.codemining.LineHeaderCodeMining;
16
17 /**
18 * Abstract class for class name mining.
19 *
20 */
21 public abstract class AbstractClassCodeMining extends LineHeaderCodeMining {
22
23 private final String className;
24
25 public AbstractClassCodeMining(String className, int afterLineNumber, IDocument document,
26 ICodeMiningProvider resolver) throws BadLocationException {
27 super(afterLineNumber, document, resolver);
28 this.className = className;
29 }
30
31 public String getClassName() {
32 return className;
33 }
34
35 public static String getLineText(IDocument document, int line) {
36 try {
37 int lo = document.getLineOffset(line);
38 int ll = document.getLineLength(line);
39 return document.get(lo, ll);
40 } catch (Exception e) {
41 e.printStackTrace();
42 return null;
43 }
44 }
45
46 }
0 /**
1 * Copyright (c) 2017 Angelo ZERR.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Add CodeMining support in SourceViewer - Bug 527515
9 */
10 package org.eclipse.jface.text.examples.codemining;
11
12 import java.util.concurrent.CompletableFuture;
13
14 import org.eclipse.core.runtime.IProgressMonitor;
15 import org.eclipse.jface.text.BadLocationException;
16 import org.eclipse.jface.text.IDocument;
17 import org.eclipse.jface.text.ITextViewer;
18 import org.eclipse.jface.text.codemining.ICodeMiningProvider;
19
20 /**
21 * Class implementation mining.
22 *
23 */
24 public class ClassImplementationCodeMining extends AbstractClassCodeMining {
25
26 public ClassImplementationCodeMining(String className, int afterLineNumber, IDocument document,
27 ICodeMiningProvider provider) throws BadLocationException {
28 super(className, afterLineNumber, document, provider);
29 }
30
31 @Override
32 protected CompletableFuture<Void> doResolve(ITextViewer viewer, IProgressMonitor monitor) {
33 return CompletableFuture.runAsync(() -> {
34 IDocument document = viewer.getDocument();
35 String className = super.getClassName();
36 int refCount = 0;
37 int lineCount = document.getNumberOfLines();
38 for (int i = 0; i < lineCount; i++) {
39 // check if request was canceled.
40 monitor.isCanceled();
41 String line = getLineText(document, i);
42 refCount += line.contains("implements " + className) ? 1 : 0;
43 }
44 super.setLabel(refCount + " implementation");
45 });
46 }
47
48 }
0 /**
1 * Copyright (c) 2017 Angelo ZERR.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Add CodeMining support in SourceViewer - Bug 527515
9 */
10 package org.eclipse.jface.text.examples.codemining;
11
12 import java.util.ArrayList;
13 import java.util.List;
14 import java.util.concurrent.CompletableFuture;
15
16 import org.eclipse.core.runtime.IProgressMonitor;
17 import org.eclipse.jface.text.BadLocationException;
18 import org.eclipse.jface.text.IDocument;
19 import org.eclipse.jface.text.ITextViewer;
20 import org.eclipse.jface.text.codemining.AbstractCodeMiningProvider;
21 import org.eclipse.jface.text.codemining.ICodeMining;
22
23 /**
24 * Class implementation mining provider.
25 *
26 */
27 public class ClassImplementationsCodeMiningProvider extends AbstractCodeMiningProvider {
28
29 @Override
30 public CompletableFuture<List<? extends ICodeMining>> provideCodeMinings(ITextViewer viewer,
31 IProgressMonitor monitor) {
32 return CompletableFuture.supplyAsync(() -> {
33 IDocument document = viewer.getDocument();
34 List<ICodeMining> lenses = new ArrayList<>();
35 int lineCount = document.getNumberOfLines();
36 for (int i = 0; i < lineCount; i++) {
37 // check if request was canceled.
38 monitor.isCanceled();
39 updateContentMining(i, document, "class ", lenses);
40 updateContentMining(i, document, "interface ", lenses);
41 }
42 return lenses;
43 });
44 }
45
46 private void updateContentMining(int lineIndex, IDocument document, String token, List<ICodeMining> lenses) {
47 String line = AbstractClassCodeMining.getLineText(document, lineIndex).trim();
48 int index = line.indexOf(token);
49 if (index == 0) {
50 String className = line.substring(index + token.length(), line.length());
51 index = className.indexOf(" ");
52 if (index != -1) {
53 className = className.substring(0, index);
54 }
55 if (className.length() > 0) {
56 try {
57 lenses.add(new ClassImplementationCodeMining(className, lineIndex, document, this));
58 } catch (BadLocationException e) {
59 e.printStackTrace();
60 }
61 }
62 }
63 }
64
65 }
0 /**
1 * Copyright (c) 2017 Angelo ZERR.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Add CodeMining support in SourceViewer - Bug 527515
9 */
10 package org.eclipse.jface.text.examples.codemining;
11
12 import java.util.concurrent.CancellationException;
13 import java.util.concurrent.CompletableFuture;
14
15 import org.eclipse.core.runtime.IProgressMonitor;
16 import org.eclipse.jface.text.BadLocationException;
17 import org.eclipse.jface.text.IDocument;
18 import org.eclipse.jface.text.ITextViewer;
19 import org.eclipse.jface.text.codemining.ICodeMiningProvider;
20
21 /**
22 * Class reference mining.
23 *
24 */
25 public class ClassReferenceCodeMining extends AbstractClassCodeMining {
26
27 private Object lock = new Object();
28
29 public ClassReferenceCodeMining(String className, int afterLineNumber, IDocument document, ICodeMiningProvider provider)
30 throws BadLocationException {
31 super(className, afterLineNumber, document, provider);
32 }
33
34 @Override
35 protected CompletableFuture<Void> doResolve(ITextViewer viewer, IProgressMonitor monitor) {
36 return CompletableFuture.runAsync(() -> {
37 IDocument document = viewer.getDocument();
38 String className = super.getClassName();
39 try {
40 int wait = Integer.parseInt(className);
41 try {
42 for (int i = 0; i < wait; i++) {
43 monitor.isCanceled();
44 synchronized (lock) {
45 lock.wait(1000);
46 }
47 }
48 } catch (InterruptedException e) {
49 Thread.currentThread().interrupt();
50 }
51 } catch (NumberFormatException e) {
52
53 } catch (CancellationException e) {
54 e.printStackTrace();
55 throw e;
56 }
57
58 int refCount = 0;
59 int lineCount = document.getNumberOfLines();
60 for (int i = 0; i < lineCount; i++) {
61 // check if request was canceled.
62 monitor.isCanceled();
63 String line = getLineText(document, i);
64 refCount += line.contains("new " + className) ? 1 : 0;
65 }
66 super.setLabel(refCount + " references");
67 });
68 }
69
70 }
0 /**
1 * Copyright (c) 2017 Angelo ZERR.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Add CodeMining support in SourceViewer - Bug 527515
9 */
10 package org.eclipse.jface.text.examples.codemining;
11
12 import java.util.ArrayList;
13 import java.util.List;
14 import java.util.concurrent.CompletableFuture;
15
16 import org.eclipse.core.runtime.IProgressMonitor;
17 import org.eclipse.jface.text.BadLocationException;
18 import org.eclipse.jface.text.IDocument;
19 import org.eclipse.jface.text.ITextViewer;
20 import org.eclipse.jface.text.codemining.AbstractCodeMiningProvider;
21 import org.eclipse.jface.text.codemining.ICodeMining;
22
23 /**
24 * Class reference mining provider.
25 *
26 */
27 public class ClassReferenceCodeMiningProvider extends AbstractCodeMiningProvider {
28
29 @Override
30 public CompletableFuture<List<? extends ICodeMining>> provideCodeMinings(ITextViewer viewer,
31 IProgressMonitor monitor) {
32 return CompletableFuture.supplyAsync(() -> {
33 IDocument document = viewer.getDocument();
34 List<ICodeMining> lenses = new ArrayList<>();
35 int lineCount = document.getNumberOfLines();
36 for (int i = 0; i < lineCount; i++) {
37 // check if request was canceled.
38 monitor.isCanceled();
39 String line = AbstractClassCodeMining.getLineText(document, i).trim();
40 int index = line.indexOf("class ");
41 if (index == 0) {
42 String className = line.substring(index + "class ".length(), line.length()).trim();
43 if (className.length() > 0) {
44 try {
45 lenses.add(new ClassReferenceCodeMining(className, i, document, this));
46 } catch (BadLocationException e) {
47 e.printStackTrace();
48 }
49 }
50 }
51 }
52 return lenses;
53 });
54 }
55
56 }
0 /**
1 * Copyright (c) 2017 Angelo ZERR.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Add CodeMining support in SourceViewer - Bug 527515
9 */
10 package org.eclipse.jface.text.examples.codemining;
11
12 import org.eclipse.jface.text.Document;
13 import org.eclipse.jface.text.IDocument;
14 import org.eclipse.jface.text.IRegion;
15 import org.eclipse.jface.text.ITextViewerExtension2;
16 import org.eclipse.jface.text.codemining.ICodeMiningProvider;
17 import org.eclipse.jface.text.reconciler.DirtyRegion;
18 import org.eclipse.jface.text.reconciler.IReconcilingStrategy;
19 import org.eclipse.jface.text.reconciler.MonoReconciler;
20 import org.eclipse.jface.text.source.Annotation;
21 import org.eclipse.jface.text.source.AnnotationModel;
22 import org.eclipse.jface.text.source.AnnotationPainter;
23 import org.eclipse.jface.text.source.IAnnotationAccess;
24 import org.eclipse.jface.text.source.ISourceViewer;
25 import org.eclipse.jface.text.source.ISourceViewerExtension5;
26 import org.eclipse.jface.text.source.SourceViewer;
27 import org.eclipse.swt.SWT;
28 import org.eclipse.swt.layout.FillLayout;
29 import org.eclipse.swt.widgets.Display;
30 import org.eclipse.swt.widgets.Shell;
31
32 /**
33 * A Code Mining demo with class references and implementations minings.
34 *
35 */
36 public class CodeMiningDemo {
37
38 public static void main(String[] args) throws Exception {
39
40 Display display = new Display();
41 Shell shell = new Shell(display);
42 shell.setLayout(new FillLayout());
43 shell.setText("Code Mining demo");
44
45 ISourceViewer sourceViewer = new SourceViewer(shell, null, SWT.V_SCROLL | SWT.BORDER);
46 sourceViewer.setDocument(
47 new Document("// Type class & new keyword and see references CodeMining\n"
48 + "// Name class with a number N to emulate Nms before resolving the references CodeMining \n\n"
49 + "class A\n" + "new A\n" + "new A\n\n" + "class 5\n" + "new 5\n" + "new 5\n" + "new 5"),
50 new AnnotationModel());
51 // Add AnnotationPainter (required by CodeMining)
52 addAnnotationPainter(sourceViewer);
53 // Initialize codemining providers
54 ((ISourceViewerExtension5) sourceViewer).setCodeMiningProviders(new ICodeMiningProvider[] {
55 new ClassReferenceCodeMiningProvider(), new ClassImplementationsCodeMiningProvider() });
56 // Execute codemining in a reconciler
57 MonoReconciler reconciler = new MonoReconciler(new IReconcilingStrategy() {
58
59 @Override
60 public void setDocument(IDocument document) {
61 ((ISourceViewerExtension5) sourceViewer).updateCodeMinings();
62 }
63
64 @Override
65 public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) {
66
67 }
68
69 @Override
70 public void reconcile(IRegion partition) {
71 ((ISourceViewerExtension5) sourceViewer).updateCodeMinings();
72 }
73 }, false);
74 reconciler.install(sourceViewer);
75
76 shell.open();
77 while (!shell.isDisposed()) {
78 if (!display.readAndDispatch())
79 display.sleep();
80 }
81 display.dispose();
82 }
83
84 private static void addAnnotationPainter(ISourceViewer viewer) {
85 IAnnotationAccess annotationAccess = new IAnnotationAccess() {
86 @Override
87 public Object getType(Annotation annotation) {
88 return annotation.getType();
89 }
90
91 @Override
92 public boolean isMultiLine(Annotation annotation) {
93 return true;
94 }
95
96 @Override
97 public boolean isTemporary(Annotation annotation) {
98 return true;
99 }
100
101 };
102 AnnotationPainter painter = new AnnotationPainter(viewer, annotationAccess);
103 ((ITextViewerExtension2) viewer).addPainter(painter);
104 // Register this annotation painter as CodeMining annotation painter.
105 ((ISourceViewerExtension5) viewer).setCodeMiningAnnotationPainter(painter);
106 }
107
108 }
0 /**s
1 * Copyright (c) 2017 Angelo ZERR.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Provide inline annotations support - Bug 527675
9 */
10 package org.eclipse.jface.text.examples.sources.inlined;
11
12 import java.util.function.Consumer;
13
14 import org.eclipse.jface.text.BadLocationException;
15 import org.eclipse.jface.text.IDocument;
16 import org.eclipse.jface.text.IRegion;
17 import org.eclipse.jface.text.Position;
18 import org.eclipse.jface.text.source.ISourceViewer;
19 import org.eclipse.jface.text.source.inlined.LineContentAnnotation;
20 import org.eclipse.jface.util.Geometry;
21 import org.eclipse.swt.custom.StyledText;
22 import org.eclipse.swt.events.MouseEvent;
23 import org.eclipse.swt.graphics.Color;
24 import org.eclipse.swt.graphics.FontMetrics;
25 import org.eclipse.swt.graphics.GC;
26 import org.eclipse.swt.graphics.RGB;
27 import org.eclipse.swt.graphics.Rectangle;
28 import org.eclipse.swt.widgets.ColorDialog;
29 import org.eclipse.swt.widgets.Shell;
30
31 /**
32 * Color annotation displays a colorized square before the rgb declaration.
33 */
34 public class ColorAnnotation extends LineContentAnnotation {
35
36 private Color color;
37
38 private Consumer<MouseEvent> action = e -> {
39 StyledText styledText = super.getTextWidget();
40 Shell shell = new Shell(styledText.getDisplay());
41 Rectangle location = Geometry.toDisplay(styledText, new Rectangle(e.x, e.y, 1, 1));
42 shell.setLocation(location.x, location.y);
43 // Open color dialog
44 ColorDialog dialog = new ColorDialog(shell);
45 // dialog.setRGB(annotation.getRGBA().rgb);
46 RGB color = dialog.open();
47 if (color != null) {
48 // Color was selected, update the viewer
49 try {
50 int offset = getPosition().getOffset();
51 IDocument document = getViewer().getDocument();
52 IRegion line = document.getLineInformation(document.getLineOfOffset(offset));
53 int length = line.getLength() - (offset - line.getOffset());
54 String rgb = formatToRGB(color);
55 document.replace(offset, length, rgb);
56 } catch (BadLocationException e1) {
57
58 }
59 }
60 };
61
62 /**
63 * Format the given rgb to hexa color.
64 *
65 * @param rgb
66 * @return the hexa color from the given rgb.
67 */
68 private static String formatToRGB(RGB rgb) {
69 return new StringBuilder("rgb(").append(rgb.red).append(",").append(rgb.green).append(",").append(rgb.blue)
70 .append(")").toString();
71 }
72
73 public ColorAnnotation(Position pos, ISourceViewer viewer) {
74 super(pos, viewer);
75 }
76
77 public void setColor(Color color) {
78 this.color = color;
79 }
80
81 @Override
82 protected int drawAndComputeWidth(GC gc, StyledText textWidget, int offset, int length, Color color, int x, int y) {
83 FontMetrics fontMetrics = gc.getFontMetrics();
84 int size = getSquareSize(fontMetrics);
85 x += fontMetrics.getLeading();
86 y += fontMetrics.getDescent();
87
88 Rectangle rect = new Rectangle(x, y, size, size);
89
90 // Fill square
91 gc.setBackground(this.color);
92 gc.fillRectangle(rect);
93
94 // Draw square box
95 gc.setForeground(textWidget.getForeground());
96 gc.drawRectangle(rect);
97 return getSquareWidth(gc.getFontMetrics());
98 }
99
100 /**
101 * Returns the colorized square size.
102 *
103 * @param fontMetrics
104 * @return the colorized square size.
105 */
106 public static int getSquareSize(FontMetrics fontMetrics) {
107 return fontMetrics.getHeight() - 2 * fontMetrics.getDescent();
108 }
109
110 /**
111 * Compute width of square
112 *
113 * @param styledText
114 * @return the width of square
115 */
116 private static int getSquareWidth(FontMetrics fontMetrics) {
117 // width = 2 spaces + size width of square
118 int width = 2 * fontMetrics.getAverageCharWidth() + getSquareSize(fontMetrics);
119 return width;
120 }
121
122 @Override
123 public Consumer<MouseEvent> getAction(MouseEvent e) {
124 return action;
125 }
126 }
0 /**
1 * Copyright (c) 2017 Angelo ZERR.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Provide inline annotations support - Bug 527675
9 */
10 package org.eclipse.jface.text.examples.sources.inlined;
11
12 import org.eclipse.jface.text.Position;
13 import org.eclipse.jface.text.source.ISourceViewer;
14 import org.eclipse.jface.text.source.inlined.LineHeaderAnnotation;
15
16 /**
17 * Color status annotation shows the result of rgb parse before each line which
18 * defines 'color:'.
19 */
20 public class ColorStatusAnnotation extends LineHeaderAnnotation {
21
22 public ColorStatusAnnotation(Position position, ISourceViewer viewer) {
23 super(position, viewer);
24 }
25
26 public void setStatus(String status) {
27 super.setText(status);
28 }
29
30 }
0 /**
1 * Copyright (c) 2017 Angelo ZERR.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Provide inline annotations support - Bug 527675
9 */
10 package org.eclipse.jface.text.examples.sources.inlined;
11
12 import java.util.HashSet;
13 import java.util.Set;
14 import java.util.regex.Matcher;
15 import java.util.regex.Pattern;
16
17 import org.eclipse.jface.text.BadLocationException;
18 import org.eclipse.jface.text.Document;
19 import org.eclipse.jface.text.IDocument;
20 import org.eclipse.jface.text.IRegion;
21 import org.eclipse.jface.text.ITextViewerExtension2;
22 import org.eclipse.jface.text.Position;
23 import org.eclipse.jface.text.reconciler.DirtyRegion;
24 import org.eclipse.jface.text.reconciler.IReconcilingStrategy;
25 import org.eclipse.jface.text.reconciler.MonoReconciler;
26 import org.eclipse.jface.text.source.Annotation;
27 import org.eclipse.jface.text.source.AnnotationModel;
28 import org.eclipse.jface.text.source.AnnotationPainter;
29 import org.eclipse.jface.text.source.IAnnotationAccess;
30 import org.eclipse.jface.text.source.ISourceViewer;
31 import org.eclipse.jface.text.source.SourceViewer;
32 import org.eclipse.jface.text.source.inlined.AbstractInlinedAnnotation;
33 import org.eclipse.jface.text.source.inlined.InlinedAnnotationSupport;
34 import org.eclipse.jface.text.source.inlined.LineContentAnnotation;
35 import org.eclipse.jface.text.source.inlined.LineHeaderAnnotation;
36 import org.eclipse.jface.text.source.inlined.Positions;
37 import org.eclipse.swt.SWT;
38 import org.eclipse.swt.graphics.Color;
39 import org.eclipse.swt.graphics.Device;
40 import org.eclipse.swt.layout.FillLayout;
41 import org.eclipse.swt.widgets.Display;
42 import org.eclipse.swt.widgets.Shell;
43
44 /**
45 * An inlined demo with {@link LineHeaderAnnotation} and
46 * {@link LineContentAnnotation} annotations both:
47 *
48 * <ul>
49 * <li>a status OK, NOK is displayed before the line which starts with 'color:'.
50 * This status is the result of the content after 'color' which must be a rgb
51 * content. Here {@link ColorStatusAnnotation} is used.</li>
52 * <li>a colorized square is displayed before the rgb declaration (inside the
53 * line content). Here {@link ColorAnnotation} is used.</li>
54 * </ul>
55 *
56 */
57 public class InlinedAnnotationDemo {
58
59 public static void main(String[] args) throws Exception {
60
61 Display display = new Display();
62 Shell shell = new Shell(display);
63 shell.setLayout(new FillLayout());
64 shell.setText("Inlined annotation demo");
65
66 // Create source viewer and initialize the content
67 ISourceViewer sourceViewer = new SourceViewer(shell, null, SWT.V_SCROLL | SWT.BORDER);
68 sourceViewer.setDocument(new Document("\ncolor:rgb(255, 255, 0)"), new AnnotationModel());
69
70 // Initialize inlined annotations support
71 InlinedAnnotationSupport support = new InlinedAnnotationSupport();
72 support.install(sourceViewer, createAnnotationPainter(sourceViewer));
73
74 // Refresh inlined annotation in none UI Thread with reconciler.
75 MonoReconciler reconciler = new MonoReconciler(new IReconcilingStrategy() {
76
77 @Override
78 public void setDocument(IDocument document) {
79 Set<AbstractInlinedAnnotation> annotations = getInlinedAnnotation(sourceViewer, support);
80 support.updateAnnotations(annotations);
81 }
82
83 @Override
84 public void reconcile(IRegion partition) {
85 Set<AbstractInlinedAnnotation> anns = getInlinedAnnotation(sourceViewer, support);
86 support.updateAnnotations(anns);
87 }
88
89 @Override
90 public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) {
91
92 }
93 }, false);
94 reconciler.setDelay(1);
95 reconciler.install(sourceViewer);
96
97 shell.open();
98 while (!shell.isDisposed()) {
99 if (!display.readAndDispatch())
100 display.sleep();
101 }
102 display.dispose();
103 }
104
105 /**
106 * Create annotation painter.
107 *
108 * @param viewer
109 * the viewer.
110 * @return annotation painter.
111 */
112 private static AnnotationPainter createAnnotationPainter(ISourceViewer viewer) {
113 IAnnotationAccess annotationAccess = new IAnnotationAccess() {
114 @Override
115 public Object getType(Annotation annotation) {
116 return annotation.getType();
117 }
118
119 @Override
120 public boolean isMultiLine(Annotation annotation) {
121 return true;
122 }
123
124 @Override
125 public boolean isTemporary(Annotation annotation) {
126 return true;
127 }
128
129 };
130 AnnotationPainter painter = new AnnotationPainter(viewer, annotationAccess);
131 ((ITextViewerExtension2) viewer).addPainter(painter);
132 return painter;
133 }
134
135 /**
136 * Returns the inlined annotations list to display in the given viewer.
137 *
138 * @param viewer
139 * the viewer
140 * @param support
141 * the inlined annotation suppor.
142 * @return the inlined annotations list to display in the given viewer.
143 */
144 private static Set<AbstractInlinedAnnotation> getInlinedAnnotation(ISourceViewer viewer,
145 InlinedAnnotationSupport support) {
146 IDocument document = viewer.getDocument();
147 Set<AbstractInlinedAnnotation> annotations = new HashSet<>();
148 int lineCount = document.getNumberOfLines();
149 for (int i = 0; i < lineCount; i++) {
150 String line = getLineText(document, i).trim();
151 int index = line.indexOf("color:");
152 if (index == 0) {
153 String rgb = line.substring(index + "color:".length(), line.length()).trim();
154 try {
155 String status = "OK!";
156 Color color = parse(rgb, viewer.getTextWidget().getDisplay());
157 if (color != null) {
158 } else {
159 status = "ERROR!";
160 }
161 // Status color annotation
162 Position pos = Positions.of(i, document, true);
163 ColorStatusAnnotation statusAnnotation = support.findExistingAnnotation(pos);
164 if (statusAnnotation == null) {
165 statusAnnotation = new ColorStatusAnnotation(pos, viewer);
166 }
167 statusAnnotation.setStatus(status);
168 annotations.add(statusAnnotation);
169
170 // Color annotation
171 if (color != null) {
172 Position colorPos = new Position(pos.offset + index + "color:".length(), 1);
173 ColorAnnotation colorAnnotation = support.findExistingAnnotation(colorPos);
174 if (colorAnnotation == null) {
175 colorAnnotation = new ColorAnnotation(colorPos, viewer);
176 }
177 colorAnnotation.setColor(color);
178 annotations.add(colorAnnotation);
179 }
180
181 // rgb parameter names annotations
182 int rgbIndex = line.indexOf("rgb");
183 if (rgbIndex != -1) {
184 rgbIndex = rgbIndex + "rgb".length();
185 int startOffset = pos.offset + rgbIndex;
186 String rgbContent = line.substring(rgbIndex, line.length());
187 int startIndex = addRGBParamNameAnnotation("red:", rgbContent, 0, startOffset, viewer, support,
188 annotations);
189 if (startIndex != -1) {
190 startIndex = addRGBParamNameAnnotation("green:", rgbContent, startIndex, startOffset, viewer,
191 support, annotations);
192 if (startIndex != -1) {
193 startIndex = addRGBParamNameAnnotation("blue:", rgbContent, startIndex, startOffset,
194 viewer, support, annotations);
195 }
196 }
197 }
198
199 } catch (BadLocationException e) {
200 e.printStackTrace();
201 }
202 }
203 }
204 return annotations;
205 }
206
207 /**
208 * Add RGB parameter name annotation
209 *
210 * @param paramName
211 * @param rgbContent
212 * @param startIndex
213 * @param startOffset
214 * @param viewer
215 * @param support
216 * @param annotations
217 * @return the current parsed index
218 */
219 private static int addRGBParamNameAnnotation(String paramName, String rgbContent, int startIndex, int startOffset,
220 ISourceViewer viewer, InlinedAnnotationSupport support, Set<AbstractInlinedAnnotation> annotations) {
221 char startChar = startIndex == 0 ? '(' : ',';
222 char[] chars = rgbContent.toCharArray();
223 for (int i = startIndex; i < chars.length; i++) {
224 char c = chars[i];
225 if (c == startChar) {
226 if (i == chars.length - 1) {
227 return -1;
228 }
229 Position paramPos = new Position(startOffset + i + 1, 1);
230 LineContentAnnotation colorParamAnnotation = support.findExistingAnnotation(paramPos);
231 if (colorParamAnnotation == null) {
232 colorParamAnnotation = new LineContentAnnotation(paramPos, viewer);
233 }
234 colorParamAnnotation.setText(paramName);
235 annotations.add(colorParamAnnotation);
236 return i + 1;
237 }
238 }
239 return -1;
240 }
241
242 /**
243 * Parse the given input rgb color and returns an instance of SWT Color and null
244 * otherwise.
245 *
246 * @param input
247 * the rgb string color
248 * @param device
249 * @return the created color and null otherwise.
250 */
251 private static Color parse(String input, Device device) {
252 Pattern c = Pattern.compile("rgb *\\( *([0-9]+), *([0-9]+), *([0-9]+) *\\)");
253 Matcher m = c.matcher(input);
254 if (m.matches()) {
255 try {
256 return new Color(device, Integer.valueOf(m.group(1)), // r
257 Integer.valueOf(m.group(2)), // g
258 Integer.valueOf(m.group(3))); // b
259 } catch (Exception e) {
260
261 }
262 }
263 return null;
264 }
265
266 /**
267 * Returns the line text.
268 *
269 * @param document
270 * the document.
271 * @param line
272 * the line index.
273 * @return the line text.
274 */
275 private static String getLineText(IDocument document, int line) {
276 try {
277 int offset = document.getLineOffset(line);
278 int length = document.getLineLength(line);
279 return document.get(offset, length);
280 } catch (Exception e) {
281 e.printStackTrace();
282 return null;
283 }
284 }
285 }
11 Bundle-ManifestVersion: 2
22 Bundle-Name: %Plugin.name
33 Bundle-SymbolicName: org.eclipse.jface.text.tests
4 Bundle-Version: 3.11.100.qualifier
4 Bundle-Version: 3.11.200.qualifier
55 Bundle-Vendor: %Plugin.providerName
66 Bundle-Localization: plugin
77 Export-Package:
1818 org.eclipse.core.runtime;bundle-version="[3.5.0,4.0.0)"
1919 Bundle-RequiredExecutionEnvironment: JavaSE-1.8
2020 Eclipse-BundleShape: dir
21 Automatic-Module-Name: org.eclipse.jface.text.tests
0 # To force a version qualifier update add the bug here
1 Pick up new signing certificate
1313 <parent>
1414 <artifactId>tests-pom</artifactId>
1515 <groupId>eclipse.platform.text</groupId>
16 <version>4.7.3-SNAPSHOT</version>
16 <version>4.8.0-SNAPSHOT</version>
1717 <relativePath>../tests-pom/</relativePath>
1818 </parent>
1919 <groupId>org.eclipse.jface</groupId>
2020 <artifactId>org.eclipse.jface.text.tests</artifactId>
21 <version>3.11.100-SNAPSHOT</version>
21 <version>3.11.200-SNAPSHOT</version>
2222 <packaging>eclipse-test-plugin</packaging>
2323 <properties>
2424 <testSuite>${project.artifactId}</testSuite>
11 Bundle-ManifestVersion: 2
22 Bundle-Name: %pluginName
33 Bundle-SymbolicName: org.eclipse.search; singleton:=true
4 Bundle-Version: 3.11.100.qualifier
4 Bundle-Version: 3.11.200.qualifier
55 Bundle-Activator: org.eclipse.search.internal.ui.SearchPlugin
66 Bundle-ActivationPolicy: lazy
77 Bundle-Vendor: %providerName
3232 org.eclipse.ltk.ui.refactoring;bundle-version="[3.5.0,4.0.0)"
3333 Bundle-RequiredExecutionEnvironment: JavaSE-1.8
3434 Import-Package: com.ibm.icu.text
35 Automatic-Module-Name: org.eclipse.search
+0
-58
org.eclipse.search/apichanges_search.html less more
0 <!DOCTYPE doctype PUBLIC "-//w3c//dtd html 4.0 transitional//en">
1 <html>
2 <head>
3 <meta http-equiv="Content-Type"
4 content="text/html; charset=iso-8859-1">
5 <meta name="Author" content="IBM">
6 <title>Search Breaking API changes</title>
7 <link rel="stylesheet" href="http://dev.eclipse.org/default_style.css"
8 type="text/css">
9 </head>
10 <body style="color: rgb(0, 0, 0); background-color: rgb(255, 255, 255);">
11 <font color="#8080ff" size="-2">platform search</font>
12 <p>This document lists the breaking API changes that occurred between
13 R3.3 and R3.4 and
14 how to migrate from the R3.3 API to the R3.4 API.
15 </p>
16 <table border="0" cellpadding="2" cellspacing="5" width="100%" summary="Breaking API changes from R3.3 to R3.4">
17 <tbody>
18 <tr>
19 <td align="left" width="72%"> <font size="+3"><b>search -
20 Breaking API changes from R3.3 to R3.4</b></font> <br>
21 </td>
22 </tr>
23 <tr>
24 <td>
25 None
26 </td>
27 </tr>
28 </tbody>
29 </table>
30 <p> </p>
31 <table border="0" cellpadding="2" cellspacing="5" width="100%" summary="Non-breaking API changes from R3.3 to R3.4">
32 <tbody>
33 <tr>
34 <td align="left" width="72%"> <font size="+3"><b>search -
35 Non-breaking API changes from R3.3 to R3.4</b></font> <br>
36 </td>
37 </tr>
38 <tr>
39 <td>New API added to AbstractTextSearchViewPage
40 <ul>
41 <li>evaluateChangedElements(Match[], Collection) - controls which elements are later sent to <code>elementsChanged</code></li>
42 </ul> </td>
43 </tr>
44 <tr><td><hr></td></tr>
45 <tr>
46 <td>New attribute for extension point <code>org.eclipse.search.searchResultViewPages</code>:
47 <ul>
48 <li>helpContextId - Help context id for the search result page</li>
49 </ul> </td>
50 </tr>
51 </tbody>
52 </table>
53 <p>
54 API changes from 3.2 to 3.3 can be found <a href="./notes/r3.3/apichanges_search.html?view=co">here</a>.
55 </p>
56 </body>
57 </html>
7575 private void createActions(IEditorPart editor) {
7676 fActions= new FindInRecentScopeActionDelegate[] {
7777 new FindInWorkspaceActionDelegate(), new FindInProjectActionDelegate(), new FindInFileActionDelegate(), new FindInWorkingSetActionDelegate()};
78 for (int i= 0; i < fActions.length; i++) {
79 FindInRecentScopeActionDelegate action= fActions[i];
78 for (FindInRecentScopeActionDelegate action : fActions) {
8079 action.setActiveEditor(action, editor);
8180 }
8281 }
9595 public void addMatches(Match[] matches) {
9696 Collection<Match> reallyAdded= new ArrayList<>();
9797 synchronized (fElementsToMatches) {
98 for (int i = 0; i < matches.length; i++) {
99 if (doAddMatch(matches[i]))
100 reallyAdded.add(matches[i]);
98 for (Match match : matches) {
99 if (doAddMatch(match))
100 reallyAdded.add(match);
101101 }
102102 }
103103 if (!reallyAdded.isEmpty())
141141
142142 private static int getInsertIndex(List<Match> matches, Match match) {
143143 int count= matches.size();
144 int min = 0, max = count - 1;
144 int min = 0;
145 int max = count - 1;
145146 while (min <= max) {
146147 int mid = (min + max) / 2;
147148 Match data = matches.get(mid);
207208 public void removeMatches(Match[] matches) {
208209 Collection<Match> existing= new ArrayList<>();
209210 synchronized (fElementsToMatches) {
210 for (int i = 0; i < matches.length; i++) {
211 if (doRemoveMatch(matches[i]))
212 existing.add(matches[i]); // no duplicate matches at this point
211 for (Match match : matches) {
212 if (doRemoveMatch(match))
213 existing.add(match); // no duplicate matches at this point
213214 }
214215 }
215216 if (!existing.isEmpty())
265266 boolean disableFiltering= getActiveMatchFilters() == null;
266267 ArrayList<Match> changed= new ArrayList<>();
267268 Object[] elements= getElements();
268 for (int i= 0; i < elements.length; i++) {
269 Match[] matches= getMatches(elements[i]);
270 for (int k= 0; k < matches.length; k++) {
271 if (disableFiltering || updateFilterState(matches[k])) {
272 changed.add(matches[k]);
269 for (Object element : elements) {
270 Match[] matches= getMatches(element);
271 for (Match match : matches) {
272 if (disableFiltering || updateFilterState(match)) {
273 changed.add(match);
273274 }
274275 }
275276 }
287288 }
288289
289290 boolean oldState= match.isFiltered();
290 for (int i= 0; i < matchFilters.length; i++) {
291 if (matchFilters[i].filters(match)) {
291 for (MatchFilter matchFilter : matchFilters) {
292 if (matchFilter.filters(match)) {
292293 match.setFiltered(true);
293294 return !oldState;
294295 }
306307 public int getMatchCount() {
307308 int count= 0;
308309 synchronized (fElementsToMatches) {
309 for (Iterator<List<Match>> elements= fElementsToMatches.values().iterator(); elements.hasNext();) {
310 List<Match> element= elements.next();
310 for (List<Match> element : fElementsToMatches.values()) {
311311 if (element != null)
312312 count+= element.size();
313313 }
00 /*******************************************************************************
1 * Copyright (c) 2000, 2016 IBM Corporation and others.
1 * Copyright (c) 2000, 2018 IBM Corporation and others.
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
1212
1313 import java.util.ArrayList;
1414 import java.util.HashSet;
15 import java.util.Iterator;
1615 import java.util.Set;
1716
1817 import org.eclipse.swt.SWT;
200199 public void selectionChanged(SelectionChangedEvent event) {
201200 // forward to my listeners
202201 SelectionChangedEvent wrappedEvent= new SelectionChangedEvent(this, event.getSelection());
203 for (Iterator<ISelectionChangedListener> listeners= fListeners.iterator(); listeners.hasNext();) {
204 ISelectionChangedListener listener= listeners.next();
202 for (ISelectionChangedListener listener : fListeners) {
205203 listener.selectionChanged(wrappedEvent);
206204 }
207205 }
854852 IMenuManager menu= bars.getMenuManager();
855853
856854 if (filterActions != null) {
857 for (int i= 0; i < filterActions.length; i++) {
858 menu.remove(filterActions[i].getId());
855 for (IAction filterAction : filterActions) {
856 menu.remove(filterAction.getId());
859857 }
860858 }
861859 menu.remove(MatchFilterSelectionAction.ACTION_ID);
891889
892890 private void updateFilterActions(IAction[] filterActions) {
893891 if (filterActions != null) {
894 for (int i= 0; i < filterActions.length; i++) {
895 IAction curr= filterActions[i];
892 for (IAction curr : filterActions) {
896893 if (curr instanceof IUpdate) {
897894 ((IUpdate) curr).update();
898895 }
11231120 }
11241121
11251122 private Object getFirstSelectedElement() {
1126 IStructuredSelection selection = (IStructuredSelection) fViewer.getSelection();
1123 IStructuredSelection selection = fViewer.getStructuredSelection();
11271124 if (selection.size() > 0)
11281125 return selection.getFirstElement();
11291126 return null;
12371234 * @since 3.4
12381235 */
12391236 protected void evaluateChangedElements(Match[] matches, Set<Object> changedElements) {
1240 for (int i = 0; i < matches.length; i++) {
1241 changedElements.add(matches[i].getElement());
1237 for (Match match : matches) {
1238 changedElements.add(match.getElement());
12421239 }
12431240 }
12441241
13511348 if (result == null)
13521349 return;
13531350 StructuredViewer viewer = getViewer();
1354 IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();
1351 IStructuredSelection selection = viewer.getStructuredSelection();
13551352
13561353 HashSet<Match> set = new HashSet<>();
13571354 if (viewer instanceof TreeViewer) {
13681365 }
13691366
13701367 private void collectAllMatches(HashSet<Match> set, Object[] elements) {
1371 for (int j = 0; j < elements.length; j++) {
1372 Match[] matches = getDisplayedMatches(elements[j]);
1373 for (int i = 0; i < matches.length; i++) {
1374 set.add(matches[i]);
1368 for (Object element : elements) {
1369 Match[] matches = getDisplayedMatches(element);
1370 for (Match match : matches) {
1371 set.add(match);
13751372 }
13761373 }
13771374 }
13781375
13791376 private void collectAllMatchesBelow(AbstractTextSearchResult result, Set<Match> set, ITreeContentProvider cp, Object[] elements) {
1380 for (int j = 0; j < elements.length; j++) {
1381 Match[] matches = getDisplayedMatches(elements[j]);
1382 for (int i = 0; i < matches.length; i++) {
1383 set.add(matches[i]);
1384 }
1385 Object[] children = cp.getChildren(elements[j]);
1377 for (Object element : elements) {
1378 Match[] matches = getDisplayedMatches(element);
1379 for (Match match : matches) {
1380 set.add(match);
1381 }
1382 Object[] children = cp.getChildren(element);
13861383 collectAllMatchesBelow(result, set, cp, children);
13871384 }
13881385 }
189189 return BasicElementLabels.getFilePattern("*"); //$NON-NLS-1$
190190 }
191191 Arrays.sort(ext);
192 StringBuffer buf= new StringBuffer();
192 StringBuilder buf= new StringBuilder();
193193 for (int i= 0; i < ext.length; i++) {
194194 if (i > 0) {
195195 buf.append(", "); //$NON-NLS-1$
261261
262262 private static IResource[] removeRedundantEntries(IResource[] elements, boolean includeDerived) {
263263 ArrayList<IResource> res= new ArrayList<>();
264 for (int i= 0; i < elements.length; i++) {
265 IResource curr= elements[i];
264 for (IResource curr : elements) {
266265 addToList(res, curr, includeDerived);
267266 }
268267 return res.toArray(new IResource[res.size()]);
270269
271270 private static IResource[] convertToResources(IWorkingSet[] workingSets, boolean includeDerived) {
272271 ArrayList<IResource> res= new ArrayList<>();
273 for (int i= 0; i < workingSets.length; i++) {
274 IWorkingSet workingSet= workingSets[i];
272 for (IWorkingSet workingSet : workingSets) {
275273 if (workingSet.isAggregateWorkingSet() && workingSet.isEmpty()) {
276274 return new IResource[] { ResourcesPlugin.getWorkspace().getRoot() };
277275 }
278276 IAdaptable[] elements= workingSet.getElements();
279 for (int k= 0; k < elements.length; k++) {
280 IResource curr= elements[k].getAdapter(IResource.class);
277 for (IAdaptable element : elements) {
278 IResource curr= element.getAdapter(IResource.class);
281279 if (curr != null) {
282280 addToList(res, curr, includeDerived);
283281 }
320320 int numberQueriesNotShown= 0;
321321 SearchViewManager searchViewManager= getSearchViewManager();
322322 ISearchQuery[] queries= searchManager.getQueries();
323 for (int i= 0; i < queries.length; i++) {
324 ISearchQuery query= queries[i];
323 for (ISearchQuery query : queries) {
325324 if (!searchViewManager.isShown(query)) {
326325 if (++numberQueriesNotShown >= historyLimit) {
327326 removeQuery(query);
331330 }
332331
333332 public void removeAllQueries() {
334 for (Iterator<ISearchQuery> queries= fSearchJobs.keySet().iterator(); queries.hasNext();) {
335 ISearchQuery query= queries.next();
333 for (ISearchQuery query : fSearchJobs.keySet()) {
336334 cancelSearch(query);
337335 }
338336 fSearchJobs.clear();
6666 AbstractTextSearchResult input= fPage.getInput();
6767 if (input != null) {
6868 MatchFilter[] activeMatchFilters= input.getActiveMatchFilters();
69 for (int i= 0; i < activeMatchFilters.length; i++) {
70 if (fFilter.equals(activeMatchFilters[i])) {
69 for (MatchFilter activeMatchFilter : activeMatchFilters) {
70 if (fFilter.equals(activeMatchFilter)) {
7171 return true;
7272 }
7373 }
00 /*******************************************************************************
1 * Copyright (c) 2000, 2008 IBM Corporation and others.
1 * Copyright (c) 2000, 2018 IBM Corporation and others.
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
3434 import org.eclipse.jface.viewers.CheckboxTableViewer;
3535 import org.eclipse.jface.viewers.ICheckStateListener;
3636 import org.eclipse.jface.viewers.ISelectionChangedListener;
37 import org.eclipse.jface.viewers.IStructuredSelection;
3837 import org.eclipse.jface.viewers.LabelProvider;
3938 import org.eclipse.jface.viewers.SelectionChangedEvent;
4039
229228 }
230229
231230 private void performFilterListSelectionChanged() {
232 Object selectedElement = ((IStructuredSelection) fListViewer.getSelection()).getFirstElement();
231 Object selectedElement = fListViewer.getStructuredSelection().getFirstElement();
233232 if (selectedElement != null)
234233 fDescription.setText(((MatchFilter) selectedElement).getDescription());
235234 else
4747 }
4848
4949 private String escapeAmp(String label) {
50 StringBuffer buf= new StringBuffer();
50 StringBuilder buf= new StringBuilder();
5151 for (int i= 0; i < label.length(); i++) {
5252 char ch= label.charAt(i);
5353 buf.append(ch);
116116
117117 ISearchQuery[] searches= NewSearchUI.getQueries();
118118 if (searches.length > 0) {
119 for (int i= 0; i < searches.length; i++) {
120 ISearchResult search= searches[i].getSearchResult();
121 ShowSearchFromHistoryAction action= new ShowSearchFromHistoryAction(search);
122 action.setChecked(search.equals(currentSearch));
119 for (ISearchQuery search : searches) {
120 ISearchResult searchResult= search.getSearchResult();
121 ShowSearchFromHistoryAction action= new ShowSearchFromHistoryAction(searchResult);
122 action.setChecked(searchResult.equals(currentSearch));
123123 addActionToMenu(fMenu, action);
124124 }
125125 new MenuItem(fMenu, SWT.SEPARATOR);
00 /*******************************************************************************
1 * Copyright (c) 2000, 2016 IBM Corporation and others.
1 * Copyright (c) 2000, 2018 IBM Corporation and others.
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
364364 }
365365
366366 protected final void validateDialogState() {
367 IStructuredSelection sel= (IStructuredSelection) fViewer.getSelection();
367 IStructuredSelection sel = fViewer.getStructuredSelection();
368368 int elementsSelected= sel.toList().size();
369369
370370 fRemoveButton.setEnabled(elementsSelected > 0);
389389 @Override
390390 protected void buttonPressed(int buttonId) {
391391 if (buttonId == REMOVE_ID) {
392 IStructuredSelection selection= (IStructuredSelection) fViewer.getSelection();
392 IStructuredSelection selection = fViewer.getStructuredSelection();
393393 Iterator<?> searchResults= selection.iterator();
394394 while (searchResults.hasNext()) {
395395 ISearchResult curr= (ISearchResult) searchResults.next();
417417 // Build a list of selected children.
418418 ISelection selection= fViewer.getSelection();
419419 if (selection instanceof IStructuredSelection)
420 setResult(((IStructuredSelection) fViewer.getSelection()).toList());
420 setResult(fViewer.getStructuredSelection().toList());
421421
422422 // remove queries
423 for (Iterator<ISearchResult> iter= fRemovedEntries.iterator(); iter.hasNext();) {
424 ISearchResult result= iter.next();
423 for (ISearchResult result : fRemovedEntries) {
425424 ISearchQuery query= result.getQuery();
426425 if (query != null) { // must not be null: invalid implementation of a search query
427426 InternalSearchUI.getInstance().removeQuery(query);
4242 fExtensionToInstance= new HashMap<>();
4343 fResultClassNameToExtension= new HashMap<>();
4444 fExtensions= Platform.getExtensionRegistry().getConfigurationElementsFor(ID_EXTENSION_POINT);
45 for (int i= 0; i < fExtensions.length; i++) {
46 fResultClassNameToExtension.put(fExtensions[i].getAttribute(ATTRIB_SEARCH_RESULT_CLASS), fExtensions[i]);
45 for (IConfigurationElement fExtension : fExtensions) {
46 fResultClassNameToExtension.put(fExtension.getAttribute(ATTRIB_SEARCH_RESULT_CLASS), fExtension);
4747 }
4848 }
4949
107107 }
108108
109109 private IConfigurationElement findConfigurationElement(String pageId) {
110 for (int i= 0; i < fExtensions.length; i++) {
111 IConfigurationElement curr= fExtensions[i];
110 for (IConfigurationElement curr : fExtensions) {
112111 if (pageId.equals(curr.getAttribute(ATTRIB_ID))) {
113112 return curr;
114113 }
132131 }
133132
134133 Class<?>[] interfaces= resultClass.getInterfaces();
135 for (int i= 0; i < interfaces.length; i++) {
136 IConfigurationElement foundExtension= findConfigurationElement(interfaces[i]);
134 for (Class<?> interface1 : interfaces) {
135 IConfigurationElement foundExtension= findConfigurationElement(interface1);
137136 if (foundExtension != null) {
138137 fResultClassNameToExtension.put(className, configElement);
139138 return foundExtension;
1414 package org.eclipse.search2.internal.ui;
1515
1616 import java.util.HashMap;
17 import java.util.Iterator;
1817 import java.util.Map.Entry;
1918
2019 import com.ibm.icu.text.MessageFormat;
555554 int bestActivation= -1;
556555 IMemento restorePageMemento= null;
557556 IMemento[] children= fPageState.getChildren(MEMENTO_TYPE);
558 for (int i= 0; i < children.length; i++) {
559 IMemento pageMemento= children[i];
557 for (IMemento pageMemento : children) {
560558 if (pageMemento.getString(MEMENTO_KEY_RESTORE) != null) {
561559 Integer lastActivation= pageMemento.getInteger(MEMENTO_KEY_LAST_ACTIVATION);
562560 if (lastActivation != null && lastActivation.intValue() > bestActivation) {
689687
690688 @Override
691689 public void saveState(IMemento memento) {
692 for (Iterator<Entry<ISearchResultPage, DummyPart>> iter= fPagesToParts.entrySet().iterator(); iter.hasNext();) {
693 Entry<ISearchResultPage, DummyPart> entry= iter.next();
690 for (Entry<ISearchResultPage, DummyPart> entry : fPagesToParts.entrySet()) {
694691 ISearchResultPage page= entry.getKey();
695692 DummyPart part= entry.getValue();
696693
724721 IMemento memento= null;
725722 if (fPageState != null) {
726723 IMemento[] mementos= fPageState.getChildren(MEMENTO_TYPE);
727 for (int i= 0; i < mementos.length; i++) {
728 if (mementos[i].getID().equals(srPage.getID())) {
729 memento= mementos[i];
724 for (IMemento memento2 : mementos) {
725 if (memento2.getID().equals(srPage.getID())) {
726 memento= memento2;
730727 break;
731728 }
732729 }
1010
1111 package org.eclipse.search2.internal.ui;
1212
13 import java.util.Iterator;
1413 import java.util.LinkedList;
1514
1615 import org.eclipse.ui.IViewReference;
119118 }
120119
121120 public boolean isShown(ISearchQuery query) {
122 for (Iterator<SearchView> iter= fLRUSearchViews.iterator(); iter.hasNext();) {
123 SearchView view= iter.next();
121 for (SearchView view : fLRUSearchViews) {
124122 ISearchResult currentSearchResult= view.getCurrentSearchResult();
125123 if (currentSearchResult != null && query == currentSearchResult.getQuery()) {
126124 return true;
141139
142140 private ISearchResultViewPart findLRUSearchResultView(IWorkbenchPage page, boolean avoidPinnedViews) {
143141 boolean viewFoundInPage= false;
144 for (Iterator<SearchView> iter= fLRUSearchViews.iterator(); iter.hasNext();) {
145 SearchView view= iter.next();
142 for (SearchView view : fLRUSearchViews) {
146143 if (page.equals(view.getSite().getPage())) {
147144 if (!avoidPinnedViews || !view.isPinned()) {
148145 return view;
153150 if (!viewFoundInPage) {
154151 // find unresolved views
155152 IViewReference[] viewReferences= page.getViewReferences();
156 for (int i= 0; i < viewReferences.length; i++) {
157 IViewReference curr= viewReferences[i];
153 for (IViewReference curr : viewReferences) {
158154 if (NewSearchUI.SEARCH_VIEW_ID.equals(curr.getId()) && page.equals(curr.getPage())) {
159155 SearchView view= (SearchView) curr.getView(true);
160156 if (view != null && (!avoidPinnedViews || !view.isPinned())) {
4343 ISearchQuery[] queries= NewSearchUI.getQueries();
4444
4545 ArrayList<ISearchResult> input= new ArrayList<>();
46 for (int j= 0; j < queries.length; j++) {
47 ISearchResult search= queries[j].getSearchResult();
46 for (ISearchQuery query : queries) {
47 ISearchResult search= query.getSearchResult();
4848 input.add(search);
4949 }
5050
66 *
77 * Contributors:
88 * IBM Corporation - initial API and implementation
9 * Karsten Thoms <karsten.thoms@itemis.de> Bug 522335
910 *******************************************************************************/
1011 package org.eclipse.search2.internal.ui.basic.views;
1112
3334 @Override
3435 public void run() {
3536 if (fViewer != null) {
36 fViewer.expandAll();
37 fViewer.getTree().setRedraw(false);
38 try {
39 fViewer.expandAll();
40 } finally {
41 fViewer.getTree().setRedraw(true);
42 }
3743 }
3844 }
3945 }
5151 TreeItem[] roots= fViewer.getTree().getItems();
5252 if (roots.length == 0)
5353 return null;
54 for (int i = 0; i < roots.length; i++) {
55 if (hasMatches(roots[i]))
56 return roots[i];
54 for (TreeItem root : roots) {
55 if (hasMatches(root))
56 return root;
5757 TreeItem firstChild= getFirstChildWithMatches(roots[0]);
5858 if (firstChild != null)
5959 return firstChild;
1313 import java.util.Collections;
1414 import java.util.HashMap;
1515 import java.util.HashSet;
16 import java.util.Iterator;
1716 import java.util.Map;
1817 import java.util.Map.Entry;
1918 import java.util.Set;
5251 @Override
5352 public void addHighlights(Match[] matches) {
5453 HashMap<Annotation, Position> map= new HashMap<>(matches.length);
55 for (int i= 0; i < matches.length; i++) {
56 int offset= matches[i].getOffset();
57 int length= matches[i].getLength();
54 for (Match match : matches) {
55 int offset= match.getOffset();
56 int length= match.getLength();
5857 if (offset >= 0 && length >= 0) {
59 Position position= createPosition(matches[i]);
58 Position position= createPosition(match);
6059 if (position != null) {
61 Annotation annotation= matches[i].isFiltered()
60 Annotation annotation= match.isFiltered()
6261 ? new Annotation(SearchPlugin.FILTERED_SEARCH_ANNOTATION_TYPE, true, null)
6362 : new Annotation(SearchPlugin.SEARCH_ANNOTATION_TYPE, true, null);
64 fMatchesToAnnotations.put(matches[i], annotation);
63 fMatchesToAnnotations.put(match, annotation);
6564 map.put(annotation, position);
6665 }
6766 }
9695 @Override
9796 public void removeHighlights(Match[] matches) {
9897 HashSet<Annotation> annotations= new HashSet<>(matches.length);
99 for (int i= 0; i < matches.length; i++) {
100 Annotation annotation= fMatchesToAnnotations.remove(matches[i]);
98 for (Match match : matches) {
99 Annotation annotation= fMatchesToAnnotations.remove(match);
101100 if (annotation != null) {
102101 annotations.add(annotation);
103102 }
137136 Annotation[] annotationArray= new Annotation[annotations.size()];
138137 ame.replaceAnnotations(annotations.toArray(annotationArray), Collections.emptyMap());
139138 } else {
140 for (Iterator<Annotation> iter= annotations.iterator(); iter.hasNext();) {
141 Annotation element= iter.next();
139 for (Annotation element : annotations) {
142140 fModel.removeAnnotation(element);
143141 }
144142 }
1212 import java.util.Collections;
1313 import java.util.HashMap;
1414 import java.util.HashSet;
15 import java.util.Iterator;
1615 import java.util.Map;
1716 import java.util.Map.Entry;
1817 import java.util.Set;
5049 @Override
5150 public void addHighlights(Match[] matches) {
5251 Map<IAnnotationModel, HashMap<Annotation, Position>> mapsByAnnotationModel= new HashMap<>();
53 for (int i= 0; i < matches.length; i++) {
54 int offset= matches[i].getOffset();
55 int length= matches[i].getLength();
52 for (Match match : matches) {
53 int offset= match.getOffset();
54 int length= match.getLength();
5655 if (offset >= 0 && length >= 0) {
5756 try {
58 Position position= createPosition(matches[i]);
57 Position position= createPosition(match);
5958 if (position != null) {
60 Map<Annotation, Position> map= getMap(mapsByAnnotationModel, matches[i]);
59 Map<Annotation, Position> map= getMap(mapsByAnnotationModel, match);
6160 if (map != null) {
62 Annotation annotation= matches[i].isFiltered()
61 Annotation annotation= match.isFiltered()
6362 ? new Annotation(SearchPlugin.FILTERED_SEARCH_ANNOTATION_TYPE, true, null)
6463 : new Annotation(SearchPlugin.SEARCH_ANNOTATION_TYPE, true, null);
65 fMatchesToAnnotations.put(matches[i], annotation);
64 fMatchesToAnnotations.put(match, annotation);
6665 map.put(annotation, position);
6766 }
6867 }
123122 @Override
124123 public void removeHighlights(Match[] matches) {
125124 Map<IAnnotationModel, HashSet<Annotation>> setsByAnnotationModel= new HashMap<>();
126 for (int i= 0; i < matches.length; i++) {
127 Annotation annotation= fMatchesToAnnotations.remove(matches[i]);
125 for (Match match : matches) {
126 Annotation annotation= fMatchesToAnnotations.remove(match);
128127 if (annotation != null) {
129 Set<Annotation> annotations= getSet(setsByAnnotationModel, matches[i]);
128 Set<Annotation> annotations= getSet(setsByAnnotationModel, match);
130129 if (annotations != null)
131130 annotations.add(annotation);
132131 }
133132 }
134133
135 for (Iterator<IAnnotationModel> maps= setsByAnnotationModel.keySet().iterator(); maps.hasNext();) {
136 IAnnotationModel model= maps.next();
137 Set<Annotation> set= setsByAnnotationModel.get(model);
138 removeAnnotations(model, set);
134 for (Entry<IAnnotationModel, HashSet<Annotation>> entry : setsByAnnotationModel.entrySet()) {
135 removeAnnotations(entry.getKey(), entry.getValue());
139136 }
140137
141138 }
145142 IAnnotationModelExtension ame= (IAnnotationModelExtension) model;
146143 ame.replaceAnnotations(new Annotation[0], annotationToPositionMap);
147144 } else {
148 for (Iterator<Annotation> elements= annotationToPositionMap.keySet().iterator(); elements.hasNext();) {
149 Annotation element= elements.next();
150 Position p= annotationToPositionMap.get(element);
151 model.addAnnotation(element, p);
145 for (Entry<Annotation, Position> entry : annotationToPositionMap.entrySet()) {
146 model.addAnnotation(entry.getKey(), entry.getValue());
152147 }
153148 }
154149 }
166161 Annotation[] annotationArray= new Annotation[annotations.size()];
167162 ame.replaceAnnotations(annotations.toArray(annotationArray), Collections.emptyMap());
168163 } else {
169 for (Iterator<Annotation> iter= annotations.iterator(); iter.hasNext();) {
170 Annotation element= iter.next();
164 for (Annotation element : annotations) {
171165 model.removeAnnotation(element);
172166 }
173167 }
186180 return;
187181 IDocument document= null;
188182 ITextFileBuffer textBuffer= (ITextFileBuffer) buffer;
189 for (Iterator<Match> matches = fMatchesToAnnotations.keySet().iterator(); matches.hasNext();) {
190 Match match = matches.next();
183 for (Match match : fMatchesToAnnotations.keySet()) {
191184 document= fEditorAcess.getDocument(match);
192185 if (document != null)
193186 break;
154154 }
155155
156156 ArrayList<Match> matchesInEditor= null; // lazy initialization
157 for (int i= 0; i < matches.length; i++) {
158 Match curr= matches[i];
157 for (Match curr : matches) {
159158 if (adapter.isShownInEditor(curr, fEditor)) {
160159 if (matchesInEditor == null) {
161160 matchesInEditor= new ArrayList<>();
4646 SearchPlugin.getWorkspace().run(new IWorkspaceRunnable() {
4747 @Override
4848 public void run(IProgressMonitor monitor) throws CoreException {
49 for (int i = 0; i < matches.length; i++) {
49 for (Match match : matches) {
5050 IMarker marker;
51 marker = createMarker(matches[i]);
51 marker = createMarker(match);
5252 if (marker != null)
53 fMatchesToAnnotations.put(matches[i], marker);
53 fMatchesToAnnotations.put(match, marker);
5454 }
5555 }
5656 }, fFile, IWorkspace.AVOID_UPDATE, null);
8686
8787 @Override
8888 public void removeHighlights(Match[] matches) {
89 for (int i= 0; i < matches.length; i++) {
90 IMarker marker= fMatchesToAnnotations.remove(matches[i]);
89 for (Match match : matches) {
90 IMarker marker= fMatchesToAnnotations.remove(match);
9191 if (marker != null) {
9292 try {
9393 marker.delete();
1111
1212 import java.util.HashMap;
1313 import java.util.HashSet;
14 import java.util.Iterator;
1514 import java.util.Map;
1615 import java.util.Set;
1716
8584 Match[] matches = evt.getMatches();
8685 int kind = evt.getKind();
8786 AbstractTextSearchResult result = (AbstractTextSearchResult) e.getSearchResult();
88 for (int i = 0; i < matches.length; i++) {
89 ITextFileBuffer fb= getTrackedFileBuffer(result, matches[i].getElement());
87 for (Match match : matches) {
88 ITextFileBuffer fb= getTrackedFileBuffer(result, match.getElement());
9089 if (fb != null) {
91 updateMatch(matches[i], fb, kind, result);
90 updateMatch(match, fb, kind, result);
9291 }
9392 }
9493 } else if (e instanceof RemoveAllEvent) {
108107
109108 private void untrackAll(AbstractTextSearchResult result) {
110109 Set<Match> matchSet= new HashSet<>(fMatchesToPositions.keySet());
111 for (Iterator<Match> matches= matchSet.iterator(); matches.hasNext();) {
112 Match match= matches.next();
110 for (Match match : matchSet) {
113111 AbstractTextSearchResult matchContainer= fMatchesToSearchResults.get(match);
114112 if (result.equals(matchContainer)) {
115113 ITextFileBuffer fb= getTrackedFileBuffer(result, match.getElement());
248246 return;
249247
250248 ISearchQuery[] queries= NewSearchUI.getQueries();
251 for (int i = 0; i < queries.length; i++) {
252 ISearchResult result = queries[i].getSearchResult();
249 for (ISearchQuery query : queries) {
250 ISearchResult result = query.getSearchResult();
253251 if (result instanceof AbstractTextSearchResult) {
254252 AbstractTextSearchResult textResult = (AbstractTextSearchResult) result;
255253 IFileMatchAdapter adapter = textResult.getFileMatchAdapter();
256254 if (adapter != null) {
257255 Match[] matches = adapter.computeContainedMatches(textResult, file);
258 for (int j = 0; j < matches.length; j++) {
256 for (Match match : matches) {
259257 trackCount[0]++;
260 trackPosition((AbstractTextSearchResult) result, (ITextFileBuffer) buffer, matches[j]);
258 trackPosition((AbstractTextSearchResult) result, (ITextFileBuffer) buffer, match);
261259 }
262260 }
263261 }
270268 Set<Match> matches= fFileBuffersToMatches.get(buffer);
271269 if (matches != null) {
272270 Set<Match> matchSet= new HashSet<>(matches);
273 for (Iterator<Match> matchIterator= matchSet.iterator(); matchIterator.hasNext();) {
274 Match element= matchIterator.next();
271 for (Match element : matchSet) {
275272 operation.run((ITextFileBuffer) buffer, element);
276273 }
277274 }
1111
1212 import java.util.ArrayList;
1313 import java.util.HashMap;
14 import java.util.Iterator;
1514 import java.util.Map;
1615
1716 import org.eclipse.ui.IEditorPart;
102101
103102 private void initEditors() {
104103 IWorkbenchPage[] pages= fWindow.getPages();
105 for (int i = 0; i < pages.length; i++) {
106 IEditorReference[] editors= pages[i].getEditorReferences();
107 for (int j = 0; j < editors.length; j++) {
108 IEditorPart editor= editors[j].getEditor(false);
109 if (editor != null && pages[i].isPartVisible(editor)) {
104 for (IWorkbenchPage page : pages) {
105 IEditorReference[] editors= page.getEditorReferences();
106 for (IEditorReference editor2 : editors) {
107 IEditorPart editor= editor2.getEditor(false);
108 if (editor != null && page.isPartVisible(editor)) {
110109 startHighlighting(editor);
111110 }
112111 }
130129
131130 void dispose() {
132131 fWindow.getPartService().removePartListener(fPartListener);
133 for (Iterator<EditorAnnotationManager> mgrs = fAnnotationManagers.values().iterator(); mgrs.hasNext();) {
134 EditorAnnotationManager mgr = mgrs.next();
132 for (EditorAnnotationManager mgr : fAnnotationManagers.values()) {
135133 mgr.dispose();
136134 }
137135 fAnnotationManagers= null;
141139 boolean alreadyShown= fSearchResults.contains(result);
142140 fSearchResults.add(result);
143141 if (!alreadyShown) {
144 for (Iterator<EditorAnnotationManager> mgrs = fAnnotationManagers.values().iterator(); mgrs.hasNext();) {
145 EditorAnnotationManager mgr = mgrs.next();
142 for (EditorAnnotationManager mgr : fAnnotationManagers.values()) {
146143 mgr.addSearchResult(result);
147144 }
148145 }
152149 fSearchResults.remove(result);
153150 boolean stillShown= fSearchResults.contains(result);
154151 if (!stillShown) {
155 for (Iterator<EditorAnnotationManager> mgrs = fAnnotationManagers.values().iterator(); mgrs.hasNext();) {
156 EditorAnnotationManager mgr = mgrs.next();
152 for (EditorAnnotationManager mgr : fAnnotationManagers.values()) {
157153 mgr.removeSearchResult(result);
158154 }
159155 }
7272 @Override
7373 public void run() throws Exception {
7474 IConfigurationElement[] extensions= Platform.getExtensionRegistry().getConfigurationElementsFor(EXTENSION_POINT_ID);
75 for (int i= 0; i < extensions.length; i++) {
76 IConfigurationElement curr= extensions[i];
75 for (IConfigurationElement curr : extensions) {
7776 if (PROVIDER_NODE_NAME.equals(curr.getName()) && id.equals(curr.getAttribute(ATTRIB_ID))) {
7877 res[0]= (TextSearchQueryProvider) curr.createExecutableExtension(ATTRIB_CLASS);
7978 return;
9493 res.add(new String[] { SearchMessages.TextSearchQueryProviderRegistry_defaultProviderLabel, "" }); //$NON-NLS-1$
9594
9695 IConfigurationElement[] extensions= Platform.getExtensionRegistry().getConfigurationElementsFor(EXTENSION_POINT_ID);
97 for (int i= 0; i < extensions.length; i++) {
98 IConfigurationElement engine= extensions[i];
96 for (IConfigurationElement engine : extensions) {
9997 if (PROVIDER_NODE_NAME.equals(engine.getName())) {
10098 res.add(new String[] { engine.getAttribute(ATTRIB_LABEL), engine.getAttribute(ATTRIB_ID) });
10199 }
1313 <parent>
1414 <artifactId>eclipse.platform.text</artifactId>
1515 <groupId>eclipse.platform.text</groupId>
16 <version>4.7.3-SNAPSHOT</version>
16 <version>4.8.0-SNAPSHOT</version>
1717 </parent>
1818 <groupId>org.eclipse.search</groupId>
1919 <artifactId>org.eclipse.search</artifactId>
20 <version>3.11.100-SNAPSHOT</version>
20 <version>3.11.200-SNAPSHOT</version>
2121 <packaging>eclipse-plugin</packaging>
2222 </project>
186186 return fBuf[pos - fOffset];
187187 }
188188
189 public StringBuffer append(StringBuffer buf, int start, int length) {
189 public StringBuilder append(StringBuilder buf, int start, int length) {
190190 return buf.append(fBuf, start - fOffset, length);
191191 }
192192
193 public StringBuffer appendAll(StringBuffer buf) {
193 public StringBuilder appendAll(StringBuilder buf) {
194194 return buf.append(fBuf, 0, fLength);
195195 }
196196
426426 throw new IndexOutOfBoundsException("end must be smaller than length"); //$NON-NLS-1$
427427 }
428428
429 StringBuffer res= new StringBuffer(length);
429 StringBuilder res= new StringBuilder(length);
430430
431431 Buffer buffer= getBuffer(pos);
432432 while (pos < endPos && buffer != null) {
463463 @Override
464464 public String toString() {
465465 int len= fLength != null ? fLength.intValue() : 4000;
466 StringBuffer res= new StringBuffer(len);
466 StringBuilder res= new StringBuilder(len);
467467 try {
468468 Buffer buffer= getBuffer(0);
469469 while (buffer != null) {
142142 public String getFileNamePatternDescription() {
143143 String[] ext= fFileNamePatterns.toArray(new String[fFileNamePatterns.size()]);
144144 Arrays.sort(ext);
145 StringBuffer buf= new StringBuffer();
145 StringBuilder buf= new StringBuilder();
146146 for (int i= 0; i < ext.length; i++) {
147147 if (i > 0) {
148148 buf.append(", "); //$NON-NLS-1$
155155
156156 private static IResource[] removeRedundantEntries(IResource[] elements, boolean includeDerived) {
157157 ArrayList<IResource> res= new ArrayList<>();
158 for (int i= 0; i < elements.length; i++) {
159 IResource curr= elements[i];
158 for (IResource curr : elements) {
160159 addToList(res, curr, includeDerived);
161160 }
162161 return res.toArray(new IResource[res.size()]);
4646 fFiles= new ArrayList<>();
4747 try {
4848 IResource[] roots= fScope.getRoots();
49 for (int i= 0; i < roots.length; i++) {
49 for (IResource resource : roots) {
5050 try {
51 IResource resource= roots[i];
5251 if (resource.isAccessible()) {
5352 resource.accept(this, 0);
5453 }
5252 Assert.isTrue(!isWholeWord, "isWholeWord unsupported together with isRegex"); //$NON-NLS-1$
5353 } else {
5454 int len= pattern.length();
55 StringBuffer buffer= new StringBuffer(len + 10);
55 StringBuilder buffer= new StringBuilder(len + 10);
5656 // don't add a word boundary if the search text does not start with
5757 // a word char. (this works around a user input error).
5858 if (isWholeWord && len > 0 && isWordChar(pattern.charAt(0))) {
8181 */
8282 private static String substituteLinebreak(String findString) throws PatternSyntaxException {
8383 int length= findString.length();
84 StringBuffer buf= new StringBuffer(length);
84 StringBuilder buf= new StringBuilder(length);
8585
8686 int inCharGroup= 0;
8787 int inBraces= 0;
165165 * @throws PatternSyntaxException if "\R" is at an illegal position
166166 */
167167 public static Pattern createPattern(String[] patterns, boolean isCaseSensitive) throws PatternSyntaxException {
168 StringBuffer pattern= new StringBuffer();
168 StringBuilder pattern= new StringBuilder();
169169 for (int i= 0; i < patterns.length; i++) {
170170 if (i > 0) {
171171 // note that this works only as we know that the operands of the
178178 }
179179
180180
181 public static StringBuffer appendAsRegEx(boolean isStringMatcher, String pattern, StringBuffer buffer) {
181 public static StringBuilder appendAsRegEx(boolean isStringMatcher, String pattern, StringBuilder buffer) {
182182 boolean isEscaped= false;
183183 for (int i = 0; i < pattern.length(); i++) {
184184 char c = pattern.charAt(i);
296296 private String interpretReplaceEscapes(String replaceText, String foundText) {
297297 int length= replaceText.length();
298298 boolean inEscape= false;
299 StringBuffer buf= new StringBuffer(length);
299 StringBuilder buf= new StringBuilder(length);
300300
301301 /* every string we did not check looks mixed at first
302302 * so initialize retain case mode with RC_MIXED
357357 * @return the new offset
358358 * @since 3.4
359359 */
360 private int interpretReplaceEscape(final char ch, int i, StringBuffer buf, String replaceText, String foundText) {
360 private int interpretReplaceEscape(final char ch, int i, StringBuilder buf, String replaceText, String foundText) {
361361 int length= replaceText.length();
362362 switch (ch) {
363363 case 'r':
487487 * @param ch the character to process
488488 * @since 3.4
489489 */
490 private void interpretRetainCase(StringBuffer buf, char ch) {
490 private void interpretRetainCase(StringBuilder buf, char ch) {
491491 if (fRetainCaseMode == RC_UPPER)
492492 buf.append(String.valueOf(ch).toUpperCase());
493493 else if (fRetainCaseMode == RC_LOWER)
8181 @Override
8282 public void run() throws Exception {
8383 IConfigurationElement[] extensions= Platform.getExtensionRegistry().getConfigurationElementsFor(EXTENSION_POINT_ID);
84 for (int i= 0; i < extensions.length; i++) {
85 IConfigurationElement curr= extensions[i];
84 for (IConfigurationElement curr : extensions) {
8685 if (ENGINE_NODE_NAME.equals(curr.getName()) && id.equals(curr.getAttribute(ATTRIB_ID))) {
8786 res[0]= (TextSearchEngine) curr.createExecutableExtension(ATTRIB_CLASS);
8887 return;
103102 res.add(new String[] { SearchMessages.TextSearchEngineRegistry_defaulttextsearch_label, "" }); //$NON-NLS-1$
104103
105104 IConfigurationElement[] extensions= Platform.getExtensionRegistry().getConfigurationElementsFor(EXTENSION_POINT_ID);
106 for (int i= 0; i < extensions.length; i++) {
107 IConfigurationElement engine= extensions[i];
105 for (IConfigurationElement engine : extensions) {
108106 if (ENGINE_NODE_NAME.equals(engine.getName())) {
109107 res.add(new String[] { engine.getAttribute(ATTRIB_LABEL), engine.getAttribute(ATTRIB_ID) });
110108 }
00 /*******************************************************************************
1 * Copyright (c) 2000, 2016 IBM Corporation and others.
1 * Copyright (c) 2000, 2018 IBM Corporation and others.
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
1818 import java.util.ArrayList;
1919 import java.util.Arrays;
2020 import java.util.Collections;
21 import java.util.Comparator;
2221 import java.util.HashMap;
2322 import java.util.List;
2423 import java.util.Map;
8079 public static final boolean TRACING= "true".equalsIgnoreCase(Platform.getDebugOption("org.eclipse.search/perf")); //$NON-NLS-1$ //$NON-NLS-2$
8180 private static final int NUMBER_OF_LOGICAL_THREADS= Runtime.getRuntime().availableProcessors();
8281 private static final int FILES_PER_JOB= 50;
82 private static final int MAX_JOBS_COUNT= 100;
8383
8484 public static class ReusableMatchAccess extends TextSearchMatchAccess {
8585
168168 public TextSearchJob(IFile[] files, int begin, int end, Map<IFile, IDocument> documentsInEditors) {
169169 super(files[begin].getName());
170170 setSystem(true);
171 fFiles = files;
172 fBegin = begin;
173 fEnd = end;
174 fDocumentsInEditors = documentsInEditors;
171 fFiles= files;
172 fBegin= begin;
173 fEnd= end;
174 fDocumentsInEditors= documentsInEditors;
175175 }
176176
177177 @Override
178178 protected IStatus run(IProgressMonitor inner) {
179179 MultiStatus multiStatus=
180180 new MultiStatus(NewSearchUI.PLUGIN_ID, IStatus.OK, SearchMessages.TextSearchEngine_statusMessage, null);
181 SubMonitor subMonitor = SubMonitor.convert(inner, fEnd - fBegin);
182 this.fileCharSequenceProvider = new FileCharSequenceProvider();
183 for (int i = fBegin; i < fEnd && !fFatalError; i++) {
181 SubMonitor subMonitor= SubMonitor.convert(inner, fEnd - fBegin);
182 this.fileCharSequenceProvider= new FileCharSequenceProvider();
183 for (int i= fBegin; i < fEnd && !fFatalError; i++) {
184184 IStatus status= processFile(fFiles[i], subMonitor.split(1));
185185 // Only accumulate interesting status
186186 if (!status.isOK())
193193 fileCharSequenceProvider.releaseCharSequence(charsequenceForPreviousLocation);
194194 } catch (IOException e) {
195195 SearchPlugin.log(e);
196 }
197 }
196 } finally {
197 charsequenceForPreviousLocation= null;
198 }
199 }
200 fileCharSequenceProvider= null;
201 previousLocationFromFile= null;
202 occurencesForPreviousLocation= null;
198203 return multiStatus;
199204 }
200205
215220 locateMatches(file, documentCharSequence, matcher, monitor);
216221 } else if (previousLocationFromFile != null && previousLocationFromFile.equals(file.getLocation()) && !occurencesForPreviousLocation.isEmpty()) {
217222 // reuse previous result
218 ReusableMatchAccess matchAccess = new ReusableMatchAccess();
223 ReusableMatchAccess matchAccess= new ReusableMatchAccess();
219224 for (TextSearchMatchAccess occurence : occurencesForPreviousLocation) {
220225 matchAccess.initialize(file, occurence.getMatchOffset(), occurence.getMatchLength(), charsequenceForPreviousLocation);
221 boolean goOn = fCollector.acceptPatternMatch(matchAccess);
226 boolean goOn= fCollector.acceptPatternMatch(matchAccess);
222227 if (!goOn) {
223228 break;
224229 }
227232 if (charsequenceForPreviousLocation != null) {
228233 try {
229234 fileCharSequenceProvider.releaseCharSequence(charsequenceForPreviousLocation);
230 charsequenceForPreviousLocation = null;
235 charsequenceForPreviousLocation= null;
231236 } catch (IOException e) {
232237 SearchPlugin.log(e);
233238 }
235240 try {
236241 charsequenceForPreviousLocation= fileCharSequenceProvider.newCharSequence(file);
237242 if (hasBinaryContent(charsequenceForPreviousLocation, file) && !fCollector.reportBinaryFile(file)) {
238 occurencesForPreviousLocation = Collections.emptyList();
243 occurencesForPreviousLocation= Collections.emptyList();
239244 return Status.OK_STATUS;
240245 }
241 occurencesForPreviousLocation = locateMatches(file, charsequenceForPreviousLocation, matcher, monitor);
242 previousLocationFromFile = file.getLocation();
246 occurencesForPreviousLocation= locateMatches(file, charsequenceForPreviousLocation, matcher, monitor);
247 previousLocationFromFile= file.getLocation();
243248 } catch (FileCharSequenceProvider.FileCharSequenceException e) {
244249 e.throwWrappedException();
245250 }
264269 String message= Messages.format(SearchMessages.TextSearchVisitor_error, args);
265270 return new Status(IStatus.ERROR, NewSearchUI.PLUGIN_ID, IStatus.ERROR, message, e);
266271 } catch (StackOverflowError e) {
267 fFatalError = true;
272 fFatalError= true;
268273 String message= SearchMessages.TextSearchVisitor_patterntoocomplex0;
269274 return new Status(IStatus.ERROR, NewSearchUI.PLUGIN_ID, IStatus.ERROR, message, e);
270275 } finally {
319324 int jobCount= 1;
320325 if (maxThreads > 1) {
321326 jobCount= (files.length + FILES_PER_JOB - 1) / FILES_PER_JOB;
327 }
328 // Too many job references can cause OOM, see bug 514961
329 if (jobCount > MAX_JOBS_COUNT) {
330 jobCount= MAX_JOBS_COUNT;
322331 }
323332 final JobGroup jobGroup= new TextSearchJobGroup("Text Search", maxThreads, jobCount); //$NON-NLS-1$
324333 long startTime= TRACING ? System.currentTimeMillis() : 0;
369378 try {
370379 fCollector.beginReporting();
371380 Map<IFile, IDocument> documentsInEditors= PlatformUI.isWorkbenchRunning() ? evalNonFileBufferDocuments() : Collections.emptyMap();
372 int filesPerJob = (files.length + jobCount - 1) / jobCount;
373 IFile[] filesByLocation = new IFile[files.length];
381 int filesPerJob = Math.max(1, files.length / jobCount);
382 IFile[] filesByLocation= new IFile[files.length];
374383 System.arraycopy(files, 0, filesByLocation, 0, files.length);
375384 // Sorting files to search by location allows to more easily reuse
376385 // search results from one file to the other when they have same location
377 Arrays.sort(filesByLocation, new Comparator<IFile>() {
378 @Override
379 public int compare(IFile o1, IFile o2) {
380 if (o1 == o2) {
381 return 0;
382 }
383 if (o1.getLocation() == o2.getLocation()) {
384 return 0;
385 }
386 if (o1.getLocation() == null) {
387 return +1;
388 }
389 if (o2.getLocation() == null) {
390 return -1;
391 }
392 return o1.getLocation().toString().compareTo(o2.getLocation().toString());
393 }
386 Arrays.sort(filesByLocation, (o1, o2) -> {
387 if (o1 == o2) {
388 return 0;
389 }
390 if (o1.getLocation() == o2.getLocation()) {
391 return 0;
392 }
393 if (o1.getLocation() == null) {
394 return +1;
395 }
396 if (o2.getLocation() == null) {
397 return -1;
398 }
399 return o1.getLocation().toString().compareTo(o2.getLocation().toString());
394400 });
395401 for (int first= 0; first < filesByLocation.length; first += filesPerJob) {
396402 int end= Math.min(filesByLocation.length, first + filesPerJob);
416422 fProgressMonitor.done();
417423 fCollector.endReporting();
418424 if (TRACING) {
419 Object[] args= { Integer.valueOf(fNumberOfScannedFiles), Integer.valueOf(jobCount), Integer.valueOf(NUMBER_OF_LOGICAL_THREADS), new Long(System.currentTimeMillis() - startTime) };
425 Object[] args= { Integer.valueOf(fNumberOfScannedFiles), Integer.valueOf(jobCount), Integer.valueOf(NUMBER_OF_LOGICAL_THREADS), Long.valueOf(System.currentTimeMillis() - startTime) };
420426 System.out.println(Messages.format(
421427 "[TextSearch] Search duration for {0} files in {1} jobs using {2} threads: {3}ms", args)); //$NON-NLS-1$
422428 }
437443 Map<IFile, IDocument> result= new HashMap<>();
438444 IWorkbench workbench= SearchPlugin.getDefault().getWorkbench();
439445 IWorkbenchWindow[] windows= workbench.getWorkbenchWindows();
440 for (int i= 0; i < windows.length; i++) {
441 IWorkbenchPage[] pages= windows[i].getPages();
442 for (int x= 0; x < pages.length; x++) {
443 IEditorReference[] editorRefs= pages[x].getEditorReferences();
444 for (int z= 0; z < editorRefs.length; z++) {
445 IEditorPart ep= editorRefs[z].getEditor(false);
446 for (IWorkbenchWindow window : windows) {
447 IWorkbenchPage[] pages= window.getPages();
448 for (IWorkbenchPage page : pages) {
449 IEditorReference[] editorRefs= page.getEditorReferences();
450 for (IEditorReference editorRef : editorRefs) {
451 IEditorPart ep= editorRef.getEditor(false);
446452 if (ep instanceof ITextEditor && ep.isDirty()) { // only dirty editors
447453 evaluateTextEditor(result, ep);
448454 }
501507 }
502508
503509 private List<TextSearchMatchAccess> locateMatches(IFile file, CharSequence searchInput, Matcher matcher, IProgressMonitor monitor) throws CoreException {
504 List<TextSearchMatchAccess> occurences = null;
510 List<TextSearchMatchAccess> occurences= null;
505511 matcher.reset(searchInput);
506512 int k= 0;
507513 while (matcher.find()) {
508514 if (occurences == null) {
509 occurences = new ArrayList<>();
515 occurences= new ArrayList<>();
510516 }
511517 int start= matcher.start();
512518 int end= matcher.end();
513519 if (end != start) { // don't report 0-length matches
514 ReusableMatchAccess access = new ReusableMatchAccess();
520 ReusableMatchAccess access= new ReusableMatchAccess();
515521 access.initialize(file, start, end - start, searchInput);
516522 occurences.add(access);
517523 boolean res= fCollector.acceptPatternMatch(access);
525531 }
526532 }
527533 if (occurences == null) {
528 occurences = Collections.emptyList();
534 occurences= Collections.emptyList();
529535 }
530536 return occurences;
531537 }
107107
108108 IBaseLabelProvider labelProvider= fViewer.getLabelProvider();
109109 String lineDelim= System.getProperty("line.separator"); //$NON-NLS-1$
110 StringBuffer buf= new StringBuffer();
110 StringBuilder buf= new StringBuilder();
111111 Iterator<?> iter= getSelection();
112112 while (iter.hasNext()) {
113113 if (buf.length() > 0) {
1010 *******************************************************************************/
1111 package org.eclipse.search.internal.ui;
1212
13 import java.util.Iterator;
1413 import java.util.List;
1514
1615 import org.eclipse.swt.events.MenuAdapter;
7675 private void fillMenu(final Menu localMenu) {
7776 List<SearchPageDescriptor> pageDescriptors= SearchPlugin.getDefault().getSearchPageDescriptors();
7877 int accelerator= 1;
79 for (Iterator<SearchPageDescriptor> iter= pageDescriptors.iterator(); iter.hasNext();) {
80 SearchPageDescriptor desc= iter.next();
78 for (SearchPageDescriptor desc : pageDescriptors) {
8179 if (!WorkbenchActivityHelper.filterItem(desc) && desc.isEnabled()) {
8280 SearchPageAction action= new SearchPageAction(fWorkbenchWindow, desc);
8381 addToMenu(localMenu, action, accelerator++);
8684 localMenu.addMenuListener(new MenuAdapter() {
8785 @Override
8886 public void menuHidden(MenuEvent e) {
89 e.display.asyncExec(new Runnable() {
90 @Override
91 public void run() {
92 localMenu.dispose();
93 }
94 });
87 e.display.asyncExec(() -> localMenu.dispose());
9588 }
9689 });
9790
9891 }
9992
10093 private void addToMenu(Menu localMenu, IAction action, int accelerator) {
101 StringBuffer label= new StringBuffer();
94 StringBuilder label= new StringBuilder();
10295 if (accelerator >= 0 && accelerator < 10) {
10396 //add the numerical accelerator
10497 label.append('&');
5151 public void run() {
5252 final IMarker[] markers= getMarkers(fSelectionProvider.getSelection());
5353 if (markers != null) {
54 BusyIndicator.showWhile(SearchPlugin.getActiveWorkbenchShell().getDisplay(), new Runnable() {
55 @Override
56 public void run() {
57 try {
58 SearchPlugin.getWorkspace().deleteMarkers(markers);
59 } catch (CoreException ex) {
60 ExceptionHandler.handle(ex, SearchMessages.Search_Error_deleteMarkers_title, SearchMessages.Search_Error_deleteMarkers_message);
61 }
54 BusyIndicator.showWhile(SearchPlugin.getActiveWorkbenchShell().getDisplay(), () -> {
55 try {
56 SearchPlugin.getWorkspace().deleteMarkers(markers);
57 } catch (CoreException ex) {
58 ExceptionHandler.handle(ex, SearchMessages.Search_Error_deleteMarkers_title, SearchMessages.Search_Error_deleteMarkers_message);
6259 }
6360 });
6461 }
00 /*******************************************************************************
1 * Copyright (c) 2000, 2011 IBM Corporation and others.
1 * Copyright (c) 2000, 2017 IBM Corporation and others.
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
66 *
77 * Contributors:
88 * IBM Corporation - initial API and implementation
9 * Lucas Bullen (Red Hat Inc.) - [Bug 526453] disambiguate "Selected Resources"
910 *******************************************************************************/
1011 package org.eclipse.search.internal.ui;
1112
13 import java.util.ArrayList;
1214 import java.util.Arrays;
15 import java.util.Collections;
1316 import java.util.HashSet;
17 import java.util.Iterator;
18 import java.util.List;
1419 import java.util.Set;
20
21 import org.eclipse.osgi.util.NLS;
1522
1623 import org.eclipse.swt.SWT;
1724 import org.eclipse.swt.accessibility.AccessibleAdapter;
2633 import org.eclipse.swt.widgets.Text;
2734
2835 import org.eclipse.core.runtime.Assert;
36 import org.eclipse.core.runtime.IAdaptable;
2937 import org.eclipse.core.runtime.IStatus;
3038 import org.eclipse.core.runtime.Status;
39
40 import org.eclipse.core.resources.IFile;
41 import org.eclipse.core.resources.IResource;
3142
3243 import org.eclipse.jface.dialogs.IDialogSettings;
3344 import org.eclipse.jface.layout.PixelConverter;
4152 import org.eclipse.ui.PlatformUI;
4253 import org.eclipse.ui.dialogs.IWorkingSetSelectionDialog;
4354
55 import org.eclipse.search.internal.ui.text.LineElement;
4456 import org.eclipse.search.internal.ui.util.SWTUtil;
4557 import org.eclipse.search.ui.ISearchPageContainer;
4658 import org.eclipse.search.ui.NewSearchUI;
125137 IWorkingSetManager workingSetManager= PlatformUI.getWorkbench().getWorkingSetManager();
126138 if (lruWorkingSetNames != null) {
127139 Set<IWorkingSet> existingWorkingSets= new HashSet<>(lruWorkingSetNames.length);
128 for (int i= 0; i < lruWorkingSetNames.length; i++) {
129 IWorkingSet workingSet= getWorkingSet(workingSetManager, lruWorkingSetNames[i]);
140 for (String lruWorkingSetName : lruWorkingSetNames) {
141 IWorkingSet workingSet= getWorkingSet(workingSetManager, lruWorkingSetName);
130142 if (workingSet != null) {
131143 existingWorkingSets.add(workingSet);
132144 }
147159 return null;
148160 }
149161
162 public static List<IResource> selectedResourcesFromContainer(ISearchPageContainer container) {
163 if (container == null)
164 return Collections.emptyList();
165 ISelection selection = container.getSelection();
166 List<IResource> resources = new ArrayList<>();
167 if (!(selection instanceof IStructuredSelection) || selection.isEmpty()) {
168 if (container.getActiveEditorInput() != null) {
169 resources.add(container.getActiveEditorInput().getAdapter(IFile.class));
170 }
171 return resources;
172 }
173 Iterator<?> iter = ((IStructuredSelection) selection).iterator();
174 while (iter.hasNext()) {
175 Object curr = iter.next();
176 if (curr instanceof IWorkingSet) {
177 IWorkingSet workingSet = (IWorkingSet) curr;
178 if (workingSet.isAggregateWorkingSet() && workingSet.isEmpty()) {
179 continue;
180 }
181 IAdaptable[] elements = workingSet.getElements();
182 for (IAdaptable element : elements) {
183 IResource resource = element.getAdapter(IResource.class);
184 if (resource != null && resource.isAccessible()) {
185 resources.add(resource);
186 }
187 }
188 } else if (curr instanceof LineElement) {
189 IResource resource = ((LineElement) curr).getParent();
190 if (resource != null && resource.isAccessible())
191 resources.add(resource);
192 } else if (curr instanceof IAdaptable) {
193 IResource resource = ((IAdaptable) curr).getAdapter(IResource.class);
194 if (resource != null && resource.isAccessible()) {
195 resources.add(resource);
196 }
197 }
198 }
199 return resources;
200 }
201
202 private String getSelectedResurcesButtonText() {
203 int size = selectedResourcesFromContainer(fSearchDialog).size();
204 if (size == 1) {
205 if (fSearchDialog.getActiveEditor() != null)
206 return SearchMessages.ScopePart_selectedResourcesScope_text_editor;
207 return NLS.bind(SearchMessages.ScopePart_selectedResourcesScope_text_singular,
208 fSearchDialog.getWorkbenchWindow().getActivePage().getActivePart().getTitle());
209 }
210 if (size > 1)
211 return NLS.bind(SearchMessages.ScopePart_selectedResourcesScope_text_plural, Integer.valueOf(size),
212 fSearchDialog.getWorkbenchWindow().getActivePage().getActivePart().getTitle());
213 return SearchMessages.ScopePart_selectedResourcesScope_text;
214 }
215
216 private String getEnclosingProjectsButtonText() {
217 int size = fSearchDialog.getEnclosingProjectNames().length;
218 if (size == 1)
219 return SearchMessages.ScopePart_enclosingProjectsScope_text_singular;
220 if (size > 1)
221 return NLS.bind(SearchMessages.ScopePart_enclosingProjectsScope_text_plural, Integer.valueOf(size));
222 return SearchMessages.ScopePart_enclosingProjectsScope_text;
223 }
150224
151225 /**
152226 * Returns the scope selected in this part
230304 setSelectedScope(ISearchPageContainer.WORKING_SET_SCOPE);
231305 fWorkingSets= null;
232306 Set<IWorkingSet> existingWorkingSets= new HashSet<>(workingSets.length);
233 for (int i= 0; i < workingSets.length; i++) {
234 String name= workingSets[i].getName();
307 for (IWorkingSet workingSet2 : workingSets) {
308 String name= workingSet2.getName();
235309 IWorkingSet workingSet= PlatformUI.getWorkbench().getWorkingSetManager().getWorkingSet(name);
236310 if (workingSet != null)
237311 existingWorkingSets.add(workingSet);
282356
283357 fUseSelection= new Button(fPart, SWT.RADIO);
284358 fUseSelection.setData(Integer.valueOf(ISearchPageContainer.SELECTION_SCOPE));
285 fUseSelection.setText(SearchMessages.ScopePart_selectedResourcesScope_text);
359 fUseSelection.setText(getSelectedResurcesButtonText());
286360
287361 boolean canSearchInSelection= canSearchInSelection();
288362 fUseSelection.setEnabled(canSearchInSelection);
293367
294368 fUseProject= new Button(fPart, SWT.RADIO);
295369 fUseProject.setData(Integer.valueOf(ISearchPageContainer.SELECTED_PROJECTS_SCOPE));
296 fUseProject.setText(SearchMessages.ScopePart_enclosingProjectsScope_text);
370 fUseProject.setText(getEnclosingProjectsButtonText());
297371 fUseProject.setEnabled(fSearchDialog.getEnclosingProjectNames().length > 0);
298372
299373 gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
416490 if (workingSets != null && workingSets.length > 0) {
417491 Arrays.sort(workingSets, new WorkingSetComparator());
418492 boolean firstFound= false;
419 for (int i= 0; i < workingSets.length; i++) {
420 String workingSetName= workingSets[i].getLabel();
493 for (IWorkingSet workingSet : workingSets) {
494 String workingSetName= workingSet.getLabel();
421495 if (firstFound)
422496 result= Messages.format(SearchMessages.ScopePart_workingSetConcatenation, new String[] { result, workingSetName });
423497 else {
2222 import org.eclipse.swt.custom.BusyIndicator;
2323 import org.eclipse.swt.custom.CTabFolder;
2424 import org.eclipse.swt.custom.CTabItem;
25 import org.eclipse.swt.events.DisposeEvent;
26 import org.eclipse.swt.events.DisposeListener;
2725 import org.eclipse.swt.events.SelectionAdapter;
2826 import org.eclipse.swt.events.SelectionEvent;
2927 import org.eclipse.swt.events.SelectionListener;
6159 import org.eclipse.jface.resource.ImageDescriptor;
6260 import org.eclipse.jface.util.SafeRunnable;
6361 import org.eclipse.jface.viewers.ArrayContentProvider;
64 import org.eclipse.jface.viewers.CheckStateChangedEvent;
6562 import org.eclipse.jface.viewers.CheckboxTableViewer;
66 import org.eclipse.jface.viewers.ICheckStateListener;
6763 import org.eclipse.jface.viewers.ILabelProvider;
6864 import org.eclipse.jface.viewers.ISelection;
6965 import org.eclipse.jface.viewers.IStructuredSelection;
106102 int x= 0;
107103 int y= 0;
108104 Control[] children= composite.getChildren();
109 for (int i= 0; i < children.length; i++) {
110 Point size= children[i].computeSize(SWT.DEFAULT, SWT.DEFAULT, flushCache);
105 for (Control element : children) {
106 Point size= element.computeSize(SWT.DEFAULT, SWT.DEFAULT, flushCache);
111107 x= Math.max(x, size.x);
112108 y= Math.max(y, size.y);
113109 }
127123 Rectangle rect= composite.getClientArea();
128124
129125 Control[] children= composite.getChildren();
130 for (int i= 0; i < children.length; i++) {
131 children[i].setBounds(rect);
126 for (Control element : children) {
127 element.setBounds(rect);
132128 }
133129 }
134130 }
203199 IWorkingSet workingSet= (IWorkingSet) curr;
204200 if (workingSet.isAggregateWorkingSet() && workingSet.isEmpty()) {
205201 IProject[] projects= ResourcesPlugin.getWorkspace().getRoot().getProjects();
206 for (int i= 0; i < projects.length; i++) {
207 IProject proj= projects[i];
202 for (IProject proj : projects) {
208203 if (proj.isOpen()) {
209204 res.add(proj.getName());
210205 }
211206 }
212207 } else {
213208 IAdaptable[] elements= workingSet.getElements();
214 for (int i= 0; i < elements.length; i++) {
215 String name= evaluateEnclosingProject(elements[i]);
209 for (IAdaptable element : elements) {
210 String name= evaluateEnclosingProject(element);
216211 if (name != null) {
217212 res.add(name);
218213 }
342337 super.create();
343338 final CheckboxTableViewer viewer= getViewer();
344339 final Button okButton= this.getOkButton();
345 viewer.addCheckStateListener(new ICheckStateListener() {
346 @Override
347 public void checkStateChanged(CheckStateChangedEvent event) {
348 okButton.setEnabled(viewer.getCheckedElements().length > 0);
349 }
350 });
340 viewer.addCheckStateListener(event -> okButton.setEnabled(viewer.getCheckedElements().length > 0));
351341 SelectionListener listener = new SelectionAdapter() {
352342 @Override
353343 public void widgetSelected(SelectionEvent e) {
381371 close();
382372 if (display != null && !display.isDisposed()) {
383373 display.asyncExec(
384 new Runnable() {
385 @Override
386 public void run() {
387 new OpenSearchDialogAction().run();
388 }
389 });
374 () -> new OpenSearchDialogAction().run());
390375 }
391376 }
392377 destroyImages(createdImages);
394379
395380 private List<SearchPageDescriptor> filterByActivities(List<SearchPageDescriptor> input) {
396381 ArrayList<SearchPageDescriptor> filteredList= new ArrayList<>(input.size());
397 for (Iterator<SearchPageDescriptor> descriptors= input.iterator(); descriptors.hasNext();) {
398 SearchPageDescriptor descriptor= descriptors.next();
382 for (SearchPageDescriptor descriptor : input) {
399383 if (!WorkbenchActivityHelper.filterItem(descriptor))
400384 filteredList.add(descriptor);
401385
448432 final CTabItem item = new CTabItem(folder, SWT.NONE);
449433 item.setData("descriptor", descriptor); //$NON-NLS-1$
450434 item.setText(descriptor.getLabel());
451 item.addDisposeListener(new DisposeListener() {
452 @Override
453 public void widgetDisposed(DisposeEvent e) {
454 item.setData("descriptor", null); //$NON-NLS-1$
455 if (item.getImage() != null)
456 item.getImage().dispose();
457 }
435 item.addDisposeListener(e -> {
436 item.setData("descriptor", null); //$NON-NLS-1$
437 if (item.getImage() != null)
438 item.getImage().dispose();
458439 });
459440 ImageDescriptor imageDesc= descriptor.getImage();
460441 if (imageDesc != null)
758739
759740 applyDialogFont(pageWrapper);
760741
761 BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() {
742 BusyIndicator.showWhile(getShell().getDisplay(), () -> SafeRunner.run(new ISafeRunnable() {
762743 @Override
763 public void run() {
764 SafeRunner.run(new ISafeRunnable() {
765 @Override
766 public void run() throws Exception {
767 // create page and control
768 ISearchPage page= descriptor.createObject(SearchDialog.this);
769 if (page != null) {
770 page.createControl(pageWrapper);
771 }
772 }
773 @Override
774 public void handleException(Throwable ex) {
775 if (ex instanceof CoreException) {
776 ExceptionHandler.handle((CoreException) ex, getShell(), SearchMessages.Search_Error_createSearchPage_title, Messages.format(SearchMessages.Search_Error_createSearchPage_message, descriptor.getLabel()));
777 } else {
778 ExceptionHandler.displayMessageDialog(ex, getShell(), SearchMessages.Search_Error_createSearchPage_title, Messages.format(SearchMessages.Search_Error_createSearchPage_message, descriptor.getLabel()));
779 }
780 }
781 });
782 }
783 });
744 public void run() throws Exception {
745 // create page and control
746 ISearchPage page= descriptor.createObject(SearchDialog.this);
747 if (page != null) {
748 page.createControl(pageWrapper);
749 }
750 }
751 @Override
752 public void handleException(Throwable ex) {
753 if (ex instanceof CoreException) {
754 ExceptionHandler.handle((CoreException) ex, getShell(), SearchMessages.Search_Error_createSearchPage_title, Messages.format(SearchMessages.Search_Error_createSearchPage_message, descriptor.getLabel()));
755 } else {
756 ExceptionHandler.displayMessageDialog(ex, getShell(), SearchMessages.Search_Error_createSearchPage_title, Messages.format(SearchMessages.Search_Error_createSearchPage_message, descriptor.getLabel()));
757 }
758 }
759 }));
784760
785761 ISearchPage page= descriptor.getPage();
786762 if (page == null || page.getControl() == null) {
235235 if (display != null && !display.isDisposed()) {
236236 final String warningTitle= SearchMessages.SearchManager_resourceChangedWarning;
237237 final String warningMsg= warningMessage;
238 display.syncExec(new Runnable() {
239 @Override
240 public void run() {
241 MessageDialog.openWarning(getShell(), warningTitle, warningMsg);
242 }
243 });
238 display.syncExec(() -> MessageDialog.openWarning(getShell(), warningTitle, warningMsg));
244239 }
245240 }
246241
250245 final Viewer visibleViewer= ((SearchResultView)SearchUI.getSearchResultView()).getViewer();
251246 while (iter2.hasNext()) {
252247 final SearchResultViewer viewer= iter2.next();
253 display.syncExec(new Runnable() {
254 @Override
255 public void run() {
256 if (previousSearch != null && viewer == visibleViewer)
257 previousSearch.setSelection(viewer.getSelection());
258 viewer.setInput(null);
259 viewer.setPageId(search.getPageId());
260 viewer.setGotoMarkerAction(search.getGotoMarkerAction());
261 viewer.setContextMenuTarget(search.getContextMenuContributor());
262 viewer.setActionGroupFactory(null);
263 viewer.setInput(getCurrentResults());
264 viewer.setActionGroupFactory(search.getActionGroupFactory());
265 viewer.setSelection(fCurrentSearch.getSelection(), true);
266 }
248 display.syncExec(() -> {
249 if (previousSearch != null && viewer == visibleViewer)
250 previousSearch.setSelection(viewer.getSelection());
251 viewer.setInput(null);
252 viewer.setPageId(search.getPageId());
253 viewer.setGotoMarkerAction(search.getGotoMarkerAction());
254 viewer.setContextMenuTarget(search.getContextMenuContributor());
255 viewer.setActionGroupFactory(null);
256 viewer.setInput(getCurrentResults());
257 viewer.setActionGroupFactory(search.getActionGroupFactory());
258 viewer.setSelection(fCurrentSearch.getSelection(), true);
267259 });
268260 }
269261 }
301293 final Viewer visibleViewer= ((SearchResultView)SearchUI.getSearchResultView()).getViewer();
302294 while (iter.hasNext()) {
303295 final SearchResultViewer viewer= iter.next();
304 display.syncExec(new Runnable() {
305 @Override
306 public void run() {
307 if (fCurrentSearch != null && viewer == visibleViewer)
308 fCurrentSearch.setSelection(viewer.getSelection());
309 setNewSearch(viewer, newSearch);
310 }
296 display.syncExec(() -> {
297 if (fCurrentSearch != null && viewer == visibleViewer)
298 fCurrentSearch.setSelection(viewer.getSelection());
299 setNewSearch(viewer, newSearch);
311300 });
312301 }
313302 }
340329 if (Thread.currentThread() == display.getThread())
341330 handleNewSearchResult();
342331 else {
343 display.syncExec(new Runnable() {
344 @Override
345 public void run() {
346 handleNewSearchResult();
347 }
348 });
332 display.syncExec(() -> handleNewSearchResult());
349333 }
350334 SearchPlugin.getWorkspace().addResourceChangeListener(this);
351335 }
372356 while (iter.hasNext())
373357 iter.next().getControl().setRedraw(false);
374358
375 for (int i=0; i < markerDeltas.length; i++) {
376 handleSearchMarkerChanged(markerDeltas[i]);
359 for (IMarkerDelta markerDelta : markerDeltas) {
360 handleSearchMarkerChanged(markerDelta);
377361 }
378362
379363 iter= fListeners.iterator();
472456 if (display == null || display.isDisposed())
473457 return;
474458
475 Runnable runnable= new Runnable() {
476 @Override
477 public void run() {
478 if (getCurrentSearch() != null) {
479 handleSearchMarkersChanged(markerDeltas);
480 // update title and actions
481 Iterator<SearchResultViewer> iter= fListeners.iterator();
482 while (iter.hasNext()) {
483 SearchResultViewer viewer= iter.next();
484 viewer.enableActions();
485 viewer.updateTitle();
486 }
459 Runnable runnable= () -> {
460 if (getCurrentSearch() != null) {
461 handleSearchMarkersChanged(markerDeltas);
462 // update title and actions
463 Iterator<SearchResultViewer> iter= fListeners.iterator();
464 while (iter.hasNext()) {
465 SearchResultViewer viewer= iter.next();
466 viewer.enableActions();
467 viewer.updateTitle();
487468 }
488469 }
489470 };
00 /*******************************************************************************
1 * Copyright (c) 2000, 2015 IBM Corporation and others.
1 * Copyright (c) 2000, 2017 IBM Corporation and others.
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
88 * IBM Corporation - initial API and implementation
99 * Christian Walther (Indel AG) - Bug 399094: Add whole word option to file search
1010 * Marco Descher <marco@descher.at> - Open Search dialog with previous page instead of using the current selection to detect the page - http://bugs.eclipse.org/33710
11 * Lucas Bullen (Red Hat Inc.) - [Bug 526453] disambiguate "Selected Resources"
1112 *******************************************************************************/
1213 package org.eclipse.search.internal.ui;
1314
172173 public static String WorkspaceScope;
173174 public static String ScopePart_group_text;
174175 public static String ScopePart_selectedResourcesScope_text;
176 public static String ScopePart_selectedResourcesScope_text_plural;
177 public static String ScopePart_selectedResourcesScope_text_singular;
178 public static String ScopePart_selectedResourcesScope_text_editor;
175179 public static String ScopePart_enclosingProjectsScope_text;
180 public static String ScopePart_enclosingProjectsScope_text_plural;
181 public static String ScopePart_enclosingProjectsScope_text_singular;
176182 public static String ScopePart_workingSetChooseButton_text;
177183 public static String ScopePart_workingSetText_accessible_label;
178184 public static String ScopePart_workingSetScope_text;
00 ###############################################################################
1 # Copyright (c) 2000, 2015 IBM Corporation and others.
1 # Copyright (c) 2000, 2017 IBM Corporation and others.
22 # All rights reserved. This program and the accompanying materials
33 # are made available under the terms of the Eclipse Public License v1.0
44 # which accompanies this distribution, and is available at
88 # IBM Corporation - initial API and implementation
99 # Christian Walther (Indel AG) - Bug 399094: Add whole word option to file search
1010 # Marco Descher <marco@descher.at> - Open Search dialog with previous page instead of using the current selection to detect the page - http://bugs.eclipse.org/33710
11 # Lucas Bullen (Red Hat Inc.) - [Bug 526453] disambiguate "Selected Resources"
1112 ###############################################################################
1213
1314 SearchDialog_title= Search
180181
181182 ScopePart_group_text= Scope
182183 ScopePart_selectedResourcesScope_text=Selecte&d resources
184 ScopePart_selectedResourcesScope_text_plural={0} selecte&d resources in ''{1}''
185 ScopePart_selectedResourcesScope_text_singular=Selecte&d resource in ''{0}''
186 ScopePart_selectedResourcesScope_text_editor=Resource in active e&ditor
183187 ScopePart_enclosingProjectsScope_text=Enclosing pro&jects
188 ScopePart_enclosingProjectsScope_text_plural={0} enclosing pro&jects
189 ScopePart_enclosingProjectsScope_text_singular=Enclosing pro&ject
184190 ScopePart_workingSetChooseButton_text= C&hoose...
185191 ScopePart_workingSetText_accessible_label=Working set name
186192 ScopePart_workingSetScope_text=Wor&king set:
232232
233233 static void setEnabled(Object[] enabledDescriptors) {
234234 fgEnabledPageIds= new ArrayList<>(5);
235 for (int i= 0; i < enabledDescriptors.length; i++) {
236 if (enabledDescriptors[i] instanceof SearchPageDescriptor)
237 fgEnabledPageIds.add(((SearchPageDescriptor)enabledDescriptors[i]).getId());
235 for (Object enabledDescriptor : enabledDescriptors) {
236 if (enabledDescriptor instanceof SearchPageDescriptor)
237 fgEnabledPageIds.add(((SearchPageDescriptor)enabledDescriptor).getId());
238238 }
239239 storeEnabledPageIds();
240240 }
112112 IWorkbenchWindow window= fgSearchPlugin.getWorkbench().getActiveWorkbenchWindow();
113113 if (window == null) {
114114 final WindowRef windowRef= new WindowRef();
115 Display.getDefault().syncExec(new Runnable() {
116 @Override
117 public void run() {
118 setActiveWorkbenchWindow(windowRef);
119 }
120 });
115 Display.getDefault().syncExec(() -> setActiveWorkbenchWindow(windowRef));
121116 return windowRef.window;
122117 }
123118 return window;
142137 shell= shell.getParent();
143138 }
144139 Shell shells[]= display.getShells();
145 for (int i= 0; i < shells.length; i++) {
146 Object data= shells[i].getData();
140 for (Shell shell2 : shells) {
141 Object data= shell2.getData();
147142 if (data instanceof IWorkbenchWindow) {
148143 windowRef.window= (IWorkbenchWindow)data;
149144 return;
281276 */
282277 private List<SearchPageDescriptor> createSearchPageDescriptors(IConfigurationElement[] elements) {
283278 List<SearchPageDescriptor> result= new ArrayList<>(5);
284 for (int i= 0; i < elements.length; i++) {
285 IConfigurationElement element= elements[i];
279 for (IConfigurationElement element : elements) {
286280 if (SearchPageDescriptor.PAGE_TAG.equals(element.getName())) {
287281 SearchPageDescriptor desc= new SearchPageDescriptor(element);
288282 result.add(desc);
325319 */
326320 private List<SorterDescriptor> createSorterDescriptors(IConfigurationElement[] elements) {
327321 List<SorterDescriptor> result= new ArrayList<>(5);
328 for (int i= 0; i < elements.length; i++) {
329 IConfigurationElement element= elements[i];
322 for (IConfigurationElement element : elements) {
330323 if (SorterDescriptor.SORTER_TAG.equals(element.getName()))
331324 result.add(new SorterDescriptor(element));
332325 }
3636
3737 @Override
3838 public String getText(Object element) {
39 StringBuffer buf= new StringBuffer(getLabelProvider().getText(element));
39 StringBuilder buf= new StringBuilder(getLabelProvider().getText(element));
4040 int count= ((ISearchResultViewEntry)element).getMatchCount();
4141 if (count > 1) {
4242 buf.append(" ("); //$NON-NLS-1$
3030 import org.eclipse.jface.operation.IRunnableWithProgress;
3131 import org.eclipse.jface.resource.ImageDescriptor;
3232 import org.eclipse.jface.util.IPropertyChangeListener;
33 import org.eclipse.jface.util.PropertyChangeEvent;
3433 import org.eclipse.jface.viewers.IBaseLabelProvider;
3534 import org.eclipse.jface.viewers.ILabelProvider;
3635 import org.eclipse.jface.viewers.ISelection;
110109
111110 fillActionBars(getViewSite().getActionBars());
112111
113 fPropertyChangeListener= new IPropertyChangeListener() {
114 @Override
115 public void propertyChange(PropertyChangeEvent event) {
116 if (SearchPreferencePage.POTENTIAL_MATCH_FG_COLOR.equals(event.getProperty()) || SearchPreferencePage.EMPHASIZE_POTENTIAL_MATCHES.equals(event.getProperty()))
117 if (fViewer != null)
118 fViewer.updatedPotentialMatchFgColor();
119 }
112 fPropertyChangeListener= event -> {
113 if (SearchPreferencePage.POTENTIAL_MATCH_FG_COLOR.equals(event.getProperty()) || SearchPreferencePage.EMPHASIZE_POTENTIAL_MATCHES.equals(event.getProperty()))
114 if (fViewer != null)
115 fViewer.updatedPotentialMatchFgColor();
120116 };
121117
122118 SearchPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(fPropertyChangeListener);
199195
200196 private void setGotoMarkerAction(final IAction gotoMarkerAction) {
201197 // Make sure we are doing it in the right thread.
202 getDisplay().syncExec(new Runnable() {
203 @Override
204 public void run() {
205 getViewer().setGotoMarkerAction(gotoMarkerAction);
206 }
207 });
198 getDisplay().syncExec(() -> getViewer().setGotoMarkerAction(gotoMarkerAction));
208199 }
209200
210201
3737 import org.eclipse.core.resources.IResource;
3838
3939 import org.eclipse.jface.action.IAction;
40 import org.eclipse.jface.action.IMenuListener;
4140 import org.eclipse.jface.action.IMenuManager;
4241 import org.eclipse.jface.action.IToolBarManager;
4342 import org.eclipse.jface.action.MenuManager;
4544 import org.eclipse.jface.viewers.ArrayContentProvider;
4645 import org.eclipse.jface.viewers.IBaseLabelProvider;
4746 import org.eclipse.jface.viewers.ILabelProvider;
48 import org.eclipse.jface.viewers.IOpenListener;
4947 import org.eclipse.jface.viewers.ISelection;
50 import org.eclipse.jface.viewers.ISelectionChangedListener;
5148 import org.eclipse.jface.viewers.IStructuredSelection;
5249 import org.eclipse.jface.viewers.LabelProviderChangedEvent;
53 import org.eclipse.jface.viewers.OpenEvent;
54 import org.eclipse.jface.viewers.SelectionChangedEvent;
5550 import org.eclipse.jface.viewers.StructuredSelection;
5651 import org.eclipse.jface.viewers.TableViewer;
5752
143138 fCopyToClipboardAction= new CopyToClipboardAction(this);
144139
145140 addSelectionChangedListener(
146 new ISelectionChangedListener() {
147 @Override
148 public void selectionChanged(SelectionChangedEvent event) {
149 if (fLastSelection == null || !fLastSelection.equals(event.getSelection())) {
150 fLastSelection= event.getSelection();
151 handleSelectionChanged();
152 }
141 event -> {
142 if (fLastSelection == null || !fLastSelection.equals(event.getSelection())) {
143 fLastSelection= event.getSelection();
144 handleSelectionChanged();
153145 }
154146 }
155147 );
156148
157 addOpenListener(new IOpenListener() {
158 @Override
159 public void open(OpenEvent event) {
160 showResult();
161 }
162 });
149 addOpenListener(event -> showResult());
163150
164151 MenuManager menuMgr= new MenuManager("#PopUp"); //$NON-NLS-1$
165152 menuMgr.setRemoveAllWhenShown(true);
166153 menuMgr.addMenuListener(
167 new IMenuListener() {
168 @Override
169 public void menuAboutToShow(IMenuManager mgr) {
170 SearchPlugin.createStandardGroups(mgr);
171 fillContextMenu(mgr);
172 }
154 mgr -> {
155 SearchPlugin.createStandardGroups(mgr);
156 fillContextMenu(mgr);
173157 });
174158 Menu menu= menuMgr.createContextMenu(getTable());
175159 getTable().setMenu(menu);
677661 Object[] changed= event.getElements();
678662 if (changed != null && !fResourceToItemsMapper.isEmpty()) {
679663 ArrayList<Object> others= new ArrayList<>(changed.length);
680 for (int i= 0; i < changed.length; i++) {
681 Object curr= changed[i];
664 for (Object curr : changed) {
682665 if (curr instanceof IResource)
683666 fResourceToItemsMapper.resourceChanged((IResource) curr);
684667 else if (curr instanceof IAdaptable) {
4444 }
4545
4646 private void collectExpandedAndVisible(TreeItem[] items, List<TreeItem> result) {
47 for (int i= 0; i < items.length; i++) {
48 TreeItem item= items[i];
47 for (TreeItem item : items) {
4948 result.add(item);
5049 if (item.getExpanded()) {
5150 collectExpandedAndVisible(item.getItems(), result);
109109 public void run() {
110110 if (!checkedId.equals(sorterDesc.getId())) {
111111 SortDropDownAction.this.setChecked(sorterDesc);
112 BusyIndicator.showWhile(parent.getDisplay(), new Runnable() {
113 @Override
114 public void run() {
115 fViewer.setSorter(sorter);
116 }
117 });
112 BusyIndicator.showWhile(parent.getDisplay(), () -> fViewer.setSorter(sorter));
118113 }
119114 }
120115 };
189184 if (memento == null)
190185 return;
191186 IMemento[] mementoElements= memento.getChildren(TAG_ELEMENT);
192 for (int i= 0; i < mementoElements.length; i++) {
193 String pageId= mementoElements[i].getString(TAG_PAGE_ID);
194 String sorterId= mementoElements[i].getString(TAG_SORTER_ID);
187 for (IMemento mementoElement : mementoElements) {
188 String pageId= mementoElement.getString(TAG_PAGE_ID);
189 String sorterId= mementoElement.getString(TAG_SORTER_ID);
195190 SorterDescriptor sorterDesc= getSorter(sorterId);
196191 if (sorterDesc != null)
197192 map.put(pageId, sorterDesc);
8989 String property= event.getProperty();
9090 if (property.equals(JFacePreferences.QUALIFIER_COLOR) || property.equals(JFacePreferences.COUNTER_COLOR) || property.equals(JFacePreferences.DECORATIONS_COLOR)
9191 || property.equals(HIGHLIGHT_BG_COLOR_NAME) || property.equals(IWorkbenchPreferenceConstants.USE_COLORED_LABELS)) {
92 Display.getDefault().asyncExec(new Runnable() {
93 @Override
94 public void run() {
95 refresh();
96 }
97 });
92 Display.getDefault().asyncExec(() -> refresh());
9893 }
9994 }
10095
4545
4646 public IEditorPart openAndSelect(IWorkbenchPage wbPage, IFile file, int offset, int length, boolean activate) throws PartInitException {
4747 String editorId= null;
48 IEditorDescriptor desc= IDE.getEditorDescriptor(file);
48 IEditorDescriptor desc = IDE.getEditorDescriptor(file, true, true);
4949 if (desc == null || !desc.isInternal()) {
5050 editorId= "org.eclipse.ui.DefaultTextEditor"; //$NON-NLS-1$
5151 } else {
7474
7575
7676 private String getEditorID(IFile file) throws PartInitException {
77 IEditorDescriptor desc= IDE.getEditorDescriptor(file);
77 IEditorDescriptor desc = IDE.getEditorDescriptor(file, true, true);
7878 if (desc == null)
7979 return SearchPlugin.getDefault().getWorkbench().getEditorRegistry().findEditor(IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID).getId();
8080 return desc.getId();
5858 fOrder= orderFlag;
5959 fPage= page;
6060 fLineMatchImage= SearchPluginImages.get(SearchPluginImages.IMG_OBJ_TEXT_SEARCH_LINE);
61 fMatchComparator= new Comparator<FileMatch>() {
62 @Override
63 public int compare(FileMatch o1, FileMatch o2) {
64 return o1.getOriginalOffset() - o2.getOriginalOffset();
65 }
66 };
61 fMatchComparator= (o1, o2) -> o1.getOriginalOffset() - o2.getOriginalOffset();
6762 }
6863
6964 public void setOrder(int orderFlag) {
00 /*******************************************************************************
1 * Copyright (c) 2000, 2015 IBM Corporation and others.
1 * Copyright (c) 2000, 2018 IBM Corporation and others.
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
125125
126126
127127 private static final String[] SHOW_IN_TARGETS= new String[] { IPageLayout.ID_RES_NAV };
128 private static final IShowInTargetList SHOW_IN_TARGET_LIST= new IShowInTargetList() {
129 @Override
130 public String[] getShowInTargetIds() {
131 return SHOW_IN_TARGETS;
132 }
133 };
128 private static final IShowInTargetList SHOW_IN_TARGET_LIST= () -> SHOW_IN_TARGETS;
134129
135130 public FileSearchPage() {
136131 fSortByNameAction= new SortAction(SearchMessages.FileSearchPage_sort_name_label, this, FileLabelProvider.SHOW_LABEL_PATH);
272267 fActionGroup.fillContextMenu(mgr);
273268 FileSearchQuery query= (FileSearchQuery) getInput().getQuery();
274269 if (query.getSearchString().length() > 0) {
275 IStructuredSelection selection= (IStructuredSelection) getViewer().getSelection();
270 IStructuredSelection selection = getViewer().getStructuredSelection();
276271 if (!selection.isEmpty()) {
277272 ReplaceAction replaceSelection= new ReplaceAction(getSite().getShell(), (FileSearchResult)getInput(), selection.toArray());
278273 replaceSelection.setText(SearchMessages.ReplaceAction_label_selected);
392387 newSelection.add(element);
393388 }
394389
395 return (T) new IShowInSource() {
396 @Override
397 public ShowInContext getShowInContext() {
398 return new ShowInContext(null, new StructuredSelection(new ArrayList<>(newSelection)));
399 }
400 };
390 return (T) (IShowInSource) () -> new ShowInContext(null, new StructuredSelection(new ArrayList<>(newSelection)));
401391 }
402392 return null;
403393 }
458448 @Override
459449 protected void evaluateChangedElements(Match[] matches, Set<Object> changedElements) {
460450 if (showLineMatches()) {
461 for (int i = 0; i < matches.length; i++) {
462 changedElements.add(((FileMatch) matches[i]).getLineElement());
451 for (Match match : matches) {
452 changedElements.add(((FileMatch) match).getLineElement());
463453 }
464454 } else {
465455 super.evaluateChangedElements(matches, changedElements);
173173 }
174174
175175 private static String getContents(TextSearchMatchAccess matchRequestor, int start, int end) {
176 StringBuffer buf= new StringBuffer();
176 StringBuilder buf= new StringBuilder();
177177 for (int i= start; i < end; i++) {
178178 char ch= matchRequestor.getFileContentChar(i);
179179 if (Character.isWhitespace(ch) || Character.isISOControl(ch)) {
258258 String[] fileNamePatterns= fScope.getFileNamePatterns();
259259 if (fileNamePatterns == null)
260260 return true;
261 for (int i= 0; i < fileNamePatterns.length; i++) {
262 if ("*".equals(fileNamePatterns[i])) { //$NON-NLS-1$
261 for (String fileNamePattern : fileNamePatterns) {
262 if ("*".equals(fileNamePattern)) { //$NON-NLS-1$
263263 return true;
264264 }
265265 }
5858 TableViewer viewer= getViewer();
5959 int elementLimit= getElementLimit();
6060 boolean tableLimited= elementLimit != -1;
61 for (int i= 0; i < updatedElements.length; i++) {
62 if (fResult.getMatchCount(updatedElements[i]) > 0) {
63 if (viewer.testFindItem(updatedElements[i]) != null)
64 viewer.update(updatedElements[i], null);
61 for (Object updatedElement : updatedElements) {
62 if (fResult.getMatchCount(updatedElement) > 0) {
63 if (viewer.testFindItem(updatedElement) != null)
64 viewer.update(updatedElement, null);
6565 else {
6666 if (!tableLimited || viewer.getTable().getItemCount() < elementLimit)
67 viewer.add(updatedElements[i]);
67 viewer.add(updatedElement);
6868 }
6969 } else
70 viewer.remove(updatedElements[i]);
70 viewer.remove(updatedElement);
7171 }
7272 }
7373
7777
7878 if (result != null) {
7979 Object[] elements= result.getElements();
80 for (int i= 0; i < elements.length; i++) {
80 for (Object element : elements) {
8181 if (showLineMatches) {
82 Match[] matches= result.getMatches(elements[i]);
83 for (int j= 0; j < matches.length; j++) {
84 insert(((FileMatch) matches[j]).getLineElement(), false);
82 Match[] matches= result.getMatches(element);
83 for (Match match : matches) {
84 insert(((FileMatch) match).getLineElement(), false);
8585 }
8686 } else {
87 insert(elements[i], false);
87 insert(element, false);
8888 }
8989 }
9090 }
6363 public FileMatch[] getMatches(AbstractTextSearchResult result) {
6464 ArrayList<FileMatch> res= new ArrayList<>();
6565 Match[] matches= result.getMatches(fParent);
66 for (int i= 0; i < matches.length; i++) {
67 FileMatch curr= (FileMatch) matches[i];
66 for (Match match : matches) {
67 FileMatch curr= (FileMatch) match;
6868 if (curr.getLineElement() == this) {
6969 res.add(curr);
7070 }
7575 public int getNumberOfMatches(AbstractTextSearchResult result) {
7676 int count= 0;
7777 Match[] matches= result.getMatches(fParent);
78 for (int i= 0; i < matches.length; i++) {
79 FileMatch curr= (FileMatch) matches[i];
78 for (Match match : matches) {
79 FileMatch curr= (FileMatch) match;
8080 if (curr.getLineElement() == this) {
8181 count++;
8282 }
1313 import java.util.regex.PatternSyntaxException;
1414
1515 import org.eclipse.swt.SWT;
16 import org.eclipse.swt.events.ModifyEvent;
17 import org.eclipse.swt.events.ModifyListener;
1816 import org.eclipse.swt.events.SelectionAdapter;
1917 import org.eclipse.swt.events.SelectionEvent;
2018 import org.eclipse.swt.layout.GridData;
102100 gd.widthHint= convertWidthInCharsToPixels(50);
103101 fTextField.setLayoutData(gd);
104102 fTextField.setFocus();
105 fTextField.addModifyListener(new ModifyListener() {
106 @Override
107 public void modifyText(ModifyEvent e) {
108 updateOKStatus();
109 }
110 });
103 fTextField.addModifyListener(e -> updateOKStatus());
111104
112105 IDialogSettings settings= SearchPlugin.getDefault().getDialogSettings().getSection(SETTINGS_GROUP);
113106 if (settings != null) {
00 /*******************************************************************************
1 * Copyright (c) 2007, 2015 IBM Corporation and others.
1 * Copyright (c) 2007, 2017 IBM Corporation and others.
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
66 *
77 * Contributors:
88 * IBM Corporation - initial API and implementation
9 * Florian Ingerl <imelflorianingerl@gmail.com> - Bug 109481 - [find/replace] replace doesn't work when using a regex with a lookahead or boundary matchers
910 *******************************************************************************/
1011 package org.eclipse.search.internal.ui.text;
1112
1617 import java.util.Comparator;
1718 import java.util.HashMap;
1819 import java.util.HashSet;
19 import java.util.Iterator;
2020 import java.util.Map;
2121 import java.util.Set;
2222 import java.util.regex.Matcher;
125125 private Match[] getMatches() {
126126 if (fMatches == null) {
127127 ArrayList<FileMatch> matches= new ArrayList<>();
128 for (int i= 0; i < fMatchGroups.length; i++) {
129 MatchGroup curr= fMatchGroups[i];
128 for (MatchGroup curr : fMatchGroups) {
130129 if (curr.group.isEnabled()) {
131130 FileMatch match= curr.match;
132131 matches.add(match);
210209 fMatches.clear();
211210
212211 if (fSelection != null) {
213 for (int i= 0; i < fSelection.length; i++) {
214 collectMatches(fSelection[i]);
212 for (Object element : fSelection) {
213 collectMatches(element);
215214 }
216215 } else {
217216 Object[] elements= fResult.getElements();
218 for (int i= 0; i < elements.length; i++) {
219 collectMatches(elements[i]);
217 for (Object element : elements) {
218 collectMatches(element);
220219 }
221220 }
222221 if (!hasMatches()) {
229228 if (object instanceof LineElement) {
230229 LineElement lineElement= (LineElement) object;
231230 FileMatch[] matches= lineElement.getMatches(fResult);
232 for (int i= 0; i < matches.length; i++) {
233 FileMatch fileMatch= matches[i];
231 for (FileMatch fileMatch : matches) {
234232 if (isMatchToBeIncluded(fileMatch)) {
235233 getBucket(fileMatch.getFile()).add(fileMatch);
236234 }
238236 } else if (object instanceof IContainer) {
239237 IContainer container= (IContainer) object;
240238 IResource[] members= container.members();
241 for (int i= 0; i < members.length; i++) {
242 collectMatches(members[i]);
239 for (IResource member : members) {
240 collectMatches(member);
243241 }
244242 } else if (object instanceof IFile) {
245243 Match[] matches= fResult.getMatches(object);
246244 if (matches.length > 0) {
247245 Collection<FileMatch> bucket= null;
248 for (int i= 0; i < matches.length; i++) {
249 FileMatch fileMatch= (FileMatch) matches[i];
246 for (Match match : matches) {
247 FileMatch fileMatch= (FileMatch) match;
250248 if (isMatchToBeIncluded(fileMatch)) {
251249 if (bucket == null) {
252250 bucket= getBucket((IFile)object);
264262
265263 public int getNumberOfMatches() {
266264 int count= 0;
267 for (Iterator<Set<FileMatch>> iterator= fMatches.values().iterator(); iterator.hasNext();) {
268 Set<FileMatch> bucket= iterator.next();
265 for (Set<FileMatch> bucket : fMatches.values()) {
269266 count += bucket.size();
270267 }
271268 return count;
289286 if (uri == null)
290287 return true;
291288
292 for (Iterator<URI> iter= fAlreadyCollected.keySet().iterator(); iter.hasNext();) {
293 if (URIUtil.equals(iter.next(), uri)) {
289 for (URI uri2 : fAlreadyCollected.keySet()) {
290 if (URIUtil.equals(uri2, uri)) {
294291 if (file.equals(fAlreadyCollected.get(uri)))
295292 return true; // another FileMatch for an IFile which already had matches
296293
357354 ArrayList<MatchGroup> matchGroups= new ArrayList<>();
358355 boolean hasChanges= false;
359356 try {
360 for (int i= 0; i < allFiles.length; i++) {
361 IFile file= allFiles[i];
357 for (IFile file : allFiles) {
362358 Set<FileMatch> bucket= fMatches.get(file);
363359 if (!bucket.isEmpty()) {
364360 try {
389385
390386 private void checkFilesToBeChanged(IFile[] filesToBeChanged, RefactoringStatus resultingStatus) throws CoreException {
391387 ArrayList<IFile> readOnly= new ArrayList<>();
392 for (int i= 0; i < filesToBeChanged.length; i++) {
393 IFile file= filesToBeChanged[i];
388 for (IFile file : filesToBeChanged) {
394389 if (file.isReadOnly())
395390 readOnly.add(file);
396391 }
424419 IDocument document= textFileBuffer.getDocument();
425420 String lineDelimiter= TextUtilities.getDefaultLineDelimiter(document);
426421
427 for (Iterator<FileMatch> iterator= matches.iterator(); iterator.hasNext();) {
428 FileMatch match= iterator.next();
422 for (FileMatch match : matches) {
429423 int offset= match.getOffset();
430424 int length= match.getLength();
431425 Position currentPosition= tracker.getCurrentPosition(match);
443437 continue;
444438 }
445439
446 String replacementString= computeReplacementString(pattern, originalText, fReplaceString, lineDelimiter);
440 String replacementString= PatternConstructor.interpretReplaceEscapes(fReplaceString, originalText,
441 lineDelimiter);
442 replacementString= computeReplacementString(pattern, document, offset, replacementString);
447443 if (replacementString == null) {
448444 resultingStatus.addError(Messages.format(SearchMessages.ReplaceRefactoring_error_match_content_changed, file.getName()));
449445 continue;
473469 return PatternConstructor.createPattern(query.getSearchString(), true, true, query.isCaseSensitive(), false);
474470 }
475471
476 private String computeReplacementString(Pattern pattern, String originalText, String replacementText, String lineDelimiter) throws PatternSyntaxException {
472 private String computeReplacementString(Pattern pattern, IDocument document, int offset, String replacementText)
473 throws PatternSyntaxException {
477474 if (pattern != null) {
478475 try {
479 replacementText= PatternConstructor.interpretReplaceEscapes(replacementText, originalText, lineDelimiter);
480
481 Matcher matcher= pattern.matcher(originalText);
482 StringBuffer sb = new StringBuffer();
483 matcher.reset();
484 if (matcher.find()) {
476 Matcher matcher= pattern.matcher(document.get());
477 if (matcher.find(offset)) {
478 StringBuffer sb= new StringBuffer();
485479 matcher.appendReplacement(sb, replacementText);
480 return sb.substring(offset);
486481 } else {
487482 return null;
488483 }
489 matcher.appendTail(sb);
490 return sb.toString();
491484 } catch (IndexOutOfBoundsException ex) {
492485 throw new PatternSyntaxException(ex.getLocalizedMessage(), replacementText, -1);
493486 }
1616 import org.eclipse.core.resources.IResourceChangeEvent;
1717 import org.eclipse.core.resources.IResourceChangeListener;
1818 import org.eclipse.core.resources.IResourceDelta;
19 import org.eclipse.core.resources.IResourceDeltaVisitor;
2019 import org.eclipse.core.resources.ResourcesPlugin;
2120
2221 import org.eclipse.search.internal.ui.SearchPlugin;
4443
4544 private void handleDelta(IResourceDelta d) {
4645 try {
47 d.accept(new IResourceDeltaVisitor() {
48 @Override
49 public boolean visit(IResourceDelta delta) throws CoreException {
50 switch (delta.getKind()) {
51 case IResourceDelta.ADDED :
52 return false;
53 case IResourceDelta.REMOVED :
54 IResource res= delta.getResource();
55 if (res instanceof IFile) {
56 Match[] matches= fResult.getMatches(res);
57 fResult.removeMatches(matches);
58 }
59 break;
60 case IResourceDelta.CHANGED :
61 // handle changed resource
62 break;
63 }
64 return true;
46 d.accept(delta -> {
47 switch (delta.getKind()) {
48 case IResourceDelta.ADDED :
49 return false;
50 case IResourceDelta.REMOVED :
51 IResource res= delta.getResource();
52 if (res instanceof IFile) {
53 Match[] matches= fResult.getMatches(res);
54 fResult.removeMatches(matches);
55 }
56 break;
57 case IResourceDelta.CHANGED :
58 // handle changed resource
59 break;
6560 }
61 return true;
6662 });
6763 } catch (CoreException e) {
6864 SearchPlugin.log(e);
1818 import java.io.StringReader;
1919 import java.util.ArrayList;
2020 import java.util.HashSet;
21 import java.util.Iterator;
2221 import java.util.LinkedHashSet;
2322 import java.util.List;
2423 import java.util.Set;
2625
2726 import org.eclipse.swt.SWT;
2827 import org.eclipse.swt.custom.CLabel;
29 import org.eclipse.swt.events.ModifyEvent;
30 import org.eclipse.swt.events.ModifyListener;
3128 import org.eclipse.swt.events.SelectionAdapter;
3229 import org.eclipse.swt.events.SelectionEvent;
3330 import org.eclipse.swt.layout.GridData;
4138
4239 import org.eclipse.core.runtime.Assert;
4340 import org.eclipse.core.runtime.CoreException;
44 import org.eclipse.core.runtime.IAdaptable;
4541 import org.eclipse.core.runtime.IStatus;
4642
4743 import org.eclipse.core.resources.IFile;
5652 import org.eclipse.jface.fieldassist.ComboContentAdapter;
5753 import org.eclipse.jface.resource.JFaceColors;
5854 import org.eclipse.jface.viewers.ISelection;
59 import org.eclipse.jface.viewers.IStructuredSelection;
6055
6156 import org.eclipse.jface.text.FindReplaceDocumentAdapter;
6257 import org.eclipse.jface.text.FindReplaceDocumentAdapterContentProposalProvider;
7469
7570 import org.eclipse.search.internal.core.text.PatternConstructor;
7671 import org.eclipse.search.internal.ui.ISearchHelpContextIds;
72 import org.eclipse.search.internal.ui.ScopePart;
7773 import org.eclipse.search.internal.ui.SearchMessages;
7874 import org.eclipse.search.internal.ui.SearchPlugin;
7975 import org.eclipse.search.internal.ui.util.FileTypeEditor;
293289 ErrorDialog.openError(getShell(), SearchMessages.TextSearchPage_replace_searchproblems_title, SearchMessages.TextSearchPage_replace_runproblem_message, status);
294290 }
295291
296 Display.getCurrent().asyncExec(new Runnable() {
297 @Override
298 public void run() {
299 ISearchResultViewPart view= NewSearchUI.activateSearchResultView();
300 if (view != null) {
301 ISearchResultPage page= view.getActivePage();
302 if (page instanceof FileSearchPage) {
303 FileSearchPage filePage= (FileSearchPage) page;
304 new ReplaceAction(filePage.getSite().getShell(), (FileSearchResult)filePage.getInput(), null).run();
305 }
292 Display.getCurrent().asyncExec(() -> {
293 ISearchResultViewPart view= NewSearchUI.activateSearchResultView();
294 if (view != null) {
295 ISearchResultPage page= view.getActivePage();
296 if (page instanceof FileSearchPage) {
297 FileSearchPage filePage= (FileSearchPage) page;
298 new ReplaceAction(filePage.getSite().getShell(), (FileSearchResult)filePage.getInput(), null).run();
306299 }
307300 }
308301 });
336329 }
337330
338331 private FileTextSearchScope getSelectedResourcesScope() {
339 HashSet<IResource> resources= new HashSet<>();
340 ISelection sel= getContainer().getSelection();
341 if (sel instanceof IStructuredSelection && !sel.isEmpty()) {
342 Iterator<?> iter= ((IStructuredSelection) sel).iterator();
343 while (iter.hasNext()) {
344 Object curr= iter.next();
345 if (curr instanceof IWorkingSet) {
346 IWorkingSet workingSet= (IWorkingSet) curr;
347 if (workingSet.isAggregateWorkingSet() && workingSet.isEmpty()) {
348 return FileTextSearchScope.newWorkspaceScope(getExtensions(), fSearchDerived);
349 }
350 IAdaptable[] elements= workingSet.getElements();
351 for (int i= 0; i < elements.length; i++) {
352 IResource resource= elements[i].getAdapter(IResource.class);
353 if (resource != null && resource.isAccessible()) {
354 resources.add(resource);
355 }
356 }
357 } else if (curr instanceof LineElement) {
358 IResource resource= ((LineElement)curr).getParent();
359 if (resource != null && resource.isAccessible())
360 resources.add(resource);
361 } else if (curr instanceof IAdaptable) {
362 IResource resource= ((IAdaptable)curr).getAdapter(IResource.class);
363 if (resource != null && resource.isAccessible()) {
364 resources.add(resource);
365 }
366 }
367 }
368 } else if (getContainer().getActiveEditorInput() != null) {
369 resources.add(getContainer().getActiveEditorInput().getAdapter(IFile.class));
370 }
371 IResource[] arr= resources.toArray(new IResource[resources.size()]);
332 IResource[] arr = ScopePart.selectedResourcesFromContainer(getContainer()).toArray(new IResource[0]);
372333 return FileTextSearchScope.newSearchScope(arr, getExtensions(), fSearchDerived);
373334 }
374335
389350
390351
391352 private SearchPatternData findInPrevious(String pattern) {
392 for (Iterator<SearchPatternData> iter= fPreviousSearchPatterns.iterator(); iter.hasNext();) {
393 SearchPatternData element= iter.next();
353 for (SearchPatternData element : fPreviousSearchPatterns) {
394354 if (pattern.equals(element.textPattern)) {
395355 return element;
396356 }
552512 }
553513 });
554514 // add some listeners for regex syntax checking
555 fPattern.addModifyListener(new ModifyListener() {
556 @Override
557 public void modifyText(ModifyEvent e) {
558 updateOKStatus();
559 }
560 });
515 fPattern.addModifyListener(e -> updateOKStatus());
561516 fPattern.setFont(group.getFont());
562517 GridData data= new GridData(GridData.FILL, GridData.FILL, true, false, 1, 2);
563518 data.widthHint= convertWidthInCharsToPixels(50);
685640 private String insertEscapeChars(String text) {
686641 if (text == null || text.equals("")) //$NON-NLS-1$
687642 return ""; //$NON-NLS-1$
688 StringBuffer sbIn= new StringBuffer(text);
643 StringBuilder sbIn= new StringBuilder(text);
689644 BufferedReader reader= new BufferedReader(new StringReader(text));
690645 int lengthOfFirstLine= 0;
691646 try {
693648 } catch (IOException ex) {
694649 return ""; //$NON-NLS-1$
695650 }
696 StringBuffer sbOut= new StringBuffer(lengthOfFirstLine + 5);
651 StringBuilder sbOut= new StringBuilder(lengthOfFirstLine + 5);
697652 int i= 0;
698653 while (i < lengthOfFirstLine) {
699654 char ch= sbIn.charAt(i);
729684 label.setFont(group.getFont());
730685
731686 fExtensions= new Combo(group, SWT.SINGLE | SWT.BORDER);
732 fExtensions.addModifyListener(new ModifyListener() {
733 @Override
734 public void modifyText(ModifyEvent e) {
735 updateOKStatus();
736 }
737 });
687 fExtensions.addModifyListener(e -> updateOKStatus());
738688 GridData data= new GridData(GridData.FILL, GridData.FILL, true, false, 1, 1);
739689 data.widthHint= convertWidthInCharsToPixels(50);
740690 fExtensions.setLayoutData(data);
1313 import java.lang.reflect.InvocationTargetException;
1414 import java.util.ArrayList;
1515 import java.util.HashMap;
16 import java.util.Iterator;
1716 import java.util.List;
1817
1918 import org.eclipse.swt.SWT;
173172 * @param state The new state
174173 */
175174 public void setPerformActionEnabled(boolean state) {
176 for (Iterator<Button> buttons = fActionButtons.iterator(); buttons.hasNext(); ) {
177 Button element = buttons.next();
175 for (Button element : fActionButtons) {
178176 element.setEnabled(state);
179177 }
180178 }
270268
271269 private void setDisplayCursor(Display d, Cursor c) {
272270 Shell[] shells= d.getShells();
273 for (int i= 0; i < shells.length; i++)
274 shells[i].setCursor(c);
271 for (Shell shell2 : shells)
272 shell2.setCursor(c);
275273 }
276274
277275 //---- UI state save and restoring ---------------------------------------------
278276
279277 private void restoreUIState(HashMap<Object, Object> state) {
280278 restoreEnableState(fCancelButton, state);
281 for (Iterator<Button> actionButtons = fActionButtons.iterator(); actionButtons.hasNext(); ) {
282 Button button = actionButtons.next();
279 for (Button button : fActionButtons) {
283280 restoreEnableState(button, state);
284281 }
285282 ControlEnableState pageState= (ControlEnableState)state.get("tabForm"); //$NON-NLS-1$
300297 private HashMap<Object, Object> saveUIState(boolean keepCancelEnabled) {
301298 HashMap<Object, Object> savedState= new HashMap<>(10);
302299 saveEnableStateAndSet(fCancelButton, savedState, keepCancelEnabled);
303 for (Iterator<Button> actionButtons = fActionButtons.iterator(); actionButtons.hasNext(); ) {
304 Button button = actionButtons.next();
300 for (Button button : fActionButtons) {
305301 saveEnableStateAndSet(button, savedState, false);
306302 }
307303 savedState.put("tabForm", ControlEnableState.disable(fContents)); //$NON-NLS-1$
3737 private final static String TYPE_DELIMITER= SearchMessages.FileTypeEditor_typeDelimiter;
3838 public final static String FILE_PATTERN_NEGATOR= "!"; //$NON-NLS-1$
3939
40 private static final Comparator<String> FILE_TYPES_COMPARATOR= new Comparator<String>() {
41 @Override
42 public int compare(String fp1, String fp2) {
43 boolean isNegative1= fp1.startsWith(FILE_PATTERN_NEGATOR);
44 boolean isNegative2= fp2.startsWith(FILE_PATTERN_NEGATOR);
45 if (isNegative1 != isNegative2) {
46 return isNegative1 ? 1 : -1;
47 }
48 return fp1.compareTo(fp2);
40 private static final Comparator<String> FILE_TYPES_COMPARATOR= (fp1, fp2) -> {
41 boolean isNegative1= fp1.startsWith(FILE_PATTERN_NEGATOR);
42 boolean isNegative2= fp2.startsWith(FILE_PATTERN_NEGATOR);
43 if (isNegative1 != isNegative2) {
44 return isNegative1 ? 1 : -1;
4945 }
46 return fp1.compareTo(fp2);
5047 };
5148
5249 public FileTypeEditor(Combo textField, Button browseButton) {
9491 Object[] result= dialog.getResult();
9592 HashSet<String> patterns= new HashSet<>();
9693 boolean starIncluded= false;
97 for (int i= 0; i < result.length; i++) {
98 String curr= result[i].toString();
94 for (Object element : result) {
95 String curr= element.toString();
9996 if (curr.equals("*")) { //$NON-NLS-1$
10097 starIncluded= true;
10198 } else {
113110
114111 public static String typesToString(String[] types) {
115112 Arrays.sort(types, FILE_TYPES_COMPARATOR);
116 StringBuffer result= new StringBuffer();
113 StringBuilder result= new StringBuilder();
117114 for (int i= 0; i < types.length; i++) {
118115 if (i > 0) {
119116 result.append(TYPE_DELIMITER);
132132 org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
133133 org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
134134 org.eclipse.jdt.core.compiler.source=1.8
135 org.eclipse.jdt.core.formatter.align_fields_grouping_blank_lines=2147483647
135136 org.eclipse.jdt.core.formatter.align_type_members_on_columns=false
136137 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16
137138 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation=0
145146 org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=48
146147 org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0
147148 org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16
149 org.eclipse.jdt.core.formatter.alignment_for_expressions_in_for_loop_header=0
148150 org.eclipse.jdt.core.formatter.alignment_for_method_declaration=0
149151 org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16
152 org.eclipse.jdt.core.formatter.alignment_for_parameterized_type_references=0
150153 org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16
151154 org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16
152155 org.eclipse.jdt.core.formatter.alignment_for_resources_in_try=80
156159 org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16
157160 org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16
158161 org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16
162 org.eclipse.jdt.core.formatter.alignment_for_type_arguments=0
163 org.eclipse.jdt.core.formatter.alignment_for_type_parameters=0
159164 org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch=16
160165 org.eclipse.jdt.core.formatter.blank_lines_after_imports=1
161166 org.eclipse.jdt.core.formatter.blank_lines_after_package=1
182187 org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line
183188 org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false
184189 org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=false
190 org.eclipse.jdt.core.formatter.comment.count_line_length_from_starting_position=false
185191 org.eclipse.jdt.core.formatter.comment.format_block_comments=false
186192 org.eclipse.jdt.core.formatter.comment.format_header=false
187193 org.eclipse.jdt.core.formatter.comment.format_html=true
214220 org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true
215221 org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true
216222 org.eclipse.jdt.core.formatter.indentation.size=4
223 org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_enum_constant=insert
217224 org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field=insert
218225 org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert
219226 org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method=insert
408415 org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=true
409416 org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0
410417 org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=3
418 org.eclipse.jdt.core.formatter.parentheses_positions_in_annotation=common_lines
419 org.eclipse.jdt.core.formatter.parentheses_positions_in_catch_clause=common_lines
420 org.eclipse.jdt.core.formatter.parentheses_positions_in_enum_constant_declaration=common_lines
421 org.eclipse.jdt.core.formatter.parentheses_positions_in_for_statment=common_lines
422 org.eclipse.jdt.core.formatter.parentheses_positions_in_if_while_statement=common_lines
423 org.eclipse.jdt.core.formatter.parentheses_positions_in_lambda_declaration=common_lines
424 org.eclipse.jdt.core.formatter.parentheses_positions_in_method_delcaration=common_lines
425 org.eclipse.jdt.core.formatter.parentheses_positions_in_method_invocation=common_lines
426 org.eclipse.jdt.core.formatter.parentheses_positions_in_switch_statement=common_lines
427 org.eclipse.jdt.core.formatter.parentheses_positions_in_try_clause=common_lines
411428 org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true
412429 org.eclipse.jdt.core.formatter.tabulation.char=tab
413430 org.eclipse.jdt.core.formatter.tabulation.size=4
414431 org.eclipse.jdt.core.formatter.use_on_off_tags=false
415432 org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false
433 org.eclipse.jdt.core.formatter.wrap_before_assignment_operator=false
416434 org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true
435 org.eclipse.jdt.core.formatter.wrap_before_conditional_operator=true
417436 org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch=true
418437 org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested=true
419438 org.eclipse.jdt.core.incompatibleJDKLevel=ignore
00 eclipse.preferences.version=1
1 editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true
12 formatter_profile=_JDT UI Code Style Conventions
2 formatter_settings_version=12
3 formatter_settings_version=13
34 org.eclipse.jdt.ui.exception.name=e
45 org.eclipse.jdt.ui.gettersetter.use.is=true
56 org.eclipse.jdt.ui.ignorelowercasenames=true
89 org.eclipse.jdt.ui.ondemandthreshold=99
910 org.eclipse.jdt.ui.overrideannotation=true
1011 org.eclipse.jdt.ui.staticondemandthreshold=99
12 sp_cleanup.add_default_serial_version_id=true
13 sp_cleanup.add_generated_serial_version_id=false
14 sp_cleanup.add_missing_annotations=true
15 sp_cleanup.add_missing_deprecated_annotations=true
16 sp_cleanup.add_missing_methods=false
17 sp_cleanup.add_missing_nls_tags=false
18 sp_cleanup.add_missing_override_annotations=true
19 sp_cleanup.add_missing_override_annotations_interface_methods=true
20 sp_cleanup.add_serial_version_id=false
21 sp_cleanup.always_use_blocks=true
22 sp_cleanup.always_use_parentheses_in_expressions=false
23 sp_cleanup.always_use_this_for_non_static_field_access=false
24 sp_cleanup.always_use_this_for_non_static_method_access=false
25 sp_cleanup.convert_functional_interfaces=false
26 sp_cleanup.convert_to_enhanced_for_loop=false
27 sp_cleanup.correct_indentation=false
28 sp_cleanup.format_source_code=true
29 sp_cleanup.format_source_code_changes_only=true
30 sp_cleanup.insert_inferred_type_arguments=false
31 sp_cleanup.make_local_variable_final=true
32 sp_cleanup.make_parameters_final=false
33 sp_cleanup.make_private_fields_final=true
34 sp_cleanup.make_type_abstract_if_missing_method=false
35 sp_cleanup.make_variable_declarations_final=false
36 sp_cleanup.never_use_blocks=false
37 sp_cleanup.never_use_parentheses_in_expressions=true
38 sp_cleanup.on_save_use_additional_actions=true
39 sp_cleanup.organize_imports=true
40 sp_cleanup.qualify_static_field_accesses_with_declaring_class=false
41 sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true
42 sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true
43 sp_cleanup.qualify_static_member_accesses_with_declaring_class=false
44 sp_cleanup.qualify_static_method_accesses_with_declaring_class=false
45 sp_cleanup.remove_private_constructors=true
46 sp_cleanup.remove_redundant_type_arguments=false
47 sp_cleanup.remove_trailing_whitespaces=true
48 sp_cleanup.remove_trailing_whitespaces_all=true
49 sp_cleanup.remove_trailing_whitespaces_ignore_empty=false
50 sp_cleanup.remove_unnecessary_casts=false
51 sp_cleanup.remove_unnecessary_nls_tags=false
52 sp_cleanup.remove_unused_imports=false
53 sp_cleanup.remove_unused_local_variables=false
54 sp_cleanup.remove_unused_private_fields=true
55 sp_cleanup.remove_unused_private_members=false
56 sp_cleanup.remove_unused_private_methods=true
57 sp_cleanup.remove_unused_private_types=true
58 sp_cleanup.sort_members=false
59 sp_cleanup.sort_members_all=false
60 sp_cleanup.use_anonymous_class_creation=false
61 sp_cleanup.use_blocks=false
62 sp_cleanup.use_blocks_only_for_return_and_throw=false
63 sp_cleanup.use_lambda=true
64 sp_cleanup.use_parentheses_in_expressions=false
65 sp_cleanup.use_this_for_non_static_field_access=false
66 sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true
67 sp_cleanup.use_this_for_non_static_method_access=false
68 sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true
11 Bundle-ManifestVersion: 2
22 Bundle-Name: %pluginName
33 Bundle-SymbolicName: org.eclipse.search.tests
4 Bundle-Version: 3.9.0.qualifier
4 Bundle-Version: 3.9.100.qualifier
55 Bundle-Activator: org.eclipse.search.tests.SearchTestPlugin
66 Bundle-Vendor: %providerName
77 Bundle-Localization: plugin
1717 org.junit;bundle-version="4.12.0",
1818 org.eclipse.ui.workbench.texteditor;bundle-version="[3.5.0,4.0.0)",
1919 org.eclipse.jface.text;bundle-version="[3.5.0,4.0.0)",
20 org.eclipse.ui.editors;bundle-version="[3.5.0,4.0.0)"
20 org.eclipse.ui.editors;bundle-version="[3.5.0,4.0.0)",
21 org.eclipse.ltk.core.refactoring;bundle-version="[3.5.0,4.0.0)"
2122 Bundle-ActivationPolicy: lazy
2223 Bundle-RequiredExecutionEnvironment: JavaSE-1.8
2324 Eclipse-BundleShape: dir
25 Automatic-Module-Name: org.eclipse.search.tests
1313 <parent>
1414 <artifactId>tests-pom</artifactId>
1515 <groupId>eclipse.platform.text</groupId>
16 <version>4.7.3-SNAPSHOT</version>
16 <version>4.8.0-SNAPSHOT</version>
1717 <relativePath>../tests-pom/</relativePath>
1818 </parent>
1919 <groupId>org.eclipse.search</groupId>
2020 <artifactId>org.eclipse.search.tests</artifactId>
21 <version>3.9.0-SNAPSHOT</version>
21 <version>3.9.100-SNAPSHOT</version>
2222 <packaging>eclipse-test-plugin</packaging>
2323 <properties>
2424 <testSuite>${project.artifactId}</testSuite>
3535 */
3636 public class LineConversionTest extends TestCase {
3737 private IFile fFile;
38
38
3939 private static final String LINE_TWO= "This is the second line\n";
4040 private static final String LINE_ONE= "This is the first line\n";
4141 private static final String LINE_THREE= "This is the third line";
4949 fFile.create(new ByteArrayInputStream(getFileContents().getBytes()), true, null);
5050 super.setUp();
5151 }
52
52
5353 @Override
5454 protected void tearDown() throws Exception {
5555 SearchPlugin.getActivePage().closeAllEditors(false);
6060 private String getFileContents() {
6161 return LINE_ONE+LINE_TWO+LINE_THREE;
6262 }
63
63
6464 public void testConvertToCharacter() throws Exception {
6565 SearchTestPlugin.openTextEditor(SearchPlugin.getActivePage(), fFile);
6666 ITextFileBuffer fb= FileBuffers.getTextFileBufferManager().getTextFileBuffer(fFile.getFullPath(), LocationKind.IFILE);
6767 IDocument doc= fb.getDocument();
68
68
6969 Position p1= new Position(2, 1);
7070 Position p2= PositionTracker.convertToCharacterPosition(p1, doc);
7171 //assertEquals(LINE_THREE, doc.get(p2.getOffset(), p2.getLength()));
8686 assertEquals("", doc.get(p2.getOffset(), p2.getLength()));
8787 assertEquals(p1, PositionTracker.convertToLinePosition(p2, doc));
8888 }
89
89
9090 public void testBogusLines() throws Exception {
9191 SearchTestPlugin.openTextEditor(SearchPlugin.getActivePage(), fFile);
9292 ITextFileBuffer fb= FileBuffers.getTextFileBufferManager().getTextFileBuffer(fFile.getFullPath(), LocationKind.IFILE);
1616 /**
1717 */
1818 public class LongQuery extends NullQuery {
19
19
2020 private boolean fIsRunning= false;
21
21
2222 @Override
2323 public boolean canRunInBackground() {
2424 return true;
2525 }
26
26
2727 @Override
2828 public IStatus run(IProgressMonitor monitor) {
2929 fIsRunning= true;
3737 fIsRunning= false;
3838 return Status.OK_STATUS;
3939 }
40
40
4141 public boolean isRunning() {
4242 return fIsRunning;
4343 }
1616 import org.eclipse.search.ui.ISearchResult;
1717
1818 public class NullQuery implements ISearchQuery {
19
19
2020 @Override
2121 public IStatus run(IProgressMonitor monitor) {
2222 return null;
2121 import org.eclipse.search2.internal.ui.InternalSearchUI;
2222
2323 public class QueryManagerTest {
24
24
2525 @Test
2626 public void testRemoveQuery() {
2727 ISearchQuery query= new NullQuery();
2424 import org.eclipse.search.ui.text.MatchEvent;
2525
2626 public class TestSearchResult {
27
27
2828 @Test
2929 public void testAddMatch() {
3030 ISearchQuery query= new NullQuery();
3131 AbstractTextSearchResult result= (AbstractTextSearchResult) query.getSearchResult();
32
33 String object= "object"; //$NON-NLS-1$
34
32
33 String object= "object"; //$NON-NLS-1$
34
3535 Match match1= new Match(object, 0, 0);
3636 result.addMatch(match1);
3737 assertEquals(result.getMatchCount(), 1);
4646 public void testAddMatchDifferentStart() {
4747 ISearchQuery query= new NullQuery();
4848 AbstractTextSearchResult result= (AbstractTextSearchResult) query.getSearchResult();
49
50 String object= "object"; //$NON-NLS-1$
51
49
50 String object= "object"; //$NON-NLS-1$
51
5252 Match match1= new Match(object, 2, 0);
5353 result.addMatch(match1);
5454 assertEquals(result.getMatchCount(), 1);
6666 public void testAddMatchDifferentStartInOrder() {
6767 ISearchQuery query= new NullQuery();
6868 AbstractTextSearchResult result= (AbstractTextSearchResult) query.getSearchResult();
69
70 String object= "object"; //$NON-NLS-1$
71
69
70 String object= "object"; //$NON-NLS-1$
71
7272 Match match1= new Match(object, 0, 0);
7373 result.addMatch(match1);
7474 assertEquals(result.getMatchCount(), 1);
8686 public void testAddMatchDifferentLength() {
8787 ISearchQuery query= new NullQuery();
8888 AbstractTextSearchResult result= (AbstractTextSearchResult) query.getSearchResult();
89
90 String object= "object"; //$NON-NLS-1$
91
89
90 String object= "object"; //$NON-NLS-1$
91
9292 Match match1= new Match(object, 1, 1);
9393 result.addMatch(match1);
9494 assertEquals(result.getMatchCount(), 1);
9898 assertTrue("matches[0]", matches[0] == match2);
9999 assertTrue("matches[1]", matches[1] == match1);
100100 }
101
101
102102 @Test
103103 public void testAddMatchOrderPreserving() {
104104 ISearchQuery query= new NullQuery();
105105 AbstractTextSearchResult result= (AbstractTextSearchResult) query.getSearchResult();
106
107 String object= "object"; //$NON-NLS-1$
108
106
107 String object= "object"; //$NON-NLS-1$
108
109109 Match match1= new Match(object, 1, 0);
110110 result.addMatch(match1);
111111 assertEquals(result.getMatchCount(), 1);
120120 public void testAddMatches() {
121121 ISearchQuery query= new NullQuery();
122122 AbstractTextSearchResult result= (AbstractTextSearchResult) query.getSearchResult();
123
124 String object= "object"; //$NON-NLS-1$
125
123
124 String object= "object"; //$NON-NLS-1$
125
126126 Match match1= new Match(object, 0, 0);
127127 Match match2= new Match(object, 0, 0);
128128 result.addMatches(new Match[] { match1, match2 });
135135 public void testRemoveMatch() {
136136 ISearchQuery query= new NullQuery();
137137 AbstractTextSearchResult result= (AbstractTextSearchResult) query.getSearchResult();
138
139 String object= "object"; //$NON-NLS-1$
140
141 Match match1= new Match(object, 0, 0);
142 result.addMatch(match1);
143 Match match2= new Match(object, 0, 0);
144 result.addMatch(match2);
145 assertEquals(result.getMatchCount(), 2);
146
138
139 String object= "object"; //$NON-NLS-1$
140
141 Match match1= new Match(object, 0, 0);
142 result.addMatch(match1);
143 Match match2= new Match(object, 0, 0);
144 result.addMatch(match2);
145 assertEquals(result.getMatchCount(), 2);
146
147147 result.removeMatch(match1);
148148 assertEquals(result.getMatchCount(), 1);
149149 result.removeMatch(match1);
150150 assertEquals(result.getMatchCount(), 1);
151
152 }
153
151
152 }
153
154154 @Test
155155 public void testRemoveMatches() {
156156 ISearchQuery query= new NullQuery();
157157 AbstractTextSearchResult result= (AbstractTextSearchResult) query.getSearchResult();
158
159 String object= "object"; //$NON-NLS-1$
160
158
159 String object= "object"; //$NON-NLS-1$
160
161161 Match match1= new Match(object, 0, 0);
162162 Match match2= new Match(object, 0, 0);
163163 result.addMatches(new Match[] { match1, match2 });
164164 assertEquals(result.getMatchCount(), 2);
165
165
166166 result.removeMatches(new Match[] { match1, match2 });
167167 assertEquals(result.getMatchCount(), 0);
168
168
169169 }
170170
171171 @Test
172172 public void testMatchEvent() {
173173 final boolean [] wasAdded= { false };
174174 final boolean [] wasRemoved= { false };
175
176 ISearchQuery query= new NullQuery();
177 AbstractTextSearchResult result= (AbstractTextSearchResult) query.getSearchResult();
178
175
176 ISearchQuery query= new NullQuery();
177 AbstractTextSearchResult result= (AbstractTextSearchResult) query.getSearchResult();
178
179179 result.addListener(new ISearchResultListener() {
180180 @Override
181181 public void searchResultChanged(SearchResultEvent e) {
189189 }
190190 }
191191 });
192
193 String object= "object"; //$NON-NLS-1$
194
192
193 String object= "object"; //$NON-NLS-1$
194
195195 Match match1= new Match(object, 0, 0);
196196 result.addMatch(match1);
197197 assertTrue(wasAdded[0]);
198198 wasAdded[0]= false;
199199 result.addMatch(match1);
200200 assertFalse(wasAdded[0]);
201
202 Match match2= new Match(object, 0, 0);
203 result.addMatch(match2);
204 assertTrue(wasAdded[0]);
205 wasAdded[0]= false;
206
201
202 Match match2= new Match(object, 0, 0);
203 result.addMatch(match2);
204 assertTrue(wasAdded[0]);
205 wasAdded[0]= false;
206
207207 result.removeMatch(match2);
208208 assertTrue(wasRemoved[0]);
209209 wasRemoved[0]= false;
210
210
211211 result.removeMatch(match2);
212212 assertFalse(wasRemoved[0]);
213213 }
214
214
215215 @Test
216216 public void testBatchedMatchEvent() {
217217 final boolean [] wasAdded= { false };
218218 final boolean [] wasRemoved= { false };
219
220 ISearchQuery query= new NullQuery();
221 AbstractTextSearchResult result= (AbstractTextSearchResult) query.getSearchResult();
222
219
220 ISearchQuery query= new NullQuery();
221 AbstractTextSearchResult result= (AbstractTextSearchResult) query.getSearchResult();
222
223223 result.addListener(new ISearchResultListener() {
224224 @Override
225225 public void searchResultChanged(SearchResultEvent e) {
233233 }
234234 }
235235 });
236
237 String object= "object"; //$NON-NLS-1$
238
236
237 String object= "object"; //$NON-NLS-1$
238
239239 Match match1= new Match(object, 0, 0);
240240 result.addMatches(new Match[] { match1 });
241241 assertTrue(wasAdded[0]);
242242 wasAdded[0]= false;
243243 result.addMatches(new Match[] { match1 });
244244 assertFalse(wasAdded[0]);
245
245
246246 Match match2= new Match(object, 0, 0);
247247 result.addMatches(new Match[] { match2 });
248248 assertTrue(wasAdded[0]);
249249 wasAdded[0]= false;
250
250
251251 result.removeMatches(new Match[] { match2 });
252252 assertTrue(wasRemoved[0]);
253253 wasRemoved[0]= false;
254
254
255255 result.removeMatches(new Match[] { match2 });
256256 assertFalse(wasRemoved[0]);
257257 }
3131
3232
3333 public class FileTool {
34
34
3535 private final static int MAX_RETRY= 5;
36
36
3737 /**
3838 * A buffer.
3939 */
4040 private static byte[] buffer = new byte[8192];
41
41
4242 /**
4343 * Unzips the given zip file to the given destination directory
4444 * extracting only those entries the pass through the given
4545 * filter.
46 *
46 *
4747 * @param zipFile the zip file to unzip
4848 * @param dstDir the destination directory
4949 * @throws IOException in case of problem
5050 */
5151 public static void unzip(ZipFile zipFile, File dstDir) throws IOException {
5252 Enumeration<? extends ZipEntry> entries = zipFile.entries();
53
53
5454 try {
5555 while(entries.hasMoreElements()){
5656 ZipEntry entry = entries.nextElement();
6060 String entryName = entry.getName();
6161 File file = new File(dstDir, changeSeparator(entryName, '/', File.separatorChar));
6262 file.getParentFile().mkdirs();
63 InputStream src = null;
64 OutputStream dst = null;
65 try {
66 src = zipFile.getInputStream(entry);
67 dst = new FileOutputStream(file);
63
64 try (
65 InputStream src = zipFile.getInputStream(entry);
66 OutputStream dst = new FileOutputStream(file);
67 ) {
6868 transferData(src, dst);
69 } finally {
70 if(dst != null){
71 try {
72 dst.close();
73 } catch(IOException e){
74 }
75 }
76 if(src != null){
77 try {
78 src.close();
79 } catch(IOException e){
80 }
81 }
8269 }
8370 }
8471 } finally {
8875 }
8976 }
9077 }
91
78
9279 /**
9380 * Returns the given file path with its separator
9481 * character changed from the given old separator to the
9582 * given new separator.
96 *
83 *
9784 * @param path a file path
9885 * @param oldSeparator a path separator character
9986 * @param newSeparator a path separator character
10491 public static String changeSeparator(String path, char oldSeparator, char newSeparator){
10592 return path.replace(oldSeparator, newSeparator);
10693 }
107
94
10895 /**
10996 * Copies all bytes in the given source file to
11097 * the given destination file.
111 *
98 *
11299 * @param source the given source file
113100 * @param destination the given destination file
114101 * @throws IOException in case of error
115102 */
116103 public static void transferData(File source, File destination) throws IOException {
117104 destination.getParentFile().mkdirs();
118 InputStream is = null;
119 OutputStream os = null;
120 try {
121 is = new FileInputStream(source);
122 os = new FileOutputStream(destination);
105 try (
106 InputStream is = new FileInputStream(source);
107 OutputStream os = new FileOutputStream(destination);
108 ) {
109
123110 transferData(is, os);
124 } finally {
125 if(os != null){
126 try {
127 os.close();
128 } catch(IOException e){
129 }
130 }
131 if(is != null){
132 try {
133 is.close();
134 } catch(IOException e){
135 }
136 }
137 }
138 }
139
111 }
112 }
113
140114 /**
141115 * Copies all bytes in the given source stream to
142116 * the given destination stream. Neither streams
143117 * are closed.
144 *
118 *
145119 * @param source the given source stream
146120 * @param destination the given destination stream
147121 * @throws IOException in case of error
158132
159133 /**
160134 * Copies the given source file to the given destination file.
161 *
135 *
162136 * @param src the given source file
163137 * @param dst the given destination file
164138 * @throws IOException in case of error
166140 public static void copy(File src, File dst) throws IOException {
167141 if(src.isDirectory()){
168142 String[] srcChildren = src.list();
143 if (srcChildren == null) {
144 throw new IOException("Content from directory '" + src.getAbsolutePath() + "' can not be listed."); //$NON-NLS-1$ //$NON-NLS-2$
145 }
169146 for(int i = 0; i < srcChildren.length; ++i){
170147 File srcChild= new File(src, srcChildren[i]);
171148 File dstChild= new File(dst, srcChildren[i]);
184161 return null;
185162 }
186163 }
187
164
188165 public static File createTempFileInPlugin(Plugin plugin, IPath path) {
189166 IPath stateLocation= plugin.getStateLocation();
190167 stateLocation= stateLocation.append(path);
191168 return stateLocation.toFile();
192169 }
193
170
194171 public static StringBuffer read(String fileName) throws IOException {
195172 return read(new FileReader(fileName));
196173 }
214191 }
215192
216193 public static void write(String fileName, StringBuffer content) throws IOException {
217 Writer writer= new FileWriter(fileName);
218 try {
194 try (Writer writer= new FileWriter(fileName);) {
219195 writer.write(content.toString());
220 } finally {
221 try {
222 writer.close();
223 } catch (IOException e) {
224 }
225 }
226 }
227
196 }
197 }
198
228199 public static void delete(File file) {
229200 if (file.exists()) {
230201 for (int i= 0; i < MAX_RETRY; i++) {
3939 * @since 3.0
4040 */
4141 public class ResourceHelper {
42
42
4343 private final static IProgressMonitor NULL_MONITOR= new NullProgressMonitor();
4444 private static final int MAX_RETRY= 10;
45
45
4646 public static IProject createProject(String projectName) throws CoreException {
47
47
4848 IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
4949 IProject project= root.getProject(projectName);
5050 if (!project.exists())
5151 project.create(NULL_MONITOR);
5252 else
5353 project.refreshLocal(IResource.DEPTH_INFINITE, null);
54
54
5555 if (!project.isOpen())
5656 project.open(NULL_MONITOR);
57
57
5858 return project;
5959 }
60
60
6161 public static void deleteProject(String projectName) throws CoreException {
6262 IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
6363 IProject project= root.getProject(projectName);
6464 if (project.exists())
6565 delete(project);
6666 }
67
67
6868 public static void delete(final IResource resource) throws CoreException {
6969 IWorkspaceRunnable runnable= new IWorkspaceRunnable() {
7070 @Override
8888 }
8989 };
9090 ResourcesPlugin.getWorkspace().run(runnable, null);
91
91
9292 }
9393
9494 /**
9595 * Creates a folder and all parent folders if not existing. Project must exist.
96 *
96 *
9797 * @param folder The folder to create
9898 * @return Returns the input folder
9999 * @throws CoreException if creation fails
108108 }
109109 return folder;
110110 }
111
111
112112 public static IFile createFile(IFolder folder, String name, String contents, String encoding) throws CoreException, IOException {
113113 IFile file= folder.getFile(name);
114114 if (contents == null)
115115 contents= ""; //$NON-NLS-1$
116 InputStream inputStream= new ByteArrayInputStream(contents.getBytes(encoding));
117 file.create(inputStream, true, NULL_MONITOR);
118 file.setCharset(encoding, null);
119 inputStream.close();
116 try (InputStream inputStream= new ByteArrayInputStream(contents.getBytes(encoding))) {
117 file.create(inputStream, true, NULL_MONITOR);
118 file.setCharset(encoding, null);
119 }
120
120121 return file;
121122 }
122
123
123124 public static IFile createFile(IFolder folder, String name, String contents) throws CoreException, IOException {
124125 return createFile(folder, name, contents, "ISO-8859-1");
125126 }
126
127
127128 public static IFile createLinkedFile(IContainer container, IPath linkPath, File linkedFileTarget) throws CoreException {
128129 IFile iFile= container.getFile(linkPath);
129130 iFile.createLink(new Path(linkedFileTarget.getAbsolutePath()), IResource.ALLOW_MISSING_LOCAL, NULL_MONITOR);
130131 return iFile;
131132 }
132
133
133134 public static IFile createLinkedFile(IContainer container, IPath linkPath, Plugin plugin, IPath linkedFileTargetPath) throws CoreException {
134135 File file= FileTool.getFileInPlugin(plugin, linkedFileTargetPath);
135136 IFile iFile= container.getFile(linkPath);
136137 iFile.createLink(new Path(file.getAbsolutePath()), IResource.ALLOW_MISSING_LOCAL, NULL_MONITOR);
137138 return iFile;
138139 }
139
140
140141 public static IFolder createLinkedFolder(IContainer container, IPath linkPath, File linkedFolderTarget) throws CoreException {
141142 IFolder folder= container.getFolder(linkPath);
142143 folder.createLink(new Path(linkedFolderTarget.getAbsolutePath()), IResource.ALLOW_MISSING_LOCAL, NULL_MONITOR);
143144 return folder;
144145 }
145
146
146147 public static IFolder createLinkedFolder(IContainer container, IPath linkPath, Plugin plugin, IPath linkedFolderTargetPath) throws CoreException {
147148 File file= FileTool.getFileInPlugin(plugin, linkedFolderTargetPath);
148149 IFolder iFolder= container.getFolder(linkPath);
149150 iFolder.createLink(new Path(file.getAbsolutePath()), IResource.ALLOW_MISSING_LOCAL, NULL_MONITOR);
150151 return iFolder;
151152 }
152
153
153154 public static IProject createLinkedProject(String projectName, Plugin plugin, IPath linkPath) throws CoreException {
154155 IWorkspace workspace= ResourcesPlugin.getWorkspace();
155156 IProject project= workspace.getRoot().getProject(projectName);
156
157
157158 IProjectDescription desc= workspace.newProjectDescription(projectName);
158159 File file= FileTool.getFileInPlugin(plugin, linkPath);
159160 IPath projectLocation= new Path(file.getAbsolutePath());
160161 if (Platform.getLocation().equals(projectLocation))
161162 projectLocation= null;
162163 desc.setLocation(projectLocation);
163
164
164165 project.create(desc, NULL_MONITOR);
165166 if (!project.isOpen())
166167 project.open(NULL_MONITOR);
167
168
168169 return project;
169170 }
170
171
171172 public static IProject createJUnitSourceProject(String projectName) throws CoreException, ZipException, IOException {
172173 IProject project= ResourceHelper.createProject(projectName);
173174 ZipFile zip= new ZipFile(FileTool.getFileInPlugin(SearchTestPlugin.getDefault(), new Path("testresources/junit37-noUI-src.zip"))); //$NON-NLS-1$
3434 public class SearchTestPlugin extends AbstractUIPlugin {
3535 //The shared instance.
3636 private static SearchTestPlugin fgPlugin;
37
37
3838 public SearchTestPlugin() {
3939 fgPlugin = this;
4040 }
4242 public static SearchTestPlugin getDefault() {
4343 return fgPlugin;
4444 }
45
45
4646 public SearchView getSearchView() {
4747 return (SearchView) NewSearchUI.activateSearchResultView();
4848 }
6464 fQuery1= new FileSearchQuery("Test", false, true, scope); //$NON-NLS-1$//$NON-NLS-2$
6565 fQuery2= new FileSearchQuery("Test", false, true, scope); //$NON-NLS-1$//$NON-NLS-2$
6666 }
67
67
6868 @After
6969 public void tearDown() {
7070 InternalSearchUI.getInstance().removeAllQueries();
7171 fQuery1= null;
7272 fQuery2= null;
73
73
7474 EditorAnnotationManager.debugSetHighlighterType(EditorAnnotationManager.HIGHLLIGHTER_ANY);
7575
7676 }
9393 positions.add(annotationModel.getPosition(annotation));
9494 }
9595 }
96
96
9797 Match[] matches= result.getMatches(file);
9898 for (int j= 0; j < matches.length; j++) {
9999 Position position= new Position(matches[j].getOffset(), matches[j].getLength());
100100 assertTrue("position not found at: "+j, positions.remove(position)); //$NON-NLS-1$
101101 }
102102 assertEquals(0, positions.size());
103
104 }
105 } finally {
106 SearchPlugin.getActivePage().closeAllEditors(false);
107 }
108 }
109
103
104 }
105 } finally {
106 SearchPlugin.getActivePage().closeAllEditors(false);
107 }
108 }
109
110110 @Test
111111 public void testBogusAnnotation() throws Exception {
112112 NewSearchUI.runQueryInForeground(null, fQuery1);
115115 SearchTestPlugin.openTextEditor(SearchTestPlugin.getDefault().getWorkbench().getWorkbenchWindows()[0].getPages()[0], file);
116116 result.addMatch(new FileMatch(file));
117117 }
118
118
119119 @Test
120120 public void testRemoveQuery() throws Exception {
121121 NewSearchUI.runQueryInForeground(null, fQuery1);
122122 AbstractTextSearchResult result= (AbstractTextSearchResult) fQuery1.getSearchResult();
123123 Object[] files= result.getElements();
124124 InternalSearchUI.getInstance().removeQuery(fQuery1);
125
125
126126 try {
127127 for (int i= 0; i < files.length; i++) {
128128 IFile file= (IFile)files[i];
169169 SearchPlugin.getActivePage().closeAllEditors(false);
170170 }
171171 }
172
172
173173 @Test
174174 public void testSwitchQuery() throws Exception {
175175 NewSearchUI.runQueryInForeground(null, fQuery1);
3030 public class FileCharSequenceTests {
3131
3232 private final String TEST_CONTENT= "ABCDEFGHIJKLMNOPQRSTUVWXYZÜöäüèéùabcdefghijklmnopqrstuvwxyz1234567890@\'\"\n$¢"; //€
33
33
3434 private IProject fProject;
35
35
3636 @Before
3737 public void setUp() throws Exception {
3838 fProject= ResourceHelper.createProject("my-project"); //$NON-NLS-1$
3939 }
40
40
4141 @After
4242 public void tearDown() throws Exception {
4343 ResourceHelper.deleteProject("my-project"); //$NON-NLS-1$
4444 }
45
45
4646 @Test
4747 public void testFileCharSequence() throws Exception {
48 StringBuffer buf= new StringBuffer();
48 StringBuilder buf= new StringBuilder();
4949 for (int i= 0; i < 500; i++) {
5050 buf.append(TEST_CONTENT);
5151 }
5555
5656 @Test
5757 public void testFileCharSequence2() throws Exception {
58 StringBuffer buf= new StringBuffer();
58 StringBuilder buf= new StringBuilder();
5959 for (int i= 0; i < 2000; i++) {
6060 buf.append(TEST_CONTENT);
6161 }
6565
6666 @Test
6767 public void testFileCharSequence3() throws Exception {
68 StringBuffer buf= new StringBuffer();
68 StringBuilder buf= new StringBuilder();
6969 for (int i= 0; i < FileCharSequenceProvider.BUFFER_SIZE * 2; i++) {
7070 buf.append(TEST_CONTENT);
7171 }
7676 private void testForEncoding(CharSequence buf, String encoding) throws CoreException, IOException {
7777 IFolder folder= ResourceHelper.createFolder(fProject.getFolder("folder1"));
7878 IFile file1= ResourceHelper.createFile(folder, "file1", buf.toString(), encoding);
79
79
8080 FileCharSequenceProvider provider= new FileCharSequenceProvider();
8181 CharSequence cs= null;
8282 try {
8383 cs= provider.newCharSequence(file1);
84
84
8585 assertEquals(encoding, cs, buf);
86
86
8787 assertSubSequence(encoding, cs, buf, 0, buf.length() / 6);
8888 assertSubSequence(encoding, cs, buf, buf.length() / 6, FileCharSequenceProvider.BUFFER_SIZE);
89
89
9090 int pos= 8 * buf.length() / 9;
9191 assertSubSequence(encoding, cs, buf, pos, buf.length() - pos);
92
92
9393 CharSequence seq1a= cs.subSequence(100, 100 + FileCharSequenceProvider.BUFFER_SIZE);
9494 CharSequence seq1e= buf.subSequence(100, 100 + FileCharSequenceProvider.BUFFER_SIZE);
9595 assertSubSequence(encoding, seq1a, seq1e, 500, 500);
96
96
9797 assertSubSequence(encoding, seq1a, seq1e, FileCharSequenceProvider.BUFFER_SIZE, 0);
98
98
9999 } finally {
100100 if (cs != null) {
101101 provider.releaseCharSequence(cs);
103103 file1.delete(true, null);
104104 }
105105 }
106
106
107107 private void assertSubSequence(String message, CharSequence actual, CharSequence expected, int start, int length) {
108108 CharSequence actualSub= actual.subSequence(start, start + length);
109109 CharSequence expectedSub= expected.subSequence(start, start + length);
110110 assertEquals(message + " - subsequence(" + start + ", " + length + ")", actualSub, expectedSub);
111111 }
112
112
113113 private void assertEquals(String desc, CharSequence actual, CharSequence expected) {
114114 for (int i= 0; i < expected.length(); i++) {
115115 Assert.assertEquals(desc + " - forward " + i, expected.charAt(i), actual.charAt(i));
124124 for (int i= 0; i < expected.length(); i+= FileCharSequenceProvider.BUFFER_SIZE) {
125125 Assert.assertEquals(desc + " - forward - buffersize" + i, expected.charAt(i), actual.charAt(i));
126126 }
127
127
128128 assertOutOfBound(desc + "access at length", actual, expected.length());
129129 assertOutOfBound(desc + "access at -1", actual, -1);
130130
131131 Assert.assertEquals(desc + " - length", actual.toString(), expected.toString());
132132 }
133
134
133
134
135135 private void assertOutOfBound(String message, CharSequence cs, int i) {
136136 try {
137137 cs.charAt(i);
142142 }
143143
144144
145
145
146146 }
00 /*******************************************************************************
1 * Copyright (c) 2000, 2016 IBM Corporation and others.
1 * Copyright (c) 2000, 2017 IBM Corporation and others.
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
88 * IBM Corporation - initial API and implementation
99 * Christian Walther (Indel AG) - Bug 399094, 402009: Add whole word option to file search
1010 * Terry Parker <tparker@google.com> (Google Inc.) - Bug 441016 - Speed up text search by parallelizing it using JobGroups
11 * Florian Ingerl <imelflorianingerl@gmail.com> - Bug 109481 - [find/replace] replace doesn't work when using a regex with a lookahead or boundary matchers
1112 *******************************************************************************/
1213 package org.eclipse.search.tests.filesearch;
1314
1415 import static org.junit.Assert.assertEquals;
1516
17 import java.io.IOException;
1618 import java.util.ArrayList;
1719 import java.util.List;
20 import java.util.Scanner;
1821 import java.util.regex.Pattern;
1922
2023 import org.junit.After;
2326 import org.junit.Test;
2427
2528 import org.eclipse.core.runtime.CoreException;
29 import org.eclipse.core.runtime.NullProgressMonitor;
30 import org.eclipse.core.runtime.OperationCanceledException;
2631
2732 import org.eclipse.core.resources.IFile;
2833 import org.eclipse.core.resources.IFolder;
3742 import org.eclipse.search.core.text.TextSearchScope;
3843 import org.eclipse.search.internal.core.text.PatternConstructor;
3944 import org.eclipse.search.internal.ui.SearchPlugin;
45 import org.eclipse.search.internal.ui.text.FileSearchQuery;
46 import org.eclipse.search.internal.ui.text.FileSearchResult;
47 import org.eclipse.search.internal.ui.text.ReplaceRefactoring;
4048 import org.eclipse.search.tests.ResourceHelper;
4149 import org.eclipse.search.tests.SearchTestPlugin;
4250 import org.eclipse.search.ui.text.FileTextSearchScope;
4351
52 import org.eclipse.ltk.core.refactoring.Change;
53
4454 public class FileSearchTests {
45
55
4656 private static class TestResult {
4757 public IResource resource;
4858 public int offset;
113123 public static JUnitSourceSetup fgJUnitSource= new JUnitSourceSetup();
114124
115125 private IProject fProject;
116
126
117127 @Before
118128 public void setUp() throws Exception{
119129 fProject= ResourceHelper.createProject("my-project"); //$NON-NLS-1$
120130 }
121
131
122132 @After
123133 public void tearDown() throws Exception {
124134 ResourceHelper.deleteProject("my-project"); //$NON-NLS-1$
128138 public void testSimpleFilesSerial() throws Exception {
129139 testSimpleFiles(new SerialTestResultCollector());
130140 }
131
141
132142 @Test
133143 public void testSimpleFilesParallel() throws Exception {
134144 testSimpleFiles(new ParallelTestResultCollector());
135145 }
136146
137147 private void testSimpleFiles(TestResultCollector collector) throws Exception {
138 StringBuffer buf= new StringBuffer();
148 StringBuilder buf= new StringBuilder();
139149 buf.append("File1\n");
140150 buf.append("hello\n");
141151 buf.append("more hello\n");
155165 assertMatches(results, 2, file1, buf.toString(), "hello");
156166 assertMatches(results, 2, file2, buf.toString(), "hello");
157167 }
158
168
159169 @Test
160170 public void testWildCards1Serial() throws Exception {
161171 testWildCards1(new SerialTestResultCollector());
162172 }
163
173
164174 @Test
165175 public void testWildCards1Parallel() throws Exception {
166176 testWildCards1(new ParallelTestResultCollector());
167177 }
168178
169179 private void testWildCards1(TestResultCollector collector) throws Exception {
170 StringBuffer buf= new StringBuffer();
180 StringBuilder buf= new StringBuilder();
171181 buf.append("File1\n");
172182 buf.append("no more\n");
173183 buf.append("mornings\n");
178188 ResourceHelper.createFile(folder, "file2", buf.toString());
179189
180190 Pattern searchPattern= PatternConstructor.createPattern("mor*", false, false);
181
191
182192 FileTextSearchScope scope= FileTextSearchScope.newSearchScope(new IResource[] {fProject}, (String[]) null, false);
183193 TextSearchEngine.create().search(scope, collector, searchPattern, null);
184
194
185195 TestResult[] results= collector.getResults();
186196 assertEquals("Number of total results", 6, results.length);
187197 }
188
198
189199 @Test
190200 public void testWildCards2Serial() throws Exception {
191201 testWildCards2(new SerialTestResultCollector());
192202 }
193
203
194204 @Test
195205 public void testWildCards2Parallel() throws Exception {
196206 testWildCards2(new ParallelTestResultCollector());
197207 }
198208
199209 private void testWildCards2(TestResultCollector collector) throws Exception {
200 StringBuffer buf= new StringBuffer();
210 StringBuilder buf= new StringBuilder();
201211 buf.append("File1\n");
202212 buf.append("no more\n");
203213 buf.append("mornings\n");
208218 ResourceHelper.createFile(folder, "file2", buf.toString());
209219
210220 Pattern searchPattern= PatternConstructor.createPattern("mo?e", false, false);
211
221
212222 FileTextSearchScope scope= FileTextSearchScope.newSearchScope(new IResource[] {fProject}, (String[]) null, false);
213223 TextSearchEngine.create().search(scope, collector, searchPattern, null);
214
224
215225 TestResult[] results= collector.getResults();
216226 assertEquals("Number of total results", 4, results.length);
217227 }
218
228
219229 @Test
220230 public void testWildCards3Serial() throws Exception {
221231 testWildCards3(new SerialTestResultCollector());
222232 }
223
233
224234 @Test
225235 public void testWildCards3Parallel() throws Exception {
226236 testWildCards3(new ParallelTestResultCollector());
227237 }
228238
229239 private void testWildCards3(TestResultCollector collector) throws Exception {
230
240
231241 IProject project= fgJUnitSource.getStandardProject();
232242 IFile openFile1= (IFile) project.findMember("junit/framework/TestCase.java");
233243 IFile openFile2= (IFile) project.findMember("junit/extensions/ExceptionTestCase.java");
234244 IFile openFile3= (IFile) project.findMember("junit/framework/Assert.java");
235245 IFile openFile4= (IFile) project.findMember("junit/samples/money/MoneyTest.java");
236
246
237247 IWorkbenchPage activePage= SearchPlugin.getActivePage();
238248 try {
239249 SearchTestPlugin.openTextEditor(activePage, openFile1);
240250 SearchTestPlugin.openTextEditor(activePage, openFile2);
241251 SearchTestPlugin.openTextEditor(activePage, openFile3);
242252 SearchTestPlugin.openTextEditor(activePage, openFile4);
243
253
244254 long start= System.currentTimeMillis();
245255
246256 Pattern searchPattern= PatternConstructor.createPattern("\\w*\\(\\)", false, true);
259269 }
260270
261271 }
262
272
263273 @Test
264274 public void testWholeWordSerial() throws Exception {
265275 testWholeWord(new SerialTestResultCollector());
266276 }
267
277
268278 @Test
269279 public void testWholeWordParallel() throws Exception {
270280 testWholeWord(new ParallelTestResultCollector());
271281 }
272282
273283 private void testWholeWord(TestResultCollector collector) throws Exception {
274 StringBuffer buf= new StringBuffer();
284 StringBuilder buf= new StringBuilder();
275285 // nothing after
276286 buf.append("hell\n"); // nothing before
277287 buf.append("hill\n"); // nothing before
315325 assertEquals("Number of partial-word results", 22, collector.getNumberOfResults());
316326 }
317327 }
318
328
319329 @Test
320330 public void testFileOpenInEditorSerial() throws Exception {
321331 testFileOpenInEditor(new SerialTestResultCollector());
322332 }
323
333
324334 @Test
325335 public void testFileOpenInEditorParallel() throws Exception {
326336 testFileOpenInEditor(new ParallelTestResultCollector());
327337 }
328338
329339 private void testFileOpenInEditor(TestResultCollector collector) throws Exception {
330 StringBuffer buf= new StringBuffer();
340 StringBuilder buf= new StringBuilder();
331341 buf.append("File1\n");
332342 buf.append("hello\n");
333343 buf.append("more hello\n");
338348
339349 try {
340350 SearchTestPlugin.openTextEditor(SearchPlugin.getActivePage(), file2);
341
351
342352 Pattern searchPattern= PatternConstructor.createPattern("hello", false, true);
343353
344354 FileTextSearchScope scope= FileTextSearchScope.newSearchScope(new IResource[] {fProject}, (String[]) null, false);
353363 SearchPlugin.getActivePage().closeAllEditors(false);
354364 }
355365 }
356
366
357367 @Test
358368 public void testDerivedFilesSerial() throws Exception {
359369 testDerivedFiles(new SerialTestResultCollector());
360370 }
361
371
362372 @Test
363373 public void testDerivedFilesParallel() throws Exception {
364374 testDerivedFiles(new ParallelTestResultCollector());
365375 }
366376
367377 private void testDerivedFiles(TestResultCollector collector) throws Exception {
368 StringBuffer buf= new StringBuffer();
378 StringBuilder buf= new StringBuilder();
369379 buf.append("hello\n");
370380 IFolder folder1= ResourceHelper.createFolder(fProject.getFolder("folder1"));
371381 ResourceHelper.createFile(folder1, "file1", buf.toString());
372382 IFile file2= ResourceHelper.createFile(folder1, "file2", buf.toString());
373383 file2.setDerived(true, null);
374
384
375385 IFolder folder2= ResourceHelper.createFolder(folder1.getFolder("folder2"));
376386 folder2.setDerived(true, null);
377387 ResourceHelper.createFile(folder2, "file3", buf.toString());
378388
379389 IFolder folder3= ResourceHelper.createFolder(folder2.getFolder("folder3"));
380390 ResourceHelper.createFile(folder3, "file4", buf.toString());
381
391
382392 IFolder folder4= ResourceHelper.createFolder(folder1.getFolder("folder4"));
383393 ResourceHelper.createFile(folder4, "file5", buf.toString());
384
394
385395 /**
386396 * folder1
387397 * file1
393403 * folder4
394404 * file5
395405 */
396
397
406
407
398408 Pattern searchPattern= PatternConstructor.createPattern("hello", false, true);
399409 Pattern fileNamePattern= PatternConstructor.createPattern("*", false, false);
400410 TextSearchEngine engine= TextSearchEngine.create();
441451 assertEquals(0, collector.getNumberOfResults());
442452 }
443453 }
444
454
445455 @Test
446456 public void testFileNamePatternsSerial() throws Exception {
447457 testFileNamePatterns(new SerialTestResultCollector());
448458 }
449
459
450460 @Test
451461 public void testFileNamePatternsParallel() throws Exception {
452462 testFileNamePatterns(new ParallelTestResultCollector());
462472
463473 Pattern searchPattern= PatternConstructor.createPattern("Test", false, false);
464474 String[] fileNamePatterns= { "*" };
465
475
466476 TestResult[] results= performSearch(collector, fileNamePatterns, searchPattern);
467477 assertEquals("Number of total results", 4, results.length);
468
478
469479 fileNamePatterns= new String[] { "*.x" };
470480 results= performSearch(collector, fileNamePatterns, searchPattern);
471481 assertEquals("Number of total results", 2, results.length);
472
482
473483 fileNamePatterns= new String[] { "*.x", "*.y*" };
474484 results= performSearch(collector, fileNamePatterns, searchPattern);
475485 assertEquals("Number of total results", 3, results.length);
476
486
477487 fileNamePatterns= new String[] { "!*.x" };
478488 results= performSearch(collector, fileNamePatterns, searchPattern);
479489 assertEquals("Number of total results", 2, results.length);
480
490
481491 fileNamePatterns= new String[] { "!*.x", "!*.y" };
482492 results= performSearch(collector, fileNamePatterns, searchPattern);
483493 assertEquals("Number of total results", 1, results.length);
484
494
485495 fileNamePatterns= new String[] { "*", "!*.y" };
486496 results= performSearch(collector, fileNamePatterns, searchPattern);
487497 assertEquals("Number of total results", 3, results.length);
488
498
489499 fileNamePatterns= new String[] { "*", "!*.*" };
490500 results= performSearch(collector, fileNamePatterns, searchPattern);
491501 assertEquals("Number of total results", 0, results.length);
492
502
493503 fileNamePatterns= new String[] { "*.x", "*.y*", "!*.y" };
494504 results= performSearch(collector, fileNamePatterns, searchPattern);
495505 assertEquals("Number of total results", 2, results.length);
496
506
497507 fileNamePatterns= new String[] { "file*", "!*.x*", "!*.y" };
498508 results= performSearch(collector, fileNamePatterns, searchPattern);
499509 assertEquals("Number of total results", 1, results.length);
500510 }
501
511
502512 private TestResult[] performSearch(TestResultCollector collector, String[] fileNamePatterns, Pattern searchPattern) {
503513 collector.reset();
504514 FileTextSearchScope scope= FileTextSearchScope.newSearchScope(new IResource[] {fProject}, fileNamePatterns, false);
505515 TextSearchEngine.create().search(scope, collector, searchPattern, null);
506
516
507517 return collector.getResults();
508518
509519 }
510
520
511521
512522
513523 private void assertMatches(TestResult[] results, int expectedCount, IFile file, String fileContent, String string) {
521531 }
522532 assertEquals("Number of results in file", expectedCount, k);
523533 }
524
525
534
535 @Test
536 public void testReplaceWithLookarounds() throws CoreException, IOException {
537 IFolder folder= ResourceHelper.createFolder(fProject.getFolder("folder1"));
538 IFile file1= ResourceHelper.createFile(folder, "file1.txt", "1<2<3<4");
539 IFile file2= ResourceHelper.createFile(folder, "file2.txt", "4<5<6<7");
540
541 FileSearchResult searchResult= performSearch(new String[] { "*.txt" }, "(?<=(\\d)\\<)\\d(?=\\<(\\d))");
542 performReplace(searchResult, "$0=($1+$2)/2");
543
544 assertFileContent(file1, "1<2=(1+3)/2<3=(2+4)/2<4");
545 assertFileContent(file2, "4<5=(4+6)/2<6=(5+7)/2<7");
546 }
547
548 @Test
549 public void testReplaceRetainCase() throws CoreException, IOException {
550 IFolder folder= ResourceHelper.createFolder(fProject.getFolder("folder1"));
551 IFile file1= ResourceHelper.createFile(folder, "file1.txt", "FOO");
552
553 FileSearchResult searchResult= performSearch(new String[] { "*.txt" }, "FOO");
554 performReplace(searchResult, "xyz\\Cbar\\Cfar");
555
556 assertFileContent(file1, "xyzBARFAR");
557 }
558
559 private FileSearchResult performSearch(String[] fileNamePatterns, String pattern) {
560 FileTextSearchScope scope= FileTextSearchScope.newSearchScope(new IResource[] { fProject }, fileNamePatterns, false);
561 FileSearchQuery query= new FileSearchQuery(pattern, true, true, scope);
562 query.run(null);
563 return (FileSearchResult) query.getSearchResult();
564 }
565
566 private void performReplace(FileSearchResult searchResult, String replacementText) throws OperationCanceledException, CoreException {
567 ReplaceRefactoring refactoring= new ReplaceRefactoring(searchResult, null);
568 refactoring.setReplaceString(replacementText);
569 refactoring.checkInitialConditions(null);
570 refactoring.checkFinalConditions(null);
571 Change change= refactoring.createChange(null);
572 change.perform(new NullProgressMonitor());
573 }
574
575 private void assertFileContent(IFile file, String expected) throws CoreException {
576 try (Scanner scanner= new Scanner(file.getContents())) {
577 scanner.useDelimiter("\\A");
578 assertEquals(expected, scanner.next());
579 }
580 }
526581 }
1919 import org.eclipse.search.tests.ResourceHelper;
2020
2121 public class JUnitSourceSetup extends ExternalResource {
22
22
2323 public static final String STANDARD_PROJECT_NAME= "JUnitSource";
24
24
2525 private IProject fProject= null;
2626 private final String fProjectName;
27
27
2828 public IProject getStandardProject() {
2929 return ResourcesPlugin.getWorkspace().getRoot().getProject(STANDARD_PROJECT_NAME);
3030 }
3232 public JUnitSourceSetup() {
3333 this(STANDARD_PROJECT_NAME);
3434 }
35
35
3636 public JUnitSourceSetup(String projectName) {
3737 fProjectName= projectName;
3838 }
39
39
4040 @Override
4141 public void before() throws Exception {
4242 IProject project= ResourcesPlugin.getWorkspace().getRoot().getProject(fProjectName);
4444 fProject= ResourceHelper.createJUnitSourceProject(fProjectName);
4545 }
4646 }
47
47
4848 @Override
4949 public void after() /*throws Exception (but JUnit4 API is stupid...)*/ {
5050 if (fProject != null) { // delete only by the setup who created the project
5656 @Before
5757 public void setUp() throws Exception {
5858 EditorAnnotationManager.debugSetHighlighterType(EditorAnnotationManager.HIGHLIGHTER_ANNOTATION);
59
59
6060 String[] fileNamePatterns= { "*.java" };
6161 FileTextSearchScope scope= FileTextSearchScope.newWorkspaceScope(fileNamePatterns, false);
62
62
6363 fLineQuery= new LineBasedFileSearch(scope, false, true, "Test");
6464 }
65
65
6666 @After
6767 public void tearDown() throws Exception {
6868 InternalSearchUI.getInstance().removeAllQueries();
6969 fLineQuery= null;
70
70
7171 EditorAnnotationManager.debugSetHighlighterType(EditorAnnotationManager.HIGHLLIGHTER_ANY);
7272 }
73
74 @Test
73
74 @Test
7575 public void testLineBasedQuery() throws Exception {
7676 NewSearchUI.runQueryInForeground(null, fLineQuery);
7777 AbstractTextSearchResult result= (AbstractTextSearchResult) fLineQuery.getSearchResult();
3838 /**
3939 */
4040 public class LineBasedFileSearch extends FileSearchQuery {
41
42
41
42
4343 private static class LineBasedTextSearchResultCollector extends TextSearchRequestor {
44
44
4545 private final AbstractTextSearchResult fResult;
4646 private IFile fLastFile;
47 private IDocument fLastDocument;
47 private IDocument fLastDocument;
4848 private Object fLock= new Object();
4949
5050 private LineBasedTextSearchResultCollector(AbstractTextSearchResult result) {
8686 FileBuffers.getTextFileBufferManager().disconnect(fLastFile.getFullPath(), LocationKind.IFILE, null);
8787 }
8888 fLastFile= file;
89
89
9090 FileBuffers.getTextFileBufferManager().connect(file.getFullPath(), LocationKind.IFILE, null);
9191 fLastDocument= FileBuffers.getTextFileBufferManager().getTextFileBuffer(file.getFullPath(), LocationKind.IFILE).getDocument();
9292 return fLastDocument;
9393 }
94
94
9595 @Override
9696 public void endReporting() {
9797 if (fLastFile != null) {
102102 }
103103 }
104104 }
105
105
106106 private final FileTextSearchScope fScope;
107
108
107
108
109109 public LineBasedFileSearch(FileTextSearchScope scope, boolean isRegEx, boolean isCaseSensitive, String searchString) {
110110 super(searchString, isRegEx, isCaseSensitive, scope);
111111 fScope= scope;
116116 public IStatus run(IProgressMonitor monitor) {
117117 AbstractTextSearchResult textResult= (AbstractTextSearchResult) getSearchResult();
118118 textResult.removeAll();
119
119
120120 LineBasedTextSearchResultCollector collector= new LineBasedTextSearchResultCollector(textResult);
121
121
122122 Pattern searchPattern= getSearchPattern();
123123 return TextSearchEngine.create().search(fScope, collector, searchPattern, monitor);
124124 }
125
125
126126
127127 }
4949 public void setUp() throws Exception {
5050 String[] fileNamePatterns= { "*.java" };
5151 FileTextSearchScope scope= FileTextSearchScope.newWorkspaceScope(fileNamePatterns, false);
52
52
5353 fQuery1= new FileSearchQuery("Test", false, true, scope);
5454 }
55
56
55
56
5757 @Test
5858 public void testInsertAt0() throws Exception {
5959 NewSearchUI.runQueryInForeground(null, fQuery1);
6767 SearchPlugin.getActivePage().closeAllEditors(false);
6868 }
6969 }
70
70
7171 @Test
7272 public void testInsertInsideMatch() throws Exception {
7373 NewSearchUI.runQueryInForeground(null, fQuery1);
100100 Position currentPosition= InternalSearchUI.getInstance().getPositionTracker().getCurrentPosition(matches[i]);
101101 assertNotNull(currentPosition);
102102 String text= doc.get(currentPosition.offset, currentPosition.length);
103 StringBuffer buf= new StringBuffer();
103 StringBuilder buf= new StringBuilder();
104104 buf.append(text.charAt(0));
105105 buf.append(text.substring(5));
106106 assertEquals(buf.toString(), ((FileSearchQuery) result.getQuery()).getSearchString());
132132 SearchPlugin.getActivePage().closeAllEditors(false);
133133 }
134134 }
135
135
136136 }
2929
3030 public class ResultUpdaterTest {
3131 private FileSearchQuery fQuery1;
32
32
3333 private IProject fProject;
34
34
3535 private static final String PROJECT_TO_MODIFY= "ModifiableProject";
3636
3737 @Before
3838 public void setUp() throws Exception {
3939 // create a own project to make modifications
4040 fProject= ResourceHelper.createJUnitSourceProject(PROJECT_TO_MODIFY);
41
41
4242 String[] fileNamePatterns= { "*.java" };
4343 FileTextSearchScope scope= FileTextSearchScope.newSearchScope(new IResource[] { fProject }, fileNamePatterns, false);
44
44
4545 fQuery1= new FileSearchQuery("Test", false, true, scope);
4646 }
47
47
4848 @After
4949 public void tearDown() throws Exception {
5050 ResourceHelper.deleteProject(PROJECT_TO_MODIFY);
5151 }
52
52
5353 @Test
5454 public void testRemoveFile() throws Exception {
5555 NewSearchUI.runQueryInForeground(null, fQuery1);
6161 assertEquals(totalCount-fileCount, result.getMatchCount());
6262 assertEquals(0, result.getMatchCount(elements[0]));
6363 }
64
64
6565 @Test
6666 public void testRemoveProject() throws Exception {
6767 NewSearchUI.runQueryInForeground(null, fQuery1);
5151 SearchTestPlugin.ensureWelcomePageClosed();
5252 String[] fileNamePatterns= { "*.java" };
5353 FileTextSearchScope scope= FileTextSearchScope.newWorkspaceScope(fileNamePatterns, false);
54
54
5555 fQuery1= new FileSearchQuery("Test", false, true, scope);
5656 }
5757
6666 page.setLayout(AbstractTextSearchViewPage.FLAG_LAYOUT_FLAT);
6767 checkViewerDisplay(page);
6868 }
69
69
7070 private void checkViewerDisplay(FileSearchPage page) {
7171 StructuredViewer viewer= page.getViewer();
7272 AbstractTextSearchResult result= (AbstractTextSearchResult) fQuery1.getSearchResult();
8080 }
8181 }
8282
83
83
8484 @Test
8585 @Ignore // checkElementDisplay(..) misses cases where one line contains multiple matches
8686 public void testRemoveTreeMatches() throws Exception {
112112 Display.getDefault().readAndDispatch();
113113 }
114114 }
115
115
116116 private void consumeEvents() {
117117 while (Display.getDefault().readAndDispatch()) {
118118 }
127127 if (itemCount > 1)
128128 assertTrue(item.getText().indexOf(String.valueOf(itemCount)) >= 0);
129129 }
130
130
131131 @Test
132132 public void testTableNavigation() {
133133 NewSearchUI.runQueryInForeground(null, fQuery1);
135135 FileSearchPage page= (FileSearchPage) view.getActivePage();
136136 page.setLayout(AbstractTextSearchViewPage.FLAG_LAYOUT_FLAT);
137137 Table table= ((TableViewer) page.getViewer()).getTable();
138
138
139139 consumeEvents();
140
140
141141 // select the first element.
142142 table.setSelection(0);
143143 table.showSelection();
144
144
145145 consumeEvents();
146146 // back from first match, goto last
147147 page.gotoPreviousMatch();
148
148
149149 consumeEvents();
150
150
151151 assertEquals(1, table.getSelectionCount());
152152 assertEquals(table.getItemCount()-1, table.getSelectionIndex());
153153
154154 // and forward again, to the first match.
155155 page.gotoNextMatch();
156
156
157157 consumeEvents();
158158 assertEquals(1, table.getSelectionCount());
159159 assertEquals(0, table.getSelectionIndex());
3535 public void setUp() throws Exception {
3636 String[] fileNamePatterns= { "*.java" };
3737 FileTextSearchScope scope= FileTextSearchScope.newWorkspaceScope(fileNamePatterns, false);
38
38
3939 fQuery1= new FileSearchQuery("Test", false, true, scope);
4040 }
41
41
4242 @Test
4343 public void testSorted() throws Exception {
4444 NewSearchUI.activateSearchResultView();
4646 AbstractTextSearchResult result= (AbstractTextSearchResult) fQuery1.getSearchResult();
4747 int originalMatchCount= result.getMatchCount();
4848 List<Match> allMatches= new ArrayList<>(originalMatchCount);
49
49
5050 // first, collect all matches
5151 Object[] elements= result.getElements();
5252 for (int i= 0; i < elements.length; i++) {
5858 // now remove them and readd them in reverse order
5959 result.removeAll();
6060 assertTrue("removed all matches", result.getMatchCount() == 0);
61
61
6262 for (int i= allMatches.size()-1; i >= 0; i--) {
6363 result.addMatch(allMatches.get(i));
6464 }
65
65
6666 assertEquals("Test that all matches have been added again", result.getMatchCount(), originalMatchCount);
67
67
6868 // now check that they're ordered by position.
6969 for (int i= 0; i < elements.length; i++) {
7070 Match[] matches= result.getMatches(elements[i]);
8989 return false;
9090 }
9191 }
92
92
9393 }
0 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
1 <component id="org.eclipse.text" version="2">
2 <resource path="src/org/eclipse/jface/text/Assert.java" type="org.eclipse.jface.text.Assert">
3 <filter comment="Planned for deletion - Bug 528191 " id="338944126">
4 <message_arguments>
5 <message_argument value="org.eclipse.jface.text.Assert"/>
6 <message_argument value="isLegal(boolean)"/>
7 </message_arguments>
8 </filter>
9 <filter comment="Planned for deletion - Bug 528191 " id="338944126">
10 <message_arguments>
11 <message_argument value="org.eclipse.jface.text.Assert"/>
12 <message_argument value="isLegal(boolean, String)"/>
13 </message_arguments>
14 </filter>
15 <filter comment="Planned for deletion - Bug 528191 " id="338944126">
16 <message_arguments>
17 <message_argument value="org.eclipse.jface.text.Assert"/>
18 <message_argument value="isNotNull(Object)"/>
19 </message_arguments>
20 </filter>
21 <filter comment="Planned for deletion - Bug 528191 " id="338944126">
22 <message_arguments>
23 <message_argument value="org.eclipse.jface.text.Assert"/>
24 <message_argument value="isNotNull(Object, String)"/>
25 </message_arguments>
26 </filter>
27 <filter comment="Planned for deletion - Bug 528191 " id="338944126">
28 <message_arguments>
29 <message_argument value="org.eclipse.jface.text.Assert"/>
30 <message_argument value="isTrue(boolean)"/>
31 </message_arguments>
32 </filter>
33 <filter comment="Planned for deletion - Bug 528191 " id="338944126">
34 <message_arguments>
35 <message_argument value="org.eclipse.jface.text.Assert"/>
36 <message_argument value="isTrue(boolean, String)"/>
37 </message_arguments>
38 </filter>
39 </resource>
40 </component>
11 Bundle-ManifestVersion: 2
22 Bundle-Name: %pluginName
33 Bundle-SymbolicName: org.eclipse.text
4 Bundle-Version: 3.6.100.qualifier
4 Bundle-Version: 3.6.300.qualifier
55 Bundle-Vendor: %providerName
66 Bundle-Localization: plugin
77 Export-Package:
1919 Import-Package:
2020 com.ibm.icu.text,
2121 com.ibm.icu.util
22 Automatic-Module-Name: org.eclipse.text
00 # To force a version qualifier update add the bug here
11 Bug 466364: Cannot run unit-tests anymore because classes from org.eclipse.jface.text cannot be loaded because of "signer information does not match signer information of other classes in the same package"
2 Pick up new signing certificate
1313 <parent>
1414 <artifactId>eclipse.platform.text</artifactId>
1515 <groupId>eclipse.platform.text</groupId>
16 <version>4.7.3-SNAPSHOT</version>
16 <version>4.8.0-SNAPSHOT</version>
1717 </parent>
1818 <groupId>org.eclipse.text</groupId>
1919 <artifactId>org.eclipse.text</artifactId>
20 <version>3.6.100-SNAPSHOT</version>
20 <version>3.6.300-SNAPSHOT</version>
2121 <packaging>eclipse-plugin</packaging>
2222 </project>
127127 public String get(int offset, int length) {
128128 try {
129129 IRegion[] fragments= fMapping.toExactOriginRegions(new Region(offset, length));
130 StringBuffer buffer= new StringBuffer();
130 StringBuilder buffer= new StringBuilder();
131131 for (int i= 0; i < fragments.length; i++) {
132132 IRegion fragment= fragments[i];
133133 buffer.append(fMasterDocument.get(fragment.getOffset(), fragment.getLength()));
15271527 protected final void stopRewriteSessionOnPartitioners(DocumentRewriteSession session) {
15281528 if (fDocumentPartitioners != null) {
15291529 DocumentPartitioningChangedEvent event= new DocumentPartitioningChangedEvent(this);
1530 Iterator<String> e= fDocumentPartitioners.keySet().iterator();
1531 while (e.hasNext()) {
1532 String partitioning= e.next();
1533 IDocumentPartitioner partitioner= fDocumentPartitioners.get(partitioning);
1530 for (Entry<String, IDocumentPartitioner> entry : fDocumentPartitioners.entrySet()) {
1531 String partitioning = entry.getKey();
1532 IDocumentPartitioner partitioner= entry.getValue();
15341533 if (partitioner instanceof IDocumentPartitionerExtension3) {
15351534 IDocumentPartitionerExtension3 extension= (IDocumentPartitionerExtension3) partitioner;
15361535 extension.stopRewriteSession(session);
16981697
16991698 /**
17001699 * Logs the given exception by reusing the code in {@link SafeRunner}.
1701 *
1700 *
17021701 * @param ex the exception
17031702 * @since 3.6
17041703 */
2929 *
3030 * @deprecated As of 3.3, replaced by {@link org.eclipse.core.runtime.Assert}
3131 * @noinstantiate This class is not intended to be instantiated by clients.
32 *
33 * @noreference This class is planned to be deleted, see Bug 528191
34 *
3235 */
3336 @Deprecated
3437 public final class Assert {
4040
4141 /** Represents the content of this text store. */
4242 private final String fText;
43
43
4444 /** Minimum length limit below which {@link #get(int, int)} will return a String copy */
4545 private final int fCopyLimit;
4646
3535 * See {@link GapTextStore} and <code>TreeLineTracker</code> for algorithmic behavior of the used
3636 * document structures.
3737 * </p>
38 *
38 *
3939 * @see org.eclipse.jface.text.GapTextStore
4040 * @see org.eclipse.jface.text.CopyOnWriteTextStore
4141 */
130130
131131 @Override
132132 public String toString() {
133 StringBuffer buffer= new StringBuffer();
133 StringBuilder buffer= new StringBuilder();
134134 buffer.append("offset: " ); //$NON-NLS-1$
135135 buffer.append(fOffset);
136136 buffer.append(", length: " ); //$NON-NLS-1$
4242
4343 @Override
4444 public String toString() {
45 return new StringBuffer().append(hashCode()).toString();
45 return new StringBuilder().append(hashCode()).toString();
4646 }
4747 }
00 /*******************************************************************************
1 * Copyright (c) 2000, 2012 IBM Corporation and others.
1 * Copyright (c) 2000, 2017 IBM Corporation and others.
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
88 * IBM Corporation - initial API and implementation
99 * Cagatay Calli <ccalli@gmail.com> - [find/replace] retain caps when replacing - https://bugs.eclipse.org/bugs/show_bug.cgi?id=28949
1010 * Cagatay Calli <ccalli@gmail.com> - [find/replace] define & fix behavior of retain caps with other escapes and text before \C - https://bugs.eclipse.org/bugs/show_bug.cgi?id=217061
11 * Florian Ingerl <imelflorianingerl@gmail.com> - [find/replace] replace doesn't work when using a regex with a lookahead or boundary matchers - https://bugs.eclipse.org/bugs/show_bug.cgi?id=109481
1112 *******************************************************************************/
1213 package org.eclipse.jface.text;
1314
193194 String prevMatch= fFindReplaceMatcher.group();
194195 try {
195196 replaceText= interpretReplaceEscapes(replaceText, prevMatch);
196 Matcher replaceTextMatcher= pattern.matcher(prevMatch);
197 replaceText= replaceTextMatcher.replaceFirst(replaceText);
197 Matcher replaceTextMatcher= pattern.matcher(this);
198 replaceTextMatcher.find(fFindReplaceMatcher.start());
199 StringBuffer sb= new StringBuffer();
200 replaceTextMatcher.appendReplacement(sb, replaceText);
201 replaceText= sb.substring(fFindReplaceMatcher.start());
198202 } catch (IndexOutOfBoundsException ex) {
199203 throw new PatternSyntaxException(ex.getLocalizedMessage(), replaceText, -1);
200204 }
268272 */
269273 private String substituteLinebreak(String findString) throws PatternSyntaxException {
270274 int length= findString.length();
271 StringBuffer buf= new StringBuffer(length);
275 StringBuilder buf= new StringBuilder(length);
272276
273277 int inCharGroup= 0;
274278 int inBraces= 0;
346350 * @param ch the character to process
347351 * @since 3.4
348352 */
349 private void interpretRetainCase(StringBuffer buf, char ch) {
353 private void interpretRetainCase(StringBuilder buf, char ch) {
350354 if (fRetainCaseMode == RC_UPPER)
351355 buf.append(String.valueOf(ch).toUpperCase());
352356 else if (fRetainCaseMode == RC_LOWER)
369373 private String interpretReplaceEscapes(String replaceText, String foundText) {
370374 int length= replaceText.length();
371375 boolean inEscape= false;
372 StringBuffer buf= new StringBuffer(length);
376 StringBuilder buf= new StringBuilder(length);
373377
374378 /* every string we did not check looks mixed at first
375379 * so initialize retain case mode with RC_MIXED
430434 * @return the new offset
431435 * @since 3.4
432436 */
433 private int interpretReplaceEscape(final char ch, int i, StringBuffer buf, String replaceText, String foundText) {
437 private int interpretReplaceEscape(final char ch, int i, StringBuilder buf, String replaceText, String foundText) {
434438 int length= replaceText.length();
435439 switch (ch) {
436440 case 'r':
560564 * @return the string converted to a regex pattern
561565 */
562566 private String asRegPattern(String string) {
563 StringBuffer out= new StringBuffer(string.length());
567 StringBuilder out= new StringBuilder(string.length());
564568 boolean quoting= false;
565569
566570 for (int i= 0, length= string.length(); i < length; i++) {
643647 */
644648 public static String escapeForRegExPattern(String string) {
645649 //implements https://bugs.eclipse.org/bugs/show_bug.cgi?id=44422
646
647 StringBuffer pattern= new StringBuffer(string.length() + 16);
650
651 StringBuilder pattern= new StringBuilder(string.length() + 16);
648652 int length= string.length();
649653 for (int i= 0; i < length; i++) {
650654 char ch= string.charAt(i);
665669 case '$':
666670 pattern.append('\\').append(ch);
667671 break;
668
672
669673 case '\r':
670674 if (i + 1 < length && string.charAt(i + 1) == '\n')
671675 i++;
685689 case 0x1B:
686690 pattern.append("\\e"); //$NON-NLS-1$
687691 break;
688
692
689693 default:
690694 if (0 <= ch && ch < 0x20) {
691695 pattern.append("\\x"); //$NON-NLS-1$
155155 if (end <= fGapStart)
156156 return new String(fContent, offset, length);
157157
158 StringBuffer buf= new StringBuffer(length);
158 StringBuilder buf= new StringBuilder(length); // see Bug 113871
159159 buf.append(fContent, offset, fGapStart - offset);
160160 buf.append(fContent, fGapEnd, end - fGapStart);
161161 return buf.toString();
587587 * <p>
588588 * Note that a document always has at least one line.
589589 * </p>
590 *
590 *
591591 * @return the number of lines in this document.
592592 */
593593 int getNumberOfLines();
6464 * <p>
6565 * Note that a document always has at least one line.
6666 * </p>
67 *
67 *
6868 * @return the number of lines in this tracker's line structure
6969 */
7070 int getNumberOfLines();
1515 * <p>
1616 * Adds the ability to query whether the repairable document would have to be repaired after
1717 * replacing some text.
18 *
18 *
1919 * @see org.eclipse.jface.text.IRepairableDocument
2020 * @since 3.4
2121 */
2424 /**
2525 * Tells whether the line information of the document implementing this interface needs to be
2626 * repaired after replacing the given text.
27 *
27 *
2828 * @param offset the document offset
2929 * @param length the length of the specified range
3030 * @param text the substitution text to check
9595 * contain the lines 8-20.
9696 * <p>
9797 * This call is without effect if the given document is unknown to this slave document manager.
98 *
98 *
9999 * @param slave the slave whose auto expand mode should be set
100100 * @param autoExpand <code>true</code> for auto expand, <code>false</code> otherwise
101101 */
131131
132132 @Override
133133 public final int getLineNumberOfOffset(int position) throws BadLocationException {
134 if (position < 0 || position > fTextLength)
135 throw new BadLocationException();
134 if (position < 0) {
135 throw new BadLocationException("Negative offset : " + position); //$NON-NLS-1$
136 } else if (position > fTextLength) {
137 throw new BadLocationException("Offset > length: " + position + " > " + fTextLength); //$NON-NLS-1$//$NON-NLS-2$
138 }
136139
137140 if (position == fTextLength) {
138141
150153 @Override
151154 public final IRegion getLineInformationOfOffset(int position) throws BadLocationException {
152155 if (position > fTextLength)
153 throw new BadLocationException();
156 throw new BadLocationException("Offset > length: " + position + " > " + fTextLength); //$NON-NLS-1$//$NON-NLS-2$
154157
155158 if (position == fTextLength) {
156159 int size= fLines.size();
190190 Assert.isTrue(offset >= 0);
191191 this.offset= offset;
192192 }
193
193
194194 @Override
195195 public String toString() {
196196 String position= "offset: " + offset + ", length: " + length; //$NON-NLS-1$//$NON-NLS-2$
234234 if (fReplaceList.isEmpty())
235235 return;
236236
237 StringBuffer buffer= new StringBuffer();
237 StringBuilder buffer= new StringBuilder();
238238
239239 int delta= 0;
240240 for (Replace replace : fReplaceList) {
1515 import java.util.List;
1616 import java.util.ListIterator;
1717 import java.util.Map;
18 import java.util.Map.Entry;
1819 import java.util.Set;
1920
2021 import org.eclipse.core.runtime.Assert;
193194 final IDocument document= unprocessedDocument;
194195 int offset= firstEvent.getOffset();
195196 int length= firstEvent.getLength();
196 final StringBuffer text= new StringBuffer(firstEvent.getText() == null ? "" : firstEvent.getText()); //$NON-NLS-1$
197 final StringBuilder text= new StringBuilder(firstEvent.getText() == null ? "" : firstEvent.getText()); //$NON-NLS-1$
197198
198199 while (iterator.hasNext()) {
199200
339340 public static void addDocumentPartitioners(IDocument document, Map<String, ? extends IDocumentPartitioner> partitioners) {
340341 if (document instanceof IDocumentExtension3) {
341342 IDocumentExtension3 extension3= (IDocumentExtension3) document;
342 Iterator<String> e= partitioners.keySet().iterator();
343 while (e.hasNext()) {
344 String partitioning= e.next();
345 IDocumentPartitioner partitioner= partitioners.get(partitioning);
343 for (Entry<String, ? extends IDocumentPartitioner> entry : partitioners.entrySet()) {
344 String partitioning= entry.getKey();
345 IDocumentPartitioner partitioner= entry.getValue();
346346 partitioner.connect(document);
347347 extension3.setDocumentPartitioner(partitioning, partitioner);
348348 }
12301230
12311231 List<Node> roots= new LinkedList<>();
12321232 roots.add(fRoot);
1233 StringBuffer buf= new StringBuffer((width + 1) * depth);
1233 StringBuilder buf= new StringBuilder((width + 1) * depth); // see Bug 137688
12341234 int indents= leaves;
12351235 char[] space= new char[leaves * WIDTH / 2];
12361236 Arrays.fill(space, ' ');
165165 }
166166
167167 private void removeManager() {
168 for (Iterator<IDocument> it= fgManagers.keySet().iterator(); it.hasNext();) {
169 IDocument doc= it.next();
170 if (fgManagers.get(doc) == this)
168 for (Iterator<LinkedModeManager> it= fgManagers.values().iterator(); it.hasNext();) {
169 if (it.next() == this)
171170 it.remove();
172171 }
173172 }
1414 import java.util.HashSet;
1515 import java.util.List;
1616 import java.util.Map;
17 import java.util.Map.Entry;
1718 import java.util.Set;
1819
1920 import org.eclipse.core.runtime.Assert;
220221
221222 if (result != null) {
222223 // edit all documents
223 for (IDocument doc : result.keySet()) {
224 TextEdit edit= result.get(doc);
224 for (Entry<IDocument, TextEdit> entry : result.entrySet()) {
225 IDocument doc = entry.getKey();
226 TextEdit edit= entry.getValue();
225227 Replace replace= new Replace(edit);
226228
227229 // apply the edition, either as post notification replace
1515 import java.util.LinkedList;
1616 import java.util.List;
1717 import java.util.Map;
18 import java.util.Map.Entry;
1819
1920 import org.eclipse.core.runtime.Assert;
2021
8081 * change.
8182 */
8283 private IRegion fLastRegion;
83
84
8485 /**
8586 * <code>true</code> iff not all positions contain the same content.
8687 * In that case, the contents of the last edited position will replace the
270271
271272 try {
272273 Map<IDocument, TextEdit> result= new HashMap<>();
273 for (IDocument d : map.keySet()) {
274 TextEdit edit= new MultiTextEdit(0, d.getLength());
275 edit.addChildren(map.get(d).toArray(new TextEdit[0]));
276 result.put(d, edit);
274 for (Entry<IDocument, List<ReplaceEdit>> edits : map.entrySet()) {
275 TextEdit edit= new MultiTextEdit(0, edits.getKey().getLength());
276 edit.addChildren(edits.getValue().toArray(new TextEdit[edits.getValue().size()]));
277 result.put(edits.getKey(), edit);
277278 }
278279
279280 return result;
183183
184184 /**
185185 * A single iterator builds its behavior based on a sequence of iterators.
186 *
186 *
187187 * @param <E> the type of elements returned by this iterator
188188 * @since 3.1
189189 */
492492 connected();
493493 }
494494
495 for (Object object : fAttachments.keySet()) {
496 IAnnotationModel model= fAttachments.get(object);
495 for (IAnnotationModel model : fAttachments.values()) {
497496 model.connect(document);
498497 }
499498 }
517516
518517 Assert.isTrue(fDocument == document);
519518
520 for (Object object : fAttachments.keySet()) {
521 IAnnotationModel model= fAttachments.get(object);
519 for (IAnnotationModel model : fAttachments.values()) {
522520 model.disconnect(document);
523521 }
524522
5151
5252 /**
5353 * The selection variable determines templates that work on a selection.
54 *
54 *
5555 * @since 3.6
5656 */
5757 public static class Selection extends SimpleTemplateVariableResolver {
5858
5959 /**
6060 * Creates a word selection variable.
61 *
61 *
6262 * @param name the name of the variable
6363 * @param description the description of the variable
6464 */
4343 public class TemplateTranslator {
4444 /**
4545 * Regex pattern for identifier.
46 * Note: For historic reasons, this pattern <em>allows</em> numbers at the beginning of an identifier.
46 * Note: For historic reasons, this pattern <em>allows</em> numbers at the beginning of an identifier.
4747 * @since 3.7
4848 */
4949 private static final String IDENTIFIER= "(?:[\\p{javaJavaIdentifierPart}&&[^\\$]]++)"; //$NON-NLS-1$
183183 private TemplateBuffer parse(String string) throws TemplateException {
184184
185185 fErrorMessage= null;
186 final StringBuffer buffer= new StringBuffer(string.length());
186 final StringBuilder buffer= new StringBuilder(string.length());
187187 final Matcher matcher= ESCAPE_PATTERN.matcher(string);
188188 final Map<String, VariableDescription> variables= new LinkedHashMap<>();
189189
169169 fModifier= modifier;
170170 }
171171
172 /*
173 * @see TextEdit#doCopy
174 */
175172 @Override
176173 protected TextEdit doCopy() {
177174 return new CopySourceEdit(this);
178175 }
179176
180 /*
181 * @see TextEdit#accept0
182 */
183177 @Override
184178 protected void accept0(TextEditVisitor visitor) {
185179 boolean visitChildren= visitor.visit(this);
203197 fSourceContent= null;
204198 }
205199
206 /*
207 * @see TextEdit#postProcessCopy
208 */
209200 @Override
210201 protected void postProcessCopy(TextEditCopier copier) {
211202 if (fTarget != null) {
320311
321312 //---- region updating ----------------------------------------------------------------
322313
323 /*
324 * @see TextEdit#deleteChildren
325 */
326314 @Override
327315 boolean deleteChildren() {
328316 return false;
9595 }
9696 }
9797
98 /*
99 * @see TextEdit#doCopy
100 */
10198 @Override
10299 protected TextEdit doCopy() {
103100 return new CopyTargetEdit(this);
104101 }
105102
106 /*
107 * @see TextEdit#postProcessCopy
108 */
109103 @Override
110104 protected void postProcessCopy(TextEditCopier copier) {
111105 if (fSource != null) {
116110 }
117111 }
118112
119 /*
120 * @see TextEdit#accept0
121 */
122113 @Override
123114 protected void accept0(TextEditVisitor visitor) {
124115 boolean visitChildren= visitor.visit(this);
127118 }
128119 }
129120
130 /*
131 * @see TextEdit#traverseConsistencyCheck
132 */
133121 @Override
134122 int traverseConsistencyCheck(TextEditProcessor processor, IDocument document, List<List<TextEdit>> sourceEdits) {
135123 return super.traverseConsistencyCheck(processor, document, sourceEdits) + 1;
136124 }
137125
138 /*
139 * @see TextEdit#performConsistencyCheck
140 */
141126 @Override
142127 void performConsistencyCheck(TextEditProcessor processor, IDocument document) throws MalformedTreeException {
143128 if (fSource == null)
146131 throw new MalformedTreeException(getParent(), this, TextEditMessages.getString("CopyTargetEdit.different_target")); //$NON-NLS-1$
147132 }
148133
149 /*
150 * @see TextEdit#performDocumentUpdating
151 */
152134 @Override
153135 int performDocumentUpdating(IDocument document) throws BadLocationException {
154136 String source= fSource.getContent();
158140 return fDelta;
159141 }
160142
161 /*
162 * @see TextEdit#deleteChildren
163 */
164143 @Override
165144 boolean deleteChildren() {
166145 return false;
4242 fText= other.fText;
4343 }
4444
45 /*
46 * @see TextEdit#doCopy
47 */
4845 @Override
4946 protected TextEdit doCopy() {
5047 return new CopyingRangeMarker(this);
5148 }
5249
53 /*
54 * @see TextEdit#accept0
55 */
5650 @Override
5751 protected void accept0(TextEditVisitor visitor) {
5852 boolean visitChildren= visitor.visit(this);
6155 }
6256 }
6357
64 /*
65 * @see TextEdit#performDocumentUpdating
66 */
6758 @Override
6859 int performDocumentUpdating(IDocument document) throws BadLocationException {
6960 fText= document.get(getOffset(), getLength());
7162 return fDelta;
7263 }
7364
74 /*
75 * @see TextEdit#deleteChildren
76 */
7765 @Override
7866 boolean deleteChildren() {
7967 return false;
3939 super(other);
4040 }
4141
42 /*
43 * @see TextEdit#doCopy
44 */
4542 @Override
4643 protected TextEdit doCopy() {
4744 return new DeleteEdit(this);
4845 }
4946
50 /*
51 * @see TextEdit#accept0
52 */
5347 @Override
5448 protected void accept0(TextEditVisitor visitor) {
5549 boolean visitChildren= visitor.visit(this);
5852 }
5953 }
6054
61 /*
62 * @see TextEdit#performDocumentUpdating
63 */
6455 @Override
6556 int performDocumentUpdating(IDocument document) throws BadLocationException {
6657 document.replace(getOffset(), getLength(), ""); //$NON-NLS-1$
6859 return fDelta;
6960 }
7061
71 /*
72 * @see TextEdit#deleteChildren
73 */
7462 @Override
7563 boolean deleteChildren() {
7664 return true;
2323
2424 class EditDocument implements IDocument {
2525
26 private StringBuffer fBuffer;
26 private StringBuilder fBuffer;
2727
2828 public EditDocument(String content) {
29 fBuffer= new StringBuffer(content);
29 fBuffer= new StringBuilder(content);
3030 }
3131
3232 @Override
5656 return fText;
5757 }
5858
59 /*
60 * @see TextEdit#doCopy
61 */
6259 @Override
6360 protected TextEdit doCopy() {
6461 return new InsertEdit(this);
6562 }
6663
67 /*
68 * @see TextEdit#accept0
69 */
7064 @Override
7165 protected void accept0(TextEditVisitor visitor) {
7266 boolean visitChildren= visitor.visit(this);
7569 }
7670 }
7771
78 /*
79 * @see TextEdit#performDocumentUpdating
80 */
8172 @Override
8273 int performDocumentUpdating(IDocument document) throws BadLocationException {
8374 document.replace(getOffset(), getLength(), fText);
8576 return fDelta;
8677 }
8778
88 /*
89 * @see TextEdit#deleteChildren
90 */
9179 @Override
9280 boolean deleteChildren() {
9381 return false;
9482 }
9583
9684 @Override
97 void internalToString(StringBuffer buffer, int indent) {
85 void internalToString(StringBuilder buffer, int indent) {
9886 super.internalToString(buffer, indent);
9987 buffer.append(" <<").append(fText); //$NON-NLS-1$
10088 }
145145
146146 //---- Copying -------------------------------------------------------------
147147
148 /*
149 * @see TextEdit#doCopy
150 */
151148 @Override
152149 protected TextEdit doCopy() {
153150 return new MoveSourceEdit(this);
154151 }
155152
156 /*
157 * @see TextEdit#postProcessCopy
158 */
159153 @Override
160154 protected void postProcessCopy(TextEditCopier copier) {
161155 if (fTarget != null) {
168162
169163 //---- Visitor -------------------------------------------------------------
170164
171 /*
172 * @see TextEdit#accept0
173 */
174165 @Override
175166 protected void accept0(TextEditVisitor visitor) {
176167 boolean visitChildren= visitor.visit(this);
275266
276267 //---- region updating --------------------------------------------------------------
277268
278 /*
279 * @see TextEdit#deleteChildren
280 */
281269 @Override
282270 boolean deleteChildren() {
283271 return false;
9494 }
9595 }
9696
97 /*
98 * @see TextEdit#doCopy
99 */
10097 @Override
10198 protected TextEdit doCopy() {
10299 return new MoveTargetEdit(this);
103100 }
104101
105 /*
106 * @see TextEdit#postProcessCopy
107 */
108102 @Override
109103 protected void postProcessCopy(TextEditCopier copier) {
110104 if (fSource != null) {
115109 }
116110 }
117111
118 /*
119 * @see TextEdit#accept0
120 */
121112 @Override
122113 protected void accept0(TextEditVisitor visitor) {
123114 boolean visitChildren= visitor.visit(this);
128119
129120 //---- consistency check ----------------------------------------------------------
130121
131 /*
132 * @see TextEdit#traverseConsistencyCheck
133 */
134122 @Override
135123 int traverseConsistencyCheck(TextEditProcessor processor, IDocument document, List<List<TextEdit>> sourceEdits) {
136124 return super.traverseConsistencyCheck(processor, document, sourceEdits) + 1;
137125 }
138126
139 /*
140 * @see TextEdit#performConsistencyCheck
141 */
142127 @Override
143128 void performConsistencyCheck(TextEditProcessor processor, IDocument document) throws MalformedTreeException {
144129 if (fSource == null)
175160
176161 //---- region updating --------------------------------------------------------------
177162
178 /*
179 * @see org.eclipse.text.edits.TextEdit#traversePassThree
180 */
181163 @Override
182164 int traverseRegionUpdating(TextEditProcessor processor, IDocument document, int accumulatedDelta, boolean delete) {
183165 // the children got already updated / normalized while they got removed
131131 return true;
132132 }
133133
134 /*
135 * @see TextEdit#copy
136 */
137134 @Override
138135 protected TextEdit doCopy() {
139136 Assert.isTrue(MultiTextEdit.class == getClass(), "Subclasses must reimplement copy0"); //$NON-NLS-1$
140137 return new MultiTextEdit(this);
141138 }
142139
143 /*
144 * @see TextEdit#accept0
145 */
146140 @Override
147141 protected void accept0(TextEditVisitor visitor) {
148142 boolean visitChildren= visitor.visit(this);
163157 super.adjustLength(delta);
164158 }
165159
166 /*
167 * @see TextEdit#performConsistencyCheck
168 */
169160 @Override
170161 void performConsistencyCheck(TextEditProcessor processor, IDocument document) throws MalformedTreeException {
171162 checkIntegrity();
172163 }
173164
174 /*
175 * @see TextEdit#performDocumentUpdating
176 */
177165 @Override
178166 int performDocumentUpdating(IDocument document) throws BadLocationException {
179167 fDelta= 0;
180168 return fDelta;
181169 }
182170
183 /*
184 * @see TextEdit#deleteChildren
185 */
186171 @Override
187172 boolean deleteChildren() {
188173 return false;
208193 }
209194
210195 @Override
211 void internalToString(StringBuffer buffer, int indent) {
196 void internalToString(StringBuilder buffer, int indent) {
212197 super.internalToString(buffer, indent);
213198 if (! fDefined)
214199 buffer.append(" [undefined]"); //$NON-NLS-1$
3737 super(other);
3838 }
3939
40 /*
41 * @see TextEdit#copy
42 */
4340 @Override
4441 protected TextEdit doCopy() {
4542 return new RangeMarker(this);
4643 }
4744
48 /*
49 * @see TextEdit#accept0
50 */
5145 @Override
5246 protected void accept0(TextEditVisitor visitor) {
5347 boolean visitChildren= visitor.visit(this);
5650 }
5751 }
5852
59 /*
60 * @see TextEdit#performDocumentUpdating
61 */
6253 @Override
6354 int performDocumentUpdating(IDocument document) throws BadLocationException {
6455 fDelta= 0;
6556 return fDelta;
6657 }
6758
68 /*
69 * @see TextEdit#deleteChildren
70 */
7159 @Override
7260 boolean deleteChildren() {
7361 return false;
5757 return fText;
5858 }
5959
60 /*
61 * @see TextEdit#doCopy
62 */
6360 @Override
6461 protected TextEdit doCopy() {
6562 return new ReplaceEdit(this);
6663 }
6764
68 /*
69 * @see TextEdit#accept0
70 */
7165 @Override
7266 protected void accept0(TextEditVisitor visitor) {
7367 boolean visitChildren= visitor.visit(this);
7670 }
7771 }
7872
79 /*
80 * @see TextEdit#performDocumentUpdating
81 */
8273 @Override
8374 int performDocumentUpdating(IDocument document) throws BadLocationException {
8475 document.replace(getOffset(), getLength(), fText);
8677 return fDelta;
8778 }
8879
89 /*
90 * @see TextEdit#deleteChildren
91 */
9280 @Override
9381 boolean deleteChildren() {
9482 return true;
9583 }
9684
9785 @Override
98 void internalToString(StringBuffer buffer, int indent) {
86 void internalToString(StringBuilder buffer, int indent) {
9987 super.internalToString(buffer, indent);
10088 buffer.append(" <<").append(fText); //$NON-NLS-1$
10189 }
513513
514514 @Override
515515 public String toString() {
516 StringBuffer buffer= new StringBuffer();
516 StringBuilder buffer= new StringBuilder();
517517 toStringWithChildren(buffer, 0);
518518 return buffer.toString();
519519 }
520520
521521 /**
522522 * Adds the string representation of this text edit without
523 * children information to the given string buffer.
524 *
525 * @param buffer the string buffer
523 * children information to the given string builder.
524 *
525 * @param buffer the string builder
526526 * @param indent the indent level in number of spaces
527527 * @since 3.3
528528 */
529 void internalToString(StringBuffer buffer, int indent) {
529 void internalToString(StringBuilder buffer, int indent) {
530530 for (int i= indent; i > 0; i--) {
531531 buffer.append(" "); //$NON-NLS-1$
532532 }
552552
553553 /**
554554 * Adds the string representation for this text edit
555 * and its children to the given string buffer.
556 *
557 * @param buffer the string buffer
555 * and its children to the given string builder.
556 *
557 * @param buffer the string builder
558558 * @param indent the indent level in number of spaces
559559 * @since 3.3
560560 */
561 private void toStringWithChildren(StringBuffer buffer, int indent) {
561 private void toStringWithChildren(StringBuilder buffer, int indent) {
562562 internalToString(buffer, indent);
563563 if (fChildren != null) {
564564 for (TextEdit child : fChildren) {
6363 return new UndoEdit(this);
6464 }
6565
66 /*
67 * @see TextEdit#accept0
68 */
6966 @Override
7067 protected void accept0(TextEditVisitor visitor) {
7168 boolean visitChildren= visitor.visit(this);
7471 }
7572 }
7673
77 /*
78 * @see TextEdit#performDocumentUpdating
79 */
8074 @Override
8175 int performDocumentUpdating(IDocument document) throws BadLocationException {
8276 fDelta= 0;
371371 @Override
372372 public String toString() {
373373 String delimiter= ", "; //$NON-NLS-1$
374 StringBuffer text= new StringBuffer(super.toString());
374 StringBuilder text= new StringBuilder(super.toString());
375375 text.append("\n"); //$NON-NLS-1$
376376 text.append(this.getClass().getName());
377377 text.append(" undo modification stamp: "); //$NON-NLS-1$
710710 /**
711711 * Text buffer to collect viewer content which has been replaced
712712 */
713 private StringBuffer fPreservedTextBuffer;
713 private StringBuilder fPreservedTextBuffer;
714714
715715 /**
716716 * The document modification stamp for undo.
725725 /**
726726 * Text buffer to collect text which is inserted into the viewer
727727 */
728 private StringBuffer fTextBuffer;
728 private StringBuilder fTextBuffer;
729729
730730 /** Indicates inserting state. */
731731 private boolean fInserting= false;
11411141 // open up the current text edit
11421142 fCurrent= new UndoableTextChange(this);
11431143 fPreviousDelete= new UndoableTextChange(this);
1144 fTextBuffer= new StringBuffer();
1145 fPreservedTextBuffer= new StringBuffer();
1144 fTextBuffer= new StringBuilder();
1145 fPreservedTextBuffer= new StringBuilder();
11461146
11471147 addListeners();
11481148 }
5353 name="*"/>
5454 <sourceLocator
5555 rootFolder="${git.clone.platform.text.location}"
56 locateNestedProjects="true"/>
56 locateNestedProjects="true">
57 <predicate
58 xsi:type="predicates:NotPredicate">
59 <operand
60 xsi:type="predicates:AndPredicate">
61 <operand
62 xsi:type="predicates:NamePredicate"
63 pattern="eclipse\.platform\.text"/>
64 </operand>
65 </predicate>
66 </sourceLocator>
5767 </targlet>
5868 </setupTask>
5969 <setupTask
96106 </workingSet>
97107 </setupTask>
98108 <stream name="master"
99 label="Master">
100 <setupTask
101 xsi:type="setup:VariableTask"
102 name="eclipse.target.platform"
103 value="Oxygen"
104 storageURI="scope://Workspace"/>
105 </stream>
109 label="Master"/>
106110 <logicalProjectContainer
107111 xsi:type="setup:Project"
108112 href="index:/org.eclipse.setup#//@projectCatalogs[name='org.eclipse']/@projects[name='platform']"/>
0 Manifest-Version: 1.0
1 Bundle-ManifestVersion: 2
2 Bundle-Name: %Plugin.name
3 Bundle-SymbolicName: org.eclipse.text.tests
4 Bundle-Version: 3.11.0.qualifier
5 Bundle-Vendor: %Plugin.providerName
6 Bundle-Localization: plugin
7 Export-Package:
8 org.eclipse.text.tests,
9 org.eclipse.text.tests.link,
10 org.eclipse.text.tests.templates
11 Require-Bundle:
12 org.eclipse.core.commands;bundle-version="[3.5.0,4.0.0)",
13 org.eclipse.core.runtime;bundle-version="[3.5.0,4.0.0)",
14 org.eclipse.text;bundle-version="[3.5.0,4.0.0)",
15 org.junit;bundle-version="4.12.0"
16 Bundle-RequiredExecutionEnvironment: JavaSE-1.8
17 Eclipse-BundleShape: dir
18 Import-Package: com.ibm.icu.text,
19 com.ibm.icu.util
0 Manifest-Version: 1.0
1 Bundle-ManifestVersion: 2
2 Bundle-Name: %Plugin.name
3 Bundle-SymbolicName: org.eclipse.text.tests
4 Bundle-Version: 3.12.0.qualifier
5 Bundle-Vendor: %Plugin.providerName
6 Bundle-Localization: plugin
7 Export-Package:
8 org.eclipse.text.tests,
9 org.eclipse.text.tests.link,
10 org.eclipse.text.tests.templates
11 Require-Bundle:
12 org.eclipse.core.commands;bundle-version="[3.5.0,4.0.0)",
13 org.eclipse.core.runtime;bundle-version="[3.5.0,4.0.0)",
14 org.eclipse.text;bundle-version="[3.6.3,4.0.0)",
15 org.junit;bundle-version="4.12.0"
16 Bundle-RequiredExecutionEnvironment: JavaSE-1.8
17 Eclipse-BundleShape: dir
18 Import-Package: com.ibm.icu.text,
19 com.ibm.icu.util
20 Automatic-Module-Name: org.eclipse.text.tests
1313 <parent>
1414 <artifactId>tests-pom</artifactId>
1515 <groupId>eclipse.platform.text</groupId>
16 <version>4.7.3-SNAPSHOT</version>
16 <version>4.8.0-SNAPSHOT</version>
1717 <relativePath>../tests-pom/</relativePath>
1818 </parent>
1919 <groupId>org.eclipse.text</groupId>
2020 <artifactId>org.eclipse.text.tests</artifactId>
21 <version>3.11.0-SNAPSHOT</version>
21 <version>3.12.0-SNAPSHOT</version>
2222 <packaging>eclipse-test-plugin</packaging>
2323 <properties>
2424 <testSuite>${project.artifactId}</testSuite>
6363 fInstance= instance;
6464 try {
6565 fClass= Class.forName(className, true, classLoader);
66 } catch (ClassNotFoundException e) {
67 fail(e);
68 } catch (ExceptionInInitializerError e) {
66 } catch (ClassNotFoundException | ExceptionInInitializerError e) {
6967 fail(e);
7068 }
7169 }
9795 public Accessor(String className, ClassLoader classLoader, Class<?>[] constructorTypes, Object[] constructorArgs) {
9896 try {
9997 fClass= Class.forName(className, true, classLoader);
100 } catch (ClassNotFoundException e) {
101 fail(e);
102 } catch (ExceptionInInitializerError e) {
98 } catch (ClassNotFoundException | ExceptionInInitializerError e) {
10399 fail(e);
104100 }
105101 Constructor<?> constructor= null;
106102 try {
107103 constructor= fClass.getDeclaredConstructor(constructorTypes);
108 } catch (SecurityException e) {
109 fail(e);
110 } catch (NoSuchMethodException e) {
104 } catch (SecurityException | NoSuchMethodException e) {
111105 fail(e);
112106 }
113107 Assert.isNotNull(constructor);
114108 constructor.setAccessible(true);
115109 try {
116110 fInstance= constructor.newInstance(constructorArgs);
117 } catch (IllegalArgumentException e) {
118 fail(e);
119 } catch (InvocationTargetException e) {
120 fail(e);
121 } catch (InstantiationException e) {
122 fail(e);
123 } catch (IllegalAccessException e) {
111 } catch (IllegalArgumentException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
124112 fail(e);
125113 }
126114 }
137125 public Accessor(String className, ClassLoader classLoader) {
138126 try {
139127 fClass= Class.forName(className, true, classLoader);
140 } catch (ClassNotFoundException e) {
141 fail(e);
142 } catch (ExceptionInInitializerError e) {
128 } catch (ClassNotFoundException | ExceptionInInitializerError e) {
143129 fail(e);
144130 }
145131 }
172158 Method method= null;
173159 try {
174160 method= fClass.getDeclaredMethod(methodName, types);
175 } catch (SecurityException e) {
176 fail(e);
177 } catch (NoSuchMethodException e) {
161 } catch (SecurityException | NoSuchMethodException e) {
178162 fail(e);
179163 }
180164 Assert.isNotNull(method);
181165 method.setAccessible(true);
182166 try {
183167 return method.invoke(fInstance, arguments);
184 } catch (IllegalArgumentException e) {
185 fail(e);
186 } catch (InvocationTargetException e) {
187 fail(e);
188 } catch (IllegalAccessException e) {
168 } catch (IllegalArgumentException | InvocationTargetException | IllegalAccessException e) {
189169 fail(e);
190170 }
191171 return null;
201181 Field field= getField(fieldName);
202182 try {
203183 field.set(fInstance, value);
204 } catch (IllegalArgumentException e) {
205 fail(e);
206 } catch (IllegalAccessException e) {
184 } catch (IllegalArgumentException | IllegalAccessException e) {
207185 fail(e);
208186 }
209187 }
218196 Field field= getField(fieldName);
219197 try {
220198 field.setBoolean(fInstance, value);
221 } catch (IllegalArgumentException e) {
222 fail(e);
223 } catch (IllegalAccessException e) {
199 } catch (IllegalArgumentException | IllegalAccessException e) {
224200 fail(e);
225201 }
226202 }
235211 Field field= getField(fieldName);
236212 try {
237213 field.setInt(fInstance, value);
238 } catch (IllegalArgumentException e) {
239 fail(e);
240 } catch (IllegalAccessException e) {
214 } catch (IllegalArgumentException | IllegalAccessException e) {
241215 fail(e);
242216 }
243217 }
252226 Field field= getField(fieldName);
253227 try {
254228 return field.get(fInstance);
255 } catch (IllegalArgumentException e) {
256 fail(e);
257 } catch (IllegalAccessException e) {
229 } catch (IllegalArgumentException | IllegalAccessException e) {
258230 fail(e);
259231 }
260232 // Unreachable code
271243 Field field= getField(fieldName);
272244 try {
273245 return field.getBoolean(fInstance);
274 } catch (IllegalArgumentException e) {
275 fail(e);
276 } catch (IllegalAccessException e) {
246 } catch (IllegalArgumentException | IllegalAccessException e) {
277247 fail(e);
278248 }
279249 // Unreachable code
290260 Field field= getField(fieldName);
291261 try {
292262 return field.getInt(fInstance);
293 } catch (IllegalArgumentException e) {
294 fail(e);
295 } catch (IllegalAccessException e) {
263 } catch (IllegalArgumentException | IllegalAccessException e) {
296264 fail(e);
297265 }
298266 // Unreachable code
303271 Field field= null;
304272 try {
305273 field= fClass.getDeclaredField(fieldName);
306 } catch (SecurityException e) {
307 fail(e);
308 } catch (NoSuchFieldException e) {
274 } catch (SecurityException | NoSuchFieldException e) {
309275 fail(e);
310276 }
311277 field.setAccessible(true);
00 /*******************************************************************************
1 * Copyright (c) 2000, 2013 IBM Corporation and others.
1 * Copyright (c) 2000, 2017 IBM Corporation and others.
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
88 * IBM Corporation - initial API and implementation
99 * Cagatay Calli <ccalli@gmail.com> - [find/replace] retain caps when replacing - https://bugs.eclipse.org/bugs/show_bug.cgi?id=28949
1010 * Cagatay Calli <ccalli@gmail.com> - [find/replace] define & fix behavior of retain caps with other escapes and text before \C - https://bugs.eclipse.org/bugs/show_bug.cgi?id=217061
11 * Florian Ingerl <imelflorianingerl@gmail.com> - [find/replace] replace doesn't work when using a regex with a lookahead or boundary matchers - https://bugs.eclipse.org/bugs/show_bug.cgi?id=109481
1112 *******************************************************************************/
1213 package org.eclipse.text.tests;
1314
499500 }
500501 fail();
501502 }
503
504 @Test
505 public void testRegexReplaceWithLookarounds() throws Exception {
506 fDocument.set("1<2<3<4");
507 replaceAllRegex("(?<=(\\d))\\<(\\d)(?=\\<(\\d))", "<($1+$3)/2=$2", true);
508 assertEquals("1<(1+3)/2=2<(2+4)/2=3<4", fDocument.get());
509
510 fDocument.set("1<2<3<4");
511 replaceAllRegex("(?<=(\\d)\\<)(\\d)\\<(?=(\\d))", "$2=($1+$3)/2<", false);
512 assertEquals("1<2=(1+3)/2<3=(2+4)/2<4", fDocument.get());
513 }
514
515 private void replaceAllRegex(String findString, String replaceString, boolean forwardSearch) throws BadLocationException {
516 FindReplaceDocumentAdapter findReplaceDocumentAdapter= new FindReplaceDocumentAdapter(fDocument);
517
518 int index= forwardSearch ? 0 : fDocument.getLength();
519 while(index!=-1) {
520 if(findReplaceDocumentAdapter.find(index, findString, forwardSearch, true, false, true)==null)
521 break;
522 IRegion region= findReplaceDocumentAdapter.replace(replaceString, true);
523 index= forwardSearch ? region.getOffset() + region.getLength() : region.getOffset() - 1;
524 }
525 }
502526 }
6262 fTextStore= null;
6363 fTracker= null;
6464 }
65
65
6666 @Test
6767 public void testGet1() throws Exception {
6868 set("xxxxx");
7676 }
7777
7878 }
79
79
8080 @Test
8181 public void testGet2() throws Exception {
8282 set("xxxxx");
9090 }
9191
9292 }
93
93
9494 @Test
9595 public void testEditScript1() throws Exception {
9696 replace(0, fTextStore.getLength(), "x");
120120 } catch (IndexOutOfBoundsException e) {
121121 }
122122 }
123
123
124124 @Test
125125 public void testEmptyLines() throws Exception {
126126
130130 replace(0, 0, "\n\n\n\n\n");
131131 assertTextStoreContents("\n\n\n\n\n");
132132 }
133
133
134134 @Test
135135 public void testInsert1() throws Exception {
136136
149149 replace(11, 5, "y\nxyz");
150150 assertTextStoreContents("x\nxyyyy\nxy\ny\nxyz\nx\n");
151151 }
152
152
153153 @Test
154154 public void testInsert2() throws Exception {
155155 replace(3, 0, "yyyy");
158158 replace(9, 0, "y\ny\ny");
159159 assertTextStoreContents("x\nxyyyy\nxy\ny\ny\nx\nx\n");
160160 }
161
161
162162 @Test
163163 public void testLinesNumbers() throws Exception {
164164 replace(0, 10, "\na\nbb\nccc\ndddd\neeeee\n");
173173 offset+= (i + 1);
174174 }
175175 }
176
176
177177 @Test
178178 public void testOffsets() throws Exception {
179179 for (int i= 0; i < 5; i++) {
195195 assertTrue("invalid line number " + line + " for position " + i + " should be " + l, l == line);
196196 }
197197 }
198
198
199199 @Test
200200 public void testRemove() throws Exception {
201201 replace(3, 1, null);
210210 replace(0, 3, null);
211211 assertTextStoreContents("");
212212 }
213
213
214214 @Test
215215 public void testReplace() throws Exception {
216216 replace(0, fTextStore.getLength(), "\tx\n\tx\n\tx\n\tx\n\tx\n");
217217 assertTextStoreContents("\tx\n\tx\n\tx\n\tx\n\tx\n");
218218 }
219
219
220220 @Test
221221 public void testReplace2() throws Exception {
222222 replace(0, fTextStore.getLength(), "x");
225225 replace(0, fTextStore.getLength(), "x\nx\nx\n");
226226 assertTextStoreContents("x\nx\nx\n");
227227 }
228
228
229229 @Test
230230 public void testReplace3() throws Exception {
231231 replace(1, 1, "\n");
232232 assertTextStoreContents("x\nx\nx\nx\nx\n");
233233 }
234
234
235235 @Test
236236 public void testReplace4() throws Exception {
237237 int lines= fTracker.getNumberOfLines();
244244 previous= fTracker.getLineInformation(i);
245245 }
246246 }
247
247
248248 @Test
249249 public void testShiftLeft() throws Exception {
250250 replace(0, fTextStore.getLength(), "\tx\n\tx\n\tx\n\tx\n\tx\n");
257257
258258 assertTextStoreContents("x\nx\nx\nx\nx\n");
259259 }
260
260
261261 @Test
262262 public void testShiftRight() throws Exception {
263263 for (int i= 0; i < 5; i++) {
267267
268268 assertTextStoreContents("\tx\n\tx\n\tx\n\tx\n\tx\n");
269269 }
270
270
271271 @Test
272272 public void testDeleteEmptyLine() throws Exception {
273273 set("x\nx\n\nx\n\n");
290290 }
291291
292292 }
293
293
294294 @Test
295295 public void testDeleteLines() throws Exception {
296 String content= "";
296 StringBuilder content= new StringBuilder();
297297 for (int i= 0; i < 50; i++) {
298 content += "x\nx\n\nx\n\n";
299 set(content);
300
301 String expected= content;
298 content.append("x\nx\n\nx\n\n");
299 set(content.toString());
300
301 String expected= content.toString();
302302 int lines= fTracker.getNumberOfLines();
303303 for (int line= 0; line < lines; line++) {
304304 int offset= fTracker.getLineOffset(0);
308308 assertTextStoreContents(expected);
309309 }
310310 }
311 content= "";
311 content = new StringBuilder();
312312 for (int i= 0; i < 50; i++) {
313 content += "x\nx\n\nx\n\n";
314 set(content);
315
316 String expected= content;
313 content.append("x\nx\n\nx\n\n");
314 set(content.toString());
315
316 String expected= content.toString();
317317 int lines= fTracker.getNumberOfLines();
318318 for (int line= lines - 1; line >= 0; line--) {
319319 int offset= fTracker.getLineOffset(line);
324324 }
325325 }
326326 }
327
327
328328 @Test
329329 public void testDeleteLines2() throws Exception {
330 String content= "";
330 StringBuilder content= new StringBuilder();
331331 for (int i= 0; i < 50; i++) {
332 content += "xxxxxxxxxxxxxx";
333 set(content);
334
335 String expected= content;
332 content.append("xxxxxxxxxxxxxx");
333 set(content.toString());
334
335 String expected= content.toString();
336336 int lines= fTracker.getNumberOfLines();
337337 for (int line= 0; line < lines; line++) {
338338 int offset= fTracker.getLineOffset(0);
342342 assertTextStoreContents(expected);
343343 }
344344 }
345 content= "";
345 content= new StringBuilder();
346346 for (int i= 0; i < 50; i++) {
347 content += "xxxxxxxxxxxxxx";
348 set(content);
349
350 String expected= content;
347 content.append("xxxxxxxxxxxxxx");
348 set(content.toString());
349
350 String expected= content.toString();
351351 int lines= fTracker.getNumberOfLines();
352352 for (int line= lines - 1; line >= 0; line--) {
353353 int offset= fTracker.getLineOffset(line);
358358 }
359359 }
360360 }
361
361
362362 @Test
363363 public void testSet() throws Exception {
364 String content= "";
364 StringBuilder content = new StringBuilder();
365365 for (int i= 0; i < 35; i++) {
366366 int[] lenghts= new int[i + 1];
367 for (int j= 0; j < i + 1; j++)
367 for (int j= 0; j < i + 1; j++) {
368368 lenghts[j]= j;
369 for (int j= 0; j < i; j++)
370 content+= "x";
371
372 set(content);
373 assertTextStoreContents(content);
374
375 content+= "\n";
376 }
377 }
378
369 }
370 for (int j= 0; j < i; j++) {
371 content.append("x");
372 }
373
374 set(content.toString());
375 assertTextStoreContents(content.toString());
376
377 content.append('\n');
378 }
379 }
380
379381 @Test
380382 public void testFunnyLastLineCompatibility() throws Exception {
381383 /* empty last line */
00 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
11 <component id="org.eclipse.ui.editors" version="2">
22 <resource path="META-INF/MANIFEST.MF">
3 <filter comment="API was backported to 4.6.2" id="926941240">
3 <filter comment="The new field has @noreference, hence not a new API" id="924844039">
44 <message_arguments>
5 <message_argument value="3.11.100"/>
56 <message_argument value="3.11.0"/>
6 <message_argument value="3.10.1"/>
77 </message_arguments>
88 </filter>
99 </resource>
1212 <message_arguments>
1313 <message_argument value="IAbstractTextEditorHelpContextIds"/>
1414 <message_argument value="ITextEditorHelpContextIds"/>
15 </message_arguments>
16 </filter>
17 </resource>
18 <resource path="src/org/eclipse/ui/texteditor/AbstractDecoratedTextEditorPreferenceConstants.java" type="org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants">
19 <filter comment="@since tag not needed since @noreference and hence no API" id="1143996420">
20 <message_arguments>
21 <message_argument value="EDITOR_PRINT_MARGIN_ALLOW_OVERRIDE"/>
1522 </message_arguments>
1623 </filter>
1724 </resource>
00 eclipse.preferences.version=1
1 editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true
12 formatter_profile=_JDT UI Code Style Conventions
23 formatter_settings_version=12
34 org.eclipse.jdt.ui.exception.name=e
89 org.eclipse.jdt.ui.ondemandthreshold=99
910 org.eclipse.jdt.ui.overrideannotation=true
1011 org.eclipse.jdt.ui.staticondemandthreshold=99
12 sp_cleanup.add_default_serial_version_id=true
13 sp_cleanup.add_generated_serial_version_id=false
14 sp_cleanup.add_missing_annotations=true
15 sp_cleanup.add_missing_deprecated_annotations=true
16 sp_cleanup.add_missing_methods=false
17 sp_cleanup.add_missing_nls_tags=false
18 sp_cleanup.add_missing_override_annotations=true
19 sp_cleanup.add_missing_override_annotations_interface_methods=true
20 sp_cleanup.add_serial_version_id=false
21 sp_cleanup.always_use_blocks=true
22 sp_cleanup.always_use_parentheses_in_expressions=false
23 sp_cleanup.always_use_this_for_non_static_field_access=false
24 sp_cleanup.always_use_this_for_non_static_method_access=false
25 sp_cleanup.convert_functional_interfaces=false
26 sp_cleanup.convert_to_enhanced_for_loop=false
27 sp_cleanup.correct_indentation=false
28 sp_cleanup.format_source_code=true
29 sp_cleanup.format_source_code_changes_only=true
30 sp_cleanup.insert_inferred_type_arguments=false
31 sp_cleanup.make_local_variable_final=true
32 sp_cleanup.make_parameters_final=false
33 sp_cleanup.make_private_fields_final=true
34 sp_cleanup.make_type_abstract_if_missing_method=false
35 sp_cleanup.make_variable_declarations_final=false
36 sp_cleanup.never_use_blocks=false
37 sp_cleanup.never_use_parentheses_in_expressions=true
38 sp_cleanup.on_save_use_additional_actions=true
39 sp_cleanup.organize_imports=true
40 sp_cleanup.qualify_static_field_accesses_with_declaring_class=false
41 sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true
42 sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true
43 sp_cleanup.qualify_static_member_accesses_with_declaring_class=false
44 sp_cleanup.qualify_static_method_accesses_with_declaring_class=false
45 sp_cleanup.remove_private_constructors=true
46 sp_cleanup.remove_redundant_type_arguments=false
47 sp_cleanup.remove_trailing_whitespaces=false
48 sp_cleanup.remove_trailing_whitespaces_all=true
49 sp_cleanup.remove_trailing_whitespaces_ignore_empty=false
50 sp_cleanup.remove_unnecessary_casts=true
51 sp_cleanup.remove_unnecessary_nls_tags=false
52 sp_cleanup.remove_unused_imports=false
53 sp_cleanup.remove_unused_local_variables=false
54 sp_cleanup.remove_unused_private_fields=true
55 sp_cleanup.remove_unused_private_members=false
56 sp_cleanup.remove_unused_private_methods=true
57 sp_cleanup.remove_unused_private_types=true
58 sp_cleanup.sort_members=false
59 sp_cleanup.sort_members_all=false
60 sp_cleanup.use_anonymous_class_creation=false
61 sp_cleanup.use_blocks=false
62 sp_cleanup.use_blocks_only_for_return_and_throw=false
63 sp_cleanup.use_lambda=true
64 sp_cleanup.use_parentheses_in_expressions=false
65 sp_cleanup.use_this_for_non_static_field_access=false
66 sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true
67 sp_cleanup.use_this_for_non_static_method_access=false
68 sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true
11 Bundle-ManifestVersion: 2
22 Bundle-Name: %pluginName
33 Bundle-SymbolicName: org.eclipse.ui.editors; singleton:=true
4 Bundle-Version: 3.11.0.qualifier
4 Bundle-Version: 3.11.100.qualifier
55 Bundle-Activator: org.eclipse.ui.internal.editors.text.EditorsPlugin
66 Bundle-ActivationPolicy: lazy
77 Bundle-Vendor: %providerName
2626 org.eclipse.core.filesystem;bundle-version="[1.2.0,2.0.0)"
2727 Bundle-RequiredExecutionEnvironment: JavaSE-1.8
2828 Import-Package: com.ibm.icu.text
29 Automatic-Module-Name: org.eclipse.ui.editors
00 # To force a version qualifier update add the bug here
11 Bug 509931: Comparator errors in M20170104-0545
2 Bug 534597 - Unanticipated comparator errors in I20180511-2000
+0
-15
org.eclipse.ui.editors/migration_guidelines.html less more
0 <!DOCTYPE doctype PUBLIC "-//w3c//dtd html 4.0 transitional//en">
1 <html><head>
2 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
3 <meta name="Author" content="IBM"><title>Platform Text Migration Guide</title>
4 <link rel="stylesheet" href="http://dev.eclipse.org/default_style.css" type="text/css">
5 </head>
6 <h1>Platform Text Migration Guide</h1>
7 <p>
8 Incompatible and interesting new APIs can be found in the documentation in two ways:
9 </p>
10 <ul>
11 <li>Help &gt; Help Contents &gt; Platform Plug-in Developer Guide &gt; 3.4 Plug-in Migration Guide</li>
12 <li>load the <code>org.eclipse.platform.doc.isv</code> plug-in from CVS and open <code>porting/eclipse_3_4_porting_guide.html</code></li>
13 </ul>
14 </body></html>
+0
-34
org.eclipse.ui.editors/migration_guidelines_3.1.html less more
0 <!DOCTYPE doctype PUBLIC "-//w3c//dtd html 4.0 transitional//en">
1 <html><head>
2 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
3 <meta name="Author" content="IBM"><title>Platform Text Migration Guide</title>
4 <link rel="stylesheet" href="http://dev.eclipse.org/default_style.css" type="text/css">
5 </head>
6 <body bgcolor="#ffffff" text="#000000">
7 <body text="#000000" bgcolor="#ffffff">
8 <p>
9 This document lists the API changes that occurred between R3.0 and R3.1 and
10 how to migrate from the R3.0 API to the R3.1 API.
11 </p>
12 <p></p>
13 <table style="width: 1000px; height: 437px;" border="0" cellpadding="2" cellspacing="5">
14 <tbody>
15 <tr>
16 <td align="left" width="72%"> <font size="+3"><b>Platform Text -
17 </b></font><font size="+3"><b>Binary Compatibility Breakage from R3.0 to R3.1</b></font><font size="+3"><b></b></font><font color="#8080ff" size="-2"><br>
18 </font></td>
19 </tr>
20 <tr>
21 <td>
22 <ul>
23 <li><span style="font-weight: bold; font-style: italic;">org.eclipse.jface.text.DefaultPositionUpdater.update(DocumentEvent event)</span>: to prevent holding on to the cached document after calling this method we set <code>fDocument</code> to <code>null</code> at the end of this method. Subclasses that extend <code>update(DocumentEvent event)</code> i.e. call <code>super.update(event)</code> will be broken if they access <code>fDocument</code> after that call. To fix this either replace <code>fDocument</code> with <code>event.getDocument()</code> or set <code>fDocument</code> again. If you do the latter do not forget to set it back to <code>null</code> at the end of your method.<br>
24 </li></ul>
25 </td>
26 </tr>
27 <tr>
28 <td align="left" width="72%"> <font size="+3"><b>Platform Text - </b></font><font size="+3"><b>Breaking API changes from R3.0 to R3.1</b></font><font color="#8080ff" size="-2">
29 </font></td></tr>
30 </tbody>
31 </table>
32 <p> </p>
33 </body></html>
+0
-33
org.eclipse.ui.editors/migration_guidelines_3.2.html less more
0 <!DOCTYPE doctype PUBLIC "-//w3c//dtd html 4.0 transitional//en">
1 <html><head>
2 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
3 <meta name="Author" content="IBM"><title>Platform Text Migration Guide</title>
4 <link rel="stylesheet" href="http://dev.eclipse.org/default_style.css" type="text/css">
5 </head>
6 <body bgcolor="#ffffff" text="#000000">
7 <body text="#000000" bgcolor="#ffffff">
8 <p>
9 This document lists the API changes that occurred between R3.1 and R3.2 and
10 how to migrate from the R3.1 API to the R3.2 API.
11 </p>
12 <p></p>
13 <table style="width: 1000px; height: 437px;" border="0" cellpadding="2" cellspacing="5">
14 <tbody>
15 <tr>
16 <td align="left" width="72%"> <font size="+3"><b>Platform Text -
17 </b></font><font size="+3"><b>Binary Compatibility Breakage from R3.1 to R3.2</b></font><font size="+3"><b></b></font><font color="#8080ff" size="-2"><br>
18 </font></td>
19 </tr>
20 <tr>
21 <td>
22 <ul>
23 </ul>
24 </td>
25 </tr>
26 <tr>
27 <td align="left" width="72%"> <font size="+3"><b>Platform Text - </b></font><font size="+3"><b>Breaking API changes from R3.1 to R3.2</b></font><font color="#8080ff" size="-2">
28 </font></td></tr>
29 </tbody>
30 </table>
31 <p> </p>
32 </body></html>
+0
-57
org.eclipse.ui.editors/migration_guidelines_3_0.html less more
0 <!DOCTYPE doctype PUBLIC "-//w3c//dtd html 4.0 transitional//en"><html><head>
1 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
2 <meta name="Author" content="IBM"><title>Platform Text Breaking API changes</title></head><body text="#000000" bgcolor="#ffffff">
3 &nbsp;
4 <table border="0" cellspacing="5" cellpadding="2" width="100%">
5 <tbody>
6 <tr>
7 <td align="left" width="72%"> <font size="+3"><b>Platform Text -
8 Breaking API changes from R2.1 to R3.0</b></font> <font size="-2" color="#8080ff"><br>
9 </font></td>
10 </tr>
11 <tr>
12 <td>
13 <ul>
14 <li><span style="font-weight: bold; font-style: italic;">org.eclipse.jface.text.source.AnnotationModel.addAnnotation(Annotation, Position, boolean)</span>:
15 changed signature to throw <code>org.eclipse.jface.text.BadLocationException</code>
16 in order to add support for better handling of invalid document
17 positions. Only clients which extend (i.e. call super) this method will be
18 broken. To fix the problem either catch the exception from the super
19 call or change the signature in the extended method. The latter is
20 suggested since clients should decide how to handle invalid document
21 positions.<br>
22 </li>
23 <li><span style="font-weight: bold; font-style: italic;">org.eclipse.ui.texteditor.TextEditorAction.canModifyEditor()</span>:
24 added predicate method that checks whether the action's editor can be modified. The method calls different methods on the underlying editor depending on
25 which interfaces the editor implements. The method will call <code>ITextEditorExtension2.isEditorInputModifiable()</code> if it is available. Modifing actions
26 can call the method when updating their enablement state.<br>
27 </li>
28 <li><span style="font-weight: bold; font-style: italic;">org.eclipse.ui.texteditor.TextEditorAction.validateEdit()</span>:
29 added predicate method that checks and updates the modifiable state of the action's editor. The method calls different methods on the underlying editor depending on
30 which interfaces the editor implements. The method will call <code>ITextEditorExtension2.validateEditorInputState()</code> if it is available. Modifing actions
31 can call the method before running modifing the editor's content.<br>
32 </li>
33 <li><span style="font-weight: bold; font-style: italic;">org.eclipse.ui.texteditor.AbstractDecoratedTextEditor</span>:
34 A new intermediate class layer has been added between <code>StatusTextEditor</code> and other editors, namely <code>TextEditor</code> and <code>JavaEditor</code>. The additional layer
35 includes features found commonly in advanced editors (and especially source editors) such as:
36 <ul>
37 <li>a vertical ruler to display annotations, line numbers, and quick diff information</li>
38 <li>an overview ruler</li>
39 <li>current line hightlighting,</li>
40 <li>and print margin display</li>
41 </ul>
42 Implementors of an editor may choose to extend <code>AbstractDecoratedTextEditor</code> instead of <code>TextEditor</code>.
43 <br>
44 </li>
45 </ul>
46 </td>
47 </tr>
48 <tr>
49 <td> <font size="-1"> This document lists the breaking API
50 changes that occurred between R2.1 and R3.0 and how to migrate from the
51 R2.1 API to the R3.0 API. </font> </td>
52 </tr>
53 </tbody>
54 </table>
55 <p> </p>
56 </body></html>
2929 removeTrailingWhitespace.description= Removes the trailing whitespace of each line
3030
3131 NewUntitledTextFile.label= Untitled Text File
32 NewUntitledTextFile.description= Creates an empty untitled text file
32 NewUntitledTextFile.description= Create an empty untitled text file
3333
3434 ActionDefinition.quickDiff.name= Quick Diff Toggle
3535 ActionDefinition.quickDiff.description= Toggles quick diff information display on the line number ruler
112112 conversionActionSet.label= Convert Line Delimiters
113113 conversionSubMenu.label= Con&vert Line Delimiters To
114114
115 preferenceKeywords.general= text editor tabs spaces undo history ruler overview hyperlink overwrite colors range indicator typing appearance derived navigation smart caret positioning invisible whitespace characters drag drop dnd hovers sticky enrich rich
115 preferenceKeywords.general= pop-up text editor tabs spaces undo history ruler overview hyperlink overwrite colors range indicator typing appearance derived navigation smart caret positioning invisible whitespace characters drag drop dnd hovers popup sticky enrich rich
116116 preferenceKeywords.tabWidth= tab width
117117 preferenceKeywords.lineNumber= line numbers
118118 preferenceKeywords.printMargin= print margin
1313 <parent>
1414 <artifactId>eclipse.platform.text</artifactId>
1515 <groupId>eclipse.platform.text</groupId>
16 <version>4.7.3-SNAPSHOT</version>
16 <version>4.8.0-SNAPSHOT</version>
1717 </parent>
1818 <groupId>org.eclipse.ui</groupId>
1919 <artifactId>org.eclipse.ui.editors</artifactId>
20 <version>3.11.0-SNAPSHOT</version>
20 <version>3.11.100-SNAPSHOT</version>
2121 <packaging>eclipse-plugin</packaging>
2222 </project>
376376 protected boolean setDocumentContent(IDocument document, IEditorInput editorInput) throws CoreException {
377377 if (editorInput instanceof IFileEditorInput) {
378378 IFile file= ((IFileEditorInput) editorInput).getFile();
379 InputStream stream= file.getContents(false);
380 try {
379 try (InputStream stream= file.getContents(false)) {
381380 setDocumentContent(document, stream);
382 } finally {
383 try {
384 stream.close();
385 } catch (IOException x) {
386 }
381 } catch (IOException x) {
387382 }
388383 return true;
389384 }
394389 protected boolean setDocumentContent(IDocument document, IEditorInput editorInput, String encoding) throws CoreException {
395390 if (editorInput instanceof IFileEditorInput) {
396391 IFile file= ((IFileEditorInput) editorInput).getFile();
397 InputStream contentStream= file.getContents(false);
398 try {
399
392 try (InputStream contentStream= file.getContents(false)) {
400393 FileInfo info= (FileInfo)getElementInfo(editorInput);
401394 boolean removeBOM= false;
402395 if (CHARSET_UTF_8.equals(encoding)) {
427420 String message= (ex.getMessage() != null ? ex.getMessage() : ""); //$NON-NLS-1$
428421 IStatus s= new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, IStatus.OK, message, ex);
429422 throw new CoreException(s);
430 } finally {
431 try {
432 contentStream.close();
433 } catch (IOException e1) {
434 }
435423 }
436424 return true;
437425 }
665653 return encoding;
666654
667655 // Probe content
668 Reader reader= new DocumentReader(document);
669 try {
656 try (Reader reader= new DocumentReader(document)) {
670657 QualifiedName[] options= new QualifiedName[] { IContentDescription.CHARSET, IContentDescription.BYTE_ORDER_MARK };
671658 IContentDescription description= Platform.getContentTypeManager().getDescriptionFor(reader, targetFile.getName(), options);
672659 if (description != null) {
676663 }
677664 } catch (IOException ex) {
678665 // continue with next strategy
679 } finally {
680 try {
681 reader.close();
682 } catch (IOException x) {
683 }
684666 }
685667
686668 // Use file's encoding if the file has a BOM
137137 encoding= getDefaultEncoding();
138138
139139 in= new BufferedReader(new InputStreamReader(contentStream, encoding), DEFAULT_FILE_SIZE);
140 StringBuffer buffer= new StringBuffer(DEFAULT_FILE_SIZE);
140 StringBuilder buffer= new StringBuilder(DEFAULT_FILE_SIZE);
141141 char[] readBuffer= new char[2048];
142142 int n= in.read(readBuffer);
143143 while (n > 0) {
190190 protected boolean setDocumentContent(IDocument document, IEditorInput editorInput, String encoding) throws CoreException {
191191 if (editorInput instanceof IStorageEditorInput) {
192192 IStorage storage= ((IStorageEditorInput) editorInput).getStorage();
193 InputStream stream= storage.getContents();
194 try {
193 try (InputStream stream= storage.getContents()) {
195194 setDocumentContent(document, stream, encoding);
196 } finally {
197 try {
198 stream.close();
199 } catch (IOException x) {
200 }
195 } catch (IOException x) {
201196 }
202197 return true;
203198 }
408403 public IContentType getContentType(Object element) throws CoreException {
409404 if (element instanceof IStorageEditorInput) {
410405 IStorage storage= ((IStorageEditorInput) element).getStorage();
411 Reader reader= null;
412 InputStream stream= null;
413406 try {
414407 IContentDescription desc;
415408 IDocument document= getDocument(element);
416409 if (document != null) {
417 reader= new DocumentReader(document);
418 desc= Platform.getContentTypeManager().getDescriptionFor(reader, storage.getName(), NO_PROPERTIES);
410 try (Reader reader= new DocumentReader(document)) {
411 desc= Platform.getContentTypeManager().getDescriptionFor(reader, storage.getName(), NO_PROPERTIES);
412 }
419413 } else {
420 stream= storage.getContents();
421 desc= Platform.getContentTypeManager().getDescriptionFor(stream, storage.getName(), NO_PROPERTIES);
414 try (InputStream stream= storage.getContents()) {
415 desc= Platform.getContentTypeManager().getDescriptionFor(stream, storage.getName(), NO_PROPERTIES);
416 }
422417 }
423418 if (desc != null && desc.getContentType() != null)
424419 return desc.getContentType();
435430 else
436431 message= TextEditorMessages.StorageDocumentProvider_getContentDescription;
437432 throw new CoreException(new Status(IStatus.ERROR, EditorsUI.PLUGIN_ID, IStatus.OK, message, x));
438 } finally {
439 try {
440 // Note: either 'reader' or 'stream' is null
441 if (reader != null)
442 reader.close();
443 if (stream != null)
444 stream.close();
445 } catch (IOException x) {
446 }
447433 }
448434 }
449435 return super.getContentType(element);
131131 URL url= FileLocator.find(plugin, Path.fromOSString(file), null);
132132 if (url != null) {
133133 ResourceBundle bundle= null;
134 InputStream bundleStream= null;
135 InputStream stream= null;
136 try {
137 String translations= element.getAttribute(TRANSLATIONS);
138 if (translations != null) {
139 URL bundleURL= FileLocator.find(plugin, Path.fromOSString(translations), null);
140 if (bundleURL != null) {
141 bundleStream= bundleURL.openStream();
134 String translations= element.getAttribute(TRANSLATIONS);
135 if (translations != null) {
136 URL bundleURL= FileLocator.find(plugin, Path.fromOSString(translations), null);
137 if (bundleURL != null) {
138 try (InputStream bundleStream= bundleURL.openStream()) {
142139 bundle= new PropertyResourceBundle(bundleStream);
143140 }
144141 }
145
146 stream= new BufferedInputStream(url.openStream());
142 }
143
144 try (InputStream stream= new BufferedInputStream(url.openStream())) {
147145 TemplateReaderWriter reader= new TemplateReaderWriter();
148146 TemplatePersistenceData[] datas= reader.read(stream, bundle);
149147 for (int i= 0; i < datas.length; i++) {
157155 templates.add(data);
158156 }
159157 }
160 } finally {
161 try {
162 if (bundleStream != null)
163 bundleStream.close();
164 } catch (IOException x) {
165 } finally {
166 try {
167 if (stream != null)
168 stream.close();
169 } catch (IOException x) {
170 }
171 }
172158 }
173159 }
174160 }
370370 in= new BufferedReader(new InputStreamReader(contentStream), DEFAULT_FILE_SIZE);
371371 else
372372 in= new BufferedReader(new InputStreamReader(contentStream, encoding), DEFAULT_FILE_SIZE);
373 StringBuffer buffer= new StringBuffer(DEFAULT_FILE_SIZE);
373 StringBuilder buffer= new StringBuilder(DEFAULT_FILE_SIZE);
374374 char[] readBuffer= new char[2048];
375375 int n= in.read(readBuffer);
376376 while (n > 0) {
00 /*******************************************************************************
1 * Copyright (c) 2000, 2015 IBM Corporation and others.
1 * Copyright (c) 2000, 2018 IBM Corporation and others.
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
4343 import org.eclipse.jface.viewers.ComboViewer;
4444 import org.eclipse.jface.viewers.ISelectionChangedListener;
4545 import org.eclipse.jface.viewers.IStructuredContentProvider;
46 import org.eclipse.jface.viewers.IStructuredSelection;
4746 import org.eclipse.jface.viewers.LabelProvider;
4847 import org.eclipse.jface.viewers.SelectionChangedEvent;
4948 import org.eclipse.jface.viewers.StructuredSelection;
316315 final boolean value= fShowInTextCheckBox.getSelection();
317316 if (value) {
318317 // enable whatever is in the combo
319 String[] decoration= (String[]) ((IStructuredSelection) fDecorationViewer.getSelection()).getFirstElement();
318 String[] decoration= (String[]) fDecorationViewer.getStructuredSelection().getFirstElement();
320319 if (HIGHLIGHT.equals(decoration))
321320 fStore.setValue(item.highlightKey, true);
322321 else
394393
395394 @Override
396395 public void selectionChanged(SelectionChangedEvent event) {
397 String[] decoration= (String[]) ((IStructuredSelection) fDecorationViewer.getSelection()).getFirstElement();
396 String[] decoration= (String[]) fDecorationViewer.getStructuredSelection().getFirstElement();
398397 ListItem item= getSelectedItem();
399398
400399 if (fShowInTextCheckBox.getSelection()) {
672671 }
673672
674673 private ListItem getSelectedItem() {
675 return (ListItem) ((IStructuredSelection) fAnnotationTypeViewer.getSelection()).getFirstElement();
674 return (ListItem) fAnnotationTypeViewer.getStructuredSelection().getFirstElement();
676675 }
677676
678677 private void updateDecorationViewer(ListItem item, boolean changed) {
5252 import org.eclipse.jface.viewers.ICheckStateListener;
5353 import org.eclipse.jface.viewers.ILabelProviderListener;
5454 import org.eclipse.jface.viewers.IStructuredContentProvider;
55 import org.eclipse.jface.viewers.IStructuredSelection;
5655 import org.eclipse.jface.viewers.ITableLabelProvider;
5756 import org.eclipse.jface.viewers.Viewer;
5857
542541 }
543542
544543 private ListItem getSelectedItem() {
545 return (ListItem)((IStructuredSelection) fHyperlinkDetectorsViewer.getSelection()).getFirstElement();
544 return (ListItem) fHyperlinkDetectorsViewer.getStructuredSelection().getFirstElement();
546545 }
547546
548547 private void handleHyperlinkKeyModifierModified() {
00 /*******************************************************************************
1 * Copyright (c) 2000, 2015 IBM Corporation and others.
1 * Copyright (c) 2000, 2018 IBM Corporation and others.
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
4343 import org.eclipse.jface.viewers.ComboViewer;
4444 import org.eclipse.jface.viewers.ISelectionChangedListener;
4545 import org.eclipse.jface.viewers.IStructuredContentProvider;
46 import org.eclipse.jface.viewers.IStructuredSelection;
4746 import org.eclipse.jface.viewers.LabelProvider;
4847 import org.eclipse.jface.viewers.SelectionChangedEvent;
4948 import org.eclipse.jface.viewers.StructuredSelection;
314313 final boolean value= fShowInTextCheckBox.getSelection();
315314 if (value) {
316315 // enable whatever is in the combo
317 String[] decoration= (String[]) ((IStructuredSelection) fDecorationViewer.getSelection()).getFirstElement();
316 String[] decoration= (String[]) fDecorationViewer.getStructuredSelection().getFirstElement();
318317 if (HIGHLIGHT.equals(decoration))
319318 getPreferenceStore().setValue(item.highlightKey, true);
320319 else
346345
347346 @Override
348347 public void selectionChanged(SelectionChangedEvent event) {
349 String[] decoration= (String[]) ((IStructuredSelection) fDecorationViewer.getSelection()).getFirstElement();
348 String[] decoration= (String[]) fDecorationViewer.getStructuredSelection().getFirstElement();
350349 ListItem item= getSelectedItem();
351350
352351 if (fShowInTextCheckBox.getSelection()) {
456455 }
457456
458457 private ListItem getSelectedItem() {
459 return (ListItem) ((IStructuredSelection) fAnnotationTypeViewer.getSelection()).getFirstElement();
458 return (ListItem) fAnnotationTypeViewer.getStructuredSelection().getFirstElement();
460459 }
461460
462461 private void updateDecorationViewer(ListItem item, boolean changed) {
00 /*******************************************************************************
1 * Copyright (c) 2000, 2016 IBM Corporation and others.
1 * Copyright (c) 2000, 2018 IBM Corporation and others.
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
649649 */
650650 @Override
651651 public void selectionChanged(SelectionChangedEvent event) {
652 IStructuredSelection selection= (IStructuredSelection) event.getSelection();
652 IStructuredSelection selection= event.getStructuredSelection();
653653 Object selectedElement= selection.getFirstElement();
654654 if (selectedElement == null) {
655655 currentTreeSelection= null;
348348
349349 private void updateSelectionCount() {
350350 List<Object> listItems= fResourceGroup.getAllCheckedListItems();
351 int checkedFiles= listItems == null ? 0 : listItems.size();
352 StringBuffer buffer= new StringBuffer();
351 int checkedFiles= listItems.size();
352 StringBuilder buffer= new StringBuilder();
353353 switch (checkedFiles) {
354354 case 0:
355355 buffer.append(TextEditorMessages.SelectResourcesDialog_noFilesSelected);
00 /*******************************************************************************
1 * Copyright (c) 2000, 2009 IBM Corporation and others.
1 * Copyright (c) 2000, 2018 IBM Corporation and others.
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
347347
348348 @Override
349349 public void selectionChanged(SelectionChangedEvent event) {
350 IStructuredSelection sel= (IStructuredSelection) event.getSelection();
350 IStructuredSelection sel= event.getStructuredSelection();
351351 if (sel.isEmpty())
352352 return;
353353 if (fCurrentBlock != null && fStatusMonitor.getStatus() != null && fStatusMonitor.getStatus().matches(IStatus.ERROR))
00 /*******************************************************************************
1 * Copyright (c) 2000, 2016 IBM Corporation and others.
1 * Copyright (c) 2000, 2018 IBM Corporation and others.
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
702702 overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLOR));
703703 overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.INT, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN));
704704 overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN));
705 overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_ALLOW_OVERRIDE));
705706
706707 overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.INT, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_UNDO_HISTORY_SIZE));
707708
843844 final IntegerDomain printMarginDomain= new IntegerDomain(20, 200);
844845 final Control[] printMarginControls= addTextField(appearanceComposite, printMarginColumn, printMarginDomain, 15, 20);
845846 createDependency(showPrintMarginButton, showPrintMargin, printMarginControls);
847
848 label= TextEditorMessages.TextEditorPreferencePage_printMarginAllowOverride;
849 Preference printMarginAllowOverride= new Preference(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_ALLOW_OVERRIDE, label, null);
850 final Button showPrintMarginAllowOverride= addCheckBox(appearanceComposite, printMarginAllowOverride, new BooleanDomain(), 0);
851 createDependency(showPrintMarginButton, showPrintMargin, new Control[] { showPrintMarginAllowOverride });
846852
847853 showPrintMarginButton.addSelectionListener(new SelectionAdapter() {
848854 @Override
00 /*******************************************************************************
1 * Copyright (c) 2000, 2015 IBM Corporation and others.
1 * Copyright (c) 2000, 2018 IBM Corporation and others.
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
3434 public static String TextEditorPreferencePage_convertTabsToSpaces;
3535 public static String TextEditorPreferencePage_undoHistorySize;
3636 public static String TextEditorPreferencePage_printMarginColumn;
37 public static String TextEditorPreferencePage_printMarginAllowOverride;
3738 public static String TextEditorPreferencePage_showLineNumbers;
3839 public static String TextEditorPreferencePage_highlightCurrentLine;
3940 public static String TextEditorPreferencePage_showPrintMargin;
00 ###############################################################################
1 # Copyright (c) 2000, 2015 IBM Corporation and others.
1 # Copyright (c) 2000, 2018 IBM Corporation and others.
22 # All rights reserved. This program and the accompanying materials
33 # are made available under the terms of the Eclipse Public License v1.0
44 # which accompanies this distribution, and is available at
1616 TextEditorPreferencePage_convertTabsToSpaces=&Insert spaces for tabs
1717 TextEditorPreferencePage_undoHistorySize=&Undo history size:
1818 TextEditorPreferencePage_printMarginColumn=Print margin colu&mn:
19 TextEditorPreferencePage_printMarginAllowOverride=Allow &editors to override the margin column
1920 TextEditorPreferencePage_showLineNumbers=Show line num&bers
2021 TextEditorPreferencePage_highlightCurrentLine=Hi&ghlight current line
2122 TextEditorPreferencePage_showPrintMargin=Sho&w print margin
00 /*******************************************************************************
1 * Copyright (c) 2000, 2016 IBM Corporation and others.
1 * Copyright (c) 2000, 2018 IBM Corporation and others.
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
201201 */
202202 private final static String PRINT_MARGIN_COLUMN= AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN;
203203 /**
204 * Preference key for telling whether editors are allowed to override the global print margin preferences.
205 */
206 private final static String PRINT_MARGIN_ALLOW_OVERRIDE= AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_ALLOW_OVERRIDE;
207 /**
204208 * Preference key to get whether the overwrite mode is disabled.
205209 * @since 3.1
206210 */
433437
434438 support.setCursorLinePainterPreferenceKeys(CURRENT_LINE, CURRENT_LINE_COLOR);
435439 support.setMarginPainterPreferenceKeys(PRINT_MARGIN, PRINT_MARGIN_COLOR, PRINT_MARGIN_COLUMN);
436 support.setSymbolicFontName(getFontPropertyPreferenceKey());
437440 }
438441
439442 /*
951954 if (fSourceViewerDecorationSupport == null) {
952955 fSourceViewerDecorationSupport= new SourceViewerDecorationSupport(viewer, getOverviewRuler(), getAnnotationAccess(), getSharedColors());
953956 configureSourceViewerDecorationSupport(fSourceViewerDecorationSupport);
957
958 // Fix for overridden print margin column, see https://bugs.eclipse.org/468307
959 if (!getPreferenceStore().getBoolean(PRINT_MARGIN_ALLOW_OVERRIDE))
960 fSourceViewerDecorationSupport.setMarginPainterPreferenceKeys(PRINT_MARGIN, PRINT_MARGIN_COLOR, PRINT_MARGIN_COLUMN);
954961 }
955962 return fSourceViewerDecorationSupport;
956963 }
00 /*******************************************************************************
1 * Copyright (c) 2000, 2015 IBM Corporation and others.
1 * Copyright (c) 2000, 2018 IBM Corporation and others.
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
125125 * </p>
126126 */
127127 public final static String EDITOR_PRINT_MARGIN_COLUMN= "printMarginColumn"; //$NON-NLS-1$
128
129 /**
130 * Tells whether editors are allowed to override the print margin preference (value
131 * <code>"printMarginAllowOverride"</code>).
132 * <p>
133 * The preference value is of type <code>boolean</code>.
134 * </p>
135 *
136 * @noreference This field is not intended to be referenced by clients.
137 */
138 public final static String EDITOR_PRINT_MARGIN_ALLOW_OVERRIDE= "printMarginAllowOverride"; //$NON-NLS-1$
128139
129140 /**
130141 * A named preference that controls whether the editor shows unknown
674685
675686 store.setDefault(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN, false);
676687 store.setDefault(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN, 80);
688 store.setDefault(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_ALLOW_OVERRIDE, false);
677689
678690 store.setDefault(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER, false);
679691
433433 if (thisValue instanceof Boolean)
434434 return store.getBoolean(property) ? Boolean.TRUE : Boolean.FALSE;
435435 else if (thisValue instanceof Double)
436 return new Double(store.getDouble(property));
436 return Double.valueOf(store.getDouble(property));
437437 else if (thisValue instanceof Float)
438 return new Float(store.getFloat(property));
438 return Float.valueOf(store.getFloat(property));
439439 else if (thisValue instanceof Integer)
440440 return Integer.valueOf(store.getInt(property));
441441 else if (thisValue instanceof Long)
442 return new Long(store.getLong(property));
442 return Long.valueOf(store.getLong(property));
443443 else if (thisValue instanceof String)
444444 return store.getString(property);
445445
4343 Editor.ManageBookmarks.remove.label=Remove Boo&kmark
4444 Editor.ManageBookmarks.add.dialog.title=Add Bookmark
4545 Editor.ManageBookmarks.add.dialog.message=Enter Bookmark name:
46 Editor.ManageBookmarks.add.dialog.addbutton=&Add
4647 Editor.ManageBookmarks.error.dialog.title=Managing Bookmarks
4748 Editor.ManageBookmarks.error.dialog.message=Problems managing bookmarks
4849
1919
2020 import org.osgi.framework.Bundle;
2121
22 import org.eclipse.swt.widgets.Button;
23 import org.eclipse.swt.widgets.Composite;
2224 import org.eclipse.swt.widgets.Shell;
2325
2426 import org.eclipse.core.commands.ExecutionException;
399401 String proposal= (o instanceof String) ? (String) o : ""; //$NON-NLS-1$
400402 String title= getString(fBundle, fPrefix + "add.dialog.title", fPrefix + "add.dialog.title"); //$NON-NLS-2$ //$NON-NLS-1$
401403 String message= getString(fBundle, fPrefix + "add.dialog.message", fPrefix + "add.dialog.message"); //$NON-NLS-2$ //$NON-NLS-1$
404 String addButtonText= getString(fBundle, fPrefix + "add.dialog.addbutton", fPrefix + "add.dialog.addbutton"); //$NON-NLS-1$ //$NON-NLS-2$
402405 IInputValidator inputValidator= new IInputValidator() {
403406 @Override
404407 public String isValid(String newText) {
405408 return (newText == null || newText.trim().length() == 0) ? " " : null; //$NON-NLS-1$
406409 }
407410 };
408 InputDialog dialog= new InputDialog(fTextEditor.getSite().getShell(), title, message, proposal, inputValidator);
411 AddBookmarkDialog dialog= new AddBookmarkDialog(fTextEditor.getSite().getShell(), title, message, proposal, inputValidator, addButtonText);
409412
410413 String label= null;
411414 if (dialog.open() != Window.CANCEL)
420423
421424 MarkerUtilities.setMessage(attributes, label);
422425 return true;
426 }
427
428 class AddBookmarkDialog extends InputDialog {
429
430 private final String addButtonText;
431
432 public AddBookmarkDialog(Shell parentShell, String dialogTitle, String dialogMessage, String initialValue, IInputValidator validator, String addButtonText) {
433 super(parentShell, dialogTitle, dialogMessage, initialValue, validator);
434 this.addButtonText= addButtonText;
435 }
436
437 @Override
438 protected void createButtonsForButtonBar(Composite parent) {
439 super.createButtonsForButtonBar(parent);
440 Button okButton= getOkButton();
441 okButton.setText(addButtonText);
442 }
443
423444 }
424445
425446 /**
5252 "dd { margin-top: 0; margin-bottom: 0 }\n" + //$NON-NLS-1$
5353 "\n" + //$NON-NLS-1$
5454 "/* Styles and colors */\n" + //$NON-NLS-1$
55 "a:link { color: #0000FF }\n" + //$NON-NLS-1$
56 "a:hover { color: #000080 }\n" + //$NON-NLS-1$
55 "a:link { color: hyperlinkColor }\n" + //$NON-NLS-1$
56 "a:hover { color: activeHyperlinkColor }\n" + //$NON-NLS-1$
5757 "a:visited { text-decoration: underline }\n" + //$NON-NLS-1$
5858 "h4 { font-style: italic }\n" + //$NON-NLS-1$
5959 "strong { font-weight: bold }\n" + //$NON-NLS-1$
9898 // there is already a header
9999 return html;
100100
101 StringBuffer info= new StringBuffer(512 + html.length());
101 StringBuilder info= new StringBuilder(512 + html.length());
102102 HTMLPrinter.insertPageProlog(info, 0, fgStyleSheet);
103103 info.append(html);
104104 HTMLPrinter.addPageEpilog(info);
11 Bundle-ManifestVersion: 2
22 Bundle-Name: %Plugin.name
33 Bundle-SymbolicName: org.eclipse.ui.editors.tests;singleton:=true
4 Bundle-Version: 3.11.0.qualifier
4 Bundle-Version: 3.11.100.qualifier
55 Bundle-Vendor: %Plugin.providerName
66 Bundle-Localization: plugin
77 Export-Package: org.eclipse.ui.editors.tests
2222 Bundle-RequiredExecutionEnvironment: JavaSE-1.8
2323 Eclipse-BundleShape: dir
2424 Bundle-ActivationPolicy: lazy
25 Automatic-Module-Name: org.eclipse.ui.editors.tests
1313 <parent>
1414 <artifactId>tests-pom</artifactId>
1515 <groupId>eclipse.platform.text</groupId>
16 <version>4.7.3-SNAPSHOT</version>
16 <version>4.8.0-SNAPSHOT</version>
1717 <relativePath>../tests-pom/</relativePath>
1818 </parent>
1919 <groupId>org.eclipse.ui</groupId>
2020 <artifactId>org.eclipse.ui.editors.tests</artifactId>
21 <version>3.11.0-SNAPSHOT</version>
21 <version>3.11.100-SNAPSHOT</version>
2222 <packaging>eclipse-test-plugin</packaging>
2323 <properties>
2424 <testSuite>${project.artifactId}</testSuite>
00 eclipse.preferences.version=1
1 editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true
12 formatter_profile=_JDT UI Code Style Conventions
23 formatter_settings_version=12
34 org.eclipse.jdt.ui.exception.name=e
89 org.eclipse.jdt.ui.ondemandthreshold=99
910 org.eclipse.jdt.ui.overrideannotation=true
1011 org.eclipse.jdt.ui.staticondemandthreshold=99
12 sp_cleanup.add_default_serial_version_id=true
13 sp_cleanup.add_generated_serial_version_id=false
14 sp_cleanup.add_missing_annotations=true
15 sp_cleanup.add_missing_deprecated_annotations=true
16 sp_cleanup.add_missing_methods=false
17 sp_cleanup.add_missing_nls_tags=false
18 sp_cleanup.add_missing_override_annotations=true
19 sp_cleanup.add_missing_override_annotations_interface_methods=true
20 sp_cleanup.add_serial_version_id=false
21 sp_cleanup.always_use_blocks=true
22 sp_cleanup.always_use_parentheses_in_expressions=false
23 sp_cleanup.always_use_this_for_non_static_field_access=false
24 sp_cleanup.always_use_this_for_non_static_method_access=false
25 sp_cleanup.convert_functional_interfaces=false
26 sp_cleanup.convert_to_enhanced_for_loop=false
27 sp_cleanup.correct_indentation=false
28 sp_cleanup.format_source_code=true
29 sp_cleanup.format_source_code_changes_only=true
30 sp_cleanup.insert_inferred_type_arguments=false
31 sp_cleanup.make_local_variable_final=true
32 sp_cleanup.make_parameters_final=false
33 sp_cleanup.make_private_fields_final=true
34 sp_cleanup.make_type_abstract_if_missing_method=false
35 sp_cleanup.make_variable_declarations_final=false
36 sp_cleanup.never_use_blocks=false
37 sp_cleanup.never_use_parentheses_in_expressions=true
38 sp_cleanup.on_save_use_additional_actions=true
39 sp_cleanup.organize_imports=true
40 sp_cleanup.qualify_static_field_accesses_with_declaring_class=false
41 sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true
42 sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true
43 sp_cleanup.qualify_static_member_accesses_with_declaring_class=false
44 sp_cleanup.qualify_static_method_accesses_with_declaring_class=false
45 sp_cleanup.remove_private_constructors=true
46 sp_cleanup.remove_redundant_type_arguments=false
47 sp_cleanup.remove_trailing_whitespaces=false
48 sp_cleanup.remove_trailing_whitespaces_all=true
49 sp_cleanup.remove_trailing_whitespaces_ignore_empty=false
50 sp_cleanup.remove_unnecessary_casts=true
51 sp_cleanup.remove_unnecessary_nls_tags=false
52 sp_cleanup.remove_unused_imports=false
53 sp_cleanup.remove_unused_local_variables=false
54 sp_cleanup.remove_unused_private_fields=true
55 sp_cleanup.remove_unused_private_members=false
56 sp_cleanup.remove_unused_private_methods=true
57 sp_cleanup.remove_unused_private_types=true
58 sp_cleanup.sort_members=false
59 sp_cleanup.sort_members_all=false
60 sp_cleanup.use_anonymous_class_creation=false
61 sp_cleanup.use_blocks=false
62 sp_cleanup.use_blocks_only_for_return_and_throw=false
63 sp_cleanup.use_lambda=true
64 sp_cleanup.use_parentheses_in_expressions=false
65 sp_cleanup.use_this_for_non_static_field_access=false
66 sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true
67 sp_cleanup.use_this_for_non_static_method_access=false
68 sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true
00 /*******************************************************************************
1 * Copyright (c) 2000, 2015 IBM Corporation and others.
1 * Copyright (c) 2000, 2018 IBM Corporation and others.
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
1717 import org.eclipse.swt.widgets.Composite;
1818 import org.eclipse.swt.widgets.Control;
1919
20 import org.eclipse.jface.viewers.ISelection;
2120 import org.eclipse.jface.viewers.IStructuredSelection;
2221 import org.eclipse.jface.viewers.ITreeContentProvider;
2322 import org.eclipse.jface.viewers.LabelProvider;
193192
194193 super.selectionChanged(event);
195194
196 ISelection selection= event.getSelection();
195 IStructuredSelection selection= event.getStructuredSelection();
197196 if (selection.isEmpty())
198197 fTextEditor.resetHighlightRange();
199198 else {
200 Segment segment= (Segment) ((IStructuredSelection) selection).getFirstElement();
199 Segment segment= (Segment) selection.getFirstElement();
201200 int start= segment.position.getOffset();
202201 int length= segment.position.getLength();
203202 try {
11 Bundle-ManifestVersion: 2
22 Bundle-Name: %pluginName
33 Bundle-SymbolicName: org.eclipse.ui.examples.javaeditor; singleton:=true
4 Bundle-Version: 3.2.100.qualifier
4 Bundle-Version: 3.2.200.qualifier
55 Bundle-Activator: org.eclipse.ui.examples.javaeditor.JavaEditorExamplePlugin
66 Bundle-Vendor: %providerName
77 Bundle-Localization: plugin
2020 org.eclipse.ui.views
2121 Bundle-ActivationPolicy: lazy
2222 Bundle-RequiredExecutionEnvironment: JavaSE-1.8
23 Automatic-Module-Name: org.eclipse.ui.examples.javaeditor
1313 <parent>
1414 <artifactId>eclipse.platform.text</artifactId>
1515 <groupId>eclipse.platform.text</groupId>
16 <version>4.7.3-SNAPSHOT</version>
16 <version>4.8.0-SNAPSHOT</version>
1717 </parent>
1818 <groupId>org.eclipse.ui</groupId>
1919 <artifactId>org.eclipse.ui.examples.javaeditor</artifactId>
20 <version>3.2.100-SNAPSHOT</version>
20 <version>3.2.200-SNAPSHOT</version>
2121 <packaging>eclipse-plugin</packaging>
2222 </project>
0 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
1 <component id="org.eclipse.ui.genericeditor" version="2">
2 <resource path="META-INF/MANIFEST.MF">
3 <filter comment="Minor version was wrongly increased" id="926941240">
4 <message_arguments>
5 <message_argument value="1.1.0"/>
6 <message_argument value="1.0.1"/>
7 </message_arguments>
8 </filter>
9 <filter id="926941240">
10 <message_arguments>
11 <message_argument value="1.1.0"/>
12 <message_argument value="1.0.2"/>
13 </message_arguments>
14 </filter>
15 </resource>
16 </component>
0 eclipse.preferences.version=1
1 editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true
2 sp_cleanup.add_default_serial_version_id=true
3 sp_cleanup.add_generated_serial_version_id=false
4 sp_cleanup.add_missing_annotations=true
5 sp_cleanup.add_missing_deprecated_annotations=true
6 sp_cleanup.add_missing_methods=false
7 sp_cleanup.add_missing_nls_tags=false
8 sp_cleanup.add_missing_override_annotations=true
9 sp_cleanup.add_missing_override_annotations_interface_methods=true
10 sp_cleanup.add_serial_version_id=false
11 sp_cleanup.always_use_blocks=true
12 sp_cleanup.always_use_parentheses_in_expressions=false
13 sp_cleanup.always_use_this_for_non_static_field_access=false
14 sp_cleanup.always_use_this_for_non_static_method_access=false
15 sp_cleanup.convert_functional_interfaces=false
16 sp_cleanup.convert_to_enhanced_for_loop=false
17 sp_cleanup.correct_indentation=false
18 sp_cleanup.format_source_code=true
19 sp_cleanup.format_source_code_changes_only=false
20 sp_cleanup.insert_inferred_type_arguments=false
21 sp_cleanup.make_local_variable_final=true
22 sp_cleanup.make_parameters_final=false
23 sp_cleanup.make_private_fields_final=true
24 sp_cleanup.make_type_abstract_if_missing_method=false
25 sp_cleanup.make_variable_declarations_final=false
26 sp_cleanup.never_use_blocks=false
27 sp_cleanup.never_use_parentheses_in_expressions=true
28 sp_cleanup.on_save_use_additional_actions=true
29 sp_cleanup.organize_imports=true
30 sp_cleanup.qualify_static_field_accesses_with_declaring_class=false
31 sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true
32 sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true
33 sp_cleanup.qualify_static_member_accesses_with_declaring_class=false
34 sp_cleanup.qualify_static_method_accesses_with_declaring_class=false
35 sp_cleanup.remove_private_constructors=true
36 sp_cleanup.remove_redundant_type_arguments=false
37 sp_cleanup.remove_trailing_whitespaces=false
38 sp_cleanup.remove_trailing_whitespaces_all=true
39 sp_cleanup.remove_trailing_whitespaces_ignore_empty=false
40 sp_cleanup.remove_unnecessary_casts=true
41 sp_cleanup.remove_unnecessary_nls_tags=false
42 sp_cleanup.remove_unused_imports=false
43 sp_cleanup.remove_unused_local_variables=false
44 sp_cleanup.remove_unused_private_fields=true
45 sp_cleanup.remove_unused_private_members=false
46 sp_cleanup.remove_unused_private_methods=true
47 sp_cleanup.remove_unused_private_types=true
48 sp_cleanup.sort_members=false
49 sp_cleanup.sort_members_all=false
50 sp_cleanup.use_anonymous_class_creation=false
51 sp_cleanup.use_blocks=false
52 sp_cleanup.use_blocks_only_for_return_and_throw=false
53 sp_cleanup.use_lambda=true
54 sp_cleanup.use_parentheses_in_expressions=false
55 sp_cleanup.use_this_for_non_static_field_access=false
56 sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true
57 sp_cleanup.use_this_for_non_static_method_access=false
58 sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true
11 Bundle-ManifestVersion: 2
22 Bundle-Name: %Bundle-Name
33 Bundle-SymbolicName: org.eclipse.ui.genericeditor;singleton:=true
4 Bundle-Version: 1.0.2.qualifier
4 Bundle-Version: 1.1.0.qualifier
55 Bundle-Vendor: %Bundle-Vendor
66 Bundle-RequiredExecutionEnvironment: JavaSE-1.8
77 Require-Bundle: org.eclipse.ui.workbench.texteditor;bundle-version="3.10.0",
88 org.eclipse.ui.editors;bundle-version="3.10.0",
99 org.eclipse.text;bundle-version="3.6.0",
10 org.eclipse.jface.text;bundle-version="3.12.0",
10 org.eclipse.jface.text;bundle-version="3.13.0",
1111 org.eclipse.core.runtime;bundle-version="3.12.0",
1212 org.eclipse.ui.workbench;bundle-version="3.109.0",
1313 org.eclipse.jface;bundle-version="3.12.0",
1414 org.eclipse.ui.ide;bundle-version="3.12.0",
15 org.eclipse.core.resources;bundle-version="3.11.0"
16 Export-Package: org.eclipse.ui.internal.genericeditor;x-internal:=true
15 org.eclipse.core.resources;bundle-version="3.11.0",
16 org.eclipse.core.expressions;bundle-version="3.6.0"
17 Export-Package: org.eclipse.ui.internal.genericeditor;x-internal:=true,
18 org.eclipse.ui.internal.genericeditor.hover;x-internal:=true,
19 org.eclipse.ui.internal.genericeditor.markers;x-internal:=true
1720 Bundle-Activator: org.eclipse.ui.internal.genericeditor.GenericEditorPlugin
1821 Bundle-Localization: plugin
1922 Bundle-ActivationPolicy: lazy
1414 plugin.xml,\
1515 plugin.properties,\
1616 about.html,\
17 icons/
17 icons/,\
18 resources/
1819
1920 src.includes = about.html,\
2021 schema/
66 #
77 # Contributors:
88 # Sopot Cela & Mickael Istria (Red Hat Inc.) - initial implementation
9 # Lucas Bullen (Red Hat Inc.) - Bug 508829 custom reconciler support
10 # - Bug 521382 default highlighter
11 # Simon Scholz <simon.scholz@vogella.com> - Bug 527830
912 ###############################################################################
1013 genericEditor_name=Generic Text Editor
14 ExtPoint.reconciliers=Reconciliers
1115 ExtPoint.presentationReconciliers=Presentation Reconciliers
1216 ExtPoint.hoverProviders= Hover Providers
1317 ExtPoint.contentAssistProcessors=Content Assist Providers
18 ExtPoint.autoEditStrategies=Auto Edit Strategies
19 ExtPoint.highlightReconcilers=Highlight Reconcilers
1420 ExtPoint.hyperlinkDetectorTarget=Generic Text Editor
1521 openDeclarationCommand_name=Open Declaration
1622 context_name=in Generic Code Editor
1824 findReferencesCommand_name=Find References
1925 findReferencesCommand_description=Find other code items referencing the current selected item.
2026 Bundle-Vendor=Eclipse.org
21 Bundle-Name=Generic and Extensible Text Editor
27 Bundle-Name=Generic and Extensible Text Editor
28 command.toggle.highlight.label = Toggle Mark Occurences
29 command.toggle.highlight.name = Toggle Highlight
00 <?xml version="1.0" encoding="UTF-8"?>
11 <?eclipse version="3.4"?>
22 <!-- ====================================================================== -->
3 <!-- Copyright (c) 2016 Red Hat Inc. and others. -->
3 <!-- Copyright (c) 2016, 2017 Red Hat Inc. and others. -->
44 <!-- All rights reserved. This program and the accompanying materials -->
55 <!-- are made available under the terms of the Eclipse Public License v1.0 -->
66 <!-- which accompanies this distribution, and is available at -->
88 <!-- -->
99 <!-- Contributors: -->
1010 <!-- Sopot Cela & Mickael Istria (Red Hat Inc). -initial implementation -->
11 <!-- Lucas Bullen (Red Hat Inc.) - Bug 508829 custom reconciler support -->
12 <!-- - Bug 521382 default highlighter -->
13 <!-- Simon Scholz <simon.scholz@vogella.com> - Bug 527830 -->
1114 <!-- ====================================================================== -->
1215 <plugin>
16 <extension-point id="reconcilers" name="%ExtPoint.reconciliers" schema="schema/reconcilers.exsd"/>
1317 <extension-point id="presentationReconcilers" name="%ExtPoint.presentationReconciliers" schema="schema/presentationReconcilers.exsd"/>
1418 <extension-point id="contentAssistProcessors" name="%ExtPoint.contentAssistProcessors" schema="schema/contentAssistProcessors.exsd"/>
1519 <extension-point id="hoverProviders" name="%ExtPoint.hoverProviders" schema="schema/hoverProviders.exsd"/>
20 <extension-point id="autoEditStrategies" name="%ExtPoint.autoEditStrategies" schema="schema/autoEditStrategies.exsd"/>
21 <extension-point id="highlightReconcilers" name="%ExtPoint.highlightReconcilers" schema="schema/highlightReconcilers.exsd"/>
1622 <extension
1723 point="org.eclipse.ui.editors">
1824 <editor
3339 description="%findReferencesCommand_description"
3440 id="org.eclipse.ui.genericeditor.findReferences"
3541 name="%findReferencesCommand_name">
42 </command>
43 <command
44 id="org.eclipse.ui.genericeditor.togglehighlight"
45 name="%command.toggle.highlight.name">
46 <state
47 class="org.eclipse.ui.handlers.RegistryToggleState:true"
48 id="org.eclipse.ui.commands.toggleState">
49 </state>
3650 </command>
3751 </extension>
3852 <extension
6983 style="push">
7084 </command>
7185 </menuContribution>
86 <menuContribution
87 allPopups="false"
88 locationURI="toolbar:org.eclipse.ui.edit.text.actionSet.presentation">
89 <command
90 commandId="org.eclipse.ui.genericeditor.togglehighlight"
91 label="%command.toggle.highlight.label"
92 style="toggle">
93 <visibleWhen>
94 <reference
95 definitionId="org.eclipse.ui.genericeditor.GenericEditor.active">
96 </reference>
97 </visibleWhen>
98 </command>
99 </menuContribution>
100 </extension>
101 <extension
102 point="org.eclipse.ui.handlers">
103 <handler
104 commandId="org.eclipse.ui.genericeditor.togglehighlight">
105 <class
106 class="org.eclipse.ui.internal.genericeditor.ToggleHighlight"></class>
107 </handler>
72108 </extension>
73109 <extension
74110 point="org.eclipse.ui.genericeditor.hoverProviders">
87123 </hoverProvider>
88124 </extension>
89125 <extension
126 point="org.eclipse.ui.commandImages">
127 <image
128 commandId="org.eclipse.ui.genericeditor.togglehighlight"
129 disabledIcon="icons/full/dtool16/mark_occurrences.png"
130 icon="icons/full/etool16/mark_occurrences.png">
131 </image>
132 </extension>
133 <extension point="org.eclipse.ui.editors.annotationTypes">
134 <type name="org.eclipse.ui.genericeditor.text"></type>
135 </extension>
136 <extension point="org.eclipse.ui.editors.markerAnnotationSpecification">
137 <specification annotationType="org.eclipse.ui.genericeditor.text"
138 label="Text Occurrence"
139 textPreferenceKey="TextOccurrenceIndication" textPreferenceValue="false"
140 highlightPreferenceKey="TextOccurrenceHighlighting"
141 highlightPreferenceValue="true" contributesToHeader="false"
142 overviewRulerPreferenceKey="TextOccurrenceIndicationInOverviewRuler"
143 overviewRulerPreferenceValue="true"
144 verticalRulerPreferenceKey="TextOccurrenceIndicationInVerticalRuler"
145 verticalRulerPreferenceValue="false" colorPreferenceKey="TextOccurrenceIndicationColor"
146 colorPreferenceValue="212,212,212" presentationLayer="4"
147 showInNextPrevDropdownToolbarAction="true"
148 textStylePreferenceKey="TextOccurrenceTextStyle"
149 textStylePreferenceValue="NONE">
150 </specification>
151 </extension>
152 <extension
153 point="org.eclipse.e4.ui.css.swt.theme">
154 <stylesheet
155 uri="resources/css/dark.css">
156 <themeid
157 refid="org.eclipse.e4.ui.css.theme.e4_dark">
158 </themeid>
159 </stylesheet>
160 </extension>
161 <extension
90162 point="org.eclipse.ui.workbench.texteditor.hyperlinkDetectorTargets">
91163 <target
92164 id="org.eclipse.ui.genericeditor.GenericEditor"
96168 </context>
97169 </target>
98170 </extension>
171 <extension
172 point="org.eclipse.ui.actionSetPartAssociations">
173 <actionSetPartAssociation
174 targetID="org.eclipse.ui.edit.text.actionSet.presentation">
175 <part
176 id="org.eclipse.ui.genericeditor.GenericEditor">
177 </part>
178 </actionSetPartAssociation>
179 </extension>
180 <extension
181 point="org.eclipse.core.expressions.definitions">
182 <definition
183 id="org.eclipse.ui.genericeditor.GenericEditor.active">
184 <with
185 variable="activeEditorId">
186 <equals
187 value="org.eclipse.ui.genericeditor.GenericEditor">
188 </equals>
189 </with>
190 </definition>
191 </extension>
99192 </plugin>
1313 <parent>
1414 <artifactId>eclipse.platform.text</artifactId>
1515 <groupId>eclipse.platform.text</groupId>
16 <version>4.7.3-SNAPSHOT</version>
16 <version>4.8.0-SNAPSHOT</version>
1717 </parent>
1818 <groupId>org.eclipse.ui</groupId>
1919 <artifactId>org.eclipse.ui.genericeditor</artifactId>
20 <version>1.0.2-SNAPSHOT</version>
20 <version>1.1.0-SNAPSHOT</version>
2121 <packaging>eclipse-plugin</packaging>
2222 </project>
0 /*******************************************************************************
1 * Copyright (c) 2017 Red Hat Inc. and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Lucas Bullen (Red Hat Inc.) - initial implementation
9 *******************************************************************************/
10
11 IEclipsePreferences#org-eclipse-ui-editors:org-eclipse-ui-genericeditor {
12 preferences:
13 'TextOccurrenceIndicationColor=27, 98, 145'
14 }
15
0 <?xml version='1.0' encoding='UTF-8'?>
1 <!-- Schema file written by PDE -->
2 <schema targetNamespace="org.eclipse.ui.genericeditor" xmlns="http://www.w3.org/2001/XMLSchema">
3 <annotation>
4 <appinfo>
5 <meta.schema plugin="org.eclipse.ui.genericeditor" id="autoEditStrategies" name="Auto edit strategies"/>
6 </appinfo>
7 <documentation>
8 This extension point is used to contribute auto edit strategies for a given content type.
9 </documentation>
10 </annotation>
11
12 <include schemaLocation="schema://org.eclipse.core.expressions/schema/expressionLanguage.exsd"/>
13
14 <element name="extension">
15 <annotation>
16 <appinfo>
17 <meta.element />
18 </appinfo>
19 </annotation>
20 <complexType>
21 <sequence minOccurs="1" maxOccurs="unbounded">
22 <element ref="autoEditStrategy"/>
23 </sequence>
24 <attribute name="point" type="string" use="required">
25 <annotation>
26 <documentation>
27 a fully qualified identifier of the target extension point
28 </documentation>
29 </annotation>
30 </attribute>
31 <attribute name="id" type="string">
32 <annotation>
33 <documentation>
34 an optional identifier of the extension instance
35 </documentation>
36 </annotation>
37 </attribute>
38 <attribute name="name" type="string">
39 <annotation>
40 <documentation>
41 an optional name of the extension instance
42 </documentation>
43 <appinfo>
44 <meta.attribute translatable="true"/>
45 </appinfo>
46 </annotation>
47 </attribute>
48 </complexType>
49 </element>
50
51 <element name="autoEditStrategy">
52 <complexType>
53 <sequence>
54 <element ref="enabledWhen" minOccurs="0" maxOccurs="1"/>
55 </sequence>
56 <attribute name="class" type="string" use="required">
57 <annotation>
58 <documentation>
59 The fully qualified class name implementing the interface &lt;code&gt;org.eclipse.jface.text.IAutoEditStrategy&lt;/code&gt;
60 </documentation>
61 <appinfo>
62 <meta.attribute kind="java" basedOn=":org.eclipse.jface.text.IAutoEditStrategy"/>
63 </appinfo>
64 </annotation>
65 </attribute>
66 <attribute name="contentType" type="string" use="required">
67 <annotation>
68 <documentation>
69 The target content-type for this extension. Content-types are defined as extension to the org.eclipse.core.contenttype.contentTypes extension point.
70 </documentation>
71 <appinfo>
72 <meta.attribute kind="identifier" basedOn="org.eclipse.core.contenttype.contentTypes/content-type/@id"/>
73 </appinfo>
74 </annotation>
75 </attribute>
76 </complexType>
77 </element>
78
79 <element name="enabledWhen">
80 <annotation>
81 <documentation>
82 A core Expression that controls the enabled of the given auto edit strategies. The viewer, editor, and editor input are registered in the evaluation context as variable:
83
84 * &lt;with variable=&quot;viewer&quot;/&gt; : use it if your expression requires the viewer.
85 * &lt;with variable=&quot;editor&quot;/&gt; : use it if your expression requires the editor.
86 * &lt;with variable=&quot;editorInput&quot;/&gt; : use it if your expression requires the editor input.
87 </documentation>
88 </annotation>
89 <complexType>
90 <choice minOccurs="0" maxOccurs="1">
91 <element ref="not"/>
92 <element ref="or"/>
93 <element ref="and"/>
94 <element ref="instanceof"/>
95 <element ref="test"/>
96 <element ref="systemTest"/>
97 <element ref="equals"/>
98 <element ref="count"/>
99 <element ref="with"/>
100 <element ref="resolve"/>
101 <element ref="adapt"/>
102 <element ref="iterate"/>
103 <element ref="reference"/>
104 </choice>
105 </complexType>
106 </element>
107
108 <annotation>
109 <appinfo>
110 <meta.section type="since"/>
111 </appinfo>
112 <documentation>
113 1.0
114 </documentation>
115 </annotation>
116
117 <annotation>
118 <appinfo>
119 <meta.section type="examples"/>
120 </appinfo>
121 <documentation>
122 This is an example of a strategy being registered for a target definition file type:
123
124 &lt;pre&gt;
125 &lt;extension point=&quot;org.eclipse.ui.genericeditor.autoEditStrategies&quot;&gt;
126 &lt;autoEditStrategy
127 class=&quot;org.eclipse.ui.genericeditor.examples.TargetDefinitionAutoEditStrategy&quot;
128 contentType=&quot;org.eclipse.pde.targetFile&quot;&gt;
129 &lt;enabledWhen&gt;
130 &lt;with variable=&quot;editor&quot;&gt;
131 &lt;test property=&quot;org.eclipse.ui.genericeditor.examples.TargetDefinitionPropertyTester&quot;&gt;
132 &lt;/test&gt;
133 &lt;/with&gt;
134 &lt;/enabledWhen&gt;
135 &lt;/autoEditStrategy&gt;
136 &lt;/extension&gt;
137 &lt;/pre&gt;
138 </documentation>
139 </annotation>
140
141
142
143 <annotation>
144 <appinfo>
145 <meta.section type="copyright"/>
146 </appinfo>
147 <documentation>
148 Copyright (c) 2017 Rogue Wave Software Inc. and others
149 All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at &lt;a href=&quot;http://www.eclipse.org/legal/epl-v10.html&quot;&gt;http://www.eclipse.org/legal/epl-v10.html&lt;/a&gt;
150 </documentation>
151 </annotation>
152
153 </schema>
5050
5151 <element name="contentAssistProcessor">
5252 <complexType>
53 <sequence>
54 <element ref="enabledWhen" minOccurs="0" maxOccurs="1"/>
55 </sequence>
5356 <attribute name="class" type="string" use="required">
5457 <annotation>
5558 <documentation>
7376 </complexType>
7477 </element>
7578
79 <element name="enabledWhen">
80 <annotation>
81 <documentation>
82 A core Expression that controls the enabled of the given content assist processor. The viewer, editor, and editor input are registered in the evaluation context as variable:
83
84 * &lt;with variable=&quot;viewer&quot;/&gt; : use it if your expression requires the viewer.
85 * &lt;with variable=&quot;editor&quot;/&gt; : use it if your expression requires the editor.
86 * &lt;with variable=&quot;editorInput&quot;/&gt; : use it if your expression requires the editor input.
87 </documentation>
88 </annotation>
89 <complexType>
90 <choice minOccurs="0" maxOccurs="1">
91 <element ref="not"/>
92 <element ref="or"/>
93 <element ref="and"/>
94 <element ref="instanceof"/>
95 <element ref="test"/>
96 <element ref="systemTest"/>
97 <element ref="equals"/>
98 <element ref="count"/>
99 <element ref="with"/>
100 <element ref="resolve"/>
101 <element ref="adapt"/>
102 <element ref="iterate"/>
103 <element ref="reference"/>
104 </choice>
105 </complexType>
106 </element>
107
76108 <annotation>
77109 <appinfo>
78110 <meta.section type="since"/>
92124 &lt;pre&gt;
93125 &lt;extension point=&quot;org.eclipse.ui.genericeditor.contentAssistProcessors&quot;&gt;
94126 &lt;contentAssistProcessor
95 class=&quot;org.eclipse.ui.genericeditor.examples.TargedDefinitionContentAssist&quot;
96 contentType=&quot;org.eclipse.pde.targetFile&quot;&gt;
127 class=&quot;org.eclipse.ui.genericeditor.examples.TargedDefinitionContentAssist&quot;
128 contentType=&quot;org.eclipse.pde.targetFile&quot;&gt;
129 &lt;enabledWhen&gt;
130 &lt;with variable=&quot;editor&quot;&gt;
131 &lt;test property=&quot;org.eclipse.ui.genericeditor.examples.TargetDefinitionPropertyTester&quot;&gt;
132 &lt;/test&gt;
133 &lt;/with&gt;
134 &lt;/enabledWhen&gt;
97135 &lt;/contentAssistProcessor&gt;
98136 &lt;/extension&gt;
99137 &lt;/pre&gt;
0 <?xml version='1.0' encoding='UTF-8'?>
1 <!-- Schema file written by PDE -->
2 <schema targetNamespace="org.eclipse.ui.genericeditor" xmlns="http://www.w3.org/2001/XMLSchema">
3 <annotation>
4 <appinfo>
5 <meta.schema plugin="org.eclipse.ui.genericeditor" id="highlightReconcilers" name="Highlight reconcilers"/>
6 </appinfo>
7 <documentation>
8 This extension point is used to contribute highlight reconcilers for controlling the highlighting on a file with a given content type. Reconcilers attached to this extension point that listen to the preference &quot;org.eclipse.ui.genericeditor.togglehighlight&quot; will be toggled with the &quot;Toggle Mark Occurences&quot; button.
9 </documentation>
10 </annotation>
11
12 <include schemaLocation="schema://org.eclipse.core.expressions/schema/expressionLanguage.exsd"/>
13
14 <element name="extension">
15 <annotation>
16 <appinfo>
17 <meta.element />
18 </appinfo>
19 </annotation>
20 <complexType>
21 <sequence minOccurs="1" maxOccurs="unbounded">
22 <element ref="highlightReconciler"/>
23 </sequence>
24 <attribute name="point" type="string" use="required">
25 <annotation>
26 <documentation>
27 a fully qualified identifier of the target extension point
28 </documentation>
29 </annotation>
30 </attribute>
31 <attribute name="id" type="string">
32 <annotation>
33 <documentation>
34 an optional identifier of the extension instance
35 </documentation>
36 </annotation>
37 </attribute>
38 <attribute name="name" type="string">
39 <annotation>
40 <documentation>
41 an optional name of the extension instance
42 </documentation>
43 <appinfo>
44 <meta.attribute translatable="true"/>
45 </appinfo>
46 </annotation>
47 </attribute>
48 </complexType>
49 </element>
50
51 <element name="highlightReconciler">
52 <complexType>
53 <sequence>
54 <element ref="enabledWhen" minOccurs="0" maxOccurs="1"/>
55 </sequence>
56 <attribute name="class" type="string" use="required">
57 <annotation>
58 <documentation>
59 The fully qualified class name implementing the interface &lt;code&gt;org.eclipse.jface.text.reconciler.IReconciler&lt;/code&gt;
60 </documentation>
61 <appinfo>
62 <meta.attribute kind="java" basedOn=":org.eclipse.jface.text.reconciler.IReconciler"/>
63 </appinfo>
64 </annotation>
65 </attribute>
66 <attribute name="contentType" type="string" use="required">
67 <annotation>
68 <documentation>
69 The target content-type for this extension. Content-types are defined as extension to the org.eclipse.core.contenttype.contentTypes extension point.
70 </documentation>
71 <appinfo>
72 <meta.attribute kind="identifier" basedOn="org.eclipse.core.contenttype.contentTypes/content-type/@id"/>
73 </appinfo>
74 </annotation>
75 </attribute>
76 </complexType>
77 </element>
78
79 <element name="enabledWhen">
80 <annotation>
81 <documentation>
82 A core Expression that controls the enabled of the given highlight reconciler. The viewer, editor, and editor input are registered in the evaluation context as variable:
83
84 * &lt;with variable=&quot;viewer&quot;/&gt; : use it if your expression requires the viewer.
85 * &lt;with variable=&quot;editor&quot;/&gt; : use it if your expression requires the editor.
86 * &lt;with variable=&quot;editorInput&quot;/&gt; : use it if your expression requires the editor input.
87 </documentation>
88 </annotation>
89 <complexType>
90 <choice minOccurs="0" maxOccurs="1">
91 <element ref="not"/>
92 <element ref="or"/>
93 <element ref="and"/>
94 <element ref="instanceof"/>
95 <element ref="test"/>
96 <element ref="systemTest"/>
97 <element ref="equals"/>
98 <element ref="count"/>
99 <element ref="with"/>
100 <element ref="resolve"/>
101 <element ref="adapt"/>
102 <element ref="iterate"/>
103 <element ref="reference"/>
104 </choice>
105 </complexType>
106 </element>
107
108 <annotation>
109 <appinfo>
110 <meta.section type="since"/>
111 </appinfo>
112 <documentation>
113 1.1
114 </documentation>
115 </annotation>
116
117 <annotation>
118 <appinfo>
119 <meta.section type="examples"/>
120 </appinfo>
121 <documentation>
122 Below is an example of how to use the Highlight Reconciler extension point:
123
124 &lt;pre&gt;
125 &lt;extension point=&quot;org.eclipse.ui.genericeditor.highlightReconcilers&quot;&gt;
126 &lt;highlightReconciler
127 class=&quot;org.eclipse.ui.genericeditor.examples.TargetDefinitionHighlightReconciler&quot;
128 contentType=&quot;org.eclipse.pde.targetFile&quot;&gt;
129 &lt;enabledWhen&gt;
130 &lt;with variable=&quot;editor&quot;&gt;
131 &lt;test property=&quot;org.eclipse.ui.genericeditor.examples.TargetDefinitionPropertyTester&quot;&gt;
132 &lt;/test&gt;
133 &lt;/with&gt;
134 &lt;/enabledWhen&gt;
135 &lt;/highlightReconciler&gt;
136 &lt;/extension&gt;
137 &lt;/pre&gt;
138 </documentation>
139 </annotation>
140
141
142
143 <annotation>
144 <appinfo>
145 <meta.section type="copyright"/>
146 </appinfo>
147 <documentation>
148 Copyright (c) 2017 Red Hat Inc. and others
149 All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at &lt;a href=&quot;http://www.eclipse.org/legal/epl-v10.html&quot;&gt;http://www.eclipse.org/legal/epl-v10.html&lt;/a&gt;
150 </documentation>
151 </annotation>
152
153 </schema>
5050
5151 <element name="hoverProvider">
5252 <complexType>
53 <sequence>
54 <element ref="enabledWhen" minOccurs="0" maxOccurs="1"/>
55 </sequence>
5356 <attribute name="id" type="string">
5457 <annotation>
5558 <documentation>
102105 </complexType>
103106 </element>
104107
108 <element name="enabledWhen">
109 <annotation>
110 <documentation>
111 A core Expression that controls the enabled of the given hover provider. The viewer, editor, and editor input are registered in the evaluation context as variable:
112
113 * &lt;with variable=&quot;viewer&quot;/&gt; : use it if your expression requires the viewer.
114 * &lt;with variable=&quot;editor&quot;/&gt; : use it if your expression requires the editor.
115 * &lt;with variable=&quot;editorInput&quot;/&gt; : use it if your expression requires the editor input.
116 </documentation>
117 </annotation>
118 <complexType>
119 <choice minOccurs="0" maxOccurs="1">
120 <element ref="not"/>
121 <element ref="or"/>
122 <element ref="and"/>
123 <element ref="instanceof"/>
124 <element ref="test"/>
125 <element ref="systemTest"/>
126 <element ref="equals"/>
127 <element ref="count"/>
128 <element ref="with"/>
129 <element ref="resolve"/>
130 <element ref="adapt"/>
131 <element ref="iterate"/>
132 <element ref="reference"/>
133 </choice>
134 </complexType>
135 </element>
136
105137 <annotation>
106138 <appinfo>
107139 <meta.section type="since"/>
120152
121153 &lt;pre&gt;
122154 &lt;extension point=&quot;org.eclipse.ui.genericeditor.hoverProviders&quot;&gt;
123 &lt;hoverProvider
124 class=&quot;org.eclipse.ui.genericeditor.tests.contributions.MagicHoverProvider&quot;
125 contentType=&quot;org.eclipse.core.runtime.text&quot;&gt;
126 &lt;/hoverProvider&gt;
155 &lt;hoverProvider
156 class=&quot;org.eclipse.ui.genericeditor.examples.TargetDefinitionHoverProvider&quot;
157 contentType=&quot;org.eclipse.pde.targetFile&quot;&gt;
158 &lt;enabledWhen&gt;
159 &lt;with variable=&quot;editor&quot;&gt;
160 &lt;test property=&quot;org.eclipse.ui.genericeditor.examples.TargetDefinitionPropertyTester&quot;&gt;
161 &lt;/test&gt;
162 &lt;/with&gt;
163 &lt;/enabledWhen&gt;
164 &lt;/hoverProvider&gt;
127165 &lt;/extension&gt;
128166 &lt;/pre&gt;
129167 </documentation>
5050
5151 <element name="presentationReconciler">
5252 <complexType>
53 <sequence>
54 <element ref="enabledWhen" minOccurs="0" maxOccurs="1"/>
55 </sequence>
5356 <attribute name="class" type="string" use="required">
5457 <annotation>
5558 <documentation>
7376 </complexType>
7477 </element>
7578
79 <element name="enabledWhen">
80 <annotation>
81 <documentation>
82 A core Expression that controls the enabled of the given presentation reconciler. The viewer, editor, and editor input are registered in the evaluation context as variable:
83
84 * &lt;with variable=&quot;viewer&quot;/&gt; : use it if your expression requires the viewer.
85 * &lt;with variable=&quot;editor&quot;/&gt; : use it if your expression requires the editor.
86 * &lt;with variable=&quot;editorInput&quot;/&gt; : use it if your expression requires the editor input.
87 </documentation>
88 </annotation>
89 <complexType>
90 <choice minOccurs="0" maxOccurs="1">
91 <element ref="not"/>
92 <element ref="or"/>
93 <element ref="and"/>
94 <element ref="instanceof"/>
95 <element ref="test"/>
96 <element ref="systemTest"/>
97 <element ref="equals"/>
98 <element ref="count"/>
99 <element ref="with"/>
100 <element ref="resolve"/>
101 <element ref="adapt"/>
102 <element ref="iterate"/>
103 <element ref="reference"/>
104 </choice>
105 </complexType>
106 </element>
107
76108 <annotation>
77109 <appinfo>
78110 <meta.section type="since"/>
91123
92124 &lt;pre&gt;
93125 &lt;extension point=&quot;org.eclipse.ui.genericeditor.presentationReconcilers&quot;&gt;
94 &lt;presentationReconciler
95 class=&quot;org.eclipse.ui.genericeditor.examples.TPPresentationReconciler&quot;
96 contentType=&quot;org.eclipse.pde.targetFile&quot;&gt;
97 &lt;/presentationReconciler&gt;
126 &lt;presentationReconciler
127 class=&quot;org.eclipse.ui.genericeditor.examples.TargetDefinitionPresentationReconciler&quot;
128 contentType=&quot;org.eclipse.pde.targetFile&quot;&gt;
129 &lt;enabledWhen&gt;
130 &lt;with variable=&quot;editor&quot;&gt;
131 &lt;test property=&quot;org.eclipse.ui.genericeditor.examples.TargetDefinitionPropertyTester&quot;&gt;
132 &lt;/test&gt;
133 &lt;/with&gt;
134 &lt;/enabledWhen&gt;
135 &lt;/presentationReconciler&gt;
98136 &lt;/extension&gt;
99137 &lt;/pre&gt;
100138 </documentation>
0 <?xml version='1.0' encoding='UTF-8'?>
1 <!-- Schema file written by PDE -->
2 <schema targetNamespace="org.eclipse.ui.genericeditor" xmlns="http://www.w3.org/2001/XMLSchema">
3 <annotation>
4 <appinfo>
5 <meta.schema plugin="org.eclipse.ui.genericeditor" id="reconcilers" name="Reconcilers"/>
6 </appinfo>
7 <documentation>
8 This extension point is used to contribute reconcilers for controlling the presentation on a file with a given content type.
9 </documentation>
10 </annotation>
11
12 <include schemaLocation="schema://org.eclipse.core.expressions/schema/expressionLanguage.exsd"/>
13
14 <element name="extension">
15 <annotation>
16 <appinfo>
17 <meta.element />
18 </appinfo>
19 </annotation>
20 <complexType>
21 <sequence minOccurs="1" maxOccurs="unbounded">
22 <element ref="reconciler"/>
23 </sequence>
24 <attribute name="point" type="string" use="required">
25 <annotation>
26 <documentation>
27 a fully qualified identifier of the target extension point
28 </documentation>
29 </annotation>
30 </attribute>
31 <attribute name="id" type="string">
32 <annotation>
33 <documentation>
34 an optional identifier of the extension instance
35 </documentation>
36 </annotation>
37 </attribute>
38 <attribute name="name" type="string">
39 <annotation>
40 <documentation>
41 an optional name of the extension instance
42 </documentation>
43 <appinfo>
44 <meta.attribute translatable="true"/>
45 </appinfo>
46 </annotation>
47 </attribute>
48 </complexType>
49 </element>
50
51 <element name="reconciler">
52 <complexType>
53 <sequence>
54 <element ref="enabledWhen" minOccurs="0" maxOccurs="1"/>
55 </sequence>
56 <attribute name="class" type="string" use="required">
57 <annotation>
58 <documentation>
59 The fully qualified class name implementing the interface &lt;code&gt;org.eclipse.jface.text.reconciler.IReconciler&lt;/code&gt;
60 </documentation>
61 <appinfo>
62 <meta.attribute kind="java" basedOn=":org.eclipse.jface.text.reconciler.IReconciler"/>
63 </appinfo>
64 </annotation>
65 </attribute>
66 <attribute name="contentType" type="string" use="required">
67 <annotation>
68 <documentation>
69 The target content-type for this extension. Content-types are defined as extension to the org.eclipse.core.contenttype.contentTypes extension point.
70 </documentation>
71 <appinfo>
72 <meta.attribute kind="identifier" basedOn="org.eclipse.core.contenttype.contentTypes/content-type/@id"/>
73 </appinfo>
74 </annotation>
75 </attribute>
76 </complexType>
77 </element>
78
79 <element name="enabledWhen">
80 <annotation>
81 <documentation>
82 A core Expression that controls the enabled of the given reconciler. The viewer, editor, and editor input are registered in the evaluation context as variable:
83
84 * &lt;with variable=&quot;viewer&quot;/&gt; : use it if your expression requires the viewer.
85 * &lt;with variable=&quot;editor&quot;/&gt; : use it if your expression requires the editor.
86 * &lt;with variable=&quot;editorInput&quot;/&gt; : use it if your expression requires the editor input.
87 </documentation>
88 </annotation>
89 <complexType>
90 <choice minOccurs="0" maxOccurs="1">
91 <element ref="not"/>
92 <element ref="or"/>
93 <element ref="and"/>
94 <element ref="instanceof"/>
95 <element ref="test"/>
96 <element ref="systemTest"/>
97 <element ref="equals"/>
98 <element ref="count"/>
99 <element ref="with"/>
100 <element ref="resolve"/>
101 <element ref="adapt"/>
102 <element ref="iterate"/>
103 <element ref="reference"/>
104 </choice>
105 </complexType>
106 </element>
107
108 <annotation>
109 <appinfo>
110 <meta.section type="since"/>
111 </appinfo>
112 <documentation>
113 1.1
114 </documentation>
115 </annotation>
116
117 <annotation>
118 <appinfo>
119 <meta.section type="examples"/>
120 </appinfo>
121 <documentation>
122 Below is an example of how to use the Reconciler extension point:
123
124 &lt;pre&gt;
125 &lt;extension point=&quot;org.eclipse.ui.genericeditor.reconcilers&quot;&gt;
126 &lt;reconciler
127 class=&quot;org.eclipse.ui.genericeditor.examples.TargetDefinitionReconciler&quot;
128 contentType=&quot;org.eclipse.pde.targetFile&quot;&gt;
129 &lt;enabledWhen&gt;
130 &lt;with variable=&quot;editor&quot;&gt;
131 &lt;test property=&quot;org.eclipse.ui.genericeditor.examples.TargetDefinitionPropertyTester&quot;&gt;
132 &lt;/test&gt;
133 &lt;/with&gt;
134 &lt;/enabledWhen&gt;
135 &lt;/reconciler&gt;
136 &lt;/extension&gt;
137 &lt;/pre&gt;
138 </documentation>
139 </annotation>
140
141
142
143 <annotation>
144 <appinfo>
145 <meta.section type="copyright"/>
146 </appinfo>
147 <documentation>
148 Copyright (c) 2017 Red Hat Inc. and others
149 All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at &lt;a href=&quot;http://www.eclipse.org/legal/epl-v10.html&quot;&gt;http://www.eclipse.org/legal/epl-v10.html&lt;/a&gt;
150 </documentation>
151 </annotation>
152
153 </schema>
0 /*******************************************************************************
1 * Copyright (c) 2017 Rogue Wave Software Inc. and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Michał Niewrzał (Rogue Wave Software Inc.) - initial implementation
9 *******************************************************************************/
10 package org.eclipse.ui.internal.genericeditor;
11
12 import java.util.HashSet;
13 import java.util.LinkedHashMap;
14 import java.util.List;
15 import java.util.Map;
16 import java.util.Set;
17 import java.util.stream.Collectors;
18
19 import org.eclipse.core.runtime.IConfigurationElement;
20 import org.eclipse.core.runtime.IRegistryChangeEvent;
21 import org.eclipse.core.runtime.IRegistryChangeListener;
22 import org.eclipse.core.runtime.IStatus;
23 import org.eclipse.core.runtime.Platform;
24 import org.eclipse.core.runtime.Status;
25 import org.eclipse.core.runtime.content.IContentType;
26 import org.eclipse.jface.text.IAutoEditStrategy;
27 import org.eclipse.jface.text.source.ISourceViewer;
28 import org.eclipse.ui.texteditor.ITextEditor;
29
30 /**
31 * A registry of auto edit strategies provided by extension
32 * <code>org.eclipse.ui.genericeditor.autoEditStrategy</code>. Those extensions
33 * are specific to a given {@link IContentType}.
34 *
35 * @since 1.1
36 */
37 public class AutoEditStrategyRegistry {
38
39 private static final String EXTENSION_POINT_ID = GenericEditorPlugin.BUNDLE_ID + ".autoEditStrategies"; //$NON-NLS-1$
40
41 private Map<IConfigurationElement, GenericContentTypeRelatedExtension<IAutoEditStrategy>> extensions = new LinkedHashMap<>();
42 private boolean outOfSync = true;
43
44 /**
45 * Creates the registry and binds it to the extension point.
46 */
47 public AutoEditStrategyRegistry() {
48 Platform.getExtensionRegistry().addRegistryChangeListener(new IRegistryChangeListener() {
49 @Override
50 public void registryChanged(IRegistryChangeEvent event) {
51 outOfSync = true;
52 }
53 }, EXTENSION_POINT_ID);
54 }
55
56 /**
57 * Get the contributed {@link IAutoEditStrategy}s that are relevant to hook
58 * on source viewer according to document content types.
59 *
60 * @param sourceViewer
61 * the source viewer we're hooking completion to.
62 * @param editor the text editor
63 * @param contentTypes
64 * the content types of the document we're editing.
65 * @return the list of {@link IAutoEditStrategy} contributed for at least
66 * one of the content types.
67 */
68 public List<IAutoEditStrategy> getAutoEditStrategies(ISourceViewer sourceViewer, ITextEditor editor, Set<IContentType> contentTypes) {
69 if (this.outOfSync) {
70 sync();
71 }
72 return this.extensions.values().stream()
73 .filter(ext -> contentTypes.contains(ext.targetContentType))
74 .filter(ext -> ext.matches(sourceViewer, editor))
75 .sorted(new ContentTypeSpecializationComparator<IAutoEditStrategy>())
76 .map(GenericContentTypeRelatedExtension<IAutoEditStrategy>::createDelegate)
77 .collect(Collectors.toList());
78 }
79
80 private void sync() {
81 Set<IConfigurationElement> toRemoveExtensions = new HashSet<>(this.extensions.keySet());
82 for (IConfigurationElement extension : Platform.getExtensionRegistry()
83 .getConfigurationElementsFor(EXTENSION_POINT_ID)) {
84 toRemoveExtensions.remove(extension);
85 if (!this.extensions.containsKey(extension)) {
86 try {
87 this.extensions.put(extension, new GenericContentTypeRelatedExtension<IAutoEditStrategy>(extension));
88 } catch (Exception ex) {
89 GenericEditorPlugin.getDefault().getLog()
90 .log(new Status(IStatus.ERROR, GenericEditorPlugin.BUNDLE_ID, ex.getMessage(), ex));
91 }
92 }
93 }
94 for (IConfigurationElement toRemove : toRemoveExtensions) {
95 this.extensions.remove(toRemove);
96 }
97 this.outOfSync = false;
98 }
99 }
4545 public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) {
4646 List<ICompletionProposal> res = new ArrayList<>();
4747 for (IContentAssistProcessor processor : this.fContentAssistProcessors) {
48 res.addAll(Arrays.asList(processor.computeCompletionProposals(viewer, offset)));
48 ICompletionProposal[] proposals = processor.computeCompletionProposals(viewer, offset);
49 if (proposals != null) {
50 res.addAll(Arrays.asList(proposals));
51 }
4952 }
5053 return res.toArray(new ICompletionProposal[res.size()]);
5154 }
0 /*******************************************************************************
1 * Copyright (c) 2017 Red Hat Inc. and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Lucas Bullen (Red Hat Inc.) - initial implementation
9 *******************************************************************************/
10 package org.eclipse.ui.internal.genericeditor;
11
12 import java.util.ArrayList;
13 import java.util.List;
14 import java.util.Objects;
15 import java.util.stream.Collectors;
16
17 import org.eclipse.jface.text.IDocumentExtension3;
18 import org.eclipse.jface.text.ITextViewer;
19 import org.eclipse.jface.text.reconciler.IReconciler;
20 import org.eclipse.jface.text.reconciler.IReconcilerExtension;
21 import org.eclipse.jface.text.reconciler.IReconcilingStrategy;
22
23 public class CompositeReconciler implements IReconciler, IReconcilerExtension {
24 private List<IReconciler> fReconcilers;
25
26 public CompositeReconciler(List<IReconciler> reconcilers) {
27 fReconcilers = reconcilers.stream().filter(Objects::nonNull).collect(Collectors.toList());
28 }
29
30 @Override
31 public String getDocumentPartitioning() {
32 boolean defaultFound = false;
33 String[] types = (String[]) fReconcilers.stream()
34 .filter(IReconcilerExtension.class::isInstance)
35 .map(IReconcilerExtension.class::cast)
36 .map(IReconcilerExtension::getDocumentPartitioning)
37 .filter(Objects::nonNull)
38 .toArray();
39 for (String type : types) {
40 if (type.equals(IDocumentExtension3.DEFAULT_PARTITIONING)) {
41 defaultFound = true;
42 } else {
43 return type;
44 }
45 }
46 return defaultFound ? IDocumentExtension3.DEFAULT_PARTITIONING : null;
47 }
48
49 @Override
50 public void install(ITextViewer textViewer) {
51 for (IReconciler iReconciler : fReconcilers) {
52 iReconciler.install(textViewer);
53 }
54 }
55
56 @Override
57 public void uninstall() {
58 for (IReconciler iReconciler : fReconcilers) {
59 iReconciler.uninstall();
60 }
61 }
62
63 @Override
64 public IReconcilingStrategy getReconcilingStrategy(String contentType) {
65 List<IReconcilingStrategy> strategies = new ArrayList<>();
66 for (IReconciler iReconciler : fReconcilers) {
67 IReconcilingStrategy strategy = iReconciler.getReconcilingStrategy(contentType);
68 if(strategy != null) {
69 strategies.add(strategy);
70 }
71 }
72
73 if(strategies.size() == 1) {
74 return strategies.get(0);
75 }
76
77 return new CompositeReconcilerStrategy(strategies);
78
79 }
80 }
0 /*******************************************************************************
1 * Copyright (c) 2017 Red Hat Inc. and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Lucas Bullen (Red Hat Inc.) - initial implementation
9 *******************************************************************************/
10 package org.eclipse.ui.internal.genericeditor;
11
12 import java.util.List;
13
14 import org.eclipse.core.runtime.IProgressMonitor;
15 import org.eclipse.jface.text.IDocument;
16 import org.eclipse.jface.text.IRegion;
17 import org.eclipse.jface.text.reconciler.DirtyRegion;
18 import org.eclipse.jface.text.reconciler.IReconcilingStrategy;
19 import org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension;
20
21 public class CompositeReconcilerStrategy implements IReconcilingStrategy, IReconcilingStrategyExtension{
22 private List<IReconcilingStrategy> fReconcilingStrategies;
23
24 public CompositeReconcilerStrategy(List<IReconcilingStrategy> strategies) {
25 this.fReconcilingStrategies = strategies;
26 }
27 @Override
28 public void setProgressMonitor(IProgressMonitor monitor) {
29 for (IReconcilingStrategy iReconcilingStrategy : fReconcilingStrategies) {
30 if (iReconcilingStrategy instanceof IReconcilingStrategyExtension) {
31 ((IReconcilingStrategyExtension) iReconcilingStrategy).setProgressMonitor(monitor);
32 }
33 }
34 }
35
36 @Override
37 public void initialReconcile() {
38 for (IReconcilingStrategy iReconcilingStrategy : fReconcilingStrategies) {
39 if (iReconcilingStrategy instanceof IReconcilingStrategyExtension) {
40 ((IReconcilingStrategyExtension) iReconcilingStrategy).initialReconcile();
41 }
42 }
43 }
44
45 @Override
46 public void setDocument(IDocument document) {
47 for (IReconcilingStrategy iReconcilingStrategy : fReconcilingStrategies) {
48 iReconcilingStrategy.setDocument(document);
49 }
50 }
51
52 @Override
53 public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) {
54 for (IReconcilingStrategy iReconcilingStrategy : fReconcilingStrategies) {
55 iReconcilingStrategy.reconcile(dirtyRegion, subRegion);
56 }
57 }
58
59 @Override
60 public void reconcile(IRegion partition) {
61 for (IReconcilingStrategy iReconcilingStrategy : fReconcilingStrategies) {
62 iReconcilingStrategy.reconcile(partition);
63 }
64 }
65
66 }
+0
-94
org.eclipse.ui.genericeditor/src/org/eclipse/ui/internal/genericeditor/CompositeTextHover.java less more
0 /*******************************************************************************
1 * Copyright (c) 2016 Red Hat Inc. and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * - Mickael Istria (Red Hat Inc.)
9 *******************************************************************************/
10 package org.eclipse.ui.internal.genericeditor;
11
12 import java.util.List;
13
14 import org.eclipse.core.runtime.Assert;
15 import org.eclipse.jface.text.IInformationControlCreator;
16 import org.eclipse.jface.text.IRegion;
17 import org.eclipse.jface.text.ITextHover;
18 import org.eclipse.jface.text.ITextHoverExtension;
19 import org.eclipse.jface.text.ITextHoverExtension2;
20 import org.eclipse.jface.text.ITextViewer;
21 import org.eclipse.ui.internal.genericeditor.TextHoverRegistry.TextHoverExtension;
22
23 /**
24 * A text hover that delegates its operations to children
25 * provided in constructor and returns the first interesting result.
26 *
27 * @since 1.0
28 */
29 public class CompositeTextHover implements ITextHover, ITextHoverExtension, ITextHoverExtension2 {
30
31 private List<TextHoverExtension> hoversToConsider;
32 private TextHoverExtension currentHover = null;
33
34 public CompositeTextHover(List<TextHoverExtension> hoversToConsider) {
35 Assert.isNotNull(hoversToConsider);
36 this.hoversToConsider = hoversToConsider;
37 }
38
39 @Override
40 public Object getHoverInfo2(ITextViewer textViewer, IRegion hoverRegion) {
41 for (TextHoverExtension hover : this.hoversToConsider) {
42 ITextHover delegate = hover.getDelegate();
43 Object res = null;
44 if (delegate instanceof ITextHoverExtension2) {
45 res = ((ITextHoverExtension2)delegate).getHoverInfo2(textViewer, hoverRegion);
46 } else {
47 res = delegate.getHoverInfo(textViewer, hoverRegion);
48 }
49 if (res != null) {
50 currentHover = hover;
51 return res;
52 }
53 }
54 return null;
55 }
56
57 @Override
58 public IInformationControlCreator getHoverControlCreator() {
59 if (this.currentHover != null) {
60 ITextHover hover = this.currentHover.getDelegate();
61 if (hover instanceof ITextHoverExtension) {
62 return ((ITextHoverExtension)hover).getHoverControlCreator();
63 }
64 }
65 return null;
66 }
67
68 @Override
69 public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
70 for (TextHoverExtension hover : this.hoversToConsider) {
71 ITextHover delegate = hover.getDelegate();
72 String res = delegate.getHoverInfo(textViewer, hoverRegion);
73 if (res != null) {
74 currentHover = hover;
75 return res;
76 }
77 }
78 return null;
79 }
80
81 @Override
82 public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
83 for (TextHoverExtension hover : this.hoversToConsider) {
84 ITextHover delegate = hover.getDelegate();
85 IRegion res = delegate.getHoverRegion(textViewer, offset);
86 if (res != null) {
87 return res;
88 }
89 }
90 return null;
91 }
92
93 }
00 /*******************************************************************************
1 * Copyright (c) 2016 Red Hat Inc. and others.
1 * Copyright (c) 2016-2017 Red Hat Inc. and others.
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
99 *******************************************************************************/
1010 package org.eclipse.ui.internal.genericeditor;
1111
12 import java.util.ArrayList;
1312 import java.util.HashMap;
1413 import java.util.HashSet;
1514 import java.util.List;
1615 import java.util.Map;
1716 import java.util.Set;
17 import java.util.stream.Collectors;
1818
1919 import org.eclipse.core.filebuffers.FileBuffers;
20 import org.eclipse.core.runtime.CoreException;
2120 import org.eclipse.core.runtime.IConfigurationElement;
2221 import org.eclipse.core.runtime.IPath;
2322 import org.eclipse.core.runtime.IRegistryChangeEvent;
3433 import org.eclipse.jface.text.contentassist.IContextInformationValidator;
3534 import org.eclipse.jface.text.source.ISourceViewer;
3635 import org.eclipse.ui.PlatformUI;
36 import org.eclipse.ui.texteditor.ITextEditor;
3737
3838 /**
3939 * A registry of content assist processors provided by extension <code>org.eclipse.ui.genericeditor.contentAssistProcessors</code>.
4444 public class ContentAssistProcessorRegistry {
4545
4646 private static final String EXTENSION_POINT_ID = GenericEditorPlugin.BUNDLE_ID + ".contentAssistProcessors"; //$NON-NLS-1$
47
48 /**
49 * This class wraps and proxies an {@link IContentAssistProcessor} provided through extensions
50 * and loads it lazily when it can contribute to the editor, then delegates all operations to
51 * actual processor.
52 * When the contribution cannot contribute to the editor, this wrapper will return neutral values
53 * that don't affect editor behavior.
54 */
55 private static class ContentAssistProcessorExtension implements IContentAssistProcessor {
56 private static final String CONTENT_TYPE_ATTRIBUTE = "contentType"; //$NON-NLS-1$
57 private static final String CLASS_ATTRIBUTE = "class"; //$NON-NLS-1$
5847
59 private IConfigurationElement extension;
48 static class ContentAssistProcessorDelegate implements IContentAssistProcessor {
49 private final IContentAssistProcessor delegate;
6050 private IContentType targetContentType;
6151
62 private IContentAssistProcessor delegate;
63
64 private ContentAssistProcessorExtension(IConfigurationElement element) throws Exception {
65 this.extension = element;
66 this.targetContentType = Platform.getContentTypeManager().getContentType(element.getAttribute(CONTENT_TYPE_ATTRIBUTE));
67 }
68
69 private IContentAssistProcessor getDelegate() {
70 if (this.delegate == null) {
71 try {
72 this.delegate = (IContentAssistProcessor) extension.createExecutableExtension(CLASS_ATTRIBUTE);
73 } catch (CoreException e) {
74 e.printStackTrace();
75 }
76 }
77 return delegate;
52 public ContentAssistProcessorDelegate(IContentAssistProcessor delegate, IContentType targetContentType) {
53 this.delegate = delegate;
54 this.targetContentType = targetContentType;
7855 }
7956
8057 /**
10380 @Override
10481 public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) {
10582 if (isActive(viewer)) {
106 return getDelegate().computeCompletionProposals(viewer, offset);
83 return delegate.computeCompletionProposals(viewer, offset);
10784 }
10885 return new ICompletionProposal[0];
10986 }
11188 @Override
11289 public IContextInformation[] computeContextInformation(ITextViewer viewer, int offset) {
11390 if (isActive(viewer)) {
114 return getDelegate().computeContextInformation(viewer, offset);
91 return delegate.computeContextInformation(viewer, offset);
11592 }
11693 return new IContextInformation[0];
11794 }
11996 @Override
12097 public char[] getCompletionProposalAutoActivationCharacters() {
12198 if (isActive(null)) {
122 return getDelegate().getCompletionProposalAutoActivationCharacters();
99 return delegate.getCompletionProposalAutoActivationCharacters();
123100 }
124101 return null;
125102 }
127104 @Override
128105 public char[] getContextInformationAutoActivationCharacters() {
129106 if (isActive(null)) {
130 return getDelegate().getContextInformationAutoActivationCharacters();
107 return delegate.getContextInformationAutoActivationCharacters();
131108 }
132109 return null;
133110 }
135112 @Override
136113 public String getErrorMessage() {
137114 if (isActive(null)) {
138 return getDelegate().getErrorMessage();
115 return delegate.getErrorMessage();
139116 }
140117 return null;
141118 }
143120 @Override
144121 public IContextInformationValidator getContextInformationValidator() {
145122 if (isActive(null)) {
146 return getDelegate().getContextInformationValidator();
123 return delegate.getContextInformationValidator();
147124 }
148125 return null;
149126 }
150127 }
151128
152 private Map<IConfigurationElement, ContentAssistProcessorExtension> extensions = new HashMap<>();
129 private Map<IConfigurationElement, GenericContentTypeRelatedExtension<IContentAssistProcessor>> extensions = new HashMap<>();
153130 private boolean outOfSync = true;
154131
155132 /**
168145 * Get the contributed {@link IContentAssistProcessor}s that are relevant to hook on source viewer according
169146 * to document content types.
170147 * @param sourceViewer the source viewer we're hooking completion to.
148 * @param editor the text editor
171149 * @param contentTypes the content types of the document we're editing.
172150 * @return the list of {@link IContentAssistProcessor} contributed for at least one of the content types.
173151 */
174 public List<IContentAssistProcessor> getContentAssistProcessors(ISourceViewer sourceViewer, Set<IContentType> contentTypes) {
152 public List<IContentAssistProcessor> getContentAssistProcessors(ISourceViewer sourceViewer, ITextEditor editor, Set<IContentType> contentTypes) {
175153 if (this.outOfSync) {
176154 sync();
177155 }
178 List<IContentAssistProcessor> res = new ArrayList<>();
179 for (ContentAssistProcessorExtension ext : this.extensions.values()) {
180 if (contentTypes.contains(ext.targetContentType)) {
181 res.add(ext);
182 }
183 }
184 return res;
156 return this.extensions.values().stream()
157 .filter(ext -> contentTypes.contains(ext.targetContentType))
158 .filter(ext -> ext.matches(sourceViewer, editor))
159 .sorted(new ContentTypeSpecializationComparator<IContentAssistProcessor>())
160 .map(GenericContentTypeRelatedExtension<IContentAssistProcessor>::createDelegate)
161 .collect(Collectors.toList());
185162 }
186163
187164 private void sync() {
190167 toRemoveExtensions.remove(extension);
191168 if (!this.extensions.containsKey(extension)) {
192169 try {
193 this.extensions.put(extension, new ContentAssistProcessorExtension(extension));
170 this.extensions.put(extension, new GenericContentTypeRelatedExtension<IContentAssistProcessor>(extension));
194171 } catch (Exception ex) {
195172 GenericEditorPlugin.getDefault().getLog().log(new Status(IStatus.ERROR, GenericEditorPlugin.BUNDLE_ID, ex.getMessage(), ex));
196173 }
0 /*******************************************************************************
1 * Copyright (c) 2017 Red Hat Inc. and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * - Mickael Istria (Red Hat Inc.)
9 *******************************************************************************/
10 package org.eclipse.ui.internal.genericeditor;
11
12 import java.util.Comparator;
13
14 import org.eclipse.core.runtime.content.IContentType;
15
16 /**
17 * Compares extension so that the ones with the most "specialized" content-types are returned first.
18 *
19 * @param <T>
20 */
21 public class ContentTypeSpecializationComparator<T> implements Comparator<GenericContentTypeRelatedExtension<T>> {
22
23 @Override
24 public int compare(GenericContentTypeRelatedExtension<T> o1, GenericContentTypeRelatedExtension<T> o2) {
25 return depth(o2.targetContentType) - depth(o1.targetContentType);
26 }
27
28 private static int depth(IContentType targetContentType) {
29 int res = 0;
30 IContentType current = targetContentType;
31 while (current != null) {
32 res++;
33 current = current.getBaseType();
34 }
35 return res;
36 }
37
38 }
7373 return proposals.toArray(new ICompletionProposal[proposals.size()]);
7474 }
7575
76 private int findStartingPoint(String text, int offset) {
76 private static int findStartingPoint(String text, int offset) {
7777 String substring = text.substring(0, offset);
7878 Matcher m = NON_ALPHANUMERIC_LAST_PATTERN.matcher(substring);
7979 m.find();
0 /*******************************************************************************
1 * Copyright (c) 2017 Red Hat Inc. and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * - Lucas Bullen (Red Hat Inc.)
9 *******************************************************************************/
10 package org.eclipse.ui.internal.genericeditor;
11
12 import org.eclipse.jface.text.IDocument;
13 import org.eclipse.jface.text.ITextViewer;
14 import org.eclipse.jface.text.reconciler.Reconciler;
15
16 public class DefaultWordHighlightReconciler extends Reconciler {
17
18 private DefaultWordHighlightStrategy fStrategy;
19
20 public DefaultWordHighlightReconciler() {
21 fStrategy = new DefaultWordHighlightStrategy();
22 this.setReconcilingStrategy(fStrategy, IDocument.DEFAULT_CONTENT_TYPE);
23 }
24
25 @Override
26 public void install(ITextViewer textViewer) {
27 super.install(textViewer);
28 fStrategy.install(textViewer);
29 }
30
31 @Override
32 public void uninstall() {
33 super.uninstall();
34 fStrategy.uninstall();
35 }
36 }
0 /*******************************************************************************
1 * Copyright (c) 2017, 2018 Red Hat Inc. and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * - Lucas Bullen (Red Hat Inc.)
9 *******************************************************************************/
10 package org.eclipse.ui.internal.genericeditor;
11
12 import java.util.HashMap;
13 import java.util.Iterator;
14 import java.util.Map;
15 import java.util.Map.Entry;
16 import java.util.regex.Matcher;
17 import java.util.regex.Pattern;
18
19 import org.eclipse.core.runtime.IProgressMonitor;
20 import org.eclipse.core.runtime.preferences.IEclipsePreferences;
21 import org.eclipse.core.runtime.preferences.IEclipsePreferences.IPreferenceChangeListener;
22 import org.eclipse.core.runtime.preferences.IEclipsePreferences.PreferenceChangeEvent;
23 import org.eclipse.core.runtime.preferences.InstanceScope;
24 import org.eclipse.jface.text.IDocument;
25 import org.eclipse.jface.text.IRegion;
26 import org.eclipse.jface.text.ISynchronizable;
27 import org.eclipse.jface.text.ITextViewer;
28 import org.eclipse.jface.text.ITextViewerExtension5;
29 import org.eclipse.jface.text.Position;
30 import org.eclipse.jface.text.reconciler.DirtyRegion;
31 import org.eclipse.jface.text.reconciler.IReconcilingStrategy;
32 import org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension;
33 import org.eclipse.jface.text.source.Annotation;
34 import org.eclipse.jface.text.source.IAnnotationModel;
35 import org.eclipse.jface.text.source.IAnnotationModelExtension;
36 import org.eclipse.jface.text.source.ISourceViewer;
37 import org.eclipse.osgi.util.NLS;
38 import org.eclipse.swt.custom.CaretEvent;
39 import org.eclipse.swt.custom.CaretListener;
40
41 /**
42 *
43 * This Reconciler Strategy is a default stategy which will be present if no
44 * other highlightReconcilers are registered for a given content-type. It splits
45 * the text into 'words' (which are defined as anything in-between
46 * non-alphanumeric characters) and searches the document highlighting all like
47 * words.
48 *
49 * E.g. if your file contains "t^he dog in the bog" and you leave your caret at
50 * ^ you will get both instances of 'the' highlighted.
51 *
52 */
53 public class DefaultWordHighlightStrategy
54 implements IReconcilingStrategy, IReconcilingStrategyExtension, CaretListener, IPreferenceChangeListener {
55
56 private static final String ANNOTATION_TYPE = "org.eclipse.ui.genericeditor.text"; //$NON-NLS-1$
57
58 private boolean enabled;
59 private ISourceViewer sourceViewer;
60 private IDocument document;
61
62 private static final String WORD_REGEXP = "\\w+"; //$NON-NLS-1$
63 private static final Pattern WORD_PATTERN = Pattern.compile(WORD_REGEXP, Pattern.UNICODE_CHARACTER_CLASS);
64 private static final Pattern CURRENT_WORD_START_PATTERN = Pattern.compile(WORD_REGEXP + "$", //$NON-NLS-1$
65 Pattern.UNICODE_CHARACTER_CLASS);
66
67 private Annotation[] fOccurrenceAnnotations = null;
68
69 private void applyHighlights(int offset) {
70 if (sourceViewer == null || !enabled) {
71 removeOccurrenceAnnotations();
72 return;
73 }
74
75 String text = document.get();
76 offset = ((ITextViewerExtension5) sourceViewer).widgetOffset2ModelOffset(offset);
77
78 String word = findCurrentWord(text, offset);
79 if (word == null) {
80 removeOccurrenceAnnotations();
81 return;
82 }
83
84 Matcher m = WORD_PATTERN.matcher(text);
85 Map<Annotation, Position> annotationMap = new HashMap<>();
86 while (m.find()) {
87 if (m.group().equals(word)) {
88 annotationMap.put(
89 new Annotation(ANNOTATION_TYPE, false,
90 NLS.bind(Messages.DefaultWordHighlightStrategy_OccurrencesOf, word)),
91 new Position(m.start(), m.end() - m.start()));
92 }
93 }
94
95 if (annotationMap.size() < 2) {
96 removeOccurrenceAnnotations();
97 return;
98 }
99
100 IAnnotationModel annotationModel = sourceViewer.getAnnotationModel();
101 synchronized (getLockObject(annotationModel)) {
102 if (annotationModel instanceof IAnnotationModelExtension) {
103 ((IAnnotationModelExtension) annotationModel).replaceAnnotations(fOccurrenceAnnotations, annotationMap);
104 } else {
105 removeOccurrenceAnnotations();
106 Iterator<Entry<Annotation, Position>> iter = annotationMap.entrySet().iterator();
107 while (iter.hasNext()) {
108 Entry<Annotation, Position> mapEntry = iter.next();
109 annotationModel.addAnnotation(mapEntry.getKey(), mapEntry.getValue());
110 }
111 }
112 fOccurrenceAnnotations = annotationMap.keySet().toArray(new Annotation[annotationMap.keySet().size()]);
113 }
114 }
115
116 private static String findCurrentWord(String text, int offset) {
117 String wordStart = null;
118 String wordEnd = null;
119
120 String substring = text.substring(0, offset);
121 Matcher m = CURRENT_WORD_START_PATTERN.matcher(substring);
122 if (m.find()) {
123 wordStart = m.group();
124 }
125 substring = text.substring(offset);
126 m = WORD_PATTERN.matcher(substring);
127 if (m.lookingAt()) {
128 wordEnd = m.group();
129 }
130 if (wordStart != null && wordEnd != null)
131 return wordStart + wordEnd;
132 if (wordStart != null)
133 return wordStart;
134 return wordEnd;
135 }
136
137 public void install(ITextViewer viewer) {
138 if (!(viewer instanceof ISourceViewer)) {
139 return;
140 }
141 IEclipsePreferences preferences = InstanceScope.INSTANCE.getNode(GenericEditorPlugin.BUNDLE_ID);
142 preferences.addPreferenceChangeListener(this);
143 this.enabled = preferences.getBoolean(ToggleHighlight.TOGGLE_HIGHLIGHT_PREFERENCE, true);
144 this.sourceViewer = (ISourceViewer) viewer;
145 this.sourceViewer.getTextWidget().addCaretListener(this);
146 }
147
148 public void uninstall() {
149 if (sourceViewer != null) {
150 sourceViewer.getTextWidget().removeCaretListener(this);
151 }
152 IEclipsePreferences preferences = InstanceScope.INSTANCE.getNode(GenericEditorPlugin.BUNDLE_ID);
153 preferences.removePreferenceChangeListener(this);
154 }
155
156 @Override
157 public void preferenceChange(PreferenceChangeEvent event) {
158 if (event.getKey().equals(ToggleHighlight.TOGGLE_HIGHLIGHT_PREFERENCE)) {
159 this.enabled = Boolean.parseBoolean(event.getNewValue().toString());
160 if (enabled) {
161 initialReconcile();
162 } else {
163 removeOccurrenceAnnotations();
164 }
165 }
166 }
167
168 @Override
169 public void caretMoved(CaretEvent event) {
170 applyHighlights(event.caretOffset);
171 }
172
173 @Override
174 public void initialReconcile() {
175 if (sourceViewer != null) {
176 sourceViewer.getTextWidget().getDisplay().asyncExec(() -> {
177 if (sourceViewer != null && sourceViewer.getTextWidget() != null) {
178 applyHighlights(sourceViewer.getTextWidget().getCaretOffset());
179 }
180 });
181 }
182 }
183
184 void removeOccurrenceAnnotations() {
185 IAnnotationModel annotationModel = sourceViewer.getAnnotationModel();
186 if (annotationModel == null || fOccurrenceAnnotations == null) {
187 return;
188 }
189
190 synchronized (getLockObject(annotationModel)) {
191 if (annotationModel instanceof IAnnotationModelExtension) {
192 ((IAnnotationModelExtension) annotationModel).replaceAnnotations(fOccurrenceAnnotations, null);
193 } else {
194 for (Annotation fOccurrenceAnnotation : fOccurrenceAnnotations) {
195 annotationModel.removeAnnotation(fOccurrenceAnnotation);
196 }
197 }
198 fOccurrenceAnnotations = null;
199 }
200 }
201
202 private static Object getLockObject(IAnnotationModel annotationModel) {
203 if (annotationModel instanceof ISynchronizable) {
204 Object lock = ((ISynchronizable) annotationModel).getLockObject();
205 if (lock != null) {
206 return lock;
207 }
208 }
209 return annotationModel;
210 }
211
212 @Override
213 public void setDocument(IDocument document) {
214 this.document = document;
215 }
216
217 @Override
218 public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) {
219 // Do nothing
220 }
221
222 @Override
223 public void reconcile(IRegion partition) {
224 // Do nothing
225 }
226
227 @Override
228 public void setProgressMonitor(IProgressMonitor monitor) {
229 // Not used
230 }
231 }
00 /*******************************************************************************
1 * Copyright (c) 2000, 2016 Red Hat Inc. and others.
1 * Copyright (c) 2000, 2017 Red Hat Inc. and others.
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
66 *
77 * Contributors:
88 * Sopot Cela, Mickael Istria (Red Hat Inc.) - initial implementation
9 * Lucas Bullen (Red Hat Inc.) - Bug 508829 custom reconciler support
910 *******************************************************************************/
1011 package org.eclipse.ui.internal.genericeditor;
1112
1213 import org.eclipse.core.runtime.CoreException;
14 import org.eclipse.jface.text.source.ISourceViewer;
15 import org.eclipse.jface.text.source.IVerticalRuler;
16 import org.eclipse.jface.text.source.projection.ProjectionSupport;
17 import org.eclipse.jface.text.source.projection.ProjectionViewer;
18 import org.eclipse.swt.widgets.Composite;
1319 import org.eclipse.ui.IEditorInput;
1420 import org.eclipse.ui.editors.text.TextEditor;
1521
1622 /**
1723 * A generic code editor that is aimed at being extended by contributions. Behavior
1824 * is supposed to be added via extensions, not by inheritance.
19 *
25 *
2026 * @since 1.0
2127 */
2228 public class ExtensionBasedTextEditor extends TextEditor {
3137 configuration = new ExtensionBasedTextViewerConfiguration(this, getPreferenceStore());
3238 setSourceViewerConfiguration(configuration);
3339 }
34
40
3541 @Override
3642 protected void setKeyBindingScopes(String[] scopes) {
3743 super.setKeyBindingScopes(new String[] { CONTEXT_ID });
4349 configuration.watchDocument(getDocumentProvider().getDocument(input));
4450 }
4551
52 @Override
53 protected ISourceViewer createSourceViewer(Composite parent, IVerticalRuler ruler, int styles) {
54 fAnnotationAccess= getAnnotationAccess();
55 fOverviewRuler= createOverviewRuler(getSharedColors());
56
57 ProjectionViewer viewer= new ProjectionViewer(parent, ruler, getOverviewRuler(), isOverviewRulerVisible(), styles);
58 getSourceViewerDecorationSupport(viewer);
59 return viewer;
60 }
61
62
63 @Override
64 public void createPartControl(Composite parent)
65 {
66 super.createPartControl(parent);
67 ProjectionViewer viewer =(ProjectionViewer)getSourceViewer();
68
69 new ProjectionSupport(viewer,getAnnotationAccess(),getSharedColors()).install();
70 viewer.doOperation(ProjectionViewer.TOGGLE);
71 }
72
4673 }
00 /*******************************************************************************
1 * Copyright (c) 2016 Red Hat Inc. and others.
1 * Copyright (c) 2016, 2017 Red Hat Inc. and others.
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
66 *
77 * Contributors:
88 * Sopot Cela, Mickael Istria (Red Hat Inc.) - initial implementation
9 * Lucas Bullen (Red Hat Inc.) - Bug 508829 custom reconciler support
10 * - Bug 521382 default highlight reconciler
11 * Simon Scholz <simon.scholz@vogella.com> - Bug 527830
912 *******************************************************************************/
1013 package org.eclipse.ui.internal.genericeditor;
1114
2326 import org.eclipse.jface.preference.IPreferenceStore;
2427 import org.eclipse.jface.text.AbstractReusableInformationControlCreator;
2528 import org.eclipse.jface.text.DefaultInformationControl;
29 import org.eclipse.jface.text.IAutoEditStrategy;
2630 import org.eclipse.jface.text.IDocument;
2731 import org.eclipse.jface.text.IDocumentPartitioningListener;
2832 import org.eclipse.jface.text.IInformationControl;
29 import org.eclipse.jface.text.IInformationControlCreator;
3033 import org.eclipse.jface.text.ITextHover;
3134 import org.eclipse.jface.text.contentassist.ContentAssistant;
3235 import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
3841 import org.eclipse.jface.text.source.ISourceViewer;
3942 import org.eclipse.swt.widgets.Shell;
4043 import org.eclipse.ui.IEditorPart;
41 import org.eclipse.ui.IPropertyListener;
4244 import org.eclipse.ui.editors.text.TextSourceViewerConfiguration;
4345 import org.eclipse.ui.internal.editors.text.EditorsPlugin;
46 import org.eclipse.ui.internal.genericeditor.hover.CompositeTextHover;
4447 import org.eclipse.ui.internal.genericeditor.markers.MarkerResoltionQuickAssistProcessor;
4548 import org.eclipse.ui.texteditor.ITextEditor;
4649 import org.eclipse.ui.texteditor.spelling.SpellingCorrectionProcessor;
7073 public ExtensionBasedTextViewerConfiguration(ITextEditor editor, IPreferenceStore preferenceStore) {
7174 super(preferenceStore);
7275 this.editor = editor;
73 this.editor.addPropertyListener(new IPropertyListener() {
74 @Override
75 public void propertyChanged(Object source, int propId) {
76 if (propId == IEditorPart.PROP_INPUT) {
77 watchDocument(editor.getDocumentProvider().getDocument(editor.getEditorInput()));
78 }
76 this.editor.addPropertyListener((source, propId) -> {
77 if (propId == IEditorPart.PROP_INPUT) {
78 watchDocument(editor.getDocumentProvider().getDocument(editor.getEditorInput()));
7979 }
8080 });
8181 }
9898
9999 @Override
100100 public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType) {
101 TextHoverRegistry registry= GenericEditorPlugin.getDefault().getHoverRegistry();
102 return registry.getAvailableHover(sourceViewer, getContentTypes());
101 List<ITextHover> hovers = GenericEditorPlugin.getDefault().getHoverRegistry().getAvailableHovers(sourceViewer, editor, getContentTypes());
102 if (hovers == null || hovers.isEmpty()) {
103 return null;
104 } else if (hovers.size() == 1) {
105 return hovers.get(0);
106 } else {
107 return new CompositeTextHover(hovers);
108 }
103109 }
104110
105111 @Override
108114 contentAssistant= new ContentAssistant(true);
109115 contentAssistant.setContextInformationPopupOrientation(ContentAssistant.CONTEXT_INFO_BELOW);
110116 contentAssistant.setProposalPopupOrientation(ContentAssistant.PROPOSAL_REMOVE);
117 contentAssistant.setAutoActivationDelay(0);
111118 contentAssistant.enableColoredLabels(true);
112119 contentAssistant.enableAutoActivation(true);
113 this.processors = registry.getContentAssistProcessors(sourceViewer, getContentTypes());
120 this.processors = registry.getContentAssistProcessors(sourceViewer, editor, getContentTypes());
114121 if (this.processors.isEmpty()) {
115122 this.processors.add(new DefaultContentAssistProcessor());
116123 }
132139 @Override
133140 public IPresentationReconciler getPresentationReconciler(ISourceViewer sourceViewer) {
134141 PresentationReconcilerRegistry registry = GenericEditorPlugin.getDefault().getPresentationReconcilerRegistry();
135 List<IPresentationReconciler> reconciliers = registry.getPresentationReconcilers(sourceViewer, getContentTypes());
142 List<IPresentationReconciler> reconciliers = registry.getPresentationReconcilers(sourceViewer, editor, getContentTypes());
136143 if (!reconciliers.isEmpty()) {
137144 return reconciliers.get(0);
138145 }
176183 ));
177184 quickAssistAssistant.setQuickAssistProcessor(processor);
178185 quickAssistAssistant.setRestoreCompletionProposalSize(EditorsPlugin.getDefault().getDialogSettingsSection("quick_assist_proposal_size")); //$NON-NLS-1$
179 quickAssistAssistant.setInformationControlCreator(new IInformationControlCreator() {
180 @Override
181 public IInformationControl createInformationControl(Shell parent) {
182 return new DefaultInformationControl(parent, EditorsPlugin.getAdditionalInfoAffordanceString());
183 }
184 });
186 quickAssistAssistant.setInformationControlCreator(parent -> new DefaultInformationControl(parent, EditorsPlugin.getAdditionalInfoAffordanceString()));
185187 return quickAssistAssistant;
186188 }
187189
188190 @Override
189191 public IReconciler getReconciler(ISourceViewer sourceViewer) {
190 return null; // to disable spell-checker
192 ReconcilerRegistry registry = GenericEditorPlugin.getDefault().getReconcilerRegistry();
193 List<IReconciler> reconciliers = registry.getReconcilers(sourceViewer, editor, getContentTypes());
194 List<IReconciler> highlightReconciliers = registry.getHighlightReconcilers(sourceViewer, editor, getContentTypes());
195
196 if(!highlightReconciliers.isEmpty()) {
197 reconciliers.addAll(highlightReconciliers);
198 }else {
199 reconciliers.add(new DefaultWordHighlightReconciler());
200 }
201
202 if (!reconciliers.isEmpty()) {
203 return new CompositeReconciler(reconciliers);
204 }
205 return null;
206 }
207
208 @Override
209 public IAutoEditStrategy[] getAutoEditStrategies(ISourceViewer sourceViewer, String contentType) {
210 AutoEditStrategyRegistry registry = GenericEditorPlugin.getDefault().getAutoEditStrategyRegistry();
211 List<IAutoEditStrategy> editStrategies = registry.getAutoEditStrategies(sourceViewer, editor, getContentTypes());
212 if (!editStrategies.isEmpty()) {
213 return editStrategies.toArray(new IAutoEditStrategy[editStrategies.size()]);
214 }
215 return super.getAutoEditStrategies(sourceViewer, contentType);
191216 }
192217
193218 @Override
0 /*******************************************************************************
1 * Copyright (c) 2017 Red Hat Inc. and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * - Mickael Istria (Red Hat Inc.)
9 *******************************************************************************/
10 package org.eclipse.ui.internal.genericeditor;
11
12 import org.eclipse.core.expressions.ElementHandler;
13 import org.eclipse.core.expressions.EvaluationContext;
14 import org.eclipse.core.expressions.EvaluationResult;
15 import org.eclipse.core.expressions.Expression;
16 import org.eclipse.core.expressions.ExpressionConverter;
17 import org.eclipse.core.runtime.CoreException;
18 import org.eclipse.core.runtime.IConfigurationElement;
19 import org.eclipse.core.runtime.IStatus;
20 import org.eclipse.core.runtime.Platform;
21 import org.eclipse.core.runtime.Status;
22 import org.eclipse.core.runtime.content.IContentType;
23 import org.eclipse.jface.text.source.ISourceViewer;
24 import org.eclipse.ui.texteditor.ITextEditor;
25
26 /**
27 * This class wraps and proxies an instance of T provided through extensions
28 * and loads it lazily when it can contribute to the editor, then delegates all operations to
29 * actual instance.
30 *
31 * @param <T> the actual type to proxy, typically the one defined on the extension point.
32 */
33 public class GenericContentTypeRelatedExtension<T> {
34 private static final String ID_ATTRIBUTE = "id"; //$NON-NLS-1$
35 private static final String CLASS_ATTRIBUTE = "class"; //$NON-NLS-1$
36 private static final String CONTENT_TYPE_ATTRIBUTE = "contentType"; //$NON-NLS-1$
37 private static final String ENABLED_WHEN_ATTRIBUTE = "enabledWhen"; //$NON-NLS-1$
38
39 public final IConfigurationElement extension;
40 public final IContentType targetContentType;
41 public final Expression enabledWhen;
42
43 public GenericContentTypeRelatedExtension(IConfigurationElement element) throws Exception {
44 this.extension = element;
45 this.targetContentType = Platform.getContentTypeManager()
46 .getContentType(element.getAttribute(CONTENT_TYPE_ATTRIBUTE));
47 this.enabledWhen = buildEnabledWhen(element);
48 }
49
50 @SuppressWarnings("unchecked")
51 public T createDelegate() {
52 try {
53 return (T) extension.createExecutableExtension(CLASS_ATTRIBUTE);
54 } catch (CoreException e) {
55 GenericEditorPlugin.getDefault().getLog().log(new Status(IStatus.ERROR, GenericEditorPlugin.BUNDLE_ID, e.getMessage(), e));
56 }
57 return null;
58 }
59
60 /**
61 * Returns the expression {@link Expression} declared in the
62 * <code>enabledWhen</code> element.
63 *
64 * @param configElement the configuration element
65 * @return the expression {@link Expression} declared in the enabledWhen
66 * element.
67 * @throws CoreException when enabledWhen expression is not valid.
68 */
69 private static Expression buildEnabledWhen(IConfigurationElement configElement) throws CoreException {
70 final IConfigurationElement[] children = configElement.getChildren(ENABLED_WHEN_ATTRIBUTE);
71 if (children.length > 0) {
72 IConfigurationElement[] subChildren = children[0].getChildren();
73 if (subChildren.length != 1) {
74 throw new CoreException(new Status(IStatus.ERROR, GenericEditorPlugin.BUNDLE_ID,
75 "One <enabledWhen> element is accepted. Disabling " //$NON-NLS-1$
76 + configElement.getAttribute(ID_ATTRIBUTE)));
77 }
78 final ElementHandler elementHandler = ElementHandler.getDefault();
79 final ExpressionConverter converter = ExpressionConverter.getDefault();
80 return elementHandler.create(converter, subChildren[0]);
81 }
82 return null;
83 }
84
85 /**
86 * Returns true if the given viewer, editor matches the enabledWhen expression
87 * and false otherwise.
88 *
89 * @param viewer the viewer
90 * @param editor the editor
91 * @return true if the given viewer, editor matches the enabledWhen expression
92 * and false otherwise.
93 */
94 public boolean matches(ISourceViewer viewer, ITextEditor editor) {
95 if (enabledWhen == null) {
96 return true;
97 }
98 EvaluationContext context = new EvaluationContext(null, editor);
99 context.setAllowPluginActivation(true);
100 context.addVariable("viewer", viewer); //$NON-NLS-1$
101 context.addVariable("editor", editor); //$NON-NLS-1$
102 context.addVariable("editorInput", editor.getEditorInput()); //$NON-NLS-1$
103 try {
104 return enabledWhen.evaluate(context) == EvaluationResult.TRUE;
105 } catch (CoreException e) {
106 GenericEditorPlugin.getDefault().getLog().log(new Status(IStatus.ERROR, GenericEditorPlugin.BUNDLE_ID,
107 "Error while 'enabledWhen' evaluation", e)); //$NON-NLS-1$
108 return false;
109 }
110 }
111 }
00 /*******************************************************************************
1 * Copyright (c) 2016 Red Hat Inc. and others.
1 * Copyright (c) 2016, 2017 Red Hat Inc. and others.
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
66 *
77 * Contributors:
88 * Sopot Cela, Mickael Istria (Red Hat Inc.) - initial implementation
9 * Lucas Bullen (Red Hat Inc.) - Bug 508829 custom reconciler support
910 *******************************************************************************/
1011 package org.eclipse.ui.internal.genericeditor;
1112
1213 import org.eclipse.jface.text.ITextHover;
1314 import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
1415 import org.eclipse.jface.text.presentation.IPresentationReconciler;
16 import org.eclipse.ui.internal.genericeditor.hover.TextHoverRegistry;
1517 import org.eclipse.ui.plugin.AbstractUIPlugin;
1618 import org.osgi.framework.BundleContext;
1719
2830
2931 private TextHoverRegistry textHoversRegistry;
3032 private ContentAssistProcessorRegistry contentAssistProcessorsRegistry;
33 private ReconcilerRegistry reconcilierRegistry;
3134 private PresentationReconcilerRegistry presentationReconcilierRegistry;
35 private AutoEditStrategyRegistry autoEditStrategyRegistry;
3236
3337 @Override
3438 public void start(BundleContext context) throws Exception{
6771 }
6872 return this.contentAssistProcessorsRegistry;
6973 }
74
75 /**
76 * @return the registry allowing to access contributed {@link IReconciler}s.
77 * @since 1.1
78 */
79 public synchronized ReconcilerRegistry getReconcilerRegistry() {
80 if (this.reconcilierRegistry == null) {
81 this.reconcilierRegistry = new ReconcilerRegistry();
82 }
83 return this.reconcilierRegistry;
84 }
7085
7186 /**
7287 * @return the registry allowing to access contributed {@link IPresentationReconciler}s.
7893 }
7994 return this.presentationReconcilierRegistry;
8095 }
96
97 /**
98 * @return the registry allowing to access contributed {@link IAutoEditStrategy}s.
99 * @since 1.1
100 */
101 public synchronized AutoEditStrategyRegistry getAutoEditStrategyRegistry() {
102 if (this.autoEditStrategyRegistry == null) {
103 this.autoEditStrategyRegistry = new AutoEditStrategyRegistry();
104 }
105 return this.autoEditStrategyRegistry;
106 }
81107 }
0 /*******************************************************************************
1 * Copyright (c) 2018 Red Hat Inc. and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Alexander Kurtakov (Red Hat Inc.) - initial version
9 *******************************************************************************/
10 package org.eclipse.ui.internal.genericeditor;
11
12 import org.eclipse.osgi.util.NLS;
13
14 public class Messages extends NLS {
15 private static final String BUNDLE_NAME = "org.eclipse.ui.internal.genericeditor.messages"; //$NON-NLS-1$
16 public static String DefaultWordHighlightStrategy_OccurrencesOf;
17 static {
18 // initialize resource bundle
19 NLS.initializeMessages(BUNDLE_NAME, Messages.class);
20 }
21
22 private Messages() {
23 }
24 }
+0
-91
org.eclipse.ui.genericeditor/src/org/eclipse/ui/internal/genericeditor/OrderedExtensionComparator.java less more
0 /*******************************************************************************
1 * Copyright (c) 2016 Red Hat Inc. and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Mickael Istria (Red Hat Inc.) - initial implementation
9 *******************************************************************************/
10 package org.eclipse.ui.internal.genericeditor;
11
12 import java.util.Collection;
13 import java.util.Comparator;
14 import java.util.Map;
15 import java.util.function.Function;
16 import java.util.stream.Collectors;
17
18 import org.eclipse.core.runtime.Assert;
19 import org.eclipse.ui.internal.genericeditor.TextHoverRegistry.TextHoverExtension;
20
21 /**
22 * A comparator that allows to sort elements according to their relative
23 * placement (isBefore and isAfter)
24 *
25 */
26 class OrderedExtensionComparator implements Comparator<TextHoverExtension> {
27
28 private Map<String, TextHoverExtension> extensionsById;
29
30 public OrderedExtensionComparator(Collection<TextHoverExtension> extensions) {
31 Assert.isNotNull(extensions);
32 this.extensionsById = extensions.stream().collect(Collectors.toMap(TextHoverExtension::getId, Function.identity()));
33 }
34
35 @Override
36 public int compare(TextHoverExtension arg0, TextHoverExtension arg1) {
37 if (isDeclaredAsBefore(arg0, arg1) || isDeclaredAsAfter(arg1, arg0)) {
38 return -1;
39 }
40 if (isDeclaredAsAfter(arg0, arg1) || isDeclaredAsBefore(arg1, arg0)) {
41 return +1;
42 }
43 return arg0.toString().compareTo(arg1.toString());
44 }
45
46 private boolean isDeclaredAsBefore(TextHoverExtension arg0, TextHoverExtension arg1) {
47 String before0 = arg0.getIsBefore();
48 if (before0 == null) {
49 return false;
50 }
51 if ("*".equals(before0) && !"*".equals(arg1.getIsBefore())) { //$NON-NLS-1$ //$NON-NLS-2$
52 return true;
53 }
54 String id1 = arg1.getId();
55 if (id1 == null) {
56 return false;
57 }
58 if (before0.equals(id1)) {
59 return true;
60 }
61 String after1 = arg1.getIsAfter();
62 if (after1 == null) {
63 return false;
64 }
65 return isDeclaredAsAfter(arg0, this.extensionsById.get(after1));
66 }
67
68 private boolean isDeclaredAsAfter(TextHoverExtension arg0, TextHoverExtension arg1) {
69 String after0 = arg0.getIsAfter();
70 if (after0 == null) {
71 return false;
72 }
73 if ("*".equals(after0) && !"*".equals(arg1.getIsAfter())) { //$NON-NLS-1$ //$NON-NLS-2$
74 return true;
75 }
76 String id1 = arg1.getId();
77 if (id1 == null) {
78 return false;
79 }
80 if (after0.equals(id1)) {
81 return true;
82 }
83 String before1 = arg1.getIsBefore();
84 if (before1 == null) {
85 return false;
86 }
87 return isDeclaredAsAfter(arg0, this.extensionsById.get(before1));
88 }
89
90 }
00 /*******************************************************************************
1 * Copyright (c) 2016 Red Hat Inc. and others.
1 * Copyright (c) 2016-2017 Red Hat Inc. and others.
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
99 *******************************************************************************/
1010 package org.eclipse.ui.internal.genericeditor;
1111
12 import java.util.ArrayList;
1312 import java.util.HashMap;
1413 import java.util.HashSet;
1514 import java.util.List;
1615 import java.util.Map;
1716 import java.util.Set;
17 import java.util.stream.Collectors;
1818
19 import org.eclipse.core.runtime.CoreException;
2019 import org.eclipse.core.runtime.IConfigurationElement;
2120 import org.eclipse.core.runtime.IRegistryChangeEvent;
2221 import org.eclipse.core.runtime.IRegistryChangeListener;
2423 import org.eclipse.core.runtime.Platform;
2524 import org.eclipse.core.runtime.Status;
2625 import org.eclipse.core.runtime.content.IContentType;
27 import org.eclipse.jface.text.ITextViewer;
28 import org.eclipse.jface.text.presentation.IPresentationDamager;
2926 import org.eclipse.jface.text.presentation.IPresentationReconciler;
30 import org.eclipse.jface.text.presentation.IPresentationRepairer;
3127 import org.eclipse.jface.text.source.ISourceViewer;
28 import org.eclipse.ui.texteditor.ITextEditor;
3229
3330 /**
3431 * A registry of presentation reconciliers provided by extension <code>org.eclipse.ui.genericeditor.presentationReconcilers</code>.
4037
4138 private static final String EXTENSION_POINT_ID = GenericEditorPlugin.BUNDLE_ID + ".presentationReconcilers"; //$NON-NLS-1$
4239
43 /**
44 * This class wraps and proxies an {@link IPresentationReconcilier} provided through extensions
45 * and loads it lazily when it can contribute to the editor, then delegates all operations to
46 * actual reconcilier.
47 */
48 private static class PresentationReconcilerExtension implements IPresentationReconciler {
49 private static final String CLASS_ATTRIBUTE = "class"; //$NON-NLS-1$
50 private static final String CONTENT_TYPE_ATTRIBUTE = "contentType"; //$NON-NLS-1$
51
52 private IConfigurationElement extension;
53 private IContentType targetContentType;
54
55 private IPresentationReconciler delegate;
56
57 private PresentationReconcilerExtension(IConfigurationElement element) throws Exception {
58 this.extension = element;
59 this.targetContentType = Platform.getContentTypeManager().getContentType(element.getAttribute(CONTENT_TYPE_ATTRIBUTE));
60 }
61
62 private IPresentationReconciler getDelegate() {
63 if (this.delegate == null) {
64 try {
65 this.delegate = (IPresentationReconciler) extension.createExecutableExtension(CLASS_ATTRIBUTE);
66 } catch (CoreException e) {
67 e.printStackTrace();
68 }
69 }
70 return delegate;
71 }
72
73 @Override
74 public void install(ITextViewer viewer) {
75 getDelegate().install(viewer);
76 }
77
78 @Override
79 public void uninstall() {
80 getDelegate().uninstall();
81 }
82
83 @Override
84 public IPresentationDamager getDamager(String contentType) {
85 return getDelegate().getDamager(contentType);
86
87 }
88
89 @Override
90 public IPresentationRepairer getRepairer(String contentType) {
91 return getDelegate().getRepairer(contentType);
92 }
93
94 }
95 private Map<IConfigurationElement, PresentationReconcilerExtension> extensions = new HashMap<>();
40 private Map<IConfigurationElement, GenericContentTypeRelatedExtension<IPresentationReconciler>> extensions = new HashMap<>();
9641 private boolean outOfSync = true;
9742
9843 /**
11156 * Get the contributed {@link IPresentationReconciliers}s that are relevant to hook on source viewer according
11257 * to document content types.
11358 * @param sourceViewer the source viewer we're hooking completion to.
59 * @param editor the text editor
11460 * @param contentTypes the content types of the document we're editing.
11561 * @return the list of {@link IPresentationReconciler} contributed for at least one of the content types.
11662 */
117 public List<IPresentationReconciler> getPresentationReconcilers(ISourceViewer sourceViewer, Set<IContentType> contentTypes) {
63 public List<IPresentationReconciler> getPresentationReconcilers(ISourceViewer sourceViewer, ITextEditor editor, Set<IContentType> contentTypes) {
11864 if (this.outOfSync) {
11965 sync();
12066 }
121 List<IPresentationReconciler> res = new ArrayList<>();
122 for (PresentationReconcilerExtension ext : this.extensions.values()) {
123 if (contentTypes.contains(ext.targetContentType)) {
124 res.add(ext);
125 }
126 }
127 return res;
67 return this.extensions.values().stream()
68 .filter(ext -> contentTypes.contains(ext.targetContentType))
69 .filter(ext -> ext.matches(sourceViewer, editor))
70 .sorted(new ContentTypeSpecializationComparator<IPresentationReconciler>())
71 .map(GenericContentTypeRelatedExtension<IPresentationReconciler>::createDelegate)
72 .collect(Collectors.toList());
12873 }
12974
13075 private void sync() {
13378 toRemoveExtensions.remove(extension);
13479 if (!this.extensions.containsKey(extension)) {
13580 try {
136 this.extensions.put(extension, new PresentationReconcilerExtension(extension));
81 this.extensions.put(extension, new GenericContentTypeRelatedExtension<IPresentationReconciler>(extension));
13782 } catch (Exception ex) {
13883 GenericEditorPlugin.getDefault().getLog().log(new Status(IStatus.ERROR, GenericEditorPlugin.BUNDLE_ID, ex.getMessage(), ex));
13984 }
0 /*******************************************************************************
1 * Copyright (c) 2017 Red Hat Inc. and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Lucas Bullen (Red Hat Inc.) - initial implementation
9 *******************************************************************************/
10 package org.eclipse.ui.internal.genericeditor;
11
12 import java.util.HashMap;
13 import java.util.HashSet;
14 import java.util.List;
15 import java.util.Map;
16 import java.util.Set;
17 import java.util.stream.Collectors;
18
19 import org.eclipse.core.runtime.IConfigurationElement;
20 import org.eclipse.core.runtime.IStatus;
21 import org.eclipse.core.runtime.Platform;
22 import org.eclipse.core.runtime.Status;
23 import org.eclipse.core.runtime.content.IContentType;
24 import org.eclipse.jface.text.reconciler.IReconciler;
25 import org.eclipse.jface.text.source.ISourceViewer;
26 import org.eclipse.ui.texteditor.ITextEditor;
27
28 /**
29 * A registry of reconciliers provided by extensions <code>org.eclipse.ui.genericeditor.reconcilers</code>
30 * and <code>org.eclipse.ui.genericeditor.foldingReconcilers</code>.
31 * Those extensions are specific to a given {@link IContentType}.
32 *
33 * @since 1.1
34 */
35 public class ReconcilerRegistry {
36
37 private static final String EXTENSION_POINT_ID = GenericEditorPlugin.BUNDLE_ID + ".reconcilers"; //$NON-NLS-1$
38 private static final String HIGHLIGHT_EXTENSION_POINT_ID = GenericEditorPlugin.BUNDLE_ID + ".highlightReconcilers"; //$NON-NLS-1$
39
40 private Map<IConfigurationElement, GenericContentTypeRelatedExtension<IReconciler>> extensions = new HashMap<>();
41 private Map<IConfigurationElement, GenericContentTypeRelatedExtension<IReconciler>> highlightExtensions = new HashMap<>();
42 private boolean outOfSync = true;
43 private boolean highlightOutOfSync = true;
44
45 /**
46 * Creates the registry and binds it to the extension point.
47 */
48 public ReconcilerRegistry() {
49 Platform.getExtensionRegistry().addRegistryChangeListener(event -> {
50 outOfSync = true;
51 }, EXTENSION_POINT_ID);
52
53 Platform.getExtensionRegistry().addRegistryChangeListener(event -> {
54 highlightOutOfSync = true;
55 }, HIGHLIGHT_EXTENSION_POINT_ID);
56 }
57
58 /**
59 * Get the contributed {@link IReconciliers}s that are relevant to hook on source viewer according
60 * to document content types.
61 * @param sourceViewer the source viewer we're hooking completion to.
62 * @param editor the text editor
63 * @param contentTypes the content types of the document we're editing.
64 * @return the list of {@link IReconciler} contributed for at least one of the content types,
65 * sorted by most generic content type to most specific.
66 */
67 public List<IReconciler> getReconcilers(ISourceViewer sourceViewer, ITextEditor editor, Set<IContentType> contentTypes) {
68 if (this.outOfSync) {
69 sync();
70 }
71 List<IReconciler> reconcilers = this.extensions.values().stream()
72 .filter(ext -> contentTypes.contains(ext.targetContentType))
73 .filter(ext -> ext.matches(sourceViewer, editor))
74 .sorted(new ContentTypeSpecializationComparator<IReconciler>().reversed())
75 .map(GenericContentTypeRelatedExtension<IReconciler>::createDelegate)
76 .collect(Collectors.toList());
77 return reconcilers;
78 }
79
80 /**
81 * Get the contributed highlight {@link IReconciliers}s that are relevant to hook on source viewer according
82 * to document content types.
83 * @param sourceViewer the source viewer we're hooking completion to.
84 * @param editor the text editor
85 * @param contentTypes the content types of the document we're editing.
86 * @return the list of highlight {@link IReconciler}s contributed for at least one of the content types,
87 * sorted by most generic content type to most specific.
88 */
89 public List<IReconciler> getHighlightReconcilers(ISourceViewer sourceViewer, ITextEditor editor, Set<IContentType> contentTypes) {
90 if (this.highlightOutOfSync) {
91 syncHighlight();
92 }
93 List<IReconciler> highlightReconcilers = this.highlightExtensions.values().stream()
94 .filter(ext -> contentTypes.contains(ext.targetContentType))
95 .filter(ext -> ext.matches(sourceViewer, editor))
96 .sorted(new ContentTypeSpecializationComparator<IReconciler>().reversed())
97 .map(GenericContentTypeRelatedExtension<IReconciler>::createDelegate)
98 .collect(Collectors.toList());
99 return highlightReconcilers;
100 }
101
102 private void sync() {
103 Set<IConfigurationElement> toRemoveExtensions = new HashSet<>(this.extensions.keySet());
104 for (IConfigurationElement extension : Platform.getExtensionRegistry().getConfigurationElementsFor(EXTENSION_POINT_ID)) {
105 toRemoveExtensions.remove(extension);
106 if (!this.extensions.containsKey(extension)) {
107 try {
108 this.extensions.put(extension, new GenericContentTypeRelatedExtension<IReconciler>(extension));
109 } catch (Exception ex) {
110 GenericEditorPlugin.getDefault().getLog().log(new Status(IStatus.ERROR, GenericEditorPlugin.BUNDLE_ID, ex.getMessage(), ex));
111 }
112 }
113 }
114 for (IConfigurationElement toRemove : toRemoveExtensions) {
115 this.extensions.remove(toRemove);
116 }
117 this.outOfSync = false;
118 }
119
120 private void syncHighlight() {
121 Set<IConfigurationElement> toRemoveExtensions = new HashSet<>(this.extensions.keySet());
122 for (IConfigurationElement extension : Platform.getExtensionRegistry().getConfigurationElementsFor(HIGHLIGHT_EXTENSION_POINT_ID)) {
123 toRemoveExtensions.remove(extension);
124 if (!this.highlightExtensions.containsKey(extension)) {
125 try {
126 this.highlightExtensions.put(extension, new GenericContentTypeRelatedExtension<IReconciler>(extension));
127 } catch (Exception ex) {
128 GenericEditorPlugin.getDefault().getLog().log(new Status(IStatus.ERROR, GenericEditorPlugin.BUNDLE_ID, ex.getMessage(), ex));
129 }
130 }
131 }
132 for (IConfigurationElement toRemove : toRemoveExtensions) {
133 this.highlightExtensions.remove(toRemove);
134 }
135 this.highlightOutOfSync = false;
136 }
137
138 }
+0
-155
org.eclipse.ui.genericeditor/src/org/eclipse/ui/internal/genericeditor/TextHoverRegistry.java less more
0 /*******************************************************************************
1 * Copyright (c) 2016 Red Hat Inc. and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * - Mickael Istria (Red Hat Inc.)
9 *******************************************************************************/
10 package org.eclipse.ui.internal.genericeditor;
11
12 import java.util.ArrayList;
13 import java.util.HashMap;
14 import java.util.HashSet;
15 import java.util.List;
16 import java.util.Map;
17 import java.util.Set;
18 import java.util.SortedSet;
19 import java.util.TreeSet;
20 import java.util.function.Function;
21 import java.util.stream.Collectors;
22
23 import org.eclipse.core.runtime.CoreException;
24 import org.eclipse.core.runtime.IConfigurationElement;
25 import org.eclipse.core.runtime.IRegistryChangeEvent;
26 import org.eclipse.core.runtime.IRegistryChangeListener;
27 import org.eclipse.core.runtime.IStatus;
28 import org.eclipse.core.runtime.Platform;
29 import org.eclipse.core.runtime.Status;
30 import org.eclipse.core.runtime.content.IContentType;
31 import org.eclipse.jface.preference.IPreferenceStore;
32 import org.eclipse.jface.text.ITextHover;
33 import org.eclipse.jface.text.source.ISourceViewer;
34
35 /**
36 * Text hover registry that manages the detectors
37 * contributed by the <code>org.eclipse.ui.workbench.texteditor.hoverProvider</code> extension point for
38 * targets contributed by the <code>org.eclipse.ui.workbench.texteditor.hyperlinkDetectorTargets</code> extension point.
39 *
40 * @since 1.0
41 */
42 public final class TextHoverRegistry {
43
44 private static final String EXTENSION_POINT_ID = GenericEditorPlugin.BUNDLE_ID + ".hoverProviders"; //$NON-NLS-1$
45
46 private SortedSet<TextHoverExtension> extensions;
47 private boolean outOfSync = true;
48
49 static class TextHoverExtension {
50 private static final String CONTENT_TYPE_ATTRIBUTE = "contentType"; //$NON-NLS-1$
51 private static final String CLASS_ATTRIBUTE = "class"; //$NON-NLS-1$
52 private static final String ID_ATTRIBUTE = "id"; //$NON-NLS-1$
53 private static final String IS_BEFORE_ATTRIBUTE = "isBefore"; //$NON-NLS-1$
54 private static final String IS_AFTER_ATTRIBUTE = "isAfter"; //$NON-NLS-1$
55
56 private IConfigurationElement extension;
57 private IContentType targetContentType;
58 private ITextHover delegate;
59 private String id;
60 private String isBefore;
61 private String isAfter;
62
63 public TextHoverExtension(IConfigurationElement extension) throws Exception {
64 this.extension = extension;
65 this.targetContentType = Platform.getContentTypeManager().getContentType(extension.getAttribute(CONTENT_TYPE_ATTRIBUTE));
66 this.id = extension.getAttribute(ID_ATTRIBUTE);
67 this.isBefore = extension.getAttribute(IS_BEFORE_ATTRIBUTE);
68 this.isAfter = extension.getAttribute(IS_AFTER_ATTRIBUTE);
69 }
70
71 public ITextHover getDelegate() {
72 if (this.delegate == null) {
73 try {
74 this.delegate = (ITextHover) extension.createExecutableExtension(CLASS_ATTRIBUTE);
75 } catch (CoreException e) {
76 e.printStackTrace();
77 }
78 }
79 return delegate;
80 }
81
82 public String getId() {
83 if (this.id != null) {
84 return this.id;
85 }
86 return this.extension.getContributor().getName() + '@' + toString();
87 }
88
89 public String getIsAfter() {
90 return this.isAfter;
91 }
92
93 public String getIsBefore() {
94 return this.isBefore;
95 }
96
97 IConfigurationElement getConfigurationElement() {
98 return this.extension;
99 }
100 }
101
102 public TextHoverRegistry(IPreferenceStore preferenceStore) {
103 Platform.getExtensionRegistry().addRegistryChangeListener(new IRegistryChangeListener() {
104 @Override
105 public void registryChanged(IRegistryChangeEvent event) {
106 outOfSync = true;
107 }
108 }, EXTENSION_POINT_ID);
109 }
110
111 public ITextHover getAvailableHover(ISourceViewer sourceViewer, Set<IContentType> contentTypes) {
112 if (this.outOfSync) {
113 sync();
114 }
115 List<TextHoverExtension> hoversToConsider = new ArrayList<>();
116 for (TextHoverExtension ext : this.extensions) {
117 if (contentTypes.contains(ext.targetContentType)) {
118 hoversToConsider.add(ext);
119 }
120 }
121 if (!hoversToConsider.isEmpty()) {
122 return new CompositeTextHover(hoversToConsider);
123 }
124 return null;
125 }
126
127 private void sync() {
128 Set<IConfigurationElement> toRemoveExtensions = new HashSet<>();
129 Map<IConfigurationElement, TextHoverExtension> ext = new HashMap<>();
130 if (this.extensions != null) {
131 ext = this.extensions.stream().collect(Collectors.toMap(TextHoverExtension::getConfigurationElement, Function.identity()));
132 toRemoveExtensions = ext.keySet();
133 }
134 for (IConfigurationElement extension : Platform.getExtensionRegistry().getConfigurationElementsFor(EXTENSION_POINT_ID)) {
135 toRemoveExtensions.remove(extension);
136 if (!ext.containsKey(extension)) {
137 try {
138 ext.put(extension, new TextHoverExtension(extension));
139 } catch (Exception ex) {
140 GenericEditorPlugin.getDefault().getLog().log(new Status(IStatus.ERROR, GenericEditorPlugin.BUNDLE_ID, ex.getMessage(), ex));
141 }
142 }
143 }
144 for (IConfigurationElement toRemove : toRemoveExtensions) {
145 ext.remove(toRemove);
146 }
147
148 OrderedExtensionComparator comparator = new OrderedExtensionComparator(ext.values());
149 this.extensions = new TreeSet<>(comparator);
150 this.extensions.addAll(ext.values());
151 this.outOfSync = false;
152 }
153
154 }
0 /*******************************************************************************
1 * Copyright (c) 2017 Red Hat Inc. and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Lucas Bullen (Red Hat Inc.) - initial implementation
9 *******************************************************************************/
10 package org.eclipse.ui.internal.genericeditor;
11
12 import org.eclipse.core.commands.AbstractHandler;
13 import org.eclipse.core.commands.Command;
14 import org.eclipse.core.commands.ExecutionEvent;
15 import org.eclipse.core.commands.ExecutionException;
16 import org.eclipse.core.runtime.preferences.IEclipsePreferences;
17 import org.eclipse.core.runtime.preferences.InstanceScope;
18 import org.eclipse.ui.handlers.HandlerUtil;
19
20 public class ToggleHighlight extends AbstractHandler {
21
22 public static final String TOGGLE_HIGHLIGHT_PREFERENCE = "org.eclipse.ui.genericeditor.togglehighlight"; //$NON-NLS-1$
23
24 @Override
25 public Object execute(ExecutionEvent event) throws ExecutionException {
26 Command command = event.getCommand();
27 boolean oldValue = HandlerUtil.toggleCommandState(command);
28
29 IEclipsePreferences preferences = InstanceScope.INSTANCE.getNode(GenericEditorPlugin.BUNDLE_ID);
30 preferences.putBoolean(TOGGLE_HIGHLIGHT_PREFERENCE, !oldValue);
31 return null;
32 }
33 }
0 /*******************************************************************************
1 * Copyright (c) 2017 Red Hat Inc. and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * - Mickael Istria (Red Hat Inc.)
9 * - Lucas Bullen (Red Hat Inc.) - [Bug 527071] Empty string as content breaks hover
10 *******************************************************************************/
11 package org.eclipse.ui.internal.genericeditor.hover;
12
13 import java.util.Arrays;
14 import java.util.LinkedHashMap;
15 import java.util.List;
16 import java.util.Map;
17 import java.util.Map.Entry;
18
19 import org.eclipse.core.runtime.Assert;
20 import org.eclipse.core.runtime.IStatus;
21 import org.eclipse.core.runtime.Status;
22 import org.eclipse.jface.text.AbstractInformationControl;
23 import org.eclipse.jface.text.IInformationControl;
24 import org.eclipse.jface.text.IInformationControlCreator;
25 import org.eclipse.jface.text.IInformationControlExtension;
26 import org.eclipse.jface.text.IInformationControlExtension2;
27 import org.eclipse.jface.text.IInformationControlExtension5;
28 import org.eclipse.jface.text.ITextHover;
29 import org.eclipse.swt.SWT;
30 import org.eclipse.swt.graphics.Point;
31 import org.eclipse.swt.layout.GridData;
32 import org.eclipse.swt.layout.GridLayout;
33 import org.eclipse.swt.widgets.Composite;
34 import org.eclipse.swt.widgets.Control;
35 import org.eclipse.swt.widgets.Shell;
36 import org.eclipse.ui.internal.genericeditor.GenericEditorPlugin;
37
38 public class CompositeInformationControl extends AbstractInformationControl implements IInformationControlExtension2 {
39
40 final LinkedHashMap<ITextHover, IInformationControlCreator> creators;
41 LinkedHashMap<ITextHover, IInformationControl> controls;
42
43 public CompositeInformationControl(Shell parentShell, LinkedHashMap<ITextHover, IInformationControlCreator> creators) {
44 super(parentShell, true); // TODO check best constructor
45 Assert.isLegal(creators.size() > 1, "Do not compose a unique hover"); //$NON-NLS-1$
46 this.creators = creators;
47 create();
48 }
49
50 @Override
51 public boolean hasContents() {
52 for (IInformationControl control : controls.values()) {
53 if (control instanceof IInformationControlExtension) {
54 if (((IInformationControlExtension)control).hasContents()) {
55 return true;
56 }
57 } else {
58 return true;
59 }
60 }
61 return false;
62 }
63
64 @Override
65 public void setInput(Object input) {
66 @SuppressWarnings("unchecked")
67 Map<ITextHover, Object> inputs = (Map<ITextHover, Object>)input;
68 for (Entry<ITextHover, Object> entry : inputs.entrySet()) {
69 IInformationControl informationControl = controls.get(entry.getKey());
70 if (informationControl != null) {
71 if (informationControl instanceof IInformationControlExtension2) {
72 ((IInformationControlExtension2)informationControl).setInput(entry.getValue());
73 continue;
74 }
75 String information = entry.getValue().toString();
76 if(!information.isEmpty()){
77 informationControl.setInformation(information);
78 }
79 }
80 }
81 }
82
83 @Override
84 public void createContent(Composite parent) {
85 this.controls = new LinkedHashMap<>(); // TODO maybe use canReuse or canReplace
86 GridLayout layout = new GridLayout(1, false);
87 parent.setLayout(layout);
88 boolean firstControl = true;
89 for (Entry<ITextHover, IInformationControlCreator> hoverControlCreator : this.creators.entrySet()) {
90 IInformationControl informationControl = hoverControlCreator.getValue().createInformationControl(parent.getShell());
91 if (informationControl instanceof AbstractInformationControl) {
92 List<Control> children = Arrays.asList(((AbstractInformationControl)informationControl).getShell().getChildren());
93 children.remove(parent);
94 if (children.size() == 0 ) {
95 continue;
96 }
97 for (Control control : children) {
98 control.setParent(parent);
99 control.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
100 }
101 if (!firstControl) {
102 ((GridData)children.get(0).getLayoutData()).verticalIndent = 15;
103 }
104 controls.put(hoverControlCreator.getKey(), informationControl);
105 firstControl = false;
106 } else {
107 GenericEditorPlugin.getDefault().getLog().log(new Status(IStatus.WARNING, GenericEditorPlugin.BUNDLE_ID,
108 "Only text hovers producing an AbstractInformationControl can be aggregated; got a " + informationControl.getClass().getSimpleName())); //$NON-NLS-1$
109 informationControl.dispose();
110 }
111 }
112 }
113
114 @Override
115 public void dispose() {
116 controls.values().forEach(IInformationControl::dispose);
117 controls.clear();
118 super.dispose();
119 }
120
121 @Override
122 public IInformationControlCreator getInformationPresenterControlCreator() {
123 if (controls.isEmpty()) {
124 return null;
125 } else if (controls.size() == 1) {
126 IInformationControl control = controls.values().iterator().next();
127 if (control instanceof IInformationControlExtension5) {
128 return ((IInformationControlExtension5)control).getInformationPresenterControlCreator();
129 }
130 } else {
131 LinkedHashMap<ITextHover, IInformationControlCreator> presenterCreators = new LinkedHashMap<>();
132 boolean allNull = true;
133 for (Entry<ITextHover, IInformationControl> hover : this.controls.entrySet()) {
134 IInformationControlCreator creator = null;
135 if (hover.getValue() instanceof IInformationControlExtension5)
136 creator = ((IInformationControlExtension5)hover.getValue()).getInformationPresenterControlCreator();
137 if (creator == null) {
138 creator = this.creators.get(hover.getKey());
139 } else {
140 allNull = false;
141 }
142 if (creator != null) {
143 presenterCreators.put(hover.getKey(), creator);
144 }
145 }
146 if (allNull) {
147 return null;
148 }
149 return new CompositeInformationControlCreator(presenterCreators);
150 }
151 return null;
152 }
153
154 @Override
155 public Point computeSizeHint() {
156 return getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
157 }
158
159 }
0 /*******************************************************************************
1 * Copyright (c) 2017 Red Hat Inc. and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * - Mickael Istria (Red Hat Inc.)
9 *******************************************************************************/
10 package org.eclipse.ui.internal.genericeditor.hover;
11
12 import java.util.Iterator;
13 import java.util.LinkedHashMap;
14 import java.util.List;
15 import java.util.Map.Entry;
16
17 import org.eclipse.jface.text.AbstractReusableInformationControlCreator;
18 import org.eclipse.jface.text.DefaultInformationControl;
19 import org.eclipse.jface.text.IInformationControl;
20 import org.eclipse.jface.text.IInformationControlCreator;
21 import org.eclipse.jface.text.IInformationControlCreatorExtension;
22 import org.eclipse.jface.text.ITextHover;
23 import org.eclipse.jface.text.ITextHoverExtension;
24 import org.eclipse.swt.widgets.Shell;
25
26 public class CompositeInformationControlCreator
27 implements IInformationControlCreator, IInformationControlCreatorExtension {
28
29 private final LinkedHashMap<ITextHover, IInformationControlCreator> creators;
30
31 public CompositeInformationControlCreator(List<ITextHover> hovers) {
32 this.creators = new LinkedHashMap<>();
33 for (ITextHover hover : hovers) {
34 creators.put(hover, getInformationControlCreator(hover));
35 }
36 }
37
38 public CompositeInformationControlCreator(LinkedHashMap<ITextHover, IInformationControlCreator> creators) {
39 this.creators = creators;
40 }
41
42 private static IInformationControlCreator getInformationControlCreator(ITextHover hover) {
43 IInformationControlCreator controlCreator = null;
44 if (hover instanceof ITextHoverExtension) {
45 controlCreator = ((ITextHoverExtension)hover).getHoverControlCreator();
46 }
47 if (controlCreator == null) {
48 controlCreator = new AbstractReusableInformationControlCreator() {
49 @Override
50 protected IInformationControl doCreateInformationControl(Shell parent) {
51 return new DefaultInformationControl(parent, true);
52 }
53 };
54 }
55 return controlCreator;
56 }
57
58
59 @Override
60 public boolean canReuse(IInformationControl control) {
61 if (control.getClass() != CompositeInformationControl.class) {
62 return false;
63 }
64 CompositeInformationControl other = (CompositeInformationControl)control;
65 if (!other.creators.equals(this.creators)) {
66 return false;
67 }
68 Iterator<Entry<ITextHover, IInformationControlCreator>> thisIterator = this.creators.entrySet().iterator();
69 Iterator<Entry<ITextHover, IInformationControl>> otherIterator = other.controls.entrySet().iterator();
70 do {
71 Entry<ITextHover, IInformationControlCreator> thisEntry = thisIterator.next();
72 Entry<ITextHover, IInformationControl> otherEntry = otherIterator.next();
73 if (!thisEntry.getKey().equals(otherEntry.getKey())) {
74 return false;
75 }
76 if (!(thisEntry.getValue() instanceof IInformationControlCreatorExtension)) {
77 return false;
78 }
79 if (!((IInformationControlCreatorExtension)thisEntry.getValue()).canReuse(otherEntry.getValue())) {
80 return false;
81 }
82 } while (thisIterator.hasNext());
83 return true;
84 }
85
86 @Override
87 public boolean canReplace(IInformationControlCreator creator) {
88 if (creator.getClass() != this.getClass()) {
89 return false;
90 }
91 CompositeInformationControlCreator other = (CompositeInformationControlCreator)creator;
92 if (other.creators.size() != this.creators.size()) {
93 return false;
94 }
95 Iterator<Entry<ITextHover, IInformationControlCreator>> thisIterator = this.creators.entrySet().iterator();
96 Iterator<Entry<ITextHover, IInformationControlCreator>> otherIterator = other.creators.entrySet().iterator();
97 do {
98 Entry<ITextHover, IInformationControlCreator> thisEntry = thisIterator.next();
99 Entry<ITextHover, IInformationControlCreator> otherEntry = otherIterator.next();
100 if (!thisEntry.getKey().equals(otherEntry.getKey())) {
101 return false;
102 }
103 if (!(thisEntry.getValue() instanceof IInformationControlCreatorExtension)) {
104 return false;
105 }
106 if (!((IInformationControlCreatorExtension)thisEntry.getValue()).canReplace(otherEntry.getValue())) {
107 return false;
108 }
109 } while (thisIterator.hasNext());
110 return true;
111 }
112
113
114 @Override
115 public IInformationControl createInformationControl(Shell parent) {
116 return new CompositeInformationControl(parent, this.creators);
117 }
118
119 }
0 /*******************************************************************************
1 * Copyright (c) 2016-2017 Red Hat Inc. and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * - Mickael Istria (Red Hat Inc.)
9 *******************************************************************************/
10 package org.eclipse.ui.internal.genericeditor.hover;
11
12 import java.util.ArrayList;
13 import java.util.Collections;
14 import java.util.LinkedHashMap;
15 import java.util.List;
16 import java.util.Objects;
17 import java.util.stream.Collectors;
18
19 import org.eclipse.core.runtime.Assert;
20 import org.eclipse.jface.text.IInformationControlCreator;
21 import org.eclipse.jface.text.IRegion;
22 import org.eclipse.jface.text.ITextHover;
23 import org.eclipse.jface.text.ITextHoverExtension;
24 import org.eclipse.jface.text.ITextHoverExtension2;
25 import org.eclipse.jface.text.ITextViewer;
26 import org.eclipse.jface.text.Region;
27
28 /**
29 * A text hover that delegates its operations to children
30 * provided in constructor and returns the first interesting result.
31 *
32 * @since 1.0
33 */
34 public class CompositeTextHover implements ITextHover, ITextHoverExtension, ITextHoverExtension2 {
35
36 private final List<ITextHover> allHovers;
37 private LinkedHashMap<ITextHover, IRegion> regions = null;
38 private LinkedHashMap<ITextHover, Object> currentHovers = null;
39
40 public CompositeTextHover(List<ITextHover> hoversToConsider) {
41 Assert.isNotNull(hoversToConsider);
42 Assert.isLegal(hoversToConsider.size() > 1, "Do not compose a single hover."); //$NON-NLS-1$
43 this.allHovers = Collections.unmodifiableList(hoversToConsider);
44 }
45
46 @Override
47 public Object getHoverInfo2(ITextViewer textViewer, IRegion requestRegion) {
48 this.currentHovers = new LinkedHashMap<>();
49 for (ITextHover hover : this.allHovers) {
50 IRegion currentRegion = this.regions.get(hover);
51 if (currentRegion == null) {
52 continue;
53 }
54 Object res = hover instanceof ITextHoverExtension2 ?
55 ((ITextHoverExtension2)hover).getHoverInfo2(textViewer, currentRegion) :
56 hover.getHoverInfo(textViewer, currentRegion);
57 if (res != null) {
58 this.currentHovers.put(hover, res);
59 }
60 }
61 if (this.currentHovers.isEmpty()) {
62 return null;
63 } else if (this.currentHovers.size() == 1) {
64 return this.currentHovers.values().iterator().next();
65 } else {
66 return this.currentHovers;
67 }
68 }
69
70 @Override
71 public IInformationControlCreator getHoverControlCreator() {
72 if (this.currentHovers == null || this.currentHovers.isEmpty()) {
73 return null;
74 } else if (currentHovers.size() == 1) {
75 ITextHover hover = this.currentHovers.keySet().iterator().next();
76 return hover instanceof ITextHoverExtension ?
77 ((ITextHoverExtension)hover).getHoverControlCreator():
78 null;
79 } else {
80 return new CompositeInformationControlCreator(new ArrayList<>(this.currentHovers.keySet()));
81 }
82 }
83
84 @Override
85 public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
86 return this.allHovers.stream()
87 .map(hover -> hover.getHoverInfo(textViewer, this.regions.get(hover)))
88 .filter(Objects::nonNull)
89 .collect(Collectors.joining("\n")); //$NON-NLS-1$
90 }
91
92 @Override
93 public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
94 this.regions = new LinkedHashMap<>();
95 IRegion res = null;
96 for (ITextHover hover : this.allHovers) {
97 IRegion region = hover.getHoverRegion(textViewer, offset);
98 if (region != null) {
99 this.regions.put(hover, region);
100 if (res == null) {
101 res = region;
102 } else {
103 int startOffset = Math.max(res.getOffset(), region.getOffset());
104 int endOffset = Math.min(res.getOffset() + res.getLength(), region.getOffset() + region.getLength());
105 res = new Region(startOffset, endOffset - startOffset);
106 }
107 }
108 }
109 return res;
110 }
111
112 }
0 /*******************************************************************************
1 * Copyright (c) 2016 Red Hat Inc. and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Mickael Istria (Red Hat Inc.) - initial implementation
9 *******************************************************************************/
10 package org.eclipse.ui.internal.genericeditor.hover;
11
12 import java.util.Collection;
13 import java.util.Comparator;
14 import java.util.Map;
15 import java.util.function.Function;
16 import java.util.stream.Collectors;
17
18 import org.eclipse.core.runtime.Assert;
19 import org.eclipse.ui.internal.genericeditor.hover.TextHoverRegistry.TextHoverExtension;
20
21 /**
22 * A comparator that allows to sort elements according to their relative
23 * placement (isBefore and isAfter)
24 *TODO: generalizing to any kind of extension supporting isBefore and isAfter
25 */
26 class OrderedExtensionComparator implements Comparator<TextHoverExtension> {
27
28 private Map<String, TextHoverExtension> extensionsById;
29
30 public OrderedExtensionComparator(Collection<TextHoverExtension> extensions) {
31 Assert.isNotNull(extensions);
32 this.extensionsById = extensions.stream().collect(Collectors.toMap(TextHoverExtension::getId, Function.identity()));
33 }
34
35 @Override
36 public int compare(TextHoverExtension arg0, TextHoverExtension arg1) {
37 if (isDeclaredAsBefore(arg0, arg1) || isDeclaredAsAfter(arg1, arg0)) {
38 return -1;
39 }
40 if (isDeclaredAsAfter(arg0, arg1) || isDeclaredAsBefore(arg1, arg0)) {
41 return +1;
42 }
43 return arg0.toString().compareTo(arg1.toString());
44 }
45
46 private boolean isDeclaredAsBefore(TextHoverExtension arg0, TextHoverExtension arg1) {
47 String before0 = arg0.getIsBefore();
48 if (before0 == null) {
49 return false;
50 }
51 if ("*".equals(before0) && !"*".equals(arg1.getIsBefore())) { //$NON-NLS-1$ //$NON-NLS-2$
52 return true;
53 }
54 String id1 = arg1.getId();
55 if (id1 == null) {
56 return false;
57 }
58 if (before0.equals(id1)) {
59 return true;
60 }
61 String after1 = arg1.getIsAfter();
62 if (after1 == null) {
63 return false;
64 }
65 return isDeclaredAsAfter(arg0, this.extensionsById.get(after1));
66 }
67
68 private boolean isDeclaredAsAfter(TextHoverExtension arg0, TextHoverExtension arg1) {
69 String after0 = arg0.getIsAfter();
70 if (after0 == null) {
71 return false;
72 }
73 if ("*".equals(after0) && !"*".equals(arg1.getIsAfter())) { //$NON-NLS-1$ //$NON-NLS-2$
74 return true;
75 }
76 String id1 = arg1.getId();
77 if (id1 == null) {
78 return false;
79 }
80 if (after0.equals(id1)) {
81 return true;
82 }
83 String before1 = arg1.getIsBefore();
84 if (before1 == null) {
85 return false;
86 }
87 return isDeclaredAsAfter(arg0, this.extensionsById.get(before1));
88 }
89
90 }
0 /*******************************************************************************
1 * Copyright (c) 2016-2017 Red Hat Inc. and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * - Mickael Istria (Red Hat Inc.)
9 *******************************************************************************/
10 package org.eclipse.ui.internal.genericeditor.hover;
11
12 import java.util.HashMap;
13 import java.util.HashSet;
14 import java.util.List;
15 import java.util.Map;
16 import java.util.Set;
17 import java.util.SortedSet;
18 import java.util.TreeSet;
19 import java.util.function.Function;
20 import java.util.stream.Collectors;
21
22 import org.eclipse.core.runtime.IConfigurationElement;
23 import org.eclipse.core.runtime.IRegistryChangeEvent;
24 import org.eclipse.core.runtime.IRegistryChangeListener;
25 import org.eclipse.core.runtime.IStatus;
26 import org.eclipse.core.runtime.Platform;
27 import org.eclipse.core.runtime.Status;
28 import org.eclipse.core.runtime.content.IContentType;
29 import org.eclipse.jface.preference.IPreferenceStore;
30 import org.eclipse.jface.text.ITextHover;
31 import org.eclipse.jface.text.source.ISourceViewer;
32 import org.eclipse.ui.internal.genericeditor.GenericContentTypeRelatedExtension;
33 import org.eclipse.ui.internal.genericeditor.GenericEditorPlugin;
34 import org.eclipse.ui.texteditor.ITextEditor;
35
36 /**
37 * Text hover registry that manages the detectors
38 * contributed by the <code>org.eclipse.ui.workbench.texteditor.hoverProvider</code> extension point for
39 * targets contributed by the <code>org.eclipse.ui.workbench.texteditor.hyperlinkDetectorTargets</code> extension point.
40 *
41 * @since 1.0
42 */
43 public final class TextHoverRegistry {
44
45 private static final String EXTENSION_POINT_ID = GenericEditorPlugin.BUNDLE_ID + ".hoverProviders"; //$NON-NLS-1$
46
47 private SortedSet<TextHoverExtension> extensions;
48 private boolean outOfSync = true;
49
50 static class TextHoverExtension extends GenericContentTypeRelatedExtension<ITextHover> {
51 private static final String ID_ATTRIBUTE = "id"; //$NON-NLS-1$
52 private static final String IS_BEFORE_ATTRIBUTE = "isBefore"; //$NON-NLS-1$
53 private static final String IS_AFTER_ATTRIBUTE = "isAfter"; //$NON-NLS-1$
54
55 private String id;
56 private String isBefore;
57 private String isAfter;
58
59 public TextHoverExtension(IConfigurationElement extension) throws Exception {
60 super(extension);
61 this.id = extension.getAttribute(ID_ATTRIBUTE);
62 this.isBefore = extension.getAttribute(IS_BEFORE_ATTRIBUTE);
63 this.isAfter = extension.getAttribute(IS_AFTER_ATTRIBUTE);
64 }
65
66 public String getId() {
67 if (this.id != null) {
68 return this.id;
69 }
70 return this.extension.getContributor().getName() + '@' + toString();
71 }
72
73 public String getIsAfter() {
74 return this.isAfter;
75 }
76
77 public String getIsBefore() {
78 return this.isBefore;
79 }
80
81 IConfigurationElement getConfigurationElement() {
82 return this.extension;
83 }
84 }
85
86 public TextHoverRegistry(IPreferenceStore preferenceStore) {
87 Platform.getExtensionRegistry().addRegistryChangeListener(new IRegistryChangeListener() {
88 @Override
89 public void registryChanged(IRegistryChangeEvent event) {
90 outOfSync = true;
91 }
92 }, EXTENSION_POINT_ID);
93 }
94
95 public List<ITextHover> getAvailableHovers(ISourceViewer sourceViewer, ITextEditor editor, Set<IContentType> contentTypes) {
96 if (this.outOfSync) {
97 sync();
98 }
99 return this.extensions.stream()
100 .filter(ext -> contentTypes.contains(ext.targetContentType))
101 .filter(ext -> ext.matches(sourceViewer, editor))
102 // don't sort in the stream as the initial structure is already sorted by isAfter/isBefore
103 .map(GenericContentTypeRelatedExtension<ITextHover>::createDelegate)
104 .collect(Collectors.toList());
105 }
106
107 private void sync() {
108 Set<IConfigurationElement> toRemoveExtensions = new HashSet<>();
109 Map<IConfigurationElement, TextHoverExtension> ext = new HashMap<>();
110 if (this.extensions != null) {
111 ext = this.extensions.stream().collect(Collectors.toMap(TextHoverExtension::getConfigurationElement, Function.identity()));
112 toRemoveExtensions = ext.keySet();
113 }
114 for (IConfigurationElement extension : Platform.getExtensionRegistry().getConfigurationElementsFor(EXTENSION_POINT_ID)) {
115 toRemoveExtensions.remove(extension);
116 if (!ext.containsKey(extension)) {
117 try {
118 ext.put(extension, new TextHoverExtension(extension));
119 } catch (Exception ex) {
120 GenericEditorPlugin.getDefault().getLog().log(new Status(IStatus.ERROR, GenericEditorPlugin.BUNDLE_ID, ex.getMessage(), ex));
121 }
122 }
123 }
124 for (IConfigurationElement toRemove : toRemoveExtensions) {
125 ext.remove(toRemove);
126 }
127
128 OrderedExtensionComparator comparator = new OrderedExtensionComparator(ext.values());
129 this.extensions = new TreeSet<>(comparator);
130 this.extensions.addAll(ext.values());
131 this.outOfSync = false;
132 }
133
134 }
1616
1717 public class MarkerHoverControlCreator implements IInformationControlCreator, IInformationControlCreatorExtension {
1818
19 private final boolean showAffordanceString;
20
21 public MarkerHoverControlCreator() {
22 this(true);
23 }
24
25 public MarkerHoverControlCreator(boolean showAffordanceString) {
26 this.showAffordanceString = showAffordanceString;
27 }
28
1929 @Override
2030 public boolean canReuse(IInformationControl control) {
21 return false;
31 return control instanceof MarkerInformationControl;
2232 }
2333
2434 @Override
2535 public boolean canReplace(IInformationControlCreator creator) {
26 return false;
36 return creator instanceof MarkerHoverControlCreator;
2737 }
2838
2939 @Override
3040 public IInformationControl createInformationControl(Shell parent) {
31 return new MarkerInformationControl(parent,this);
41 return new MarkerInformationControl(parent, showAffordanceString);
3242 }
3343
3444 }
1010 package org.eclipse.ui.internal.genericeditor.markers;
1111
1212 import java.util.Collection;
13 import java.util.LinkedHashMap;
1314 import java.util.List;
1415
1516 import org.eclipse.core.resources.IMarker;
1819 import org.eclipse.core.runtime.Status;
1920 import org.eclipse.core.runtime.jobs.Job;
2021 import org.eclipse.jface.text.AbstractInformationControl;
21 import org.eclipse.jface.text.AbstractReusableInformationControlCreator;
2222 import org.eclipse.jface.text.IInformationControl;
2323 import org.eclipse.jface.text.IInformationControlCreator;
2424 import org.eclipse.jface.text.IInformationControlExtension;
4545
4646 public class MarkerInformationControl extends AbstractInformationControl implements IInformationControl, IInformationControlExtension, IInformationControlExtension2 {
4747
48 private IInformationControlCreator creator;
48 private final LinkedHashMap<IMarker, Composite> composites = new LinkedHashMap<>();
4949
50 public MarkerInformationControl(Shell parentShell, IInformationControlCreator creator) {
51 super(parentShell, EditorsUI.getTooltipAffordanceString());
52 this.creator = creator;
50 public MarkerInformationControl(Shell parentShell, boolean showAffordanceString) {
51 super(parentShell, showAffordanceString ? EditorsUI.getTooltipAffordanceString() : null);
5352 create();
5453 }
5554
6059 public boolean hasContents() {
6160 return this.markers != null && !this.markers.isEmpty();
6261 }
63
62
6463 @Override
6564 protected void createContent(Composite parent) {
6665 parent.setLayout(new RowLayout(SWT.VERTICAL));
8382 @SuppressWarnings("unchecked")
8483 @Override
8584 public void setInput(Object input) {
85 this.composites.values().forEach(Composite::dispose);
8686 this.markers = (List<IMarker>)input;
8787 for (IMarker marker : this.markers) {
8888 Composite markerComposite = new Composite(parent, SWT.NONE);
89 this.composites.put(marker, markerComposite);
8990 GridLayout gridLayout = new GridLayout(1, false);
9091 gridLayout.verticalSpacing = 0;
92 gridLayout.horizontalSpacing = 0;
93 gridLayout.marginHeight = 0;
94 gridLayout.marginWidth = 0;
9195 markerComposite.setLayout(gridLayout);
9296 Composite markerLine = new Composite(markerComposite, SWT.NONE);
93 markerLine.setLayout(new RowLayout());
94 Label markerImage = new Label(markerLine, SWT.NONE);
95 markerImage.setImage(getImage(marker));
97 RowLayout rowLayout = new RowLayout();
98 rowLayout.marginTop = 0;
99 rowLayout.marginBottom = 0;
100 rowLayout.marginLeft = 0;
101 rowLayout.marginRight = 0;
102 markerLine.setLayout(rowLayout);
103 IMarkerResolution[] resolutions = IDE.getMarkerHelpRegistry().getResolutions(marker);
104 if(resolutions.length > 0) {
105 Label markerImage = new Label(markerLine, SWT.NONE);
106 markerImage.setImage(getImage(marker));
107 }
96108 Label markerLabel = new Label(markerLine, SWT.NONE);
97109 markerLabel.setText(marker.getAttribute(IMarker.MESSAGE, "missing message")); //$NON-NLS-1$
98 for (IMarkerResolution resolution : IDE.getMarkerHelpRegistry().getResolutions(marker)) {
110 for (IMarkerResolution resolution : resolutions) {
99111 Composite resolutionComposite = new Composite(markerComposite, SWT.NONE);
100112 GridData layoutData = new GridData();
101113 layoutData.horizontalIndent = 10;
102114 resolutionComposite.setLayoutData(layoutData);
103 RowLayout rowLayout = new RowLayout();
104 rowLayout.marginBottom = 0;
105 resolutionComposite.setLayout(rowLayout);
115 RowLayout resolutionRowLayout = new RowLayout();
116 resolutionRowLayout.marginBottom = 0;
117 resolutionComposite.setLayout(resolutionRowLayout);
106118 Label resolutionImage = new Label(resolutionComposite, SWT.NONE);
107119 // TODO: try to retrieve icon from QuickFix command
108 Image resolutionPic = null;
120 Image resolutionPic = null;
109121 if (resolution instanceof IMarkerResolution2) {
110122 resolutionPic = ((IMarkerResolution2) resolution).getImage();
111123 }
134146 });
135147 }
136148 }
137 parent.pack(true);
149 parent.layout(true);
138150 }
139
151
140152 @Override
141153 public IInformationControlCreator getInformationPresenterControlCreator() {
142 return new AbstractReusableInformationControlCreator() {
143 @Override
144 protected IInformationControl doCreateInformationControl(Shell parent) {
145 return creator.createInformationControl(parent);
146 }
147 };
154 return new MarkerHoverControlCreator(false);
148155 }
149
156
150157 @Override
151158 public Point computeSizeHint() {
152159 getShell().pack();
153160 return getShell().getSize();
154161 }
155
162
156163 }
0 ###############################################################################
1 # Copyright (c) 2018 Red Hat Inc. and others.
2 # All rights reserved. This program and the accompanying materials
3 # are made available under the terms of the Eclipse Public License v1.0
4 # which accompanies this distribution, and is available at
5 # http://www.eclipse.org/legal/epl-v10.html
6 #
7 # Contributors:
8 # Alexander Kurtakov (Red Hat Inc.) - initial API and implementation
9 ###############################################################################
10 DefaultWordHighlightStrategy_OccurrencesOf=Occurrence of ''{0}''
11 Bundle-ManifestVersion: 2
22 Bundle-Name: Examples for Generic Editor
33 Bundle-SymbolicName: org.eclipse.ui.genericeditor.examples;singleton:=true
4 Bundle-Version: 1.0.0.qualifier
4 Bundle-Version: 1.1.0.qualifier
55 Bundle-Vendor: Eclipse.org
66 Bundle-RequiredExecutionEnvironment: JavaSE-1.8
77 Require-Bundle: org.eclipse.ui.genericeditor;bundle-version="1.0.0",
1010 org.eclipse.core.resources;bundle-version="3.11.0",
1111 org.eclipse.ui;bundle-version="3.108.0",
1212 org.eclipse.core.runtime;bundle-version="3.11.0",
13 org.eclipse.ui.workbench.texteditor;bundle-version="3.10.100"
13 org.eclipse.ui.workbench.texteditor;bundle-version="3.10.100",
14 org.eclipse.e4.core.commands;bundle-version="0.12.100",
15 org.eclipse.ui.ide
16 Export-Package: org.eclipse.ui.genericeditor.examples.dotproject
17 Automatic-Module-Name: org.eclipse.ui.genericeditor.examples
0 == Example project demonstrating contributing to the Generic Editor for ".project" files
1
2 This is an example of a usable and feature rich editor for .project files which contributes to the Generic Editor proposal.
3
4 To test this plug-in open a .project file with the generic editor, you may have to remove the filter in the Project Explorer / Package explorer for . files.
0 Bug 521182 - [compiler] method reference on null object should throw NPE at runtime (JLS compliance)
00 <?xml version="1.0" encoding="UTF-8"?>
11 <?eclipse version="3.4"?>
22 <!-- ====================================================================== -->
3 <!-- Copyright (c) 2016 Red Hat Inc. and others. -->
3 <!-- Copyright (c) 2016, 2017 Red Hat Inc. and others. -->
44 <!-- All rights reserved. This program and the accompanying materials -->
55 <!-- are made available under the terms of the Eclipse Public License v1.0 -->
66 <!-- which accompanies this distribution, and is available at -->
88 <!-- -->
99 <!-- Contributors: -->
1010 <!-- Sopot Cela & Mickael Istria (Red Hat Inc). -initial implementation -->
11 <!-- Lucas Bullen (Red Hat Inc.) - Bug 508829 custom reconciler support -->
12 <!-- - Bug 521382 default highlighter -->
13 <!-- Simon Scholz <simon.scholz@vogella.com> - Bug 527834 -->
1114 <!-- ====================================================================== -->
1215 <plugin>
1316 <extension
4346 </presentationReconciler>
4447 </extension>
4548 <extension
49 point="org.eclipse.ui.genericeditor.reconcilers">
50 <reconciler
51 class="org.eclipse.ui.genericeditor.examples.dotproject.FoldingReconciler"
52 contentType="org.eclipse.ui.genericeditor.examples.dotproject">
53 </reconciler>
54 <reconciler
55 class="org.eclipse.ui.genericeditor.examples.dotproject.BracketMatchingReconciler"
56 contentType="org.eclipse.ui.genericeditor.examples.dotproject">
57 </reconciler>
58 </extension>
59 <extension
4660 point="org.eclipse.ui.editors">
4761 <editorContentTypeBinding
4862 contentTypeId="org.eclipse.ui.genericeditor.examples.dotproject"
5670 contentTypeId="org.eclipse.ui.genericeditor.examples.dotproject">
5771 </participant>
5872 </extension>
59
60 </plugin>
73 <extension
74 point="org.eclipse.ui.genericeditor.autoEditStrategies">
75 <autoEditStrategy
76 class="org.eclipse.ui.genericeditor.examples.dotproject.TagAutoEditStrategy"
77 contentType="org.eclipse.ui.genericeditor.examples.dotproject">
78 </autoEditStrategy>
79 </extension>
80 <extension
81 point="org.eclipse.ui.genericeditor.highlightReconcilers">
82 <highlightReconciler
83 class="org.eclipse.ui.genericeditor.examples.dotproject.HighlightReconciler"
84 contentType="org.eclipse.ui.genericeditor.examples.dotproject">
85 </highlightReconciler>
86 </extension>
87 <extension
88 point="org.eclipse.ui.workbench.texteditor.hyperlinkDetectors">
89 <hyperlinkDetector
90 activate="true"
91 class="org.eclipse.ui.genericeditor.examples.dotproject.hyperlink.ProjectHyperlinkDetector"
92 id="org.eclipse.ui.genericeditor.examples.hyperlinkDetector"
93 name="Project Settings Hyperlink Detector"
94 targetId="org.eclipse.ui.genericeditor.GenericEditor">
95 </hyperlinkDetector>
96 </extension>
97 <!-- ================== CodeMining support for .project ================== -->
98 <!-- 1) register CodeMining provider with extension point -->
99 <extension
100 point="org.eclipse.ui.workbench.texteditor.codeMiningProviders">
101 <codeMiningProvider
102 class="org.eclipse.ui.genericeditor.examples.dotproject.codemining.ProjectReferencesCodeMiningProvider"
103 id="org.eclipse.ui.genericeditor.examples.dotproject.codemining.references"
104 label="Project references">
105 <enabledWhen>
106 <with variable="editorInput">
107 <adapt type="org.eclipse.core.resources.IFile">
108 <test property="org.eclipse.core.resources.contentTypeId" value="org.eclipse.ui.genericeditor.examples.dotproject" />
109 </adapt>
110 </with>
111 </enabledWhen>
112 </codeMiningProvider>
113 </extension>
114 <!-- 2) update CodeMining provider with a reconciler -->
115 <extension
116 point="org.eclipse.ui.genericeditor.reconcilers">
117 <reconciler
118 class="org.eclipse.jface.text.codemining.CodeMiningReconciler"
119 contentType="org.eclipse.ui.genericeditor.examples.dotproject">
120 </reconciler>
121 </extension>
122 </plugin>
1313 <parent>
1414 <artifactId>eclipse.platform.text</artifactId>
1515 <groupId>eclipse.platform.text</groupId>
16 <version>4.7.3-SNAPSHOT</version>
16 <version>4.8.0-SNAPSHOT</version>
1717 </parent>
1818 <groupId>org.eclipse.ui</groupId>
1919 <artifactId>org.eclipse.ui.genericeditor.examples</artifactId>
20 <version>1.0.0-SNAPSHOT</version>
20 <version>1.1.0-SNAPSHOT</version>
2121 <packaging>eclipse-plugin</packaging>
2222 </project>
00 /*******************************************************************************
1 * Copyright (c) 2016 Red Hat Inc. and others
1 * Copyright (c) 2016, 2017 Red Hat Inc. and others
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
99 *******************************************************************************/
1010 package org.eclipse.ui.genericeditor.examples.dotproject;
1111
12 import org.eclipse.swt.graphics.Color;
13 import org.eclipse.swt.graphics.RGB;
14 import org.eclipse.swt.widgets.Display;
15
1612 import org.eclipse.jface.text.IDocument;
1713 import org.eclipse.jface.text.TextAttribute;
1814 import org.eclipse.jface.text.presentation.PresentationReconciler;
2117 import org.eclipse.jface.text.rules.RuleBasedScanner;
2218 import org.eclipse.jface.text.rules.SingleLineRule;
2319 import org.eclipse.jface.text.rules.Token;
20 import org.eclipse.swt.SWT;
21 import org.eclipse.swt.widgets.Display;
2422
2523 public class BlueTagsPresentationReconciler extends PresentationReconciler {
2624
27 private final TextAttribute tagAttribute = new TextAttribute(new Color(Display.getCurrent(), new RGB(0,0, 255)));
28 private final TextAttribute headerAttribute = new TextAttribute(new Color(Display.getCurrent(), new RGB(128,128,128)));
25 private final TextAttribute tagAttribute = new TextAttribute(Display.getCurrent().getSystemColor(SWT.COLOR_BLUE));
26 private final TextAttribute headerAttribute = new TextAttribute(Display.getCurrent().getSystemColor(SWT.COLOR_DARK_GRAY));
2927
3028 public BlueTagsPresentationReconciler() {
3129 RuleBasedScanner scanner= new RuleBasedScanner();
0 /*******************************************************************************
1 * Copyright (c) 2017 Red Hat Inc. and others
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Lucas Bullen (Red Hat Inc.) - initial implementation
9 *******************************************************************************/
10 package org.eclipse.ui.genericeditor.examples.dotproject;
11
12 import org.eclipse.jface.text.BadLocationException;
13 import org.eclipse.jface.text.IDocument;
14 import org.eclipse.jface.text.IRegion;
15 import org.eclipse.jface.text.ITextViewer;
16 import org.eclipse.jface.text.ITextViewerExtension2;
17 import org.eclipse.jface.text.Region;
18 import org.eclipse.jface.text.reconciler.IReconciler;
19 import org.eclipse.jface.text.reconciler.IReconcilingStrategy;
20 import org.eclipse.jface.text.source.ICharacterPairMatcher;
21 import org.eclipse.jface.text.source.MatchingCharacterPainter;
22 import org.eclipse.jface.text.source.SourceViewer;
23 import org.eclipse.swt.graphics.Color;
24 import org.eclipse.swt.graphics.RGBA;
25 import org.eclipse.swt.widgets.Display;
26
27 public class BracketMatchingReconciler implements IReconciler{
28 private RGBA fBoxingRGB = new RGBA(155, 155, 155, 50);
29 private MatchingCharacterPainter fMatchingCharacterPainter;
30 private SourceViewer fSourceViewer;
31 private ICharacterPairMatcher fCharacterPairMatcher = new ICharacterPairMatcher() {
32 @Override
33 public IRegion match(IDocument document, int offset){
34 try {
35 String before = document.get(0, offset);
36 String after = document.get(offset, document.getLength() - offset);
37 int closingIndex = after.indexOf('>');
38 int openingIndex = before.lastIndexOf('<');
39 int previousClosingIndex = after.indexOf('<');
40 int previousOpeningIndex = before.lastIndexOf('>');
41 if((previousClosingIndex != -1 && closingIndex > previousClosingIndex)
42 || (previousOpeningIndex != -1 && openingIndex < previousOpeningIndex)) {
43 return null;
44 }
45 return new Region(openingIndex, offset - openingIndex + closingIndex + 1);
46 } catch (BadLocationException e) {
47 return null;
48 }
49 }
50
51 @Override
52 public int getAnchor() {
53 return ICharacterPairMatcher.RIGHT;
54 }
55
56 @Override
57 public void dispose() {
58 if(fMatchingCharacterPainter != null) {
59 fMatchingCharacterPainter.dispose();
60 }
61 }
62
63 @Override
64 public void clear() {
65 // No memory implemented
66 }
67 };
68
69 @Override
70 public void install(ITextViewer textViewer) {
71 if (textViewer instanceof ITextViewerExtension2 && textViewer instanceof SourceViewer) {
72 fSourceViewer = (SourceViewer)textViewer;
73 fMatchingCharacterPainter = new MatchingCharacterPainter(fSourceViewer, fCharacterPairMatcher);
74 fMatchingCharacterPainter.setColor(new Color (Display.getCurrent(), fBoxingRGB));
75 fMatchingCharacterPainter.setHighlightCharacterAtCaretLocation(true);
76 fMatchingCharacterPainter.setHighlightEnclosingPeerCharacters(true);
77 fSourceViewer.addPainter(fMatchingCharacterPainter);
78 }
79 }
80
81 @Override
82 public void uninstall() {
83 fSourceViewer.removePainter(fMatchingCharacterPainter);
84 }
85
86 @Override
87 public IReconcilingStrategy getReconcilingStrategy(String contentType) {
88 return null;
89 }
90 }
0 /*******************************************************************************
1 * Copyright (c) 2017 Red Hat Inc. and others
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Lucas Bullen (Red Hat Inc.) - initial implementation
9 *******************************************************************************/
10 package org.eclipse.ui.genericeditor.examples.dotproject;
11
12 import org.eclipse.jface.text.IDocument;
13 import org.eclipse.jface.text.ITextViewer;
14 import org.eclipse.jface.text.reconciler.Reconciler;
15 import org.eclipse.jface.text.source.projection.ProjectionViewer;
16
17 public class FoldingReconciler extends Reconciler {
18
19 private FoldingStrategy fStrategy;
20
21 public FoldingReconciler() {
22 fStrategy = new FoldingStrategy();
23 this.setReconcilingStrategy(fStrategy, IDocument.DEFAULT_CONTENT_TYPE);
24 }
25
26 @Override
27 public void install(ITextViewer textViewer) {
28 super.install(textViewer);
29 ProjectionViewer pViewer =(ProjectionViewer)textViewer;
30 fStrategy.setProjectionViewer(pViewer);
31 }
32 }
0 /*******************************************************************************
1 * Copyright (c) 2017 Red Hat Inc. and others
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Lucas Bullen (Red Hat Inc.) - initial implementation
9 *******************************************************************************/
10 package org.eclipse.ui.genericeditor.examples.dotproject;
11
12 import java.util.ArrayList;
13 import java.util.HashMap;
14 import java.util.List;
15 import java.util.Map;
16
17 import org.eclipse.core.runtime.IProgressMonitor;
18 import org.eclipse.jface.text.BadLocationException;
19 import org.eclipse.jface.text.IDocument;
20 import org.eclipse.jface.text.IRegion;
21 import org.eclipse.jface.text.Position;
22 import org.eclipse.jface.text.reconciler.DirtyRegion;
23 import org.eclipse.jface.text.reconciler.IReconcilingStrategy;
24 import org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension;
25 import org.eclipse.jface.text.source.Annotation;
26 import org.eclipse.jface.text.source.projection.ProjectionAnnotation;
27 import org.eclipse.jface.text.source.projection.ProjectionViewer;
28
29 public class FoldingStrategy implements IReconcilingStrategy, IReconcilingStrategyExtension {
30
31 private IDocument document;
32 private String oldDocument;
33 private ProjectionViewer projectionViewer;
34 private List<Annotation> oldAnnotations = new ArrayList<>();
35 private List<Position> oldPositions = new ArrayList<>();
36
37 @Override
38 public void setDocument(IDocument document) {
39 this.document = document;
40 }
41
42 public void setProjectionViewer(ProjectionViewer projectionViewer) {
43 this.projectionViewer = projectionViewer;
44 }
45
46 @Override
47 public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) {
48 initialReconcile();
49 }
50
51 @Override
52 public void reconcile(IRegion partition) {
53 initialReconcile();
54 }
55
56 @Override
57 public void initialReconcile() {
58 if(document.get().equals(oldDocument)) return;
59 oldDocument = document.get();
60
61 List<Position> positions = getNewPositionsOfAnnotations();
62
63 List<Position> positionsToRemove = new ArrayList<>();
64 List<Annotation> annotationToRemove = new ArrayList<>();
65
66 for (Position position : oldPositions) {
67 if(!positions.contains(position)) {
68 projectionViewer.getProjectionAnnotationModel().removeAnnotation(oldAnnotations.get(oldPositions.indexOf(position)));
69 positionsToRemove.add(position);
70 annotationToRemove.add(oldAnnotations.get(oldPositions.indexOf(position)));
71 }else {
72 positions.remove(position);
73 }
74 }
75 oldPositions.removeAll(positionsToRemove);
76 oldAnnotations.removeAll(annotationToRemove);
77
78 for (Position position : positions) {
79 Annotation annotation = new ProjectionAnnotation();
80 projectionViewer.getProjectionAnnotationModel().addAnnotation(annotation, position);
81 oldPositions.add(position);
82 oldAnnotations.add(annotation);
83 }
84 }
85
86 private static enum SearchingFor {
87 START_OF_TAG, START_OF_WORD, END_OF_WORD, END_OF_LINE
88 }
89
90 private List<Position> getNewPositionsOfAnnotations(){
91 List<Position> positions = new ArrayList<>();
92 Map<String, Integer> startOfAnnotation = new HashMap<>();
93 SearchingFor searchingFor = SearchingFor.START_OF_TAG;
94
95 int characters = document.getLength();
96 int currentCharIndex = 0;
97
98 int wordStartIndex = 0;
99 int sectionStartIndex = 0;
100 String word = "";
101
102 try {
103 while (currentCharIndex < characters) {
104 char currentChar = document.getChar(currentCharIndex);
105 switch (searchingFor) {
106 case START_OF_TAG:
107 if(currentChar == '<') {
108 char nextChar = document.getChar(currentCharIndex+1);
109 if(nextChar != '?') {
110 sectionStartIndex = currentCharIndex;
111 searchingFor = SearchingFor.START_OF_WORD;
112 }
113 }
114 break;
115 case START_OF_WORD:
116 if(Character.isLetter(currentChar)) {
117 wordStartIndex = currentCharIndex;
118 searchingFor = SearchingFor.END_OF_WORD;
119 }
120 break;
121 case END_OF_WORD:
122 if(!Character.isLetter(currentChar)) {
123 word = document.get(wordStartIndex, currentCharIndex - wordStartIndex);
124 if(startOfAnnotation.containsKey(word)) {
125 searchingFor = SearchingFor.END_OF_LINE;
126 }else {
127 startOfAnnotation.put(word, sectionStartIndex);
128 searchingFor = SearchingFor.START_OF_TAG;
129 }
130 }
131 break;
132 case END_OF_LINE:
133 if(currentChar == '\n') {
134 int start = startOfAnnotation.get(word);
135 if(document.getLineOfOffset(start) != document.getLineOfOffset(currentCharIndex)) {
136 positions.add(new Position(start,currentCharIndex + 1 - start));
137 }
138 startOfAnnotation.remove(word);
139 searchingFor = SearchingFor.START_OF_TAG;
140 }
141 break;
142 }
143 currentCharIndex++;
144 }
145 } catch (BadLocationException e) {
146 // skip the remainder of file due to error
147 }
148 return positions;
149 }
150
151 @Override
152 public void setProgressMonitor(IProgressMonitor monitor) {
153 // no progress monitor used
154 }
155
156 }
0 /*******************************************************************************
1 * Copyright (c) 2017 Red Hat Inc. and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * - Lucas Bullen (Red Hat Inc.)
9 *******************************************************************************/
10 package org.eclipse.ui.genericeditor.examples.dotproject;
11
12 import org.eclipse.jface.text.IDocument;
13 import org.eclipse.jface.text.ITextViewer;
14 import org.eclipse.jface.text.reconciler.Reconciler;
15
16 public class HighlightReconciler extends Reconciler {
17
18 private HighlightStrategy fStrategy;
19
20 public HighlightReconciler() {
21 fStrategy = new HighlightStrategy();
22 this.setReconcilingStrategy(fStrategy, IDocument.DEFAULT_CONTENT_TYPE);
23 }
24
25 @Override
26 public void install(ITextViewer textViewer) {
27 super.install(textViewer);
28 fStrategy.install(textViewer);
29 }
30
31 @Override
32 public void uninstall() {
33 super.uninstall();
34 fStrategy.uninstall();
35 }
36 }
0 /*******************************************************************************
1 * Copyright (c) 2017 Red Hat Inc. and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * - Lucas Bullen (Red Hat Inc.)
9 *******************************************************************************/
10 package org.eclipse.ui.genericeditor.examples.dotproject;
11
12 import java.util.HashMap;
13 import java.util.Iterator;
14 import java.util.Map;
15 import java.util.Map.Entry;
16 import java.util.regex.Matcher;
17 import java.util.regex.Pattern;
18
19 import org.eclipse.core.runtime.IProgressMonitor;
20 import org.eclipse.core.runtime.preferences.IEclipsePreferences;
21 import org.eclipse.core.runtime.preferences.IEclipsePreferences.IPreferenceChangeListener;
22 import org.eclipse.core.runtime.preferences.IEclipsePreferences.PreferenceChangeEvent;
23 import org.eclipse.core.runtime.preferences.InstanceScope;
24 import org.eclipse.jface.text.IDocument;
25 import org.eclipse.jface.text.IRegion;
26 import org.eclipse.jface.text.ISynchronizable;
27 import org.eclipse.jface.text.ITextViewer;
28 import org.eclipse.jface.text.ITextViewerExtension5;
29 import org.eclipse.jface.text.Position;
30 import org.eclipse.jface.text.reconciler.DirtyRegion;
31 import org.eclipse.jface.text.reconciler.IReconcilingStrategy;
32 import org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension;
33 import org.eclipse.jface.text.source.Annotation;
34 import org.eclipse.jface.text.source.IAnnotationModel;
35 import org.eclipse.jface.text.source.IAnnotationModelExtension;
36 import org.eclipse.jface.text.source.ISourceViewer;
37 import org.eclipse.swt.custom.CaretEvent;
38 import org.eclipse.swt.custom.CaretListener;
39
40 /**
41 *
42 * This Reconciler Strategy is an example for how to override the default highlight strategy.
43 * It will highlight closing and opening tag names that match the current word the user is on.
44 *
45 */
46 public class HighlightStrategy implements IReconcilingStrategy, IReconcilingStrategyExtension, CaretListener, IPreferenceChangeListener {
47
48 private static final String ANNOTATION_TYPE = "org.eclipse.ui.genericeditor.text"; //$NON-NLS-1$
49 public static final String TOGGLE_HIGHLIGHT_PREFERENCE = "org.eclipse.ui.genericeditor.togglehighlight"; //$NON-NLS-1$
50 public static final String GENERIC_EDITOR_BUNDLE_ID = "org.eclipse.ui.genericeditor"; //$NON-NLS-1$
51
52 private boolean enabled;
53 private ISourceViewer sourceViewer;
54 private IDocument document;
55
56 private static final String TAG_NAME_REGEX = "<\\/?\\s*([a-zA-Z]+)"; //$NON-NLS-1$
57 private static final Pattern TAG_NAME_PATTERN = Pattern.compile(TAG_NAME_REGEX);
58
59 private Annotation[] fOccurrenceAnnotations = null;
60
61 private void applyHighlights(int offset) {
62 if (sourceViewer == null || !enabled) {
63 return;
64 }
65 String text = document.get();
66 offset = ((ITextViewerExtension5)sourceViewer).widgetOffset2ModelOffset(offset);
67
68 int wordStartOffset = Math.max(text.lastIndexOf('/',offset),text.lastIndexOf('<',offset))+1;
69 int wordEndOffset = findEndingOffset(text, offset);
70 if(wordEndOffset <= wordStartOffset || wordEndOffset == -1 || wordStartOffset == -1)
71 return;
72 String word = text.substring(wordStartOffset, wordEndOffset);
73 if(word.indexOf('>') != -1 || word.indexOf('<') != -1) {
74 removeOccurrenceAnnotations();
75 return;
76 }
77
78 Matcher m = TAG_NAME_PATTERN.matcher(text);
79 Map<Annotation, Position> annotationMap = new HashMap<>();
80 while(m.find()) {
81 if(m.group(1).equals(word)) {
82 annotationMap.put(new Annotation(ANNOTATION_TYPE, false, null),
83 new Position(m.start(1), m.end(1) - m.start(1)));
84 }
85 }
86
87 if(annotationMap.size() < 2) {
88 removeOccurrenceAnnotations();
89 return;
90 }
91
92 IAnnotationModel annotationModel = sourceViewer.getAnnotationModel();
93 synchronized (getLockObject(annotationModel)) {
94 if (annotationModel instanceof IAnnotationModelExtension) {
95 ((IAnnotationModelExtension) annotationModel).replaceAnnotations(fOccurrenceAnnotations, annotationMap);
96 } else {
97 removeOccurrenceAnnotations();
98 Iterator<Entry<Annotation, Position>> iter = annotationMap.entrySet().iterator();
99 while (iter.hasNext()) {
100 Entry<Annotation, Position> mapEntry = iter.next();
101 annotationModel.addAnnotation(mapEntry.getKey(), mapEntry.getValue());
102 }
103 }
104 fOccurrenceAnnotations = annotationMap.keySet().toArray(new Annotation[annotationMap.keySet().size()]);
105 }
106 }
107
108 private static int findEndingOffset(String text, int offset) {
109 String substring = text.substring(offset);
110 String[] split = substring.split("[^a-zA-Z0-9]+");//$NON-NLS-1$
111 if(split.length == 0) {
112 return -1;
113 }
114 return offset + split[0].length();
115 }
116
117 public void install(ITextViewer viewer) {
118 if (!(viewer instanceof ISourceViewer)) {
119 return;
120 }
121 IEclipsePreferences preferences = InstanceScope.INSTANCE.getNode(GENERIC_EDITOR_BUNDLE_ID);
122 preferences.addPreferenceChangeListener(this);
123 this.enabled = preferences.getBoolean(TOGGLE_HIGHLIGHT_PREFERENCE, true);
124 this.sourceViewer = (ISourceViewer) viewer;
125 this.sourceViewer.getTextWidget().addCaretListener(this);
126 }
127
128 public void uninstall() {
129 if (sourceViewer != null) {
130 sourceViewer.getTextWidget().removeCaretListener(this);
131 }
132 IEclipsePreferences preferences = InstanceScope.INSTANCE.getNode(GENERIC_EDITOR_BUNDLE_ID);
133 preferences.removePreferenceChangeListener(this);
134 }
135
136 @Override
137 public void preferenceChange(PreferenceChangeEvent event) {
138 if (event.getKey().equals(TOGGLE_HIGHLIGHT_PREFERENCE)) {
139 this.enabled = Boolean.parseBoolean(event.getNewValue().toString());
140 if (enabled) {
141 initialReconcile();
142 } else {
143 removeOccurrenceAnnotations();
144 }
145 }
146 }
147
148 @Override
149 public void caretMoved(CaretEvent event) {
150 applyHighlights(event.caretOffset);
151 }
152
153 @Override
154 public void initialReconcile() {
155 if (sourceViewer != null) {
156 sourceViewer.getTextWidget().getDisplay().asyncExec(() -> {
157 if (sourceViewer != null && sourceViewer.getTextWidget() != null) {
158 applyHighlights(sourceViewer.getTextWidget().getCaretOffset());
159 }
160 });
161 }
162 }
163
164 void removeOccurrenceAnnotations() {
165 IAnnotationModel annotationModel = sourceViewer.getAnnotationModel();
166 if (annotationModel == null || fOccurrenceAnnotations == null)
167 return;
168
169 synchronized (getLockObject(annotationModel)) {
170 if (annotationModel instanceof IAnnotationModelExtension) {
171 ((IAnnotationModelExtension) annotationModel).replaceAnnotations(fOccurrenceAnnotations, null);
172 } else {
173 for (Annotation fOccurrenceAnnotation : fOccurrenceAnnotations)
174 annotationModel.removeAnnotation(fOccurrenceAnnotation);
175 }
176 fOccurrenceAnnotations = null;
177 }
178 }
179
180 private static Object getLockObject(IAnnotationModel annotationModel) {
181 if (annotationModel instanceof ISynchronizable) {
182 Object lock = ((ISynchronizable) annotationModel).getLockObject();
183 if (lock != null)
184 return lock;
185 }
186 return annotationModel;
187 }
188
189 @Override
190 public void setDocument(IDocument document) {
191 this.document = document;
192 }
193
194 @Override
195 public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) {
196 // Do nothing
197 }
198
199 @Override
200 public void reconcile(IRegion partition) {
201 // Do nothing
202 }
203
204 @Override
205 public void setProgressMonitor(IProgressMonitor monitor) {
206 // Not used
207 }
208 }
00 /*******************************************************************************
1 * Copyright (c) 2016 Red Hat Inc. and others
1 * Copyright (c) 2016, 2017 Red Hat Inc. and others
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
66 *
77 * Contributors:
88 * Mickael Istria, Sopot Cela (Red Hat Inc.)
9 * Lucas Bullen (Red Hat Inc.) - [Bug 527071] Hover breaks with missing nature
910 *******************************************************************************/
1011 package org.eclipse.ui.genericeditor.examples.dotproject;
1112
3839 if (natureDescriptors[i].getNatureId().equals(selection))
3940 return natureDescriptors[i].getLabel();
4041 }
41 return "";
42 return null;
4243 }
4344
4445 @Override
1313 import org.eclipse.core.resources.IProjectNatureDescriptor;
1414 import org.eclipse.core.resources.IWorkspace;
1515 import org.eclipse.core.resources.ResourcesPlugin;
16
1716 import org.eclipse.jface.text.ITextViewer;
1817 import org.eclipse.jface.text.contentassist.CompletionProposal;
1918 import org.eclipse.jface.text.contentassist.ICompletionProposal;
2221 import org.eclipse.jface.text.contentassist.IContextInformationValidator;
2322
2423 public class NaturesAndProjectsContentAssistProcessor implements IContentAssistProcessor {
24
25 public NaturesAndProjectsContentAssistProcessor() {
26 // TODO Auto-generated constructor stub
27 }
2528
2629 @Override
2730 public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) {
66 *
77 * Contributors:
88 * - Mickael Istria (Red Hat Inc.)
9 * - Lucas Bullen (Red Hat Inc.) - avoid NPE for when TextFileBuffer does not exist
910 *******************************************************************************/
1011 package org.eclipse.ui.genericeditor.examples.dotproject;
1112
1415 import java.util.Map;
1516 import java.util.Set;
1617
18 import org.eclipse.core.filebuffers.ITextFileBuffer;
1719 import org.eclipse.core.filebuffers.ITextFileBufferManager;
1820 import org.eclipse.core.runtime.IProgressMonitor;
1921 import org.eclipse.core.runtime.IStatus;
4951 this.lastJob = new Job("Spellcheck") {
5052 @Override
5153 protected IStatus run(IProgressMonitor monitor) {
52 IAnnotationModel model = ITextFileBufferManager.DEFAULT.getTextFileBuffer(event.getDocument()).getAnnotationModel();
54 ITextFileBuffer iTextFileBuffer = ITextFileBufferManager.DEFAULT.getTextFileBuffer(event.getDocument());
55 if(iTextFileBuffer == null) {
56 return Status.CANCEL_STATUS;
57 }
58 IAnnotationModel model = iTextFileBuffer.getAnnotationModel();
5359 String text = event.getDocument().get();
5460 int commentStart = text.indexOf("<comment>");
5561 if (commentStart < 0) {
0 /*******************************************************************************
1 * Copyright (c) 2017 Rogue Wave Software Inc. and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Michał Niewrzał (Rogue Wave Software Inc.) - initial implementation
9 *******************************************************************************/
10 package org.eclipse.ui.genericeditor.examples.dotproject;
11
12 import org.eclipse.jface.text.BadLocationException;
13 import org.eclipse.jface.text.DocumentCommand;
14 import org.eclipse.jface.text.IAutoEditStrategy;
15 import org.eclipse.jface.text.IDocument;
16 import org.eclipse.jface.text.IRegion;
17
18 public class TagAutoEditStrategy implements IAutoEditStrategy {
19
20 public TagAutoEditStrategy() {
21 // TODO Auto-generated constructor stub
22 }
23
24 @Override
25 public void customizeDocumentCommand(IDocument document, DocumentCommand command) {
26 if (!">".equals(command.text)) { //$NON-NLS-1$
27 return;
28 }
29 try {
30 IRegion region = document.getLineInformationOfOffset(command.offset);
31 String line = document.get(region.getOffset(), command.offset - region.getOffset());
32 int index = line.lastIndexOf('<');
33 if (index != -1 && (index != line.length() - 1) && line.charAt(index + 1) != '/') {
34 String tag = line.substring(index + 1);
35 command.text += "</" + tag + command.text; //$NON-NLS-1$
36 }
37 } catch (BadLocationException e) {
38 e.printStackTrace();
39 }
40 }
41
42 }
0 /**
1 * Copyright (c) 2017 Angelo ZERR.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Provide extension point for CodeMining - Bug 528419
9 */
10 package org.eclipse.ui.genericeditor.examples.dotproject.codemining;
11
12 import java.util.concurrent.CompletableFuture;
13
14 import org.eclipse.core.resources.IProject;
15 import org.eclipse.core.resources.ResourcesPlugin;
16 import org.eclipse.core.runtime.IProgressMonitor;
17 import org.eclipse.jface.text.BadLocationException;
18 import org.eclipse.jface.text.IDocument;
19 import org.eclipse.jface.text.ITextViewer;
20 import org.eclipse.jface.text.codemining.ICodeMiningProvider;
21 import org.eclipse.jface.text.codemining.LineHeaderCodeMining;
22
23 /**
24 * Project reference mining.
25 */
26 public class ProjectReferenceCodeMining extends LineHeaderCodeMining {
27
28 private final String projectName;
29
30 public ProjectReferenceCodeMining(String projectName, int beforeLineNumber, IDocument document,
31 ICodeMiningProvider provider) throws BadLocationException {
32 super(beforeLineNumber, document, provider);
33 this.projectName = projectName;
34 }
35
36 @Override
37 protected CompletableFuture<Void> doResolve(ITextViewer viewer, IProgressMonitor monitor) {
38 return CompletableFuture.runAsync(() -> {
39 IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
40 int refCount = project != null ? project.getReferencingProjects().length : 0;
41 super.setLabel(refCount + (refCount > 1 ? " references" : " reference"));
42 });
43 }
44
45 }
0 /**
1 * Copyright (c) 2017 Angelo ZERR.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Provide extension point for CodeMining - Bug 528419
9 */
10 package org.eclipse.ui.genericeditor.examples.dotproject.codemining;
11
12 import java.util.ArrayList;
13 import java.util.List;
14 import java.util.concurrent.CompletableFuture;
15
16 import org.eclipse.core.runtime.IProgressMonitor;
17 import org.eclipse.jface.text.BadLocationException;
18 import org.eclipse.jface.text.IDocument;
19 import org.eclipse.jface.text.ITextViewer;
20 import org.eclipse.jface.text.codemining.AbstractCodeMiningProvider;
21 import org.eclipse.jface.text.codemining.ICodeMining;
22
23 /**
24 * Project reference minings provider.
25 */
26 public class ProjectReferencesCodeMiningProvider extends AbstractCodeMiningProvider {
27
28 @Override
29 public CompletableFuture<List<? extends ICodeMining>> provideCodeMinings(ITextViewer viewer,
30 IProgressMonitor monitor) {
31 return CompletableFuture.supplyAsync(() -> {
32 IDocument document = viewer.getDocument();
33 List<ICodeMining> minings = new ArrayList<>();
34 int lineCount = document.getNumberOfLines();
35 for (int i = 0; i < lineCount; i++) {
36 // check if request was canceled.
37 monitor.isCanceled();
38 String line = getLineText(document, i).trim();
39 int startIndex = line.indexOf("<name>");
40 if (startIndex != -1) {
41 // It's the first name, we consider we are in <projectDescription></name>
42 startIndex += "<name>".length();
43 int endIndex = line.indexOf("</name>");
44 if (endIndex > startIndex) {
45 // Check if parent element is projectDescription
46 String projectName = line.substring(startIndex, endIndex);
47 if (projectName.length() > 0) {
48 try {
49 minings.add(new ProjectReferenceCodeMining(projectName, i, document, this));
50 } catch (BadLocationException e) {
51 e.printStackTrace();
52 }
53 }
54 }
55 // stop the compute of minings to avoid process other name like
56 // <buildCommand><name>
57 break;
58 }
59 }
60 return minings;
61 });
62 }
63
64 private static String getLineText(IDocument document, int line) {
65 try {
66 int lo = document.getLineOffset(line);
67 int ll = document.getLineLength(line);
68 return document.get(lo, ll);
69 } catch (Exception e) {
70 e.printStackTrace();
71 return null;
72 }
73 }
74 }
0 /*******************************************************************************
1 * Copyright (c) 2017 vogella GmbH and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * - Simon Scholz <simon.scholz@vogella.com> - initial implementation
9 *******************************************************************************/
10 package org.eclipse.ui.genericeditor.examples.dotproject.hyperlink;
11
12 import org.eclipse.core.resources.IResource;
13 import org.eclipse.jface.text.IRegion;
14 import org.eclipse.jface.text.ITextViewer;
15 import org.eclipse.jface.text.hyperlink.AbstractHyperlinkDetector;
16 import org.eclipse.jface.text.hyperlink.IHyperlink;
17 import org.eclipse.jface.text.hyperlink.URLHyperlink;
18 import org.eclipse.osgi.util.TextProcessor;
19 import org.eclipse.ui.internal.ide.dialogs.IDEResourceInfoUtils;
20 import org.eclipse.ui.texteditor.ITextEditor;
21
22 @SuppressWarnings("restriction")
23 public class ProjectHyperlinkDetector extends AbstractHyperlinkDetector {
24
25 @Override
26 public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) {
27 ITextEditor textEditor = getAdapter(ITextEditor.class);
28
29 IResource resource = textEditor.getEditorInput().getAdapter(IResource.class);
30
31 String fileLocation = TextProcessor.process(IDEResourceInfoUtils.getLocationText(resource));
32
33 ShowInSystemExplorerHyperlink showInSystemExplorerHyperlink = new ShowInSystemExplorerHyperlink(fileLocation,
34 region);
35
36 URLHyperlink fileUrlHyperlink = new URLHyperlink(region, fileLocation);
37
38 URLHyperlink projectFileHelpLink = new URLHyperlink(region,
39 "https://help.eclipse.org/oxygen/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fmisc%2Fproject_description_file.html");
40
41 return new IHyperlink[] { showInSystemExplorerHyperlink, fileUrlHyperlink, projectFileHelpLink };
42 }
43
44 }
0 /*******************************************************************************
1 * Copyright (c) 2017 vogella GmbH and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * - Simon Scholz <simon.scholz@vogella.com> - initial implementation
9 *******************************************************************************/
10 package org.eclipse.ui.genericeditor.examples.dotproject.hyperlink;
11
12 import java.util.Collections;
13
14 import org.eclipse.core.commands.Command;
15 import org.eclipse.core.commands.ParameterizedCommand;
16 import org.eclipse.e4.core.commands.ECommandService;
17 import org.eclipse.e4.core.commands.EHandlerService;
18 import org.eclipse.jface.text.IRegion;
19 import org.eclipse.jface.text.hyperlink.IHyperlink;
20 import org.eclipse.ui.PlatformUI;
21 import org.eclipse.ui.internal.ide.handlers.ShowInSystemExplorerHandler;
22
23 @SuppressWarnings("restriction")
24 public class ShowInSystemExplorerHyperlink implements IHyperlink {
25
26 private String fileLocation;
27 private IRegion region;
28
29 public ShowInSystemExplorerHyperlink(String fileLocation, IRegion region) {
30 this.fileLocation = fileLocation;
31 this.region = region;
32 }
33
34 @Override
35 public IRegion getHyperlinkRegion() {
36 return region;
37 }
38
39 @Override
40 public String getTypeLabel() {
41 return null;
42 }
43
44 @Override
45 public String getHyperlinkText() {
46 return "Show in System Explorer";
47 }
48
49 @Override
50 public void open() {
51 ECommandService commandService = PlatformUI.getWorkbench().getService(ECommandService.class);
52 EHandlerService handlerService = PlatformUI.getWorkbench().getService(EHandlerService.class);
53
54 Command command = commandService.getCommand(ShowInSystemExplorerHandler.ID);
55 if (command.isDefined()) {
56 ParameterizedCommand parameterizedCommand = commandService.createCommand(ShowInSystemExplorerHandler.ID,
57 Collections.singletonMap(ShowInSystemExplorerHandler.RESOURCE_PATH_PARAMETER, fileLocation));
58 if (handlerService.canExecute(parameterizedCommand)) {
59 handlerService.executeHandler(parameterizedCommand);
60 }
61 }
62 }
63
64 }
11 Bundle-ManifestVersion: 2
22 Bundle-Name: %Plugin.name
33 Bundle-SymbolicName: org.eclipse.ui.genericeditor.tests;singleton:=true
4 Bundle-Version: 1.0.0.qualifier
4 Bundle-Version: 1.1.0.qualifier
55 Bundle-Vendor: %Plugin.providerName
66 Bundle-Localization: plugin
77 Export-Package: org.eclipse.ui.genericeditor.tests,
1919 org.eclipse.jface.text.tests;bundle-version="3.11.100",
2020 org.eclipse.text.tests;bundle-version="3.11.0",
2121 org.eclipse.ui.workbench.texteditor.tests;bundle-version="3.11.100",
22 org.eclipse.ui.editors;bundle-version="3.11.0"
22 org.eclipse.ui.editors;bundle-version="3.11.0",
23 org.eclipse.core.expressions
2324 Bundle-RequiredExecutionEnvironment: JavaSE-1.8
2425 Eclipse-BundleShape: dir
2526 Bundle-ActivationPolicy: lazy
27 Automatic-Module-Name: org.eclipse.ui.genericeditor.tests
00 <?xml version="1.0" encoding="UTF-8"?>
11 <?eclipse version="3.4"?>
22 <!-- ====================================================================== -->
3 <!-- Copyright (c) 2016 Red Hat Inc. and others. -->
3 <!-- Copyright (c) 2016, 2017 Red Hat Inc. and others. -->
44 <!-- All rights reserved. This program and the accompanying materials -->
55 <!-- are made available under the terms of the Eclipse Public License v1.0 -->
66 <!-- which accompanies this distribution, and is available at -->
88 <!-- -->
99 <!-- Contributors: -->
1010 <!-- Sopot Cela & Mickael Istria (Red Hat Inc). -initial implementation -->
11 <!-- Lucas Bullen (Red Hat Inc.) - Bug 508829 custom reconciler support -->
12 <!-- - Bug 521382 default highlighter -->
1113 <!-- ====================================================================== -->
1214 <plugin>
13 <extension
14 point="org.eclipse.ui.genericeditor.contentAssistProcessors">
15 <extension
16 point="org.eclipse.ui.genericeditor.contentAssistProcessors">
1517 <contentAssistProcessor
16 class="org.eclipse.ui.genericeditor.tests.contributions.BarContentAssistProcessor"
17 contentType="org.eclipse.ui.genericeditor.tests.content-type">
18 class="org.eclipse.ui.genericeditor.tests.contributions.BarContentAssistProcessor"
19 contentType="org.eclipse.ui.genericeditor.tests.content-type">
1820 </contentAssistProcessor>
19 <contentAssistProcessor
20 class="org.eclipse.ui.genericeditor.tests.contributions.LongRunningBarContentAssistProcessor"
21 contentType="org.eclipse.ui.genericeditor.tests.content-type">
22 </contentAssistProcessor>
23 </extension>
24 <extension
25 point="org.eclipse.ui.genericeditor.hoverProviders">
26 <hoverProvider
27 class="org.eclipse.ui.genericeditor.tests.contributions.MagicHoverProvider"
28 contentType="org.eclipse.ui.genericeditor.tests.content-type">
29 </hoverProvider>
30 </extension>
31 <extension
32 point="org.eclipse.ui.genericeditor.presentationReconcilers">
21 <contentAssistProcessor
22 class="org.eclipse.ui.genericeditor.tests.contributions.LongRunningBarContentAssistProcessor"
23 contentType="org.eclipse.ui.genericeditor.tests.specialized-content-type">
24 </contentAssistProcessor>
25 <contentAssistProcessor
26 class="org.eclipse.ui.genericeditor.tests.contributions.BarContentAssistProcessor"
27 contentType="org.eclipse.ui.genericeditor.tests.enabled-when-content-type">
28 <enabledWhen>
29 <test
30 forcePluginActivation="true"
31 property="org.eclipse.ui.genericeditor.tests.contributions.enabled">
32 </test>
33 </enabledWhen>
34 </contentAssistProcessor>
35 </extension>
36 <extension
37 point="org.eclipse.ui.genericeditor.hoverProviders">
38 <hoverProvider
39 class="org.eclipse.ui.genericeditor.tests.contributions.AlrightyHoverProvider"
40 contentType="org.eclipse.ui.genericeditor.tests.enabled-when-content-type">
41 <enabledWhen>
42 <test
43 forcePluginActivation="true"
44 property="org.eclipse.ui.genericeditor.tests.contributions.enabled">
45 </test>
46 </enabledWhen>
47 </hoverProvider>
48 <hoverProvider
49 class="org.eclipse.ui.genericeditor.tests.contributions.AlrightyHoverProvider"
50 contentType="org.eclipse.ui.genericeditor.tests.content-type">
51 </hoverProvider>
52 <hoverProvider
53 class="org.eclipse.ui.genericeditor.tests.contributions.WorldHoverProvider"
54 contentType="org.eclipse.ui.genericeditor.tests.content-type-bar">
55 </hoverProvider>
56 <hoverProvider
57 class="org.eclipse.ui.genericeditor.tests.contributions.HelloHoverProvider"
58 contentType="org.eclipse.ui.genericeditor.tests.specialized-content-type-bar">
59 </hoverProvider>
60 <hoverProvider
61 class="org.eclipse.ui.genericeditor.tests.contributions.WorldHoverProvider"
62 contentType="org.eclipse.ui.genericeditor.tests.enabled-when-content-type">
63 <enabledWhen>
64 <not>
65 <test
66 forcePluginActivation="true"
67 property="org.eclipse.ui.genericeditor.tests.contributions.enabled">
68 </test>
69 </not>
70 </enabledWhen>
71 </hoverProvider>
72 </extension>
73 <extension
74 point="org.eclipse.ui.genericeditor.reconcilers">
75 <reconciler
76 class="org.eclipse.ui.genericeditor.tests.contributions.TheReconcilerFirst"
77 contentType="org.eclipse.ui.genericeditor.tests.content-type-bar">
78 </reconciler>
79 <reconciler
80 class="org.eclipse.ui.genericeditor.tests.contributions.TheReconcilerSecond"
81 contentType="org.eclipse.ui.genericeditor.tests.specialized-content-type-bar">
82 </reconciler>
83 <reconciler
84 class="org.eclipse.ui.genericeditor.tests.contributions.TheReconcilerFirst"
85 contentType="org.eclipse.ui.genericeditor.tests.content-type">
86 </reconciler>
87 <reconciler
88 class="org.eclipse.ui.genericeditor.tests.contributions.TheReconcilerFirst"
89 contentType="org.eclipse.ui.genericeditor.tests.enabled-when-content-type">
90 <enabledWhen>
91 <test
92 forcePluginActivation="true"
93 property="org.eclipse.ui.genericeditor.tests.contributions.enabled">
94 </test>
95 </enabledWhen>
96 </reconciler>
97 <reconciler
98 class="org.eclipse.ui.genericeditor.tests.contributions.TheReconcilerSecond"
99 contentType="org.eclipse.ui.genericeditor.tests.enabled-when-content-type">
100 <enabledWhen>
101 <not>
102 <test
103 forcePluginActivation="true"
104 property="org.eclipse.ui.genericeditor.tests.contributions.enabled">
105 </test>
106 </not>
107 </enabledWhen>
108 </reconciler>
109 </extension>
110 <extension
111 point="org.eclipse.ui.genericeditor.presentationReconcilers">
33112 <presentationReconciler
34 class="org.eclipse.ui.genericeditor.tests.contributions.ThePresentationReconciler"
35 contentType="org.eclipse.ui.genericeditor.tests.content-type">
113 class="org.eclipse.ui.genericeditor.tests.contributions.ThePresentationReconcilerBlue"
114 contentType="org.eclipse.ui.genericeditor.tests.content-type">
36115 </presentationReconciler>
37 </extension>
38 <extension
39 point="org.eclipse.ui.ide.markerResolution">
40 <markerResolutionGenerator
41 class="org.eclipse.ui.genericeditor.tests.contributions.MarkerResolutionGenerator"
42 markerType="org.eclipse.core.resources.problemmarker">
43 </markerResolutionGenerator>
44 </extension>
45 <extension
46 point="org.eclipse.core.contenttype.contentTypes">
47 <content-type
48 base-type="org.eclipse.core.runtime.text"
49 file-names="foo.txt"
50 id="org.eclipse.ui.genericeditor.tests.content-type"
51 name="Generic Editor Test content-type"
52 priority="normal">
53 </content-type>
54 </extension>
55
116 <presentationReconciler
117 class="org.eclipse.ui.genericeditor.tests.contributions.ThePresentationReconcilerGreen"
118 contentType="org.eclipse.ui.genericeditor.tests.specialized-content-type">
119 </presentationReconciler>
120 <presentationReconciler
121 class="org.eclipse.ui.genericeditor.tests.contributions.ThePresentationReconcilerRed"
122 contentType="org.eclipse.ui.genericeditor.tests.sub-specialized-content-type">
123 </presentationReconciler>
124 <presentationReconciler
125 class="org.eclipse.ui.genericeditor.tests.contributions.ThePresentationReconcilerBlue"
126 contentType="org.eclipse.ui.genericeditor.tests.enabled-when-content-type">
127 <enabledWhen>
128 <test
129 forcePluginActivation="true"
130 property="org.eclipse.ui.genericeditor.tests.contributions.enabled">
131 </test>
132 </enabledWhen>
133 </presentationReconciler>
134 </extension>
135 <extension
136 point="org.eclipse.ui.ide.markerResolution">
137 <markerResolutionGenerator
138 class="org.eclipse.ui.genericeditor.tests.contributions.MarkerResolutionGenerator"
139 markerType="org.eclipse.core.resources.problemmarker">
140 </markerResolutionGenerator>
141 </extension>
142 <extension
143 point="org.eclipse.core.contenttype.contentTypes">
144 <content-type
145 base-type="org.eclipse.core.runtime.text"
146 file-names="foo.txt"
147 id="org.eclipse.ui.genericeditor.tests.content-type"
148 name="Generic Editor Test content-type"
149 priority="normal">
150 </content-type>
151 <content-type
152 base-type="org.eclipse.ui.genericeditor.tests.content-type"
153 file-names="foo.txt"
154 id="org.eclipse.ui.genericeditor.tests.specialized-content-type"
155 name="Specialized Generic Editor content-type"
156 priority="normal">
157 </content-type>
158 <content-type
159 base-type="org.eclipse.ui.genericeditor.tests.specialized-content-type"
160 file-names="foo.txt"
161 id="org.eclipse.ui.genericeditor.tests.sub-specialized-content-type"
162 name="Sub-Specialized Generic Editor content-type"
163 priority="normal">
164 </content-type>
165 <content-type
166 base-type="org.eclipse.ui.genericeditor.tests.content-type"
167 file-names="foobar.txt"
168 id="org.eclipse.ui.genericeditor.tests.specialized-content-type-foobartxt"
169 name="Specialized Generic Editor content-type for &apos;foobar.txt&apos;"
170 priority="normal">
171 </content-type>
172 <content-type
173 base-type="org.eclipse.core.runtime.text"
174 file-names="bar.txt"
175 id="org.eclipse.ui.genericeditor.tests.content-type-bar"
176 name="Generic Editor Test content-type for &apos;bar.txt&apos;"
177 priority="normal">
178 </content-type>
179 <content-type
180 base-type="org.eclipse.ui.genericeditor.tests.content-type-bar"
181 file-names="bar.txt"
182 id="org.eclipse.ui.genericeditor.tests.specialized-content-type-bar"
183 name="Specialized Generic Editor content-type for &apos;bar.txt&apos;"
184 priority="normal">
185 </content-type>
186 <content-type
187 base-type="org.eclipse.core.runtime.text"
188 file-names="enabledWhen.txt"
189 id="org.eclipse.ui.genericeditor.tests.enabled-when-content-type"
190 name="enabledWhen content-type for &apos;enabledWhen.txt&apos;"
191 priority="normal">
192 </content-type>
193 </extension>
194 <extension
195 point="org.eclipse.ui.genericeditor.autoEditStrategies">
196 <autoEditStrategy
197 class="org.eclipse.ui.genericeditor.tests.contributions.TheAutoEditStrategyFirst"
198 contentType="org.eclipse.ui.genericeditor.tests.content-type">
199 </autoEditStrategy>
200 <autoEditStrategy
201 class="org.eclipse.ui.genericeditor.tests.contributions.TheAutoEditStrategySecond"
202 contentType="org.eclipse.ui.genericeditor.tests.specialized-content-type">
203 </autoEditStrategy>
204 <autoEditStrategy
205 class="org.eclipse.ui.genericeditor.tests.contributions.TheAutoEditStrategyThird"
206 contentType="org.eclipse.ui.genericeditor.tests.sub-specialized-content-type">
207 </autoEditStrategy>
208 <autoEditStrategy
209 class="org.eclipse.ui.genericeditor.tests.contributions.TheAutoEditStrategyFirst"
210 contentType="org.eclipse.ui.genericeditor.tests.enabled-when-content-type">
211 <enabledWhen>
212 <test
213 forcePluginActivation="true"
214 property="org.eclipse.ui.genericeditor.tests.contributions.enabled">
215 </test>
216 </enabledWhen>
217 </autoEditStrategy>
218 </extension>
219 <extension
220 point="org.eclipse.ui.genericeditor.highlightReconcilers">
221 <highlightReconciler
222 class="org.eclipse.ui.genericeditor.tests.contributions.HighlightReconciler"
223 contentType="org.eclipse.ui.genericeditor.tests.content-type-bar">
224 </highlightReconciler>
225 <highlightReconciler
226 class="org.eclipse.ui.genericeditor.tests.contributions.HighlightReconciler"
227 contentType="org.eclipse.ui.genericeditor.tests.enabled-when-content-type">
228 <enabledWhen>
229 <test
230 forcePluginActivation="true"
231 property="org.eclipse.ui.genericeditor.tests.contributions.enabled">
232 </test>
233 </enabledWhen>
234 </highlightReconciler>
235 </extension>
236 <extension
237 point="org.eclipse.core.expressions.propertyTesters">
238 <propertyTester
239 class="org.eclipse.ui.genericeditor.tests.contributions.EnabledPropertyTester"
240 id="org.eclipse.ui.genericeditor.tests.contributions.enabled"
241 namespace="org.eclipse.ui.genericeditor.tests.contributions"
242 properties="enabled"
243 type="org.eclipse.ui.internal.genericeditor.ExtensionBasedTextEditor">
244 </propertyTester>
245 </extension>
56246 </plugin>
1313 <parent>
1414 <artifactId>tests-pom</artifactId>
1515 <groupId>eclipse.platform.text</groupId>
16 <version>4.7.3-SNAPSHOT</version>
16 <version>4.8.0-SNAPSHOT</version>
1717 <relativePath>../tests-pom/</relativePath>
1818 </parent>
1919 <groupId>org.eclipse.ui</groupId>
2020 <artifactId>org.eclipse.ui.genericeditor.tests</artifactId>
21 <version>1.0.0-SNAPSHOT</version>
21 <version>1.1.0-SNAPSHOT</version>
2222 <packaging>eclipse-test-plugin</packaging>
2323 <properties>
2424 <testSuite>${project.artifactId}</testSuite>
1616
1717 import org.eclipse.swt.widgets.Display;
1818
19 import org.eclipse.core.runtime.NullProgressMonitor;
20
1921 import org.eclipse.core.resources.IFile;
2022 import org.eclipse.core.resources.IProject;
2123 import org.eclipse.core.resources.ResourcesPlugin;
24
25 import org.eclipse.text.tests.Accessor;
26
27 import org.eclipse.jface.text.source.SourceViewer;
2228
2329 import org.eclipse.ui.PlatformUI;
2430 import org.eclipse.ui.internal.genericeditor.ExtensionBasedTextEditor;
2531 import org.eclipse.ui.intro.IIntroPart;
2632 import org.eclipse.ui.part.FileEditorInput;
33
34 import org.eclipse.ui.texteditor.AbstractTextEditor;
2735
2836 /**
2937 * Closes intro, create {@link #project}, create {@link #file} and open {@link #editor}; and clean up.
4654 project = ResourcesPlugin.getWorkspace().getRoot().getProject(getClass().getName() + System.currentTimeMillis());
4755 project.create(null);
4856 project.open(null);
49 file = project.getFile("foo.txt");
50 file.create(new ByteArrayInputStream("bar 'bar'".getBytes()), true, null);
51 editor = (ExtensionBasedTextEditor) PlatformUI.getWorkbench().getActiveWorkbenchWindow()
52 .getActivePage().openEditor(new FileEditorInput(this.file), "org.eclipse.ui.genericeditor.GenericEditor");
57 project.setDefaultCharset("UTF-8", null);
58 createAndOpenFile();
5359 }
5460
61 protected void createAndOpenFile() throws Exception {
62 createAndOpenFile("foo.txt", "bar 'bar'");
63 }
64
65 /**
66 * Creates a new file in the project, opens it, and associate that file with the test state
67 * @param name name of the file in the project
68 * @param contents content of the file
69 * @throws Exception ex
70 * @since 1.1
71 */
72 protected void createAndOpenFile(String name, String contents) throws Exception {
73 this.file = project.getFile(name);
74 this.file.create(new ByteArrayInputStream(contents.getBytes("UTF-8")), true, null);
75 this.file.setCharset("UTF-8", null);
76 this.editor = (ExtensionBasedTextEditor) PlatformUI.getWorkbench().getActiveWorkbenchWindow()
77 .getActivePage().openEditor(new FileEditorInput(this.file), "org.eclipse.ui.genericeditor.GenericEditor");
78 }
79
80 /**
81 * Closes editor and delete file. Keeps project open.
82 * @throws Exception ex
83 * @since 1.1
84 */
85 protected void cleanFileAndEditor() throws Exception {
86 if (editor != null) {
87 editor.close(false);
88 editor = null;
89 }
90 while(Display.getDefault().readAndDispatch()) {}
91 if (file != null) {
92 file.delete(true, new NullProgressMonitor());
93 file = null;
94 }
95 }
96
97 protected SourceViewer getSourceViewer() {
98 SourceViewer sourceViewer= (SourceViewer) new Accessor(editor, AbstractTextEditor.class).invoke("getSourceViewer", new Object[0]);
99 return sourceViewer;
100 }
101
55102 @After
56103 public void tearDown() throws Exception {
57 if (file != null) {
58 file.delete(true, null);
59 }
104 cleanFileAndEditor();
60105 if (project != null) {
61106 project.delete(true, null);
62107 }
0 /*******************************************************************************
1 * Copyright (c) 2017 Rogue Wave Software Inc. and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Michał Niewrzał (Rogue Wave Software Inc.) - initial implementation
9 *******************************************************************************/
10 package org.eclipse.ui.genericeditor.tests;
11
12 import org.junit.Assert;
13 import org.junit.Test;
14
15 import org.eclipse.swt.custom.StyledText;
16 import org.eclipse.swt.widgets.Control;
17
18 import org.eclipse.jface.text.IDocument;
19
20 import org.eclipse.ui.genericeditor.tests.contributions.EnabledPropertyTester;
21
22 public class AutoEditTest extends AbstratGenericEditorTest {
23
24 @Test
25 public void testAutoEdit() throws Exception {
26 IDocument document= editor.getDocumentProvider().getDocument(editor.getEditorInput());
27 StyledText control= (StyledText) editor.getAdapter(Control.class);
28 control.setText("");
29 // order of auto-edits from most specialized to least specialized
30 Assert.assertEquals("AutoAddedThird!AutoAddedSecond!AutoAddedFirst!", document.get());
31 }
32
33 @Test
34 public void testEnabledWhenAutoEdit() throws Exception {
35 EnabledPropertyTester.setEnabled(true);
36 createAndOpenFile("enabledWhen.txt", "bar 'bar'");
37 IDocument document= editor.getDocumentProvider().getDocument(editor.getEditorInput());
38 StyledText control= (StyledText) editor.getAdapter(Control.class);
39 control.setText("");
40 // order of auto-edits from most specialized to least specialized
41 Assert.assertEquals("AutoAddedFirst!", document.get());
42 cleanFileAndEditor();
43
44 EnabledPropertyTester.setEnabled(false);
45 createAndOpenFile("enabledWhen.txt", "bar 'bar'");
46 document= editor.getDocumentProvider().getDocument(editor.getEditorInput());
47 control= (StyledText) editor.getAdapter(Control.class);
48 control.setText("");
49 // order of auto-edits from most specialized to least specialized
50 Assert.assertEquals("", document.get());
51 }
52 }
00 /*******************************************************************************
1 * Copyright (c) 2016 Red Hat Inc. and others
1 * Copyright (c) 2016-2017 Red Hat Inc. and others
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
1010 package org.eclipse.ui.genericeditor.tests;
1111
1212 import static org.junit.Assert.assertEquals;
13 import static org.junit.Assert.assertNotNull;
1314 import static org.junit.Assert.assertTrue;
1415
1516 import java.util.Arrays;
16 import java.util.HashSet;
1717 import java.util.Set;
18
18 import java.util.stream.Collectors;
19
20 import org.junit.After;
1921 import org.junit.Test;
2022
23 import org.eclipse.swt.SWT;
24 import org.eclipse.swt.custom.ST;
25 import org.eclipse.swt.custom.StyledText;
2126 import org.eclipse.swt.widgets.Composite;
22 import org.eclipse.swt.widgets.Display;
27 import org.eclipse.swt.widgets.Control;
28 import org.eclipse.swt.widgets.Event;
2329 import org.eclipse.swt.widgets.Shell;
2430 import org.eclipse.swt.widgets.Table;
2531 import org.eclipse.swt.widgets.TableItem;
2632 import org.eclipse.swt.widgets.Widget;
2733
34 import org.eclipse.jface.text.ITextSelection;
2835 import org.eclipse.jface.text.contentassist.ICompletionProposal;
2936 import org.eclipse.jface.text.tests.util.DisplayHelper;
3037
3138 import org.eclipse.ui.genericeditor.tests.contributions.BarContentAssistProcessor;
39 import org.eclipse.ui.genericeditor.tests.contributions.EnabledPropertyTester;
3240 import org.eclipse.ui.genericeditor.tests.contributions.LongRunningBarContentAssistProcessor;
3341
3442 import org.eclipse.ui.texteditor.ContentAssistAction;
3947 */
4048 public class CompletionTest extends AbstratGenericEditorTest {
4149
50 private Shell completionShell;
51
4252 @Test
4353 public void testCompletion() throws Exception {
44 Set<Shell> beforeShell = new HashSet<>(Arrays.asList(Display.getDefault().getShells()));
54 final Set<Shell> beforeShells = Arrays.stream(editor.getSite().getShell().getDisplay().getShells()).filter(Shell::isVisible).collect(Collectors.toSet());
55 openConentAssist();
56 this.completionShell= findNewShell(beforeShells);
57 final Table completionProposalList = findCompletionSelectionControl(completionShell);
58 checkCompletionContent(completionProposalList);
59 // TODO find a way to actually trigger completion and verify result against Editor content
60 // Assert.assertEquals("Completion didn't complete", "bars are good for a beer.", ((StyledText)editor.getAdapter(Control.class)).getText());
61 }
62
63 @Test
64 public void testEnabledWhenCompletion() throws Exception {
65 // Confirm that when disabled, a completion shell is present
66 EnabledPropertyTester.setEnabled(false);
67 createAndOpenFile("enabledWhen.txt", "bar 'bar'");
68 final Set<Shell> beforeShells = Arrays.stream(editor.getSite().getShell().getDisplay().getShells()).filter(Shell::isVisible).collect(Collectors.toSet());
69 openConentAssist();
70 Shell[] afterShells = Arrays.stream(editor.getSite().getShell().getDisplay().getShells())
71 .filter(Shell::isVisible)
72 .filter(shell -> !beforeShells.contains(shell))
73 .toArray(Shell[]::new);
74 assertEquals("A new shell was found", 0, afterShells.length);
75 cleanFileAndEditor();
76
77 // Confirm that when enabled, a completion shell is present
78 EnabledPropertyTester.setEnabled(true);
79 createAndOpenFile("enabledWhen.txt", "bar 'bar'");
80 final Set<Shell> beforeEnabledShells = Arrays.stream(editor.getSite().getShell().getDisplay().getShells()).filter(Shell::isVisible).collect(Collectors.toSet());
81 openConentAssist();
82 assertNotNull(findNewShell(beforeEnabledShells));
83 }
84
85 private void openConentAssist() {
4586 editor.selectAndReveal(3, 0);
4687 ContentAssistAction action = (ContentAssistAction) editor.getAction(ITextEditorActionConstants.CONTENT_ASSIST);
4788 action.update();
4889 action.run();
4990 waitAndDispatch(100);
50 Set<Shell> afterShell = new HashSet<>(Arrays.asList(Display.getDefault().getShells()));
51 afterShell.removeAll(beforeShell);
52 assertEquals("No completion", 1, afterShell.size());
53 Shell completionShell= afterShell.iterator().next();
54 final Table completionProposalList = findCompletionSelectionControl(completionShell);
91 }
92
93 /**
94 * Checks that completion behaves as expected:
95 * 1. Computing is shown instantaneously
96 * 2. 1st proposal shown instantaneously
97 * 3. 2s later, 2nd proposal is shown
98 * @param completionProposalList the completion list
99 */
100 private void checkCompletionContent(final Table completionProposalList) {
55101 // should be instantaneous, but happens to go asynchronous on CI so let's allow a wait
56102 new DisplayHelper() {
57103 @Override
58104 protected boolean condition() {
59105 return completionProposalList.getItemCount() == 2;
60106 }
61 }.waitForCondition(completionShell.getDisplay(), 200);
107 }.waitForCondition(completionProposalList.getDisplay(), 200);
62108 assertEquals(2, completionProposalList.getItemCount());
63109 final TableItem computingItem = completionProposalList.getItem(0);
64110 assertTrue("Missing computing info entry", computingItem.getText().contains("Computing")); //$NON-NLS-1$ //$NON-NLS-2$
65111 TableItem completionProposalItem = completionProposalList.getItem(1);
66 ICompletionProposal completionProposal = (ICompletionProposal)completionProposalItem.getData();
67 assertEquals(BarContentAssistProcessor.PROPOSAL, completionProposal .getDisplayString());
112 final ICompletionProposal selectedProposal = (ICompletionProposal)completionProposalItem.getData();
113 assertTrue("Incorrect proposal content", BarContentAssistProcessor.PROPOSAL.endsWith(selectedProposal .getDisplayString()));
68114 completionProposalList.setSelection(completionProposalItem);
69115 // asynchronous
70116 new DisplayHelper() {
71117 @Override
72118 protected boolean condition() {
73 return completionProposalList.getItem(0) != computingItem;
74 }
75 }.waitForCondition(completionShell.getDisplay(), LongRunningBarContentAssistProcessor.DELAY + 200);
119 return completionProposalList.getItem(0) != computingItem && completionProposalList.getItemCount() == 2;
120 }
121 }.waitForCondition(completionProposalList.getDisplay(), LongRunningBarContentAssistProcessor.DELAY + 200);
122 completionProposalItem = completionProposalList.getItem(0);
123 assertTrue("Proposal content seems incorrect", BarContentAssistProcessor.PROPOSAL.endsWith(((ICompletionProposal)completionProposalItem.getData()).getDisplayString()));
124 TableItem otherProposalItem = completionProposalList.getItem(1);
125 assertTrue("Proposal content seems incorrect", LongRunningBarContentAssistProcessor.PROPOSAL.endsWith(((ICompletionProposal)otherProposalItem.getData()).getDisplayString()));
126 assertEquals("Addition of completion proposal should keep selection", selectedProposal, completionProposalList.getSelection()[0].getData());
127 }
128
129 private Shell findNewShell(Set<Shell> beforeShells) {
130 Shell[] afterShells = Arrays.stream(editor.getSite().getShell().getDisplay().getShells())
131 .filter(Shell::isVisible)
132 .filter(shell -> !beforeShells.contains(shell))
133 .toArray(Shell[]::new);
134 assertEquals("No new shell found", 1, afterShells.length);
135 return afterShells[0];
136 }
137
138 @Test
139 public void testCompletionFreeze_bug521484() throws Exception {
140 final Set<Shell> beforeShells = Arrays.stream(editor.getSite().getShell().getDisplay().getShells()).filter(Shell::isVisible).collect(Collectors.toSet());
141 openConentAssist();
142 this.completionShell= findNewShell(beforeShells);
143 final Table completionProposalList = findCompletionSelectionControl(this.completionShell);
144 // should be instantaneous, but happens to go asynchronous on CI so let's allow a wait
145 new DisplayHelper() {
146 @Override
147 protected boolean condition() {
148 return completionProposalList.getItemCount() == 2;
149 }
150 }.waitForCondition(completionShell.getDisplay(), 200);
76151 assertEquals(2, completionProposalList.getItemCount());
77 completionProposalItem = completionProposalList.getItem(0);
78 assertEquals(BarContentAssistProcessor.PROPOSAL, ((ICompletionProposal)completionProposalItem.getData()).getDisplayString());
79 TableItem otherProposalItem = completionProposalList.getItem(1);
80 assertEquals(LongRunningBarContentAssistProcessor.PROPOSAL, ((ICompletionProposal)otherProposalItem.getData()).getDisplayString());
81 assertEquals("Addition of completion proposal should keep selection", completionProposal, completionProposalList.getSelection()[0].getData());
82
83 // TODO find a way to actually trigger completion and verify result against Editor content
84 // Assert.assertEquals("Completion didn't complete", "bars are good for a beer.", ((StyledText)editor.getAdapter(Control.class)).getText());
85 completionShell.close();
152 final TableItem computingItem = completionProposalList.getItem(0);
153 assertTrue("Missing computing info entry", computingItem.getText().contains("Computing")); //$NON-NLS-1$ //$NON-NLS-2$
154 // Some processors are long running, moving cursor can cause freeze (bug 521484)
155 // asynchronous
156 long timestamp = System.currentTimeMillis();
157 emulatePressLeftArrowKey();
158 DisplayHelper.sleep(editor.getSite().getShell().getDisplay(), 200); //give time to process events
159 long processingDuration = System.currentTimeMillis() - timestamp;
160 assertTrue("UI Thread frozen for " + processingDuration + "ms", processingDuration < LongRunningBarContentAssistProcessor.DELAY);
161 }
162
163 @Test
164 public void testMoveCaretBackUsesAllProcessors_bug522255() throws Exception {
165 final Set<Shell> beforeShells = Arrays.stream(editor.getSite().getShell().getDisplay().getShells()).filter(Shell::isVisible).collect(Collectors.toSet());
166 testCompletion();
167 emulatePressLeftArrowKey();
168 DisplayHelper.sleep(editor.getSite().getShell().getDisplay(), LongRunningBarContentAssistProcessor.DELAY + 500); // adding delay is a workaround for bug521484, use only 100ms without the bug
169 this.completionShell= findNewShell(beforeShells);
170 final Table completionProposalList = findCompletionSelectionControl(this.completionShell);
171 assertEquals("Missing proposals from a Processor", 2, completionProposalList.getItemCount()); // replace with line below when #5214894 is done
172 // checkCompletionContent(completionProposalList); // use this instead of assert above when #521484 is done
173 }
174
175 private void emulatePressLeftArrowKey() {
176 editor.selectAndReveal(((ITextSelection)editor.getSelectionProvider().getSelection()).getOffset() - 1, 0);
177 StyledText styledText = (StyledText) editor.getAdapter(Control.class);
178 Event e = new Event();
179 e.type = ST.VerifyKey;
180 e.widget = styledText;
181 e.keyCode = SWT.ARROW_LEFT;
182 e.display = styledText.getDisplay();
183 styledText.notifyListeners(ST.VerifyKey, e);
86184 }
87185
88186 private Table findCompletionSelectionControl(Widget control) {
99197 return null;
100198 }
101199
200 @After
201 public void closeShell() {
202 if (this.completionShell != null && !completionShell.isDisposed()) {
203 completionShell.close();
204 }
205 }
102206 }
0 /*******************************************************************************
1 * Copyright (c) 2017 Stephan Wahlbrink and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Stephan Wahlbrink <sw@wahlbrink.eu>
9 *******************************************************************************/
10 package org.eclipse.ui.genericeditor.tests;
11
12 import static org.junit.Assert.assertEquals;
13 import static org.junit.Assert.assertTrue;
14
15 import java.util.Arrays;
16 import java.util.Set;
17 import java.util.stream.Collectors;
18
19 import org.junit.After;
20 import org.junit.Test;
21
22 import org.eclipse.swt.custom.StyledText;
23 import org.eclipse.swt.widgets.Control;
24 import org.eclipse.swt.widgets.Shell;
25 import org.eclipse.swt.widgets.Text;
26
27 import org.eclipse.text.tests.Accessor;
28
29 import org.eclipse.jface.text.contentassist.ContentAssistant;
30 import org.eclipse.jface.text.source.SourceViewer;
31
32 import org.eclipse.ui.genericeditor.tests.contributions.BarContentAssistProcessor;
33
34 import org.eclipse.ui.texteditor.ITextEditorActionConstants;
35 import org.eclipse.ui.texteditor.TextOperationAction;
36
37
38 public class ContextInfoTest extends AbstratGenericEditorTest {
39
40
41 private Shell completionShell;
42
43
44 @Test
45 public void testContextInfo() throws Exception {
46 cleanFileAndEditor();
47 createAndOpenFile("foobar.txt", BarContentAssistProcessor.PROPOSAL);
48
49 final Set<Shell> beforeShells = Arrays.stream(editor.getSite().getShell().getDisplay().getShells()).filter(Shell::isVisible).collect(Collectors.toSet());
50 TextOperationAction action = (TextOperationAction) editor.getAction(ITextEditorActionConstants.CONTENT_ASSIST_CONTEXT_INFORMATION);
51
52 editor.selectAndReveal(4, 0);
53 action.update();
54 action.run();
55 waitAndDispatch(100);
56 this.completionShell= findNewShell(beforeShells);
57 assertEquals("idx= 0", getInfoText(this.completionShell));
58
59 editor.selectAndReveal(8, 0);
60 action.update();
61 action.run();
62 waitAndDispatch(100);
63 this.completionShell= findNewShell(beforeShells);
64 assertEquals("idx= 1", getInfoText(this.completionShell));
65 }
66
67 @Test
68 public void testContextInfo_hide_Bug512251() throws Exception {
69 cleanFileAndEditor();
70 createAndOpenFile("foobar.txt", BarContentAssistProcessor.PROPOSAL);
71
72 final Set<Shell> beforeShells = Arrays.stream(editor.getSite().getShell().getDisplay().getShells()).filter(Shell::isVisible).collect(Collectors.toSet());
73 TextOperationAction action = (TextOperationAction) editor.getAction(ITextEditorActionConstants.CONTENT_ASSIST_CONTEXT_INFORMATION);
74
75 editor.selectAndReveal(4, 0);
76 action.update();
77 action.run();
78 waitAndDispatch(100);
79 this.completionShell= findNewShell(beforeShells);
80
81 editor.selectAndReveal(8, 0);
82 action.update();
83 action.run();
84 waitAndDispatch(100);
85 this.completionShell= findNewShell(beforeShells);
86
87 editor.getAction(ITextEditorActionConstants.DELETE_LINE).run();
88
89 SourceViewer sourceViewer= getSourceViewer();
90 ContentAssistant assist= (ContentAssistant) new Accessor(sourceViewer, SourceViewer.class).get("fContentAssistant");
91 new Accessor(assist, ContentAssistant.class).invoke("hide", new Object[0]);
92 }
93
94
95 private Shell findNewShell(Set<Shell> beforeShells) {
96 Shell[] afterShells = Arrays.stream(editor.getSite().getShell().getDisplay().getShells())
97 .filter(Shell::isVisible)
98 .filter(shell -> !beforeShells.contains(shell))
99 .toArray(Shell[]::new);
100 assertEquals("No new shell found", 1, afterShells.length);
101 return afterShells[0];
102 }
103
104 private String getInfoText(final Shell shell) {
105 assertTrue(shell.isVisible());
106 Control[] children= shell.getChildren();
107 for (Control child : children) {
108 if (child instanceof Text) {
109 return ((Text) child).getText();
110 }
111 if (child instanceof StyledText) {
112 return ((StyledText) child).getText();
113 }
114 }
115 return null;
116 }
117
118 @After
119 public void closeShell() {
120 if (this.completionShell != null && !completionShell.isDisposed()) {
121 completionShell.close();
122 }
123 }
124
125 }
66 *
77 * Contributors:
88 * Mickael Istria, Sopot Cela (Red Hat Inc.)
9 * Lucas Bullen (Red Hat Inc.)
910 *******************************************************************************/
1011 package org.eclipse.ui.genericeditor.tests;
1112
1617 @RunWith(Suite.class)
1718 @SuiteClasses({
1819 CompletionTest.class,
20 ContextInfoTest.class,
1921 StylingTest.class,
2022 HoverTest.class,
21 EditorTest.class
23 EditorTest.class,
24 AutoEditTest.class,
25 ReconcilerTest.class,
26 HighlightTest.class
2227 })
2328 public class GenericEditorTestSuite {
2429 // see @SuiteClasses
25
30
2631 }
0 /*******************************************************************************
1 * Copyright (c) 2017, 2018 Red Hat Inc. and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * - Lucas Bullen (Red Hat Inc.)
9 *******************************************************************************/
10 package org.eclipse.ui.genericeditor.tests;
11
12 import static org.junit.Assert.assertEquals;
13
14 import java.util.ArrayList;
15 import java.util.Iterator;
16 import java.util.List;
17
18 import org.junit.Assert;
19 import org.junit.Test;
20
21 import org.eclipse.swt.widgets.Display;
22
23 import org.eclipse.jface.text.IDocument;
24 import org.eclipse.jface.text.Position;
25 import org.eclipse.jface.text.source.Annotation;
26 import org.eclipse.jface.text.source.IAnnotationModel;
27 import org.eclipse.jface.text.tests.util.DisplayHelper;
28
29 import org.eclipse.ui.genericeditor.tests.contributions.EnabledPropertyTester;
30
31 import org.eclipse.ui.texteditor.IDocumentProvider;
32
33 public class HighlightTest extends AbstratGenericEditorTest {
34
35 private static final String ANNOTATION_TYPE= "org.eclipse.ui.genericeditor.text"; //$NON-NLS-1$
36
37 private static final String EDITOR_TEXT= "Lorem ipsum dolor sit amet, consectetur adipiscing elit.\n" +
38 "Lorem ipsum dolor sit amet, consectetur adipiscing elit.\n" +
39 "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
40
41 @Override
42 protected void createAndOpenFile() throws Exception {
43 //leave editor creation to individual tests
44 }
45
46 @Test
47 public void testCustomHighlightReconciler() throws Exception {
48 createAndOpenFile("bar.txt", "bar 'bar'");
49
50 checkHighlightForCaretOffset(0, "'bar'", 1);
51 }
52
53 @Test
54 public void testEnabledWhenCustomHighlightReconciler() throws Exception {
55 EnabledPropertyTester.setEnabled(true);
56 createAndOpenFile("enabledWhen.txt", "bar 'bar'");
57 checkHighlightForCaretOffset(0, "'bar'", 1);
58 cleanFileAndEditor();
59
60 EnabledPropertyTester.setEnabled(false);
61 createAndOpenFile("enabledWhen.txt", "bar 'bar'");
62 checkHighlightForCaretOffset(0, "'bar'", 0);
63 }
64
65 @Test
66 public void testHighlightWordAtDocumentStart() throws Exception {
67 createAndOpenFile("foo.txt", EDITOR_TEXT);
68
69 checkHighlightForCaretOffset(0, "Lorem", 3);
70 }
71
72 @Test
73 public void testHighlightWordWithNonLetterParts() throws Exception {
74 String complexWord= "dolor_sit123amet45";
75 String editorText= EDITOR_TEXT.replaceFirst("dolor sit amet", complexWord).replaceFirst("dolor sit amet", complexWord);
76 createAndOpenFile("foo.txt", editorText);
77
78 checkHighlightForCaretOffset(editorText.indexOf("dolor") + 3, complexWord, 2);
79 checkHighlightForCaretOffset(editorText.indexOf("_sit") + 3, complexWord, 2);
80 checkHighlightForCaretOffset(editorText.indexOf("123") + 1, complexWord, 2);
81 checkHighlightForCaretOffset(editorText.indexOf("amet") + 1, complexWord, 2);
82 }
83
84 @Test
85 public void testHighlightSimpleWordNotMatchingWordPart() throws Exception {
86 String complexWord= "dolor_sit123amet45";
87 String editorText= EDITOR_TEXT.replaceFirst("dolor sit amet", complexWord);
88 createAndOpenFile("foo.txt", editorText);
89
90 checkHighlightForCaretOffset(editorText.indexOf("dolor ") + 1, "dolor", 2);
91 checkHighlightForCaretOffset(editorText.indexOf(" sit") + 1, "sit", 2);
92 checkHighlightForCaretOffset(editorText.indexOf(" amet") + 1, "amet", 2);
93 }
94
95 @Test
96 public void testHighlightNonAsciiCharacters() throws Exception {
97 String complexWord= "sit\u00f6\u00f6amet";
98 String editorText= EDITOR_TEXT.replaceFirst("sit amet", complexWord).replaceFirst("sit amet", complexWord);
99 createAndOpenFile("foo.txt", editorText);
100
101 checkHighlightForCaretOffset(editorText.indexOf("sit") + 1, complexWord, 2);
102 checkHighlightForCaretOffset(editorText.indexOf("\u00f6") + 1, complexWord, 2);
103 checkHighlightForCaretOffset(editorText.indexOf("amet") + 1, complexWord, 2);
104 }
105
106 private void checkHighlightForCaretOffset(int pos, String expectedHighlight, int expectedHighlightCount) throws Exception {
107 clearAnnotations();
108
109 editor.selectAndReveal(pos, 0);
110 waitForAnnotations(expectedHighlightCount);
111
112 List<Annotation> annotations= getAnnotationsFromAnnotationModel();
113
114 IAnnotationModel annotationModel= getAnnotationModel();
115 IDocument document= editor.getDocumentProvider().getDocument(editor.getEditorInput());
116 for (int i= 0; i < annotations.size(); i++) {
117 Annotation annotation= annotations.get(i);
118 Position position= annotationModel.getPosition(annotation);
119 String highlight= document.get(position.offset, position.length);
120 assertEquals("Wrong highlight " + i + " at position " + position.offset, expectedHighlight, highlight);
121 }
122 Assert.assertEquals("Wrong number of highlights", expectedHighlightCount, annotations.size());
123 }
124
125 private void clearAnnotations() {
126 editor.selectAndReveal(0, 0);
127 IAnnotationModel annotationModel= getAnnotationModel();
128 List<Annotation> annotations= getAnnotationsFromAnnotationModel();
129 for (Annotation annotation : annotations) {
130 annotationModel.removeAnnotation(annotation);
131 }
132 }
133
134 private IAnnotationModel getAnnotationModel() {
135 IDocumentProvider dp= editor.getDocumentProvider();
136 IAnnotationModel am= dp.getAnnotationModel(editor.getEditorInput());
137 return am;
138 }
139
140 private void waitForAnnotations(int count) {
141 new DisplayHelper() {
142 @Override
143 protected boolean condition() {
144 return getAnnotationsFromAnnotationModel().size() == count;
145 }
146 }.waitForCondition(Display.getDefault(), 2000);
147 }
148
149 private List<Annotation> getAnnotationsFromAnnotationModel() {
150 List<Annotation> annotationList= new ArrayList<>();
151 Iterator<Annotation> annotationIterator= getAnnotationModel().getAnnotationIterator();
152 while (annotationIterator.hasNext()) {
153 Annotation ann= annotationIterator.next();
154 if (ann.getType().indexOf(ANNOTATION_TYPE) > -1) {
155 annotationList.add(ann);
156 }
157 }
158 return annotationList;
159 }
160 }
99 *******************************************************************************/
1010 package org.eclipse.ui.genericeditor.tests;
1111
12 import static org.junit.Assert.assertEquals;
1312 import static org.junit.Assert.assertFalse;
1413 import static org.junit.Assert.assertNotNull;
14 import static org.junit.Assert.assertNull;
1515 import static org.junit.Assert.assertTrue;
1616 import static org.junit.Assert.fail;
1717
1818 import java.util.Collections;
19 import java.util.Map;
1920
2021 import org.junit.Assume;
2122 import org.junit.Before;
4546 import org.eclipse.jface.text.TextViewer;
4647 import org.eclipse.jface.text.tests.util.DisplayHelper;
4748
48 import org.eclipse.ui.genericeditor.tests.contributions.MagicHoverProvider;
49 import org.eclipse.ui.genericeditor.tests.contributions.AlrightyHoverProvider;
50 import org.eclipse.ui.genericeditor.tests.contributions.EnabledPropertyTester;
51 import org.eclipse.ui.genericeditor.tests.contributions.HelloHoverProvider;
4952 import org.eclipse.ui.genericeditor.tests.contributions.MarkerResolutionGenerator;
53 import org.eclipse.ui.genericeditor.tests.contributions.WorldHoverProvider;
5054
5155 import org.eclipse.ui.workbench.texteditor.tests.ScreenshotTest;
5256
6670 }
6771
6872 @Test
69 public void testHover() throws Exception {
73 public void testSingleHover() throws Exception {
7074 Shell shell = getHoverShell(triggerCompletionAndRetrieveInformationControlManager());
71 assertNotNull(findControl(shell, StyledText.class, MagicHoverProvider.LABEL));
75 assertNotNull(findControl(shell, StyledText.class, AlrightyHoverProvider.LABEL));
76 assertNull(findControl(shell, StyledText.class, HelloHoverProvider.LABEL));
77 assertNull(findControl(shell, StyledText.class, WorldHoverProvider.LABEL));
78 }
79
80 @Test
81 public void testEnabledWhenHover() throws Exception {
82 EnabledPropertyTester.setEnabled(true);
83 createAndOpenFile("enabledWhen.txt", "bar 'bar'");
84 Shell shell = getHoverShell(triggerCompletionAndRetrieveInformationControlManager());
85 assertNotNull(findControl(shell, StyledText.class, AlrightyHoverProvider.LABEL));
86 assertNull(findControl(shell, StyledText.class, WorldHoverProvider.LABEL));
87 cleanFileAndEditor();
88
89 EnabledPropertyTester.setEnabled(false);
90 createAndOpenFile("enabledWhen.txt", "bar 'bar'");
91 shell = getHoverShell(triggerCompletionAndRetrieveInformationControlManager());
92 assertNull(findControl(shell, StyledText.class, AlrightyHoverProvider.LABEL));
93 assertNotNull(findControl(shell, StyledText.class, WorldHoverProvider.LABEL));
94 }
95
96 /**
97 * @throws Exception ex
98 * @since 1.1
99 */
100 @Test
101 public void testMultipleHover() throws Exception {
102 cleanFileAndEditor();
103 createAndOpenFile("bar.txt", "Hi");
104 Shell shell = getHoverShell(triggerCompletionAndRetrieveInformationControlManager());
105 assertNull(findControl(shell, StyledText.class, AlrightyHoverProvider.LABEL));
106 assertNotNull(findControl(shell, StyledText.class, WorldHoverProvider.LABEL));
107 assertNotNull(findControl(shell, StyledText.class, HelloHoverProvider.LABEL));
72108 }
73109
74110 @Test
84120 marker.setAttribute(IMarker.MESSAGE, problemMessage);
85121 marker.setAttribute(MarkerResolutionGenerator.FIXME, true);
86122 AbstractInformationControlManager manager = triggerCompletionAndRetrieveInformationControlManager();
87 assertEquals(Collections.singletonList(marker), getHoverData(manager));
123 Object hoverData = getHoverData(manager);
124 assertTrue(hoverData instanceof Map);
125 assertTrue(((Map<?,?>)hoverData).containsValue(Collections.singletonList(marker)));
126 assertTrue(((Map<?,?>)hoverData).containsValue(AlrightyHoverProvider.LABEL));
127 assertFalse(((Map<?,?>)hoverData).containsValue(HelloHoverProvider.LABEL));
88128 // check dialog content
89129 Shell shell= getHoverShell(manager);
90130 assertNotNull(findControl(shell, Label.class, marker.getAttribute(IMarker.MESSAGE, "NONE")));
131 assertNotNull(findControl(shell, StyledText.class, AlrightyHoverProvider.LABEL));
132 assertNull(findControl(shell, StyledText.class, HelloHoverProvider.LABEL));
133 // check quick-fix works
91134 Link link = findControl(shell, Link.class, MarkerResolutionGenerator.FIXME);
92135 assertNotNull(link);
93136 Event event = new Event();
125168 fail();
126169 }
127170 Shell shell = (Shell)new Accessor(control[0], AbstractInformationControl.class).get("fShell");
171 new DisplayHelper() {
172 @Override
173 protected boolean condition() {
174 return shell.isVisible();
175 }
176 }.waitForCondition(this.editor.getSite().getShell().getDisplay(), 2000);
128177 assertTrue(shell.isVisible());
129178 return shell;
130179 }
131180
132181 private <T extends Control> T findControl(Control control, Class<T> controlType, String label) {
133182 if (control.getClass() == controlType) {
134 T res = (T)control;
183 @SuppressWarnings("unchecked")
184 T res = (T) control;
135185 if (label == null) {
136186 return res;
137187 }
0 /*******************************************************************************
1 * Copyright (c) 2017 Red Hat Inc. and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Lucas Bullen (Red Hat Inc.) - initial implementation
9 *******************************************************************************/
10 package org.eclipse.ui.genericeditor.tests;
11
12 import java.io.ByteArrayInputStream;
13
14 import org.junit.Assert;
15 import org.junit.Test;
16
17 import org.eclipse.swt.widgets.Display;
18
19 import org.eclipse.core.runtime.NullProgressMonitor;
20
21 import org.eclipse.core.resources.IFile;
22 import org.eclipse.core.resources.IProject;
23 import org.eclipse.core.resources.ResourcesPlugin;
24
25 import org.eclipse.jface.text.BadLocationException;
26 import org.eclipse.jface.text.IDocument;
27 import org.eclipse.jface.text.tests.util.DisplayHelper;
28
29 import org.eclipse.ui.PlatformUI;
30 import org.eclipse.ui.genericeditor.tests.contributions.EnabledPropertyTester;
31 import org.eclipse.ui.genericeditor.tests.contributions.ReconcilerStrategyFirst;
32 import org.eclipse.ui.genericeditor.tests.contributions.ReconcilerStrategySecond;
33 import org.eclipse.ui.internal.genericeditor.ExtensionBasedTextEditor;
34 import org.eclipse.ui.part.FileEditorInput;
35
36 import org.eclipse.ui.texteditor.IDocumentProvider;
37
38 public class ReconcilerTest extends AbstratGenericEditorTest {
39
40 protected ExtensionBasedTextEditor secondEditor;
41 protected IFile secondFile;
42 protected IProject secondProject;
43
44 @Test
45 public void testReconciler() throws Exception {
46 performTestOnEditor(ReconcilerStrategyFirst.SEARCH_TERM, editor, ReconcilerStrategyFirst.REPLACEMENT);
47 }
48
49 @Test
50 public void testEnabledWhenReconciler() throws Exception {
51 EnabledPropertyTester.setEnabled(true);
52 createAndOpenFile("enabledWhen.txt", "");
53 performTestOnEditor(ReconcilerStrategyFirst.SEARCH_TERM, editor, ReconcilerStrategyFirst.REPLACEMENT);
54 cleanFileAndEditor();
55
56 EnabledPropertyTester.setEnabled(false);
57 createAndOpenFile("enabledWhen.txt", "");
58 performTestOnEditor(ReconcilerStrategySecond.SEARCH_TERM, editor, ReconcilerStrategySecond.REPLACEMENT);
59 }
60
61 @Test
62 public void testMultipleEditors() throws Exception {
63 secondProject= ResourcesPlugin.getWorkspace().getRoot().getProject(getClass().getName() + System.currentTimeMillis());
64 secondProject.create(null);
65 secondProject.open(null);
66 secondFile= secondProject.getFile("foo.txt");
67 secondFile.create(new ByteArrayInputStream("bar 'bar'".getBytes()), true, null);
68 secondEditor = (ExtensionBasedTextEditor) PlatformUI.getWorkbench().getActiveWorkbenchWindow()
69 .getActivePage().openEditor(new FileEditorInput(secondFile), "org.eclipse.ui.genericeditor.GenericEditor");
70 performTestOnEditor(ReconcilerStrategyFirst.SEARCH_TERM, editor, ReconcilerStrategyFirst.REPLACEMENT);
71 }
72
73 @Test
74 public void testMultipleReconcilers() throws Exception {
75 secondFile = project.getFile("bar.txt");
76 secondFile.create(new ByteArrayInputStream("".getBytes()), true, null);
77 secondEditor = (ExtensionBasedTextEditor) PlatformUI.getWorkbench().getActiveWorkbenchWindow()
78 .getActivePage().openEditor(new FileEditorInput(secondFile), "org.eclipse.ui.genericeditor.GenericEditor");
79 performTestOnEditor(ReconcilerStrategyFirst.SEARCH_TERM, secondEditor, ReconcilerStrategySecond.REPLACEMENT);
80 }
81
82 private void performTestOnEditor(String startingText, ExtensionBasedTextEditor textEditor, String expectedText) throws Exception {
83 IDocumentProvider dp = textEditor.getDocumentProvider();
84 IDocument doc = dp.getDocument(textEditor.getEditorInput());
85
86 doc.set(startingText);
87
88 new DisplayHelper() {
89 @Override
90 protected boolean condition() {
91 try {
92 return doc.get(0, doc.getLineLength(0)).contains(expectedText);
93 } catch (BadLocationException e) {
94 return false;
95 }
96 }
97 }.waitForCondition(Display.getDefault().getActiveShell().getDisplay(), 2000);
98 Assert.assertTrue("file was not affected by reconciler", doc.get().contains(expectedText));
99 }
100
101 @Override
102 public void tearDown() throws Exception {
103 if (secondEditor != null)
104 {
105 secondEditor.close(false);
106 secondEditor = null;
107 while(Display.getDefault().readAndDispatch()) {}
108 }
109 if (secondFile != null)
110 {
111 secondFile.delete(true, new NullProgressMonitor());
112 secondFile = null;
113 }
114 super.tearDown();
115 if (secondProject != null)
116 {
117 secondProject.delete(true, new NullProgressMonitor());
118 }
119 }
120 }
99 *******************************************************************************/
1010 package org.eclipse.ui.genericeditor.tests;
1111
12 import static org.junit.Assert.assertNull;
13
1214 import org.junit.Assert;
1315 import org.junit.Test;
1416
1618 import org.eclipse.swt.custom.StyledText;
1719 import org.eclipse.swt.graphics.RGB;
1820 import org.eclipse.swt.widgets.Control;
21
22 import org.eclipse.ui.genericeditor.tests.contributions.EnabledPropertyTester;
1923
2024 public class StylingTest extends AbstratGenericEditorTest {
2125
2832 Assert.assertTrue("Token is not of expected color", isRed);
2933 }
3034
35 @Test
36 public void testEnabledWhenStyle() throws Exception {
37 EnabledPropertyTester.setEnabled(true);
38 createAndOpenFile("enabledWhen.txt", "bar 'bar'");
39 editor.selectAndReveal(4, 8);
40 StyledText widget = (StyledText) editor.getAdapter(Control.class);
41 StyleRange style= widget.getStyleRangeAtOffset(4);//get the style of first token
42 boolean isBlue= style.foreground.getRGB().equals(new RGB(0, 0, 255));//is it Blue?
43 Assert.assertTrue("Token is not of expected color", isBlue);
44 cleanFileAndEditor();
45
46 EnabledPropertyTester.setEnabled(false);
47 createAndOpenFile("enabledWhen.txt", "bar 'bar'");
48 editor.selectAndReveal(4, 8);
49 widget = (StyledText) editor.getAdapter(Control.class);
50 assertNull(widget.getStyleRangeAtOffset(4));
51 }
52
3153 }
0 /*******************************************************************************
1 * Copyright (c) 2016 Red Hat Inc. and others
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Mickael Istria (Red Hat Inc.)
9 *******************************************************************************/
10 package org.eclipse.ui.genericeditor.tests.contributions;
11
12 import org.eclipse.jface.text.IRegion;
13 import org.eclipse.jface.text.ITextHover;
14 import org.eclipse.jface.text.ITextHoverExtension2;
15 import org.eclipse.jface.text.ITextViewer;
16 import org.eclipse.jface.text.Region;
17
18 public class AlrightyHoverProvider implements ITextHover,ITextHoverExtension2 {
19
20 public static final String LABEL= "Alrighty!";
21
22 @Deprecated
23 @Override
24 public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
25 return null;
26 }
27
28 @Override
29 public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
30 return new Region(0, textViewer.getTextWidget().getText().length());
31 }
32
33 @Override
34 public Object getHoverInfo2(ITextViewer textViewer, IRegion hoverRegion) {
35 return LABEL;
36 }
37
38 }
66 *
77 * Contributors:
88 * - Mickael Istria (Red Hat Inc.)
9 * Stephan Wahlbrink <sw@wahlbrink.eu> - Bug 512251 - Fix IllegalArgumentException in ContextInformationPopup
910 *******************************************************************************/
1011 package org.eclipse.ui.genericeditor.tests.contributions;
1112
13 import java.util.Arrays;
14
15 import org.eclipse.jface.text.BadLocationException;
16 import org.eclipse.jface.text.IDocument;
17 import org.eclipse.jface.text.IRegion;
1218 import org.eclipse.jface.text.ITextViewer;
1319 import org.eclipse.jface.text.contentassist.CompletionProposal;
20 import org.eclipse.jface.text.contentassist.ContextInformation;
1421 import org.eclipse.jface.text.contentassist.ICompletionProposal;
1522 import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
1623 import org.eclipse.jface.text.contentassist.IContextInformation;
1825
1926 public class BarContentAssistProcessor implements IContentAssistProcessor {
2027
21 public static final String PROPOSAL = "s are good for a beer.";
28 public static final String PROPOSAL = "bars are good for a beer.";
29 private final String completeString;
30
31 public BarContentAssistProcessor() {
32 this(PROPOSAL);
33 }
34
35 public BarContentAssistProcessor(String completeString) {
36 this.completeString = completeString;
37 }
2238
2339 @Override
2440 public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) {
25 String text = viewer.getDocument().get();
26 if (text.length() >= 3 && text.substring(offset - 3, offset).equals("bar")) {
27 String message = PROPOSAL;
28 CompletionProposal proposal = new CompletionProposal(message, offset, 0, message.length());
29 return new ICompletionProposal[] { proposal };
41 for (int offsetInProposal = Math.min(this.completeString.length(), viewer.getDocument().getLength()); offsetInProposal > 0; offsetInProposal--) {
42 String maybeMatchingString = this.completeString.substring(0, offsetInProposal);
43 try {
44 int lastIndex = offset - offsetInProposal + this.completeString.length();
45 if (offset >= offsetInProposal && viewer.getDocument().get(offset - offsetInProposal, maybeMatchingString.length()).equals(maybeMatchingString)) {
46 CompletionProposal proposal = new CompletionProposal(this.completeString.substring(offsetInProposal), offset, 0, lastIndex);
47 return new ICompletionProposal[] { proposal };
48 }
49 } catch (BadLocationException e) {
50 e.printStackTrace();
51 }
3052 }
3153 return new ICompletionProposal[0];
32 }
33
34 @Override
35 public IContextInformation[] computeContextInformation(ITextViewer viewer, int offset) {
36 return null;
3754 }
3855
3956 @Override
4663 return null;
4764 }
4865
66 /**
67 * Creates context info "idx= <word index in #PROPOSAL>" at the end of a word.
68 **/
69 @Override
70 public IContextInformation[] computeContextInformation(ITextViewer viewer, int offset) {
71 try {
72 IDocument document= viewer.getDocument();
73 int begin= offset;
74 while (begin > 0 && Character.isLetterOrDigit(document.getChar(begin - 1))) {
75 begin--;
76 }
77 if (begin < offset) {
78 String word= document.get(begin, offset - begin);
79 int idx= Arrays.asList(completeString.split("\\W")).indexOf(word);
80 if (idx >= 0) {
81 return new IContextInformation[] {
82 new ContextInformation(word, "idx= " + idx)
83 };
84 }
85 }
86 } catch (BadLocationException e) {
87 e.printStackTrace();
88 }
89 return null;
90 }
91
92 @Override
93 public IContextInformationValidator getContextInformationValidator() {
94 return new IContextInformationValidator() {
95 ITextViewer viewer;
96 int offset;
97 @Override
98 public void install(IContextInformation info, ITextViewer viewer, int offset) {
99 this.viewer= viewer;
100 this.offset= offset;
101 }
102 @Override
103 public boolean isContextInformationValid(int offset) {
104 try {
105 IDocument document= viewer.getDocument();
106 IRegion line= document.getLineInformationOfOffset(this.offset);
107 int end= line.getOffset() + line.getLength();
108 return (offset >= this.offset && offset < end);
109 } catch (BadLocationException e) {
110 return false;
111 }
112 }
113 };
114 }
115
49116 @Override
50117 public String getErrorMessage() {
51118 return null;
52119 }
53120
54 @Override
55 public IContextInformationValidator getContextInformationValidator() {
56 return null;
57 }
58
59121 }
0 /*******************************************************************************
1 * Copyright (c) 2018 Red Hat Inc. and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * - Lucas Bullen (Red Hat Inc.)
9 *******************************************************************************/
10 package org.eclipse.ui.genericeditor.tests.contributions;
11
12 import org.eclipse.core.expressions.PropertyTester;
13
14 public class EnabledPropertyTester extends PropertyTester {
15
16 private static final String PROPERTY_NAME = "enabled";
17 private static boolean isEnabled = true;
18
19 @Override
20 public boolean test(Object receiver, String property, Object[] args, Object expectedValue) {
21 if (property.equals(PROPERTY_NAME)) {
22 return isEnabled;
23 }
24 return false;
25 }
26
27 public static void setEnabled(boolean isEnabled) {
28 EnabledPropertyTester.isEnabled = isEnabled;
29 }
30
31 }
0 /*******************************************************************************
1 * Copyright (c) 2017 Red Hat Inc. and others
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Mickael Istria (Red Hat Inc.)
9 *******************************************************************************/
10 package org.eclipse.ui.genericeditor.tests.contributions;
11
12 import org.eclipse.jface.text.IRegion;
13 import org.eclipse.jface.text.ITextHover;
14 import org.eclipse.jface.text.ITextHoverExtension2;
15 import org.eclipse.jface.text.ITextViewer;
16 import org.eclipse.jface.text.Region;
17
18 public class HelloHoverProvider implements ITextHover, ITextHoverExtension2 {
19
20 public static final String LABEL= "Hello!";
21
22 @Deprecated
23 @Override
24 public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
25 return null;
26 }
27
28 @Override
29 public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
30 return new Region(0, textViewer.getTextWidget().getText().length());
31 }
32
33 @Override
34 public Object getHoverInfo2(ITextViewer textViewer, IRegion hoverRegion) {
35 return LABEL;
36 }
37 }
0 /*******************************************************************************
1 * Copyright (c) 2017 Red Hat Inc. and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * - Lucas Bullen (Red Hat Inc.)
9 *******************************************************************************/
10 package org.eclipse.ui.genericeditor.tests.contributions;
11
12 import org.eclipse.jface.text.IDocument;
13 import org.eclipse.jface.text.ITextViewer;
14 import org.eclipse.jface.text.reconciler.Reconciler;
15
16 public class HighlightReconciler extends Reconciler {
17
18 private HighlightStrategy fStrategy;
19
20 public HighlightReconciler() {
21 fStrategy = new HighlightStrategy();
22 this.setReconcilingStrategy(fStrategy, IDocument.DEFAULT_CONTENT_TYPE);
23 }
24
25 @Override
26 public void install(ITextViewer textViewer) {
27 super.install(textViewer);
28 fStrategy.install(textViewer);
29 }
30
31 @Override
32 public void uninstall() {
33 super.uninstall();
34 fStrategy.uninstall();
35 }
36 }
0 /*******************************************************************************
1 * Copyright (c) 2017 Red Hat Inc. and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * - Lucas Bullen (Red Hat Inc.)
9 *******************************************************************************/
10 package org.eclipse.ui.genericeditor.tests.contributions;
11
12 import org.eclipse.swt.custom.CaretEvent;
13 import org.eclipse.swt.custom.CaretListener;
14
15 import org.eclipse.core.runtime.IProgressMonitor;
16 import org.eclipse.core.runtime.preferences.IEclipsePreferences;
17 import org.eclipse.core.runtime.preferences.IEclipsePreferences.IPreferenceChangeListener;
18 import org.eclipse.core.runtime.preferences.IEclipsePreferences.PreferenceChangeEvent;
19 import org.eclipse.core.runtime.preferences.InstanceScope;
20
21 import org.eclipse.jface.text.IDocument;
22 import org.eclipse.jface.text.IRegion;
23 import org.eclipse.jface.text.ISynchronizable;
24 import org.eclipse.jface.text.ITextViewer;
25 import org.eclipse.jface.text.Position;
26 import org.eclipse.jface.text.reconciler.DirtyRegion;
27 import org.eclipse.jface.text.reconciler.IReconcilingStrategy;
28 import org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension;
29 import org.eclipse.jface.text.source.Annotation;
30 import org.eclipse.jface.text.source.IAnnotationModel;
31 import org.eclipse.jface.text.source.IAnnotationModelExtension;
32 import org.eclipse.jface.text.source.ISourceViewer;
33
34 /**
35 *
36 * This Reconciler Strategy is an example for how to override the default highlight strategy.
37 * It will highlight closing and opening tag names that match the current word the user is on.
38 *
39 */
40 public class HighlightStrategy implements IReconcilingStrategy, IReconcilingStrategyExtension, CaretListener, IPreferenceChangeListener {
41
42 private static final String ANNOTATION_TYPE = "org.eclipse.ui.genericeditor.text"; //$NON-NLS-1$
43 public static final String TOGGLE_HIGHLIGHT_PREFERENCE = "org.eclipse.ui.genericeditor.togglehighlight"; //$NON-NLS-1$
44 public static final String GENERIC_EDITOR_BUNDLE_ID = "org.eclipse.ui.genericeditor"; //$NON-NLS-1$
45
46 private boolean enabled;
47 private ISourceViewer sourceViewer;
48 private IDocument document;
49
50 public static final String SEARCH_TERM = "'bar'";
51
52 private Annotation[] fOccurrenceAnnotations = null;
53
54 private void applyHighlights() {
55 if (sourceViewer == null || !enabled) {
56 return;
57 }
58
59 removeOccurrenceAnnotations();
60 int searchOffset = document.get().indexOf(SEARCH_TERM);
61 if(searchOffset == -1) {
62 return;
63 }
64 sourceViewer.getAnnotationModel().addAnnotation(new Annotation(ANNOTATION_TYPE, false, null),
65 new Position(searchOffset, 5));
66
67 }
68
69 public void install(ITextViewer viewer) {
70 if (!(viewer instanceof ISourceViewer)) {
71 return;
72 }
73 IEclipsePreferences preferences = InstanceScope.INSTANCE.getNode(GENERIC_EDITOR_BUNDLE_ID);
74 preferences.addPreferenceChangeListener(this);
75 this.enabled = preferences.getBoolean(TOGGLE_HIGHLIGHT_PREFERENCE, true);
76 this.sourceViewer = (ISourceViewer) viewer;
77 this.sourceViewer.getTextWidget().addCaretListener(this);
78 }
79
80 public void uninstall() {
81 if (sourceViewer != null) {
82 sourceViewer.getTextWidget().removeCaretListener(this);
83 }
84 IEclipsePreferences preferences = InstanceScope.INSTANCE.getNode(GENERIC_EDITOR_BUNDLE_ID);
85 preferences.removePreferenceChangeListener(this);
86 }
87
88 @Override
89 public void preferenceChange(PreferenceChangeEvent event) {
90 if (event.getKey().equals(TOGGLE_HIGHLIGHT_PREFERENCE)) {
91 this.enabled = Boolean.parseBoolean(event.getNewValue().toString());
92 if (enabled) {
93 initialReconcile();
94 } else {
95 removeOccurrenceAnnotations();
96 }
97 }
98 }
99
100 @Override
101 public void caretMoved(CaretEvent event) {
102 applyHighlights();
103 }
104
105 @Override
106 public void initialReconcile() {
107 if (sourceViewer != null) {
108 sourceViewer.getTextWidget().getDisplay().asyncExec(() -> {
109 if (sourceViewer != null && sourceViewer.getTextWidget() != null) {
110 applyHighlights();
111 }
112 });
113 }
114 }
115
116 void removeOccurrenceAnnotations() {
117 IAnnotationModel annotationModel = sourceViewer.getAnnotationModel();
118 if (annotationModel == null || fOccurrenceAnnotations == null) {
119 return;
120 }
121
122 synchronized (getLockObject(annotationModel)) {
123 if (annotationModel instanceof IAnnotationModelExtension) {
124 ((IAnnotationModelExtension) annotationModel).replaceAnnotations(fOccurrenceAnnotations, null);
125 } else {
126 for (Annotation fOccurrenceAnnotation : fOccurrenceAnnotations) {
127 annotationModel.removeAnnotation(fOccurrenceAnnotation);
128 }
129 }
130 fOccurrenceAnnotations = null;
131 }
132 }
133
134 private static Object getLockObject(IAnnotationModel annotationModel) {
135 if (annotationModel instanceof ISynchronizable) {
136 Object lock = ((ISynchronizable) annotationModel).getLockObject();
137 if (lock != null) {
138 return lock;
139 }
140 }
141 return annotationModel;
142 }
143
144 @Override
145 public void setDocument(IDocument document) {
146 this.document = document;
147 }
148
149 @Override
150 public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) {
151 // Do nothing
152 }
153
154 @Override
155 public void reconcile(IRegion partition) {
156 // Do nothing
157 }
158
159 @Override
160 public void setProgressMonitor(IProgressMonitor monitor) {
161 // Not used
162 }
163 }
1010 package org.eclipse.ui.genericeditor.tests.contributions;
1111
1212 import org.eclipse.jface.text.ITextViewer;
13 import org.eclipse.jface.text.contentassist.CompletionProposal;
1413 import org.eclipse.jface.text.contentassist.ICompletionProposal;
15 import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
16 import org.eclipse.jface.text.contentassist.IContextInformation;
17 import org.eclipse.jface.text.contentassist.IContextInformationValidator;
1814
19 public class LongRunningBarContentAssistProcessor implements IContentAssistProcessor {
15 public class LongRunningBarContentAssistProcessor extends BarContentAssistProcessor {
2016
21 public static final String PROPOSAL = "s are also good for soft drink cocktails.";
17 public static final String PROPOSAL = "bars are also good for soft drink cocktails.";
2218 public static final int DELAY = 2000;
19
20 public LongRunningBarContentAssistProcessor() {
21 super(PROPOSAL);
22 }
2323
2424 @Override
2525 public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) {
2929 // TODO Auto-generated catch block
3030 e.printStackTrace();
3131 }
32 String text = viewer.getDocument().get();
33 if (text.length() >= 3 && text.substring(offset - 3, offset).equals("bar")) {
34 String message = PROPOSAL;
35 CompletionProposal proposal = new CompletionProposal(message, offset, 0, message.length());
36 return new ICompletionProposal[] { proposal };
37 }
38 return new ICompletionProposal[0];
32 return super.computeCompletionProposals(viewer, offset);
3933 }
40
41 @Override
42 public IContextInformation[] computeContextInformation(ITextViewer viewer, int offset) {
43 return null;
44 }
45
46 @Override
47 public char[] getCompletionProposalAutoActivationCharacters() {
48 return null;
49 }
50
51 @Override
52 public char[] getContextInformationAutoActivationCharacters() {
53 return null;
54 }
55
56 @Override
57 public String getErrorMessage() {
58 return null;
59 }
60
61 @Override
62 public IContextInformationValidator getContextInformationValidator() {
63 return null;
64 }
65
6634 }
+0
-39
org.eclipse.ui.genericeditor.tests/src/org/eclipse/ui/genericeditor/tests/contributions/MagicHoverProvider.java less more
0 /*******************************************************************************
1 * Copyright (c) 2016 Red Hat Inc. and others
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Mickael Istria (Red Hat Inc.)
9 *******************************************************************************/
10 package org.eclipse.ui.genericeditor.tests.contributions;
11
12 import org.eclipse.jface.text.IRegion;
13 import org.eclipse.jface.text.ITextHover;
14 import org.eclipse.jface.text.ITextHoverExtension2;
15 import org.eclipse.jface.text.ITextViewer;
16 import org.eclipse.jface.text.Region;
17
18 public class MagicHoverProvider implements ITextHover,ITextHoverExtension2 {
19
20 public static final String LABEL= "Alrighty!";
21
22 @Deprecated
23 @Override
24 public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
25 return null;
26 }
27
28 @Override
29 public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
30 return new Region(0, textViewer.getTextWidget().getText().length());
31 }
32
33 @Override
34 public Object getHoverInfo2(ITextViewer textViewer, IRegion hoverRegion) {
35 return LABEL;
36 }
37
38 }
0 /*******************************************************************************
1 * Copyright (c) 2017 Red Hat Inc. and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Lucas Bullen (Red Hat Inc.) - initial implementation
9 *******************************************************************************/
10 package org.eclipse.ui.genericeditor.tests.contributions;
11
12 import org.eclipse.swt.widgets.Display;
13
14 import org.eclipse.core.runtime.IProgressMonitor;
15
16 import org.eclipse.jface.text.IDocument;
17 import org.eclipse.jface.text.IRegion;
18 import org.eclipse.jface.text.reconciler.DirtyRegion;
19 import org.eclipse.jface.text.reconciler.IReconcilingStrategy;
20 import org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension;
21
22 public class ReconcilerStrategyFirst implements IReconcilingStrategy, IReconcilingStrategyExtension{
23
24 IDocument document;
25 public static final String SEARCH_TERM = "foo";
26 public static final String REPLACEMENT = "BAR";
27
28 @Override
29 public void setDocument(IDocument document) {
30 this.document = document;
31 }
32
33 @Override
34 public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) {
35 initialReconcile();
36 }
37
38 @Override
39 public void reconcile(IRegion partition) {
40 initialReconcile();
41 }
42
43 @Override
44 public void setProgressMonitor(IProgressMonitor monitor) {
45 // no progress monitor in use
46 }
47
48 @Override
49 public void initialReconcile() {
50 String doc = document.get();
51 if(doc.contains(SEARCH_TERM)) {
52 Display.getDefault().asyncExec(() -> {
53 document.set(document.get().replaceAll(SEARCH_TERM, REPLACEMENT));
54 });
55 }
56 }
57
58 }
0 /*******************************************************************************
1 * Copyright (c) 2017 Red Hat Inc. and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Lucas Bullen (Red Hat Inc.) - initial implementation
9 *******************************************************************************/
10 package org.eclipse.ui.genericeditor.tests.contributions;
11
12 import org.eclipse.swt.widgets.Display;
13
14 import org.eclipse.core.runtime.IProgressMonitor;
15
16 import org.eclipse.jface.text.IDocument;
17 import org.eclipse.jface.text.IRegion;
18 import org.eclipse.jface.text.reconciler.DirtyRegion;
19 import org.eclipse.jface.text.reconciler.IReconcilingStrategy;
20 import org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension;
21
22 public class ReconcilerStrategySecond implements IReconcilingStrategy, IReconcilingStrategyExtension{
23
24 IDocument document;
25 public static final String SEARCH_TERM = "BAR";
26 public static final String REPLACEMENT = "second";
27
28 @Override
29 public void setDocument(IDocument document) {
30 this.document = document;
31 }
32
33 @Override
34 public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) {
35 initialReconcile();
36 }
37
38 @Override
39 public void reconcile(IRegion partition) {
40 initialReconcile();
41 }
42
43 @Override
44 public void setProgressMonitor(IProgressMonitor monitor) {
45 // no progress monitor in use
46 }
47
48 @Override
49 public void initialReconcile() {
50 String doc = document.get();
51 if(doc.contains(SEARCH_TERM)) {
52 Display.getDefault().asyncExec(() -> {
53 document.set(document.get().replaceAll(SEARCH_TERM, REPLACEMENT));
54 });
55 }
56 }
57
58 }
0 /*******************************************************************************
1 * Copyright (c) 2017 Rogue Wave Software Inc. and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Michał Niewrzał (Rogue Wave Software Inc.) - initial implementation
9 *******************************************************************************/
10 package org.eclipse.ui.genericeditor.tests.contributions;
11
12 import org.eclipse.jface.text.DocumentCommand;
13 import org.eclipse.jface.text.IAutoEditStrategy;
14 import org.eclipse.jface.text.IDocument;
15
16 public class TheAutoEditStrategyFirst implements IAutoEditStrategy {
17
18 @Override
19 public void customizeDocumentCommand(IDocument document, DocumentCommand command) {
20 command.text = command.text + "AutoAddedFirst!";
21 }
22
23 }
0 /*******************************************************************************
1 * Copyright (c) 2017 Rogue Wave Software Inc. and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Michał Niewrzał (Rogue Wave Software Inc.) - initial implementation
9 *******************************************************************************/
10 package org.eclipse.ui.genericeditor.tests.contributions;
11
12 import org.eclipse.jface.text.DocumentCommand;
13 import org.eclipse.jface.text.IAutoEditStrategy;
14 import org.eclipse.jface.text.IDocument;
15
16 public class TheAutoEditStrategySecond implements IAutoEditStrategy {
17
18 @Override
19 public void customizeDocumentCommand(IDocument document, DocumentCommand command) {
20 command.text = command.text + "AutoAddedSecond!";
21 }
22
23 }
0 /*******************************************************************************
1 * Copyright (c) 2017 Rogue Wave Software Inc. and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Michał Niewrzał (Rogue Wave Software Inc.) - initial implementation
9 *******************************************************************************/
10 package org.eclipse.ui.genericeditor.tests.contributions;
11
12 import org.eclipse.jface.text.DocumentCommand;
13 import org.eclipse.jface.text.IAutoEditStrategy;
14 import org.eclipse.jface.text.IDocument;
15
16 public class TheAutoEditStrategyThird implements IAutoEditStrategy {
17
18 @Override
19 public void customizeDocumentCommand(IDocument document, DocumentCommand command) {
20 command.text = command.text + "AutoAddedThird!";
21 }
22
23 }
+0
-38
org.eclipse.ui.genericeditor.tests/src/org/eclipse/ui/genericeditor/tests/contributions/ThePresentationReconciler.java less more
0 /*******************************************************************************
1 * Copyright (c) 2016 Red Hat Inc. and others
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Sopot Cela (Red Hat Inc.)
9 *******************************************************************************/
10 package org.eclipse.ui.genericeditor.tests.contributions;
11
12 import org.eclipse.swt.graphics.Color;
13 import org.eclipse.swt.graphics.RGB;
14 import org.eclipse.swt.widgets.Display;
15
16 import org.eclipse.jface.text.IDocument;
17 import org.eclipse.jface.text.TextAttribute;
18 import org.eclipse.jface.text.presentation.PresentationReconciler;
19 import org.eclipse.jface.text.rules.DefaultDamagerRepairer;
20 import org.eclipse.jface.text.rules.IRule;
21 import org.eclipse.jface.text.rules.RuleBasedScanner;
22 import org.eclipse.jface.text.rules.SingleLineRule;
23 import org.eclipse.jface.text.rules.Token;
24
25 public class ThePresentationReconciler extends PresentationReconciler {
26
27 public ThePresentationReconciler() {
28 RuleBasedScanner scanner= new RuleBasedScanner();
29 IRule[] rules = new IRule[1];
30 rules[0]= new SingleLineRule("'", "'", new Token(new TextAttribute(new Color(Display.getCurrent(), new RGB(255, 0, 0))))); //$NON-NLS-1$ //$NON-NLS-2$
31 scanner.setRules(rules);
32 DefaultDamagerRepairer dr= new DefaultDamagerRepairer(scanner);
33 this.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE);
34 this.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE);
35 }
36
37 }
0 /*******************************************************************************
1 * Copyright (c) 2016 Red Hat Inc. and others
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Sopot Cela (Red Hat Inc.)
9 *******************************************************************************/
10 package org.eclipse.ui.genericeditor.tests.contributions;
11
12 import org.eclipse.swt.graphics.Color;
13 import org.eclipse.swt.graphics.RGB;
14 import org.eclipse.swt.widgets.Display;
15
16 import org.eclipse.jface.text.IDocument;
17 import org.eclipse.jface.text.TextAttribute;
18 import org.eclipse.jface.text.presentation.PresentationReconciler;
19 import org.eclipse.jface.text.rules.DefaultDamagerRepairer;
20 import org.eclipse.jface.text.rules.IRule;
21 import org.eclipse.jface.text.rules.RuleBasedScanner;
22 import org.eclipse.jface.text.rules.SingleLineRule;
23 import org.eclipse.jface.text.rules.Token;
24
25 public class ThePresentationReconcilerBlue extends PresentationReconciler {
26
27 public ThePresentationReconcilerBlue() {
28 RuleBasedScanner scanner= new RuleBasedScanner();
29 IRule[] rules = new IRule[1];
30 rules[0]= new SingleLineRule("'", "'", new Token(new TextAttribute(new Color(Display.getCurrent(), new RGB(0, 0, 255))))); //$NON-NLS-1$ //$NON-NLS-2$
31 scanner.setRules(rules);
32 DefaultDamagerRepairer dr= new DefaultDamagerRepairer(scanner);
33 this.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE);
34 this.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE);
35 }
36
37 }
0 /*******************************************************************************
1 * Copyright (c) 2016-2017 Red Hat Inc. and others
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Sopot Cela (Red Hat Inc.)
9 *******************************************************************************/
10 package org.eclipse.ui.genericeditor.tests.contributions;
11
12 import org.eclipse.swt.graphics.Color;
13 import org.eclipse.swt.graphics.RGB;
14 import org.eclipse.swt.widgets.Display;
15
16 import org.eclipse.jface.text.IDocument;
17 import org.eclipse.jface.text.TextAttribute;
18 import org.eclipse.jface.text.presentation.PresentationReconciler;
19 import org.eclipse.jface.text.rules.DefaultDamagerRepairer;
20 import org.eclipse.jface.text.rules.IRule;
21 import org.eclipse.jface.text.rules.RuleBasedScanner;
22 import org.eclipse.jface.text.rules.SingleLineRule;
23 import org.eclipse.jface.text.rules.Token;
24
25 /**
26 * This presentation reconciler is associated to a more "basic" content-type so it
27 * shouldn't be used.
28 */
29 public class ThePresentationReconcilerGreen extends PresentationReconciler {
30
31 public ThePresentationReconcilerGreen() {
32 RuleBasedScanner scanner= new RuleBasedScanner();
33 IRule[] rules = new IRule[1];
34 rules[0]= new SingleLineRule("'", "'", new Token(new TextAttribute(new Color(Display.getCurrent(), new RGB(0, 255, 0))))); //$NON-NLS-1$ //$NON-NLS-2$
35 scanner.setRules(rules);
36 DefaultDamagerRepairer dr= new DefaultDamagerRepairer(scanner);
37 this.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE);
38 this.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE);
39 }
40
41 }
0 /*******************************************************************************
1 * Copyright (c) 2016 Red Hat Inc. and others
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Sopot Cela (Red Hat Inc.)
9 *******************************************************************************/
10 package org.eclipse.ui.genericeditor.tests.contributions;
11
12 import org.eclipse.swt.graphics.Color;
13 import org.eclipse.swt.graphics.RGB;
14 import org.eclipse.swt.widgets.Display;
15
16 import org.eclipse.jface.text.IDocument;
17 import org.eclipse.jface.text.TextAttribute;
18 import org.eclipse.jface.text.presentation.PresentationReconciler;
19 import org.eclipse.jface.text.rules.DefaultDamagerRepairer;
20 import org.eclipse.jface.text.rules.IRule;
21 import org.eclipse.jface.text.rules.RuleBasedScanner;
22 import org.eclipse.jface.text.rules.SingleLineRule;
23 import org.eclipse.jface.text.rules.Token;
24
25 public class ThePresentationReconcilerRed extends PresentationReconciler {
26
27 public ThePresentationReconcilerRed() {
28 RuleBasedScanner scanner= new RuleBasedScanner();
29 IRule[] rules = new IRule[1];
30 rules[0]= new SingleLineRule("'", "'", new Token(new TextAttribute(new Color(Display.getCurrent(), new RGB(255, 0, 0))))); //$NON-NLS-1$ //$NON-NLS-2$
31 scanner.setRules(rules);
32 DefaultDamagerRepairer dr= new DefaultDamagerRepairer(scanner);
33 this.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE);
34 this.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE);
35 }
36
37 }
0 /*******************************************************************************
1 * Copyright (c) 2017 Red Hat Inc. and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Lucas Bullen (Red Hat Inc.) - initial implementation
9 *******************************************************************************/
10 package org.eclipse.ui.genericeditor.tests.contributions;
11
12 import org.eclipse.jface.text.IDocument;
13 import org.eclipse.jface.text.reconciler.Reconciler;
14
15 public class TheReconcilerFirst extends Reconciler{
16 public TheReconcilerFirst() {
17 this.setReconcilingStrategy(new ReconcilerStrategyFirst(), IDocument.DEFAULT_CONTENT_TYPE);
18 }
19 }
0 /*******************************************************************************
1 * Copyright (c) 2017 Red Hat Inc. and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Lucas Bullen (Red Hat Inc.) - initial implementation
9 *******************************************************************************/
10 package org.eclipse.ui.genericeditor.tests.contributions;
11
12 import org.eclipse.jface.text.IDocument;
13 import org.eclipse.jface.text.reconciler.Reconciler;
14
15 public class TheReconcilerSecond extends Reconciler{
16 public TheReconcilerSecond() {
17 this.setReconcilingStrategy(new ReconcilerStrategySecond(), IDocument.DEFAULT_CONTENT_TYPE);
18 }
19 }
0 /*******************************************************************************
1 * Copyright (c) 2017 Red Hat Inc. and others
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Lucas Bullen (Red Hat Inc.)
9 *******************************************************************************/
10 package org.eclipse.ui.genericeditor.tests.contributions;
11
12 import org.eclipse.jface.text.IRegion;
13 import org.eclipse.jface.text.ITextHover;
14 import org.eclipse.jface.text.ITextHoverExtension2;
15 import org.eclipse.jface.text.ITextViewer;
16 import org.eclipse.jface.text.Region;
17
18 public class WorldHoverProvider implements ITextHover,ITextHoverExtension2 {
19
20 public static final String LABEL= "World!";
21
22 @Deprecated
23 @Override
24 public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
25 return null;
26 }
27
28 @Override
29 public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
30 return new Region(0, textViewer.getTextWidget().getText().length());
31 }
32
33 @Override
34 public Object getHoverInfo2(ITextViewer textViewer, IRegion hoverRegion) {
35 return LABEL;
36 }
37
38 }
1111 org.eclipse.jdt.ui.staticondemandthreshold=99
1212 sp_cleanup.add_default_serial_version_id=false
1313 sp_cleanup.add_generated_serial_version_id=false
14 sp_cleanup.add_missing_annotations=false
14 sp_cleanup.add_missing_annotations=true
1515 sp_cleanup.add_missing_deprecated_annotations=true
1616 sp_cleanup.add_missing_methods=false
1717 sp_cleanup.add_missing_nls_tags=false
4343 sp_cleanup.qualify_static_member_accesses_with_declaring_class=false
4444 sp_cleanup.qualify_static_method_accesses_with_declaring_class=false
4545 sp_cleanup.remove_private_constructors=false
46 sp_cleanup.remove_redundant_type_arguments=false
46 sp_cleanup.remove_redundant_type_arguments=true
4747 sp_cleanup.remove_trailing_whitespaces=true
4848 sp_cleanup.remove_trailing_whitespaces_all=true
4949 sp_cleanup.remove_trailing_whitespaces_ignore_empty=false
50 sp_cleanup.remove_unnecessary_casts=false
50 sp_cleanup.remove_unnecessary_casts=true
5151 sp_cleanup.remove_unnecessary_nls_tags=false
5252 sp_cleanup.remove_unused_imports=false
5353 sp_cleanup.remove_unused_local_variables=false
11 Bundle-ManifestVersion: 2
22 Bundle-Name: %pluginName
33 Bundle-SymbolicName: org.eclipse.ui.workbench.texteditor; singleton:=true
4 Bundle-Version: 3.10.100.qualifier
4 Bundle-Version: 3.11.0.qualifier
55 Bundle-Activator: org.eclipse.ui.internal.texteditor.TextEditorPlugin
66 Bundle-ActivationPolicy: lazy
77 Bundle-Vendor: %providerName
99 Export-Package:
1010 org.eclipse.ui.contentassist,
1111 org.eclipse.ui.internal.texteditor; texteditor="split"; mandatory:="texteditor"; x-friends:="org.eclipse.ui.editors",
12 org.eclipse.ui.internal.texteditor.codemining;x-internal:=true,
1213 org.eclipse.ui.internal.texteditor.quickdiff;x-internal:=true,
1314 org.eclipse.ui.internal.texteditor.quickdiff.compare.equivalence;x-internal:=true,
1415 org.eclipse.ui.internal.texteditor.rulers;x-internal:=true,
2425 org.eclipse.compare.core;bundle-version="[3.5.0,4.0.0)",
2526 org.eclipse.core.expressions;bundle-version="[3.4.100,4.0.0)",
2627 org.eclipse.jface.text;bundle-version="[3.8.0,4.0.0)",
28 org.eclipse.swt;bundle-version="[3.107.0,4.0.0)",
2729 org.eclipse.ui;bundle-version="[3.5.0,4.0.0)"
2830 Bundle-RequiredExecutionEnvironment: JavaSE-1.8
2931 Import-Package: com.ibm.icu.text
32 Automatic-Module-Name: org.eclipse.ui.workbench.texteditor
99 # Tom Eicher (Avaloq Evolution AG) - block selection mode
1010 # Daesung Ha <nberserk@gmail.com> - update recenter command description
1111 # Mickael Istria (Red Hat Inc.) - 469918 Zoom In/Out
12 # Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Provide extension point for CodeMining - Bug 528419
1213 ###############################################################################
1314 pluginName= Text Editor Framework
1415 providerName= Eclipse.org
2021 ExtPoint.rulerColumns= Ruler Columns
2122 ExtPoint.hyperlinkDetectors= Hyperlink Detectors
2223 ExtPoint.hyperlinkDetectorTargets= Hyperlink Detector Targets
24 ExtPoint.codeMiningProviders=CodeMining Providers
2325
2426 textEditorPresentationActionSet.label= Editor Presentation
2527
183185 command.openHyperlink.name= Open Hyperlink
184186 command.openHyperlink.description= Opens the hyperlink at the caret location or opens a chooser if more than one hyperlink is available
185187
188 Color.rangeIndicator= Range indicator color
189 Color.rangeIndicatorDesc= The color that is used for the ruler that marks the range of the current selected text block.
190
186191 SpellingEngine= Spelling Engine
187192
188193 blockSelectionModeFont.label= Text Editor Block Selection Font
66 <extension-point id="rulerColumns" name="%ExtPoint.rulerColumns" schema="schema/rulerColumns.exsd"/>
77 <extension-point id="hyperlinkDetectors" name="%ExtPoint.hyperlinkDetectors" schema="schema/hyperlinkDetectors.exsd"/>
88 <extension-point id="hyperlinkDetectorTargets" name="%ExtPoint.hyperlinkDetectorTargets" schema="schema/hyperlinkDetectorTargets.exsd"/>
9 <extension-point id="codeMiningProviders" name="%ExtPoint.codeMiningProviders" schema="schema/codeMiningProviders.exsd"/>
910
1011 <extension
1112 point="org.eclipse.ui.commands">
13001301 value="Monaco-regular-11">
13011302 </fontValue>
13021303 </fontDefinition>
1304 <colorDefinition
1305 categoryId="org.eclipse.ui.workbenchMisc"
1306 id="org.eclipse.ui.editors.rangeIndicatorColor"
1307 label="%Color.rangeIndicator"
1308 value="COLOR_LIST_SELECTION">
1309 <description>
1310 %Color.rangeIndicatorDesc
1311 </description>
1312 </colorDefinition>
13031313 </extension>
13041314
13051315 <extension
13071317 <handler
13081318 class="org.eclipse.ui.texteditor.TextZoomInHandler"
13091319 commandId="org.eclipse.ui.edit.text.zoomIn">
1310 <enabledWhen>
1311 <with variable="activePart">
1312 <instanceof
1313 value="org.eclipse.ui.texteditor.ITextEditor">
1314 </instanceof>
1315 </with>
1316 </enabledWhen>
13171320 </handler>
13181321 <handler
13191322 class="org.eclipse.ui.texteditor.TextZoomOutHandler"
13201323 commandId="org.eclipse.ui.edit.text.zoomOut">
1321 <enabledWhen>
1322 <with variable="activePart">
1323 <instanceof
1324 value="org.eclipse.ui.texteditor.ITextEditor">
1325 </instanceof>
1326 </with>
1327 </enabledWhen>
13281324 </handler>
13291325 </extension>
13301326 <extension
00 <?xml version="1.0" encoding="UTF-8"?>
11 <!--
2 Copyright (c) 2012, 2016 Eclipse Foundation and others.
2 Copyright (c) 2012, 2018 Eclipse Foundation and others.
33 All rights reserved. This program and the accompanying materials
44 are made available under the terms of the Eclipse Distribution License v1.0
55 which accompanies this distribution, and is available at
1313 <parent>
1414 <artifactId>eclipse.platform.text</artifactId>
1515 <groupId>eclipse.platform.text</groupId>
16 <version>4.7.3-SNAPSHOT</version>
16 <version>4.8.0-SNAPSHOT</version>
1717 </parent>
1818 <groupId>org.eclipse.ui</groupId>
1919 <artifactId>org.eclipse.ui.workbench.texteditor</artifactId>
20 <version>3.10.100-SNAPSHOT</version>
20 <version>3.11.0-SNAPSHOT</version>
2121 <packaging>eclipse-plugin</packaging>
2222 </project>
0 <?xml version='1.0' encoding='UTF-8'?>
1 <!-- Schema file written by PDE -->
2 <schema targetNamespace="org.eclipse.ui.workbench.texteditor" xmlns="http://www.w3.org/2001/XMLSchema">
3 <annotation>
4 <appInfo>
5 <meta.schema plugin="org.eclipse.ui.workbench.texteditor" id="codeMiningProviders" name="CodeMining Providers"/>
6 </appInfo>
7 <documentation>
8 This extension point is used to register codemining providers. Associating providers via this extension doesn&apos;t automatically enable code-mining, and that clients are also supposed to use a reconcilier or whatever event mechanism to invoke ISourceViewerExtension5.updateCodeMinings().
9 </documentation>
10 </annotation>
11
12 <include schemaLocation="schema://org.eclipse.core.expressions/schema/expressionLanguage.exsd"/>
13
14 <element name="extension">
15 <annotation>
16 <appInfo>
17 <meta.element />
18 </appInfo>
19 </annotation>
20 <complexType>
21 <sequence>
22 <element ref="codeMiningProvider" minOccurs="1" maxOccurs="unbounded"/>
23 </sequence>
24 <attribute name="point" type="string" use="required">
25 <annotation>
26 <documentation>
27 a fully qualified identifier of the target extension point
28 </documentation>
29 </annotation>
30 </attribute>
31 <attribute name="id" type="string">
32 <annotation>
33 <documentation>
34 an optional identifier of the extension instance
35 </documentation>
36 </annotation>
37 </attribute>
38 <attribute name="name" type="string">
39 <annotation>
40 <documentation>
41 an optional name of the extension instance
42 </documentation>
43 <appInfo>
44 <meta.attribute translatable="true"/>
45 </appInfo>
46 </annotation>
47 </attribute>
48 </complexType>
49 </element>
50
51 <element name="codeMiningProvider">
52 <annotation>
53 <documentation>
54 A CodeMining provider.
55 </documentation>
56 </annotation>
57 <complexType>
58 <sequence>
59 <element ref="enabledWhen" minOccurs="0" maxOccurs="1"/>
60 </sequence>
61 <attribute name="id" type="string" use="required">
62 <annotation>
63 <documentation>
64 a string uniquely identifying this codemining provider
65 </documentation>
66 </annotation>
67 </attribute>
68 <attribute name="class" type="string" use="required">
69 <annotation>
70 <documentation>
71 the fully qualified class name implementing the interface &lt;code&gt;org.eclipse.jface.text.codemining.ICodeMiningProvider&lt;/code&gt;.
72 </documentation>
73 <appInfo>
74 <meta.attribute kind="java" basedOn=":org.eclipse.jface.text.codemining.ICodeMiningProvider"/>
75 </appInfo>
76 </annotation>
77 </attribute>
78 <attribute name="label" type="string">
79 <annotation>
80 <documentation>
81 the display label for the codemining provider, which will show in the CodeMining UI preferences
82 </documentation>
83 <appInfo>
84 <meta.attribute translatable="true"/>
85 </appInfo>
86 </annotation>
87 </attribute>
88 </complexType>
89 </element>
90
91 <element name="enabledWhen">
92 <annotation>
93 <documentation>
94 A core Expression that controls the enabled of the given codemining provider
95 </documentation>
96 </annotation>
97 <complexType>
98 <choice minOccurs="0" maxOccurs="1">
99 <element ref="not"/>
100 <element ref="or"/>
101 <element ref="and"/>
102 <element ref="instanceof"/>
103 <element ref="test"/>
104 <element ref="systemTest"/>
105 <element ref="equals"/>
106 <element ref="count"/>
107 <element ref="with"/>
108 <element ref="resolve"/>
109 <element ref="adapt"/>
110 <element ref="iterate"/>
111 <element ref="reference"/>
112 </choice>
113 </complexType>
114 </element>
115
116 <annotation>
117 <appInfo>
118 <meta.section type="since"/>
119 </appInfo>
120 <documentation>
121 3.10
122 </documentation>
123 </annotation>
124
125 <annotation>
126 <appInfo>
127 <meta.section type="examples"/>
128 </appInfo>
129 <documentation>
130 The following is an example of a codemining provider definition:
131
132 &lt;pre&gt;
133 &lt;extension
134 point=&quot;org.eclipse.ui.workbench.texteditor.codeMiningProviders&quot;&gt;
135 &lt;codeMiningProvider
136 class=&quot;org.eclipse.jdt.internal.ui.codemining.JavaReferencesCodeMiningProvider&quot;
137 id=&quot;org.eclipse.jdt.ui.codemining.references&quot;
138 label=&quot;Java References&quot;&gt;
139 &lt;enabledWhen&gt;
140 &lt;with variable=&quot;editor&quot;&gt;
141 &lt;instanceof value=&quot;org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor&quot;/&gt;
142 &lt;/with&gt;
143 &lt;/enabledWhen&gt;
144 &lt;/codeMiningProvider&gt;
145 &lt;/extension&gt;
146 &lt;/pre&gt;
147 </documentation>
148 </annotation>
149
150 <annotation>
151 <appInfo>
152 <meta.section type="apiInfo"/>
153 </appInfo>
154 <documentation>
155 See the org.eclipse.jface.text.codemining.ICodeMiningProvider class and the org.eclipse.ui.workbench.texteditor.codeMiningProviders extension point.
156 </documentation>
157 </annotation>
158
159
160 <annotation>
161 <appInfo>
162 <meta.section type="copyright"/>
163 </appInfo>
164 <documentation>
165 Copyright (c) 2017 Angelo ZERR.&lt;br&gt;
166 All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at &lt;a href=&quot;http://www.eclipse.org/legal/epl-v10.html&quot;&gt;http://www.eclipse.org/legal/epl-v10.html&lt;/a&gt;
167 </documentation>
168 </annotation>
169
170 </schema>
104104 * @return the string converted to a regex pattern
105105 */
106106 private String asRegPattern(CharSequence string) {
107 StringBuffer out= new StringBuffer(string.length());
107 StringBuilder out= new StringBuilder(string.length());
108108 boolean quoting= false;
109109
110110 for (int i= 0, length= string.length(); i < length; i++) {
66 *
77 * Contributors:
88 * IBM Corporation - initial API and implementation
9 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Provide extension point for CodeMining - Bug 528419
910 *******************************************************************************/
1011 package org.eclipse.ui.internal.texteditor;
1112
2223
2324 import org.eclipse.jface.action.IAction;
2425
26 import org.eclipse.ui.internal.texteditor.codemining.CodeMiningProviderRegistry;
2527 import org.eclipse.ui.internal.texteditor.quickdiff.QuickDiffExtensionsRegistry;
2628 import org.eclipse.ui.internal.texteditor.spelling.SpellingEngineRegistry;
2729 import org.eclipse.ui.plugin.AbstractUIPlugin;
6264 private SpellingEngineRegistry fSpellingEngineRegistry;
6365
6466 /**
67 * The codemining provider registry
68 *
69 * @since 3.10
70 */
71 private CodeMiningProviderRegistry fCodeMiningProviderRegistry;
72
73 /**
6574 * Creates a plug-in instance.
6675 */
6776 public TextEditorPlugin() {
149158 super.start(context);
150159 fQuickDiffExtensionRegistry= new QuickDiffExtensionsRegistry();
151160 fSpellingEngineRegistry= new SpellingEngineRegistry();
161 fCodeMiningProviderRegistry = new CodeMiningProviderRegistry();
152162 Platform.getExtensionRegistry().addRegistryChangeListener(this, PLUGIN_ID);
153163 }
154164
157167 Platform.getExtensionRegistry().removeRegistryChangeListener(this);
158168 fQuickDiffExtensionRegistry= null;
159169 fSpellingEngineRegistry= null;
170 fCodeMiningProviderRegistry = null;
160171 super.stop(context);
161172 }
162173
166177 fQuickDiffExtensionRegistry.reloadExtensions();
167178 if (fSpellingEngineRegistry != null && event.getExtensionDeltas(PLUGIN_ID, SpellingEngineRegistry.SPELLING_ENGINE_EXTENSION_POINT).length > 0)
168179 fSpellingEngineRegistry.reloadExtensions();
180 if (fCodeMiningProviderRegistry != null && event.getExtensionDeltas(PLUGIN_ID,
181 CodeMiningProviderRegistry.CODEMINING_PROVIDERS_EXTENSION_POINT).length > 0)
182 fCodeMiningProviderRegistry.reloadExtensions();
169183 }
170184
171185 /**
187201 public SpellingEngineRegistry getSpellingEngineRegistry() {
188202 return fSpellingEngineRegistry;
189203 }
204
205 /**
206 * Returns this plug-ins codemining provider registry.
207 *
208 * @return the codemining provider registry or <code>null</code> if this plug-in
209 * has been shutdown
210 * @since 3.10
211 */
212 public CodeMiningProviderRegistry getCodeMiningProviderRegistry() {
213 return fCodeMiningProviderRegistry;
214 }
190215 }
0 /**
1 * Copyright (c) 2017 Angelo ZERR.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Provide extension point for CodeMining - Bug 528419
9 */
10 package org.eclipse.ui.internal.texteditor.codemining;
11
12 import org.eclipse.core.expressions.ElementHandler;
13 import org.eclipse.core.expressions.EvaluationContext;
14 import org.eclipse.core.expressions.EvaluationResult;
15 import org.eclipse.core.expressions.Expression;
16 import org.eclipse.core.expressions.ExpressionConverter;
17
18 import org.eclipse.core.runtime.Assert;
19 import org.eclipse.core.runtime.CoreException;
20 import org.eclipse.core.runtime.IConfigurationElement;
21 import org.eclipse.core.runtime.IStatus;
22 import org.eclipse.core.runtime.Status;
23
24 import org.eclipse.jface.text.codemining.AbstractCodeMiningProvider;
25 import org.eclipse.jface.text.codemining.ICodeMiningProvider;
26 import org.eclipse.jface.text.source.ISourceViewer;
27
28 import org.eclipse.ui.internal.texteditor.TextEditorPlugin;
29
30 import org.eclipse.ui.texteditor.ITextEditor;
31
32 /**
33 * Describes an extension to the <code>codeMiningProviders</code> extension
34 * point.
35 * <p>
36 * This class is not intended to be subclassed by clients.
37 * </p>
38 *
39 * @since 3.10
40 * @noextend This class is not intended to be subclassed by clients.
41 */
42 class CodeMiningProviderDescriptor {
43
44 /** Name of the <code>label</code> attribute. */
45 private static final String LABEL_ATTRIBUTE = "label"; //$NON-NLS-1$
46 /** Name of the <code>class</code> attribute. */
47 private static final String CLASS_ATTRIBUTE = "class"; //$NON-NLS-1$
48 /** Name of the <code>id</code> attribute. */
49 private static final String ID_ATTRIBUTE = "id"; //$NON-NLS-1$
50 /** Name of the <code>enabledWhen</code> attribute. **/
51 private static final String ENABLED_WHEN_ATTR = "enabledWhen"; //$NON-NLS-1$
52
53 /** The configuration element describing this extension. */
54 private IConfigurationElement fConfiguration;
55 /** The value of the <code>label</code> attribute, if read. */
56 private String fLabel;
57 /** The value of the <code>id</code> attribute, if read. */
58 private String fId;
59 /** The expression value of the <code>enabledWhen</code> attribute. */
60 private final Expression fEnabledWhen;
61
62 /**
63 * Creates a new descriptor for <code>element</code>.
64 * <p>
65 * This method is for internal use only.
66 * </p>
67 *
68 * @param element
69 * the extension point element to be described.
70 * @throws CoreException
71 * when <code>enabledWhen</code> expression is not valid.
72 */
73 public CodeMiningProviderDescriptor(IConfigurationElement element) throws CoreException {
74 Assert.isLegal(element != null);
75 fConfiguration = element;
76 fEnabledWhen = createEnabledWhen(fConfiguration, getId());
77 }
78
79 /**
80 * Returns the expression {@link Expression} declared in the
81 * <code>enabledWhen</code> element.
82 *
83 * @param configElement
84 * the configuration element
85 * @param id
86 * the id of the codemining provider.
87 * @return the expression {@link Expression} declared in the enabledWhen
88 * element.
89 * @throws CoreException
90 * when enabledWhen expression is not valid.
91 */
92 private static Expression createEnabledWhen(IConfigurationElement configElement, String id) throws CoreException {
93 final IConfigurationElement[] children = configElement.getChildren(ENABLED_WHEN_ATTR);
94 if (children.length > 0) {
95 IConfigurationElement[] subChildren = children[0].getChildren();
96 if (subChildren.length != 1) {
97 throw new CoreException(new Status(IStatus.ERROR, TextEditorPlugin.PLUGIN_ID,
98 "One <enabledWhen> element is accepted. Disabling " + id)); //$NON-NLS-1$
99 }
100 final ElementHandler elementHandler = ElementHandler.getDefault();
101 final ExpressionConverter converter = ExpressionConverter.getDefault();
102 return elementHandler.create(converter, subChildren[0]);
103
104 }
105 throw new CoreException(new Status(IStatus.ERROR, TextEditorPlugin.PLUGIN_ID,
106 "<enabledWhen> element is required. Disabling " + id)); //$NON-NLS-1$
107 }
108
109 /**
110 * Reads (if needed) and returns the label of this extension.
111 *
112 * @return the label for this extension.
113 */
114 public String getLabel() {
115 if (fLabel == null) {
116 fLabel = fConfiguration.getAttribute(LABEL_ATTRIBUTE);
117 Assert.isNotNull(fLabel);
118 }
119 return fLabel;
120 }
121
122 /**
123 * Reads (if needed) and returns the id of this extension.
124 *
125 * @return the id for this extension.
126 */
127 public String getId() {
128 if (fId == null) {
129 fId = fConfiguration.getAttribute(ID_ATTRIBUTE);
130 Assert.isNotNull(fId);
131 }
132 return fId;
133 }
134
135 /**
136 * Creates a codemining provider as described in the extension's xml. and null
137 * otherwise.
138 *
139 * @param editor
140 * the text editor
141 *
142 * @return the created codemining provider and null otherwise.
143 */
144 protected ICodeMiningProvider createCodeMiningProvider(ITextEditor editor) {
145 try {
146 Object extension = fConfiguration.createExecutableExtension(CLASS_ATTRIBUTE);
147 if (extension instanceof ICodeMiningProvider) {
148 if (extension instanceof AbstractCodeMiningProvider) {
149 ((AbstractCodeMiningProvider) extension).setContext(editor);
150 }
151 return (ICodeMiningProvider) extension;
152 } else {
153 String message = "Invalid extension to codeMiningProviders. Must extends ICodeMiningProvider: " //$NON-NLS-1$
154 + getId();
155 TextEditorPlugin.getDefault().getLog()
156 .log(new Status(IStatus.ERROR, TextEditorPlugin.PLUGIN_ID, message));
157 return null;
158 }
159 } catch (CoreException e) {
160 TextEditorPlugin.getDefault().getLog().log(new Status(IStatus.ERROR, TextEditorPlugin.PLUGIN_ID,
161 "Error while creating codeMiningProvider: " + getId(), e)); //$NON-NLS-1$
162 return null;
163 }
164 }
165
166 /**
167 * Returns true if the given viewer, editor matches the enabledWhen expression
168 * and false otherwise.
169 *
170 * @param viewer
171 * the viewer
172 * @param editor
173 * the editor
174 * @return true if the given viewer, editor matches the enabledWhen expression
175 * and false otherwise.
176 */
177 public boolean matches(ISourceViewer viewer, ITextEditor editor) {
178 EvaluationContext context = new EvaluationContext(null, editor);
179 context.setAllowPluginActivation(true);
180 context.addVariable("viewer", viewer); //$NON-NLS-1$
181 context.addVariable("editor", editor); //$NON-NLS-1$
182 context.addVariable("editorInput", editor.getEditorInput()); //$NON-NLS-1$
183 try {
184 return fEnabledWhen.evaluate(context) == EvaluationResult.TRUE;
185 } catch (CoreException e) {
186 TextEditorPlugin.getDefault().getLog().log(
187 new Status(IStatus.ERROR, TextEditorPlugin.PLUGIN_ID, "Error while 'enabledWhen' evaluation", e)); //$NON-NLS-1$
188 return false;
189 }
190 }
191
192 }
0 /**
1 * Copyright (c) 2017 Angelo ZERR.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Provide extension point for CodeMining - Bug 528419
9 */
10 package org.eclipse.ui.internal.texteditor.codemining;
11
12 import java.util.ArrayList;
13 import java.util.List;
14
15 import org.eclipse.core.runtime.CoreException;
16 import org.eclipse.core.runtime.IConfigurationElement;
17 import org.eclipse.core.runtime.IStatus;
18 import org.eclipse.core.runtime.Platform;
19 import org.eclipse.core.runtime.Status;
20
21 import org.eclipse.jface.text.codemining.ICodeMiningProvider;
22 import org.eclipse.jface.text.source.ISourceViewer;
23
24 import org.eclipse.ui.internal.texteditor.TextEditorPlugin;
25
26 import org.eclipse.ui.texteditor.ITextEditor;
27
28 /**
29 * A codemining providers registry used to access the
30 * {@link CodeMiningProviderDescriptor}s that describe the codemining provider
31 * extensions.
32 *
33 * @see CodeMiningProviderDescriptor
34 * @since 3.10
35 */
36 public class CodeMiningProviderRegistry {
37
38 /**
39 * Extension id of spelling engine extension point. (value
40 * <code>"codeMiningProviders"</code>).
41 */
42 public static final String CODEMINING_PROVIDERS_EXTENSION_POINT = "codeMiningProviders"; //$NON-NLS-1$
43
44 /** All descriptors */
45 private CodeMiningProviderDescriptor[] fDescriptors;
46
47 /** <code>true</code> iff the extensions have been loaded at least once */
48 private boolean fLoaded = false;
49
50 /**
51 * Returns all descriptors.
52 *
53 * @return all descriptors
54 */
55 private CodeMiningProviderDescriptor[] getDescriptors() {
56 ensureExtensionsLoaded();
57 return fDescriptors;
58 }
59
60 /**
61 * Reads all extensions.
62 * <p>
63 * This method can be called more than once in order to reload from a changed
64 * extension registry.
65 * </p>
66 */
67 public synchronized void reloadExtensions() {
68 List<CodeMiningProviderDescriptor> descriptors = new ArrayList<>();
69 IConfigurationElement[] elements = Platform.getExtensionRegistry()
70 .getConfigurationElementsFor(TextEditorPlugin.PLUGIN_ID, CODEMINING_PROVIDERS_EXTENSION_POINT);
71 for (int i = 0; i < elements.length; i++) {
72 IConfigurationElement element = elements[i];
73 try {
74 CodeMiningProviderDescriptor descriptor = new CodeMiningProviderDescriptor(element);
75 descriptors.add(descriptor);
76 } catch (CoreException e) {
77 TextEditorPlugin.getDefault().getLog()
78 .log(new Status(IStatus.ERROR, element.getNamespaceIdentifier(), e.getMessage()));
79 }
80 }
81 fDescriptors = descriptors.toArray(new CodeMiningProviderDescriptor[descriptors.size()]);
82 fLoaded = true;
83 }
84
85 /**
86 * Ensures the extensions have been loaded at least once.
87 */
88 private void ensureExtensionsLoaded() {
89 if (!fLoaded)
90 reloadExtensions();
91 }
92
93 /**
94 * Returns the codemining providers for the given viewer and editor and null
95 * otherwise.
96 *
97 * @param viewer
98 * the viewer
99 * @param editor
100 * the editor
101 * @return the codemining providers for the given viewer and editor and null
102 * otherwise.
103 */
104 public ICodeMiningProvider[] getProviders(ISourceViewer viewer, ITextEditor editor) {
105 List<ICodeMiningProvider> providers = new ArrayList<>();
106 for (CodeMiningProviderDescriptor descriptor : getDescriptors()) {
107 if (descriptor.matches(viewer, editor)) {
108 ICodeMiningProvider provider = descriptor.createCodeMiningProvider(editor);
109 if (provider != null) {
110 providers.add(provider);
111 }
112 }
113 }
114 return providers.size() > 0 ? providers.toArray(new ICodeMiningProvider[providers.size()]) : null;
115 }
116 }
2323
2424 public static String serialize(Set<String> strings) {
2525 Assert.isLegal(strings != null);
26 StringBuffer buf= new StringBuffer(strings.size() * 20);
26 StringBuilder buf= new StringBuilder(strings.size() * 20);
2727 for (Iterator<String> it= strings.iterator(); it.hasNext();) {
2828 buf.append(it.next());
2929 if (it.hasNext())
00 /*******************************************************************************
1 * Copyright (c) 2000, 2016 IBM Corporation and others.
1 * Copyright (c) 2000, 2018 IBM Corporation and others.
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
1616 * Holger Voormann - Word Wrap - https://bugs.eclipse.org/bugs/show_bug.cgi?id=35779
1717 * Florian Weßling <flo@cdhq.de> - Word Wrap - https://bugs.eclipse.org/bugs/show_bug.cgi?id=35779
1818 * Andrey Loskutov <loskutov@gmx.de> - Word Wrap - https://bugs.eclipse.org/bugs/show_bug.cgi?id=35779
19 * Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Provide extension point for CodeMining - Bug 528419
1920 *******************************************************************************/
2021 package org.eclipse.ui.texteditor;
2122
149150 import org.eclipse.jface.text.TextEvent;
150151 import org.eclipse.jface.text.TextSelection;
151152 import org.eclipse.jface.text.TextUtilities;
153 import org.eclipse.jface.text.codemining.ICodeMiningProvider;
152154 import org.eclipse.jface.text.hyperlink.HyperlinkManager;
153155 import org.eclipse.jface.text.hyperlink.IHyperlinkDetector;
154156 import org.eclipse.jface.text.information.IInformationProvider;
164166 import org.eclipse.jface.text.source.ISourceViewer;
165167 import org.eclipse.jface.text.source.ISourceViewerExtension3;
166168 import org.eclipse.jface.text.source.ISourceViewerExtension4;
169 import org.eclipse.jface.text.source.ISourceViewerExtension5;
167170 import org.eclipse.jface.text.source.IVerticalRuler;
168171 import org.eclipse.jface.text.source.IVerticalRulerColumn;
169172 import org.eclipse.jface.text.source.IVerticalRulerExtension;
192195 import org.eclipse.ui.IWorkbenchActionConstants;
193196 import org.eclipse.ui.IWorkbenchCommandConstants;
194197 import org.eclipse.ui.IWorkbenchPart;
198 import org.eclipse.ui.IWorkbenchPartSite;
195199 import org.eclipse.ui.IWorkbenchWindow;
196200 import org.eclipse.ui.PartInitException;
197201 import org.eclipse.ui.PlatformUI;
201205 import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;
202206 import org.eclipse.ui.actions.CommandNotMappedException;
203207 import org.eclipse.ui.actions.ContributedAction;
208 import org.eclipse.ui.commands.ICommandImageService;
204209 import org.eclipse.ui.dialogs.PropertyDialogAction;
205210 import org.eclipse.ui.dnd.IDragAndDropService;
206211 import org.eclipse.ui.internal.texteditor.EditPosition;
618623 IDocument document= getDocumentProvider().getDocument(input);
619624
620625 if (fLocalLastEditPosition != null) {
621 document.removePosition(fLocalLastEditPosition);
626 if (document != null) {
627 document.removePosition(fLocalLastEditPosition);
628 }
622629 fLocalLastEditPosition= null;
623630 }
624631
625632 if (sel instanceof ITextSelection && !sel.isEmpty()) {
626633 ITextSelection s= (ITextSelection) sel;
627634 fLocalLastEditPosition= new Position(s.getOffset(), s.getLength());
628 try {
629 document.addPosition(fLocalLastEditPosition);
630 } catch (BadLocationException ex) {
631 fLocalLastEditPosition= null;
635 if (document != null) {
636 try {
637 document.addPosition(fLocalLastEditPosition);
638 } catch (BadLocationException ex) {
639 fLocalLastEditPosition = null;
640 }
632641 }
633642 }
634643
18901899 StyledText styledText= textViewer.getTextWidget();
18911900 IDocument document= textViewer.getDocument();
18921901
1893 if (document == null)
1902 int widgetOffset = styledText.getOffsetAtPoint(new Point(x, y));
1903 if (document == null || widgetOffset == -1) {
18941904 return -1;
1905 }
18951906
18961907 try {
1897 int widgetOffset= styledText.getOffsetAtLocation(new Point(x, y));
18981908 Point p= styledText.getLocationAtOffset(widgetOffset);
1899 if (p.x > x)
1909 if (p.x > x) {
19001910 widgetOffset--;
1911 }
19011912
19021913 if (textViewer instanceof ITextViewerExtension5) {
19031914 ITextViewerExtension5 extension= (ITextViewerExtension5) textViewer;
35253536 if (isBlockSelectionModeEnabled())
35263537 return false;
35273538
3528 int offset= st.getOffsetAtLocation(point);
3539 int offset = st.getOffsetAtPoint(point);
35293540 Point p= st.getLocationAtOffset(offset);
35303541 if (p.x > point.x)
35313542 offset--;
40204031 EnrichMode mode= store != null ? convertEnrichModePreference(store.getInt(PREFERENCE_HOVER_ENRICH_MODE)) : EnrichMode.AFTER_DELAY;
40214032 ((ITextViewerExtension8)fSourceViewer).setHoverEnrichMode(mode);
40224033 }
4034
4035 if (fSourceViewer instanceof ISourceViewerExtension5)
4036 installCodeMiningProviders();
4037 }
4038
4039 /**
4040 * Install codemining providers.
4041 *
4042 * @since 3.11
4043 */
4044 protected void installCodeMiningProviders() {
4045 ICodeMiningProvider[] providers = TextEditorPlugin.getDefault().getCodeMiningProviderRegistry()
4046 .getProviders(this.getSourceViewer(), this);
4047 ((ISourceViewerExtension5) fSourceViewer).setCodeMiningProviders(providers);
40234048 }
40244049
40254050 /**
53225347 for (int i= 0; i < elements.length; i++) {
53235348 IConfigurationElement element= elements[i];
53245349 if (TAG_CONTRIBUTION_TYPE.equals(element.getName())) {
5325 if (!getSite().getId().equals(element.getAttribute("targetID"))) //$NON-NLS-1$
5350 IWorkbenchPartSite site = getSite();
5351 if (site == null) {
5352 return null;
5353 }
5354 if (!site.getId().equals(element.getAttribute("targetID"))) //$NON-NLS-1$
53265355 continue;
53275356
53285357 IConfigurationElement[] children= element.getChildren("action"); //$NON-NLS-1$
56635692 action= new TextOperationAction(EditorMessages.getBundleForConstructedKeys(), "Editor.Cut.", this, ITextOperationTarget.CUT); //$NON-NLS-1$
56645693 action.setHelpContextId(IAbstractTextEditorHelpContextIds.CUT_ACTION);
56655694 action.setActionDefinitionId(IWorkbenchCommandConstants.EDIT_CUT);
5695 updateImages(action, IWorkbenchCommandConstants.EDIT_CUT);
56665696 setAction(ITextEditorActionConstants.CUT, action);
56675697
56685698 setAction(IWorkbenchCommandConstants.EDIT_COPY, null);
56695699 action= new TextOperationAction(EditorMessages.getBundleForConstructedKeys(), "Editor.Copy.", this, ITextOperationTarget.COPY, true); //$NON-NLS-1$
56705700 action.setHelpContextId(IAbstractTextEditorHelpContextIds.COPY_ACTION);
56715701 action.setActionDefinitionId(IWorkbenchCommandConstants.EDIT_COPY);
5702 updateImages(action, IWorkbenchCommandConstants.EDIT_COPY);
56725703 setAction(ITextEditorActionConstants.COPY, action);
56735704
56745705 setAction(IWorkbenchCommandConstants.EDIT_PASTE, null);
56755706 action= new TextOperationAction(EditorMessages.getBundleForConstructedKeys(), "Editor.Paste.", this, ITextOperationTarget.PASTE); //$NON-NLS-1$
56765707 action.setHelpContextId(IAbstractTextEditorHelpContextIds.PASTE_ACTION);
56775708 action.setActionDefinitionId(IWorkbenchCommandConstants.EDIT_PASTE);
5709 updateImages(action, IWorkbenchCommandConstants.EDIT_PASTE);
56785710 setAction(ITextEditorActionConstants.PASTE, action);
56795711
56805712 action= new TextOperationAction(EditorMessages.getBundleForConstructedKeys(), "Editor.Delete.", this, ITextOperationTarget.DELETE); //$NON-NLS-1$
56815713 action.setHelpContextId(IAbstractTextEditorHelpContextIds.DELETE_ACTION);
56825714 action.setActionDefinitionId(IWorkbenchCommandConstants.EDIT_DELETE);
5715 updateImages(action, IWorkbenchCommandConstants.EDIT_DELETE);
56835716 setAction(ITextEditorActionConstants.DELETE, action);
56845717
56855718 action= new DeleteLineAction(EditorMessages.getBundleForConstructedKeys(), "Editor.DeleteLine.", this, DeleteLineAction.WHOLE, false); //$NON-NLS-1$
57585791 action= new TextOperationAction(EditorMessages.getBundleForConstructedKeys(), "Editor.Print.", this, ITextOperationTarget.PRINT, true); //$NON-NLS-1$
57595792 action.setHelpContextId(IAbstractTextEditorHelpContextIds.PRINT_ACTION);
57605793 action.setActionDefinitionId(IWorkbenchCommandConstants.FILE_PRINT);
5794 updateImages(action, IWorkbenchCommandConstants.FILE_PRINT);
57615795 setAction(ITextEditorActionConstants.PRINT, action);
57625796
57635797 action= new FindReplaceAction(EditorMessages.getBundleForConstructedKeys(), "Editor.FindReplace.", this); //$NON-NLS-1$
57645798 action.setHelpContextId(IAbstractTextEditorHelpContextIds.FIND_ACTION);
57655799 action.setActionDefinitionId(IWorkbenchCommandConstants.EDIT_FIND_AND_REPLACE);
5800 updateImages(action, IWorkbenchCommandConstants.EDIT_FIND_AND_REPLACE);
57665801 setAction(ITextEditorActionConstants.FIND, action);
57675802
57685803 action= new FindNextAction(EditorMessages.getBundleForConstructedKeys(), "Editor.FindNext.", this, true); //$NON-NLS-1$
57915826 action= new RevertToSavedAction(EditorMessages.getBundleForConstructedKeys(), "Editor.Revert.", this); //$NON-NLS-1$
57925827 action.setHelpContextId(IAbstractTextEditorHelpContextIds.REVERT_TO_SAVED_ACTION);
57935828 action.setActionDefinitionId(IWorkbenchCommandConstants.FILE_REVERT);
5829 updateImages(action, IWorkbenchCommandConstants.FILE_REVERT);
57945830 setAction(ITextEditorActionConstants.REVERT_TO_SAVED, action);
57955831
57965832 action= new GotoLineAction(EditorMessages.getBundleForConstructedKeys(), "Editor.GotoLine.", this); //$NON-NLS-1$
59485984 }
59495985 });
59505986 openProperties.setActionDefinitionId(IWorkbenchCommandConstants.FILE_PROPERTIES);
5987 updateImages(openProperties, IWorkbenchCommandConstants.FILE_PROPERTIES);
59515988 setAction(ITextEditorActionConstants.PROPERTIES, openProperties);
59525989
59535990 markAsContentDependentAction(ITextEditorActionConstants.UNDO, true);
59946031 setActionActivationCode(ITextEditorActionConstants.SHIFT_LEFT, '\t', -1, SWT.SHIFT);
59956032 }
59966033
6034 private void updateImages(IAction action, String commandId) {
6035 if (action.getImageDescriptor() != null) {
6036 return;
6037 }
6038 ICommandImageService imgService = getSite().getService(ICommandImageService.class);
6039 if (imgService == null) {
6040 return;
6041 }
6042 action.setImageDescriptor(imgService.getImageDescriptor(commandId));
6043 action.setDisabledImageDescriptor(imgService.getImageDescriptor(commandId, ICommandImageService.TYPE_DISABLED));
6044 action.setHoverImageDescriptor(imgService.getImageDescriptor(commandId, ICommandImageService.TYPE_HOVER));
6045 }
6046
59976047 /**
59986048 * Convenience method to add the action installed under the given action id to the given menu.
59996049 * @param menu the menu to add the action to
61866236
61876237 @Override
61886238 public void setFocus() {
6189 if (fSourceViewer != null && fSourceViewer.getTextWidget() != null)
6190 fSourceViewer.getTextWidget().setFocus();
6239 if (fSourceViewer != null) {
6240 StyledText widget= fSourceViewer.getTextWidget();
6241 if (widget != null && !widget.isDisposed()) {
6242 widget.setFocus();
6243 }
6244 }
61916245 }
61926246
61936247 @Override
65366590
65376591 Caret caret= new Caret(styledText, SWT.NULL);
65386592 Image image= createRawInsertModeCaretImage(styledText);
6539 if (image != null)
6540 caret.setImage(image);
6541 else {
6542 // XXX: Filed request to get a caret with auto-height: https://bugs.eclipse.org/bugs/show_bug.cgi?id=118612
6543 caret.setSize(getCaretWidthPreference(), styledText.getLineHeight());
6544 }
6545
6593 caret.setImage(image);
65466594 caret.setFont(styledText.getFont());
65476595
65486596 return caret;
65566604 }
65576605
65586606 private void updateCaret() {
6559
6560 if (fSourceViewer == null)
6607 if (fSourceViewer == null || fSourceViewer.getTextWidget() == null) {
65616608 return;
6609 }
65626610
65636611 StyledText styledText= fSourceViewer.getTextWidget();
65646612
69106958 boolean currentAnnotation= false;
69116959
69126960 IDocument document= getDocumentProvider().getDocument(getEditorInput());
6913 int endOfDocument= document.getLength();
6961 int endOfDocument = 0;
6962 if (document != null) {
6963 endOfDocument = document.getLength();
6964 }
69146965 int distance= Integer.MAX_VALUE;
69156966
69166967 IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
2121 import org.eclipse.core.commands.AbstractHandler;
2222 import org.eclipse.core.commands.ExecutionEvent;
2323 import org.eclipse.core.commands.ExecutionException;
24 import org.eclipse.core.expressions.IEvaluationContext;
2425
2526 import org.eclipse.core.runtime.IConfigurationElement;
2627 import org.eclipse.core.runtime.Platform;
3031 import org.eclipse.jface.resource.FontRegistry;
3132 import org.eclipse.jface.resource.JFaceResources;
3233
33 import org.eclipse.ui.IWorkbenchPart;
34 import org.eclipse.ui.IEditorPart;
35 import org.eclipse.ui.ISources;
3436 import org.eclipse.ui.handlers.HandlerUtil;
3537 import org.eclipse.ui.part.AbstractMultiEditor;
3638 import org.eclipse.ui.part.MultiPageEditorPart;
9294 }
9395
9496 private AbstractTextEditor getActiveTextEditor(ExecutionEvent event) {
95 IWorkbenchPart part= HandlerUtil.getActiveEditor(event);
97 return getActiveTextEditor(HandlerUtil.getActiveEditor(event));
98 }
99
100 private AbstractTextEditor getActiveTextEditor(IEditorPart part) {
96101 if (part instanceof AbstractTextEditor) {
97102 return (AbstractTextEditor)part;
98103 } else if ((part instanceof AbstractMultiEditor) && ((AbstractMultiEditor)part).getActiveEditor() instanceof AbstractTextEditor) {
104109 }
105110
106111 @Override
107 public boolean isEnabled() {
108 return true;
112 public void setEnabled(Object evaluationContext) {
113 boolean enabled = false;
114 if (evaluationContext instanceof IEvaluationContext) {
115 Object activeEditor = ((IEvaluationContext) evaluationContext).getVariable(ISources.ACTIVE_EDITOR_NAME);
116 if (activeEditor instanceof IEditorPart) {
117 enabled = getActiveTextEditor((IEditorPart) activeEditor) != null;
118 }
119 }
120 setBaseEnabled(enabled);
109121 }
110122
111123 /**
148148 Editor.GotoLine.tooltip=Go to Line
149149 Editor.GotoLine.image=
150150 Editor.GotoLine.description=Go to Line
151 Editor.GotoLine.button=&Go to Line
151152
152153 Editor.GotoLine.dialog.title=Go to Line
153154 Editor.GotoLine.dialog.message=Enter line number (1..{0}):
2626 import org.eclipse.swt.widgets.Control;
2727 import org.eclipse.swt.widgets.Display;
2828
29 import org.eclipse.jface.resource.JFaceResources;
30
2931 import org.eclipse.jface.text.source.Annotation;
3032 import org.eclipse.jface.text.source.IAnnotationPresentation;
3133
4042 */
4143 public class DefaultRangeIndicator extends Annotation implements IAnnotationPresentation {
4244
43 /** The color palette data of this range indicator */
44 private static PaletteData fgPaletteData;
45 private static final String RANGE_INDICATOR_COLOR= "org.eclipse.ui.editors.rangeIndicatorColor"; //$NON-NLS-1$
4546 /** The image of this range indicator */
4647 private Image fImage;
48 /** The color used to draw the range indicator during the last paint action. */
49 private Color fLastRangeIndicatorColor;
4750
4851 /**
4952 * Creates a new range indicator.
5356
5457 @Override
5558 public void paint(GC gc, Canvas canvas, Rectangle bounds) {
56
5759 Point canvasSize= canvas.getSize();
5860
5961 int x= 0;
7375 if (h <= 0)
7476 return;
7577
76 Image image = getImage(canvas);
78 Color currentRangeIndicatorColor= JFaceResources.getColorRegistry().get(RANGE_INDICATOR_COLOR);
79 Image image= getImage(canvas, currentRangeIndicatorColor);
7780 gc.drawImage(image, 0, 0, w, h, x, y, w, h);
7881
79 gc.setBackground(canvas.getDisplay().getSystemColor(SWT.COLOR_LIST_SELECTION));
82 gc.setBackground(currentRangeIndicatorColor);
8083 gc.fillRectangle(x, bounds.y, w, b);
8184 gc.fillRectangle(x, bounds.y + bounds.height - b, w, b);
85
86 fLastRangeIndicatorColor= currentRangeIndicatorColor;
8287 }
8388
8489 @Override
9095 * Returns the image of this range indicator.
9196 *
9297 * @param control the control
98 * @param rangeIndicatorColor the color to be used to paint the range indicator
9399 * @return an image
94100 */
95 private Image getImage(Control control) {
101 private Image getImage(Control control, Color rangeIndicatorColor) {
96102 if (fImage == null) {
97 fImage= createImage(control.getDisplay(), control.getSize());
103 fImage= createImage(control.getDisplay(), control.getSize(), rangeIndicatorColor);
98104
99 control.addDisposeListener(new DisposeListener() {
100 @Override
101 public void widgetDisposed(DisposeEvent e) {
102 if (fImage != null && !fImage.isDisposed()) {
103 fImage.dispose();
104 fImage= null;
105 }
105 control.addDisposeListener(new DisposeListener() {
106 @Override
107 public void widgetDisposed(DisposeEvent e) {
108 if (fImage != null && !fImage.isDisposed()) {
109 fImage.dispose();
110 fImage = null;
106111 }
107 });
112 }
113 });
108114 } else {
109115 Rectangle imageRectangle= fImage.getBounds();
110116 Point controlSize= control.getSize();
111117
112 if (imageRectangle.width < controlSize.x || imageRectangle.height < controlSize.y) {
118 if (imageRectangle.width < controlSize.x || imageRectangle.height < controlSize.y
119 || !rangeIndicatorColor.equals(fLastRangeIndicatorColor)) {
113120 fImage.dispose();
114 fImage= createImage(control.getDisplay(), controlSize);
121 fImage= createImage(control.getDisplay(), controlSize, rangeIndicatorColor);
115122 }
116123 }
117124
124131 *
125132 * @param display the display on which to create the image
126133 * @param size the image size
134 * @param rangeIndicatorColor the color to be used to paint the range indicator
127135 * @return a new image
128 */
129 private static Image createImage(Display display, Point size) {
136 */
137 private static Image createImage(Display display, Point size, Color rangeIndicatorColor) {
130138
131139 int width= size.x;
132140 int height= size.y;
133141
134 if (fgPaletteData == null)
135 fgPaletteData= createPalette(display);
136142
137 ImageData imageData= new ImageData(width, height, 1, fgPaletteData);
143 ImageData imageData= new ImageData(width, height, 1, createPalette(display, rangeIndicatorColor));
138144
139145 for (int y= 0; y < height; y++)
140146 for (int x= 0; x < width; x++)
141147 imageData.setPixel(x, y, (x + y) % 2);
148
149 imageData.transparentPixel= imageData.palette.getPixel(imageData.getRGBs()[1]);
150
142151
143152 return new Image(display, imageData);
144153 }
147156 * Creates and returns a new color palette data.
148157 *
149158 * @param display the display
159 * @param rangeIndicatorColor the color to be used to paint the range indicator
150160 * @return the new color palette data
151161 */
152 private static PaletteData createPalette(Display display) {
153 Color c1;
154 Color c2;
155
156 c1= display.getSystemColor(SWT.COLOR_LIST_SELECTION);
157 c2= display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND);
158
159 RGB rgbs[]= new RGB[] {
160 new RGB(c1.getRed(), c1.getGreen(), c1.getBlue()),
161 new RGB(c2.getRed(), c2.getGreen(), c2.getBlue())};
162
163 return new PaletteData(rgbs);
162 private static PaletteData createPalette(Display display, Color rangeIndicatorColor) {
163 return new PaletteData(new RGB[] { rangeIndicatorColor.getRGB(),
164 display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND).getRGB() });
164165 }
165166 }
455455 e.doit= false;
456456 }
457457 else if (e.detail == SWT.TRAVERSE_MNEMONIC) {
458 Character mnemonic= new Character(Character.toLowerCase(e.character));
458 Character mnemonic= Character.valueOf(Character.toLowerCase(e.character));
459459 if (fMnemonicButtonMap.containsKey(mnemonic)) {
460460 Button button= fMnemonicButtonMap.get(mnemonic);
461461 if ((fFindField.isFocusControl() || fReplaceField.isFocusControl() || (button.getStyle() & SWT.PUSH) != 0)
12841284 private void storeButtonWithMnemonicInMap(Button button) {
12851285 char mnemonic= LegacyActionTools.extractMnemonic(button.getText());
12861286 if (mnemonic != LegacyActionTools.MNEMONIC_NONE)
1287 fMnemonicButtonMap.put(new Character(Character.toLowerCase(mnemonic)), button);
1287 fMnemonicButtonMap.put(Character.valueOf(Character.toLowerCase(mnemonic)), button);
12881288 }
12891289
12901290 /**
1212 import java.util.ResourceBundle;
1313
1414 import org.eclipse.swt.custom.StyledText;
15 import org.eclipse.swt.widgets.Button;
16 import org.eclipse.swt.widgets.Composite;
1517 import org.eclipse.swt.widgets.Control;
1618 import org.eclipse.swt.widgets.Shell;
1719
8587 *
8688 * @since 2.0
8789 */
88 static class GotoLineDialog extends InputDialog {
89
90 /*
91 * @see InputDialog#InputDialog(org.eclipse.swt.widgets.Shell, java.lang.String, java.lang.String, java.lang.String, org.eclipse.jface.dialogs.IInputValidator)
92 */
90 class GotoLineDialog extends InputDialog {
91
9392 public GotoLineDialog(Shell parent, String title, String message, String initialValue, IInputValidator validator) {
9493 super(parent, title, message, initialValue, validator);
9594 }
102101 if (section == null)
103102 section= settings.addNewSection(sectionName);
104103 return section;
104 }
105
106 @Override
107 protected void createButtonsForButtonBar(Composite parent) {
108 super.createButtonsForButtonBar(parent);
109 Button button = getOkButton();
110 button.setText(GotoLineAction.this.fBundle.getString(fPrefix + "button")); //$NON-NLS-1$
105111 }
106112
107113 @Override
8888 /** The find replace target to delegate find requests */
8989 private final IFindReplaceTarget fTarget;
9090 /** The current find string */
91 private StringBuffer fFindString= new StringBuffer();
91 private StringBuilder fFindString= new StringBuilder();
9292 /** The position of the first upper case character, -1 if none */
9393 private int fCasePosition;
9494 /**
192192 text.setSelectionRange(searchResult.selection, searchResult.length);
193193 text.showSelection();
194194
195 // relies on the contents of the StringBuffer
195 // relies on the contents of the StringBuilder
196196 fFindString.setLength(searchResult.findLength);
197197 fCurrentIndex= searchResult.index;
198198 fFound= searchResult.found;
502502 */
503503 private boolean repeatSearch(boolean forward) {
504504 if (fFindString.length() == 0) {
505 fFindString= new StringBuffer(fPrevFindString);
505 fFindString= new StringBuilder(fPrevFindString);
506506 fCasePosition= fPrevCasePosition;
507507 }
508508
717717 * @return the given string with all tab characters replace with a proper status line presentation
718718 */
719719 private String escapeTabs(String string) {
720 StringBuffer buffer= new StringBuffer();
720 StringBuilder buffer= new StringBuilder();
721721
722722 int begin= 0;
723723 int end= string.indexOf('\t', begin);
148148 if (startLine == endLine)
149149 endLine++; // append join with the next line
150150
151 StringBuffer buffer= new StringBuffer();
151 StringBuilder buffer= new StringBuilder();
152152 for (int line= startLine; line <= endLine; line++) {
153153 buffer.append(trim(document, line, line == startLine));
154154 if (line != endLine)
00 /*******************************************************************************
1 * Copyright (c) 2000, 2012 IBM Corporation and others.
1 * Copyright (c) 2000, 2017 IBM Corporation and others.
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
2222
2323 import org.eclipse.jface.preference.IPreferenceStore;
2424 import org.eclipse.jface.preference.PreferenceConverter;
25 import org.eclipse.jface.resource.JFaceResources;
2625 import org.eclipse.jface.util.IPropertyChangeListener;
2726 import org.eclipse.jface.util.PropertyChangeEvent;
2827
4039 import org.eclipse.jface.text.source.IOverviewRuler;
4140 import org.eclipse.jface.text.source.ISharedTextColors;
4241 import org.eclipse.jface.text.source.ISourceViewer;
42 import org.eclipse.jface.text.source.ISourceViewerExtension5;
4343 import org.eclipse.jface.text.source.MatchingCharacterPainter;
4444
4545
186186 private static ITextStyleStrategy fgProblemUnderlineStrategy= new AnnotationPainter.UnderlineStrategy(SWT.UNDERLINE_ERROR);
187187
188188
189 /*
190 * @see IPropertyChangeListener
191 */
192 private class FontPropertyChangeListener implements IPropertyChangeListener {
193 @Override
194 public void propertyChange(PropertyChangeEvent event) {
195 if (fMarginPainter != null && fSymbolicFontName != null && fSymbolicFontName.equals(event.getProperty()))
196 fMarginPainter.initialize();
197 }
198 }
199
200
201189 /** The viewer */
202190 private ISourceViewer fSourceViewer;
203191 /** The viewer's overview ruler */
242230 private IPropertyChangeListener fPropertyChangeListener;
243231 /** The preference store */
244232 private IPreferenceStore fPreferenceStore;
245 /** The symbolic font name */
246 private String fSymbolicFontName;
247 /** The font change listener */
248 private FontPropertyChangeListener fFontPropertyChangeListener;
249233
250234
251235 /**
387371 updateTextDecorations();
388372 updateOverviewDecorations();
389373
390 if (fFontPropertyChangeListener != null) {
391 JFaceResources.getFontRegistry().removeListener(fFontPropertyChangeListener);
392 fFontPropertyChangeListener= null;
393 }
394
395374 fOverviewRuler= null;
396375
397376 // Painters got disposed in updateTextDecorations() or by the PaintManager
496475 /**
497476 * Sets the symbolic font name that is used for computing the margin width.
498477 *
499 * @param symbolicFontName the symbolic font name
500 */
478 * @param symbolicFontName
479 * the symbolic font name
480 * @deprecated As of 4.8, this is no longer used
481 */
482 @Deprecated
501483 public void setSymbolicFontName(String symbolicFontName) {
502 fSymbolicFontName= symbolicFontName;
503484 }
504485
505486 /**
800781 fMarginPainter.setMarginRulerColumn(fPreferenceStore.getInt(fMarginPainterColumnKey));
801782 ITextViewerExtension2 extension= (ITextViewerExtension2) fSourceViewer;
802783 extension.addPainter(fMarginPainter);
803
804 fFontPropertyChangeListener= new FontPropertyChangeListener();
805 JFaceResources.getFontRegistry().addListener(fFontPropertyChangeListener);
806784 }
807785 }
808786 }
813791 private void hideMargin() {
814792 if (fMarginPainter != null) {
815793 if (fSourceViewer instanceof ITextViewerExtension2) {
816 JFaceResources.getFontRegistry().removeListener(fFontPropertyChangeListener);
817 fFontPropertyChangeListener= null;
818
819794 ITextViewerExtension2 extension= (ITextViewerExtension2) fSourceViewer;
820795 extension.removePainter(fMarginPainter);
821796 fMarginPainter.deactivate(true);
851826 ((ITextViewerExtension4)fSourceViewer).addTextPresentationListener(fAnnotationPainter);
852827 ITextViewerExtension2 extension= (ITextViewerExtension2) fSourceViewer;
853828 extension.addPainter(fAnnotationPainter);
829 if (fSourceViewer instanceof ISourceViewerExtension5)
830 ((ISourceViewerExtension5) fSourceViewer).setCodeMiningAnnotationPainter(fAnnotationPainter);
854831 }
855832 fAnnotationPainter.setAnnotationTypeColor(annotationType, getAnnotationTypeColor(annotationType));
856833 Object decorationType= getAnnotationDecorationType(annotationType);
7777 /** The clip board. */
7878 private Clipboard fClipboard;
7979 /** A string buffer. */
80 private final StringBuffer fBuffer= new StringBuffer();
80 private final StringBuilder fBuffer= new StringBuilder();
8181 /** The delete flag indicates if a deletion is in progress. */
8282 private boolean fDeleting;
8383
00 /*******************************************************************************
1 * Copyright (c) 2007, 2012 Dakshinamurthy Karra, IBM Corporation and others.
1 * Copyright (c) 2007, 2018 Dakshinamurthy Karra, IBM Corporation and others.
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
11971197 * Set the selected templates
11981198 */
11991199 private void setSelectedTemplates() {
1200 IStructuredSelection selection= (IStructuredSelection) fTreeViewer.getSelection();
1200 IStructuredSelection selection = fTreeViewer.getStructuredSelection();
12011201
12021202 Iterator<?> it= selection.iterator();
12031203 TemplatePersistenceData[] data= new TemplatePersistenceData[selection.size()];
12441244 * registry if no templates are selected
12451245 */
12461246 private String getContextTypeId() {
1247 IStructuredSelection selection= (IStructuredSelection) fTreeViewer.getSelection();
1247 IStructuredSelection selection = fTreeViewer.getStructuredSelection();
12481248 Object item;
12491249
12501250 if (selection.size() == 0)
15701570 int widgetCaret= fViewer.getTextWidget().getCaretOffset();
15711571 if (fViewer instanceof ITextViewerExtension5) {
15721572 ITextViewerExtension5 ext= (ITextViewerExtension5) fViewer;
1573 try {
1574 return ext.widgetOffset2ModelOffset(textWidget.getOffsetAtLocation(point));
1575 } catch (IllegalArgumentException e) {
1573 int widgetOffset = textWidget.getOffsetAtPoint(point);
1574 int offset = widgetOffset != -1 ? ext.widgetOffset2ModelOffset(textWidget.getOffsetAtPoint(point)) : -1;
1575 if (offset == -1) {
15761576 int docLineIndex= ext.widgetLine2ModelLine(textWidget.getLineIndex(point.y));
15771577 String lineDelimiter= document.getLineDelimiter(docLineIndex);
15781578 int delimLength= lineDelimiter == null ? 0 : lineDelimiter.length();
15791579 return document.getLineOffset(docLineIndex) + document.getLineLength(docLineIndex)
15801580 - delimLength;
15811581 }
1582 return offset;
15821583 }
15831584 IRegion visible= fViewer.getVisibleRegion();
15841585 return widgetCaret + visible.getOffset();
00 /*******************************************************************************
1 * Copyright (c) 2000, 2015 IBM Corporation and others.
1 * Copyright (c) 2000, 2018 IBM Corporation and others.
22 * All rights reserved. This program and the accompanying materials
33 * are made available under the terms of the Eclipse Public License v1.0
44 * which accompanies this distribution, and is available at
11811181 * Updates the pattern viewer.
11821182 */
11831183 protected void updateViewerInput() {
1184 IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection();
1184 IStructuredSelection selection = fTableViewer.getStructuredSelection();
11851185
11861186 if (selection.size() == 1) {
11871187 TemplatePersistenceData data= (TemplatePersistenceData) selection.getFirstElement();
11961196 * Updates the buttons.
11971197 */
11981198 protected void updateButtons() {
1199 IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection();
1199 IStructuredSelection selection = fTableViewer.getStructuredSelection();
12001200 int selectionCount= selection.size();
12011201 int itemCount= fTableViewer.getTable().getItemCount();
12021202 boolean canRestore= fTemplateStore.getTemplateData(true).length != fTemplateStore.getTemplateData(false).length;
12671267 }
12681268
12691269 private void edit() {
1270 IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection();
1270 IStructuredSelection selection = fTableViewer.getStructuredSelection();
12711271
12721272 Object[] objects= selection.toArray();
12731273 if ((objects == null) || (objects.length != 1))
13141314 TemplateReaderWriter reader= new TemplateReaderWriter();
13151315 File file= new File(path);
13161316 if (file.exists()) {
1317 InputStream input= new BufferedInputStream(new FileInputStream(file));
1318 try {
1317 try (InputStream input = new BufferedInputStream(new FileInputStream(file))) {
13191318 TemplatePersistenceData[] datas= reader.read(input, null);
13201319 for (int i= 0; i < datas.length; i++) {
13211320 TemplatePersistenceData data= datas[i];
13301329 }
13311330 }
13321331 }
1333 } finally {
1334 try {
1335 input.close();
1336 } catch (IOException x) {
1337 // ignore
1338 }
13391332 }
13401333 }
13411334
13531346 }
13541347
13551348 private void export() {
1356 IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection();
1349 IStructuredSelection selection = fTableViewer.getStructuredSelection();
13571350 Object[] templates= selection.toArray();
13581351
13591352 TemplatePersistenceData[] datas= new TemplatePersistenceData[templates.length];
13901383 }
13911384
13921385 if (!file.exists() || confirmOverwrite(file)) {
1393 OutputStream output= null;
1394 try {
1395 output= new BufferedOutputStream(new FileOutputStream(file));
1386 try (OutputStream output = new BufferedOutputStream(new FileOutputStream(file))) {
13961387 TemplateReaderWriter writer= new TemplateReaderWriter();
13971388 writer.save(templates, output);
13981389 } catch (IOException e) {
13991390 openWriteErrorDialog(e);
1400 } finally {
1401 if (output != null) {
1402 try {
1403 output.close();
1404 } catch (IOException e) {
1405 // ignore
1406 }
1407 }
14081391 }
14091392 }
14101393 }
14161399 }
14171400
14181401 private void remove() {
1419 IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection();
1402 IStructuredSelection selection = fTableViewer.getStructuredSelection();
14201403
14211404 Iterator<?> elements= selection.iterator();
14221405 while (elements.hasNext()) {
14411424 }
14421425
14431426 private void revert() {
1444 IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection();
1427 IStructuredSelection selection = fTableViewer.getStructuredSelection();
14451428
14461429 Iterator<?> elements= selection.iterator();
14471430 while (elements.hasNext()) {
11 Bundle-ManifestVersion: 2
22 Bundle-Name: %Plugin.name
33 Bundle-SymbolicName: org.eclipse.ui.workbench.texteditor.tests
4 Bundle-Version: 3.11.100.qualifier
4 Bundle-Version: 3.12.0.qualifier
55 Bundle-Vendor: %Plugin.providerName
66 Bundle-Localization: plugin
77 Export-Package:
1414 org.eclipse.ui.workbench.texteditor;bundle-version="[3.5.0,4.0.0)",
1515 org.eclipse.ui;bundle-version="[3.5.0,4.0.0)",
1616 org.junit;bundle-version="4.12.0",
17 org.eclipse.text.tests;bundle-version="[3.5.0,4.0.0)"
17 org.eclipse.text.tests;bundle-version="[3.5.0,4.0.0)",
18 org.eclipse.core.expressions;bundle-version="[3.5.0,4.0.0)"
1819 Bundle-RequiredExecutionEnvironment: JavaSE-1.8
1920 Eclipse-BundleShape: dir
21 Automatic-Module-Name: org.eclipse.ui.workbench.texteditor.tests
1313 <parent>
1414 <artifactId>tests-pom</artifactId>
1515 <groupId>eclipse.platform.text</groupId>
16 <version>4.7.3-SNAPSHOT</version>
16 <version>4.8.0-SNAPSHOT</version>
1717 <relativePath>../tests-pom/</relativePath>
1818 </parent>
1919 <groupId>org.eclipse.ui</groupId>
2020 <artifactId>org.eclipse.ui.workbench.texteditor.tests</artifactId>
21 <version>3.11.100-SNAPSHOT</version>
21 <version>3.12.0-SNAPSHOT</version>
2222 <packaging>eclipse-test-plugin</packaging>
2323 <properties>
2424 <testSuite>${project.artifactId}</testSuite>
0 /*******************************************************************************
1 * Copyright (c) 2017 SAP SE and others.
2 * All rights reserved. This program and the accompanying materials
3 * are made available under the terms of the Eclipse Public License v1.0
4 * which accompanies this distribution, and is available at
5 * http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * SAP SE - initial API and implementation
9 *******************************************************************************/
10 package org.eclipse.ui.workbench.texteditor.tests;
11
12 import static org.junit.Assert.assertEquals;
13
14 import org.junit.Test;
15
16 import org.eclipse.swt.widgets.Composite;
17
18 import org.eclipse.core.expressions.EvaluationContext;
19
20 import org.eclipse.core.runtime.IProgressMonitor;
21
22 import org.eclipse.ui.IEditorInput;
23 import org.eclipse.ui.IEditorPart;
24 import org.eclipse.ui.IEditorReference;
25 import org.eclipse.ui.IEditorSite;
26 import org.eclipse.ui.ISources;
27 import org.eclipse.ui.PartInitException;
28 import org.eclipse.ui.part.AbstractMultiEditor;
29 import org.eclipse.ui.part.EditorPart;
30 import org.eclipse.ui.part.MultiPageEditorPart;
31
32 import org.eclipse.ui.texteditor.AbstractTextEditor;
33 import org.eclipse.ui.texteditor.TextZoomInHandler;
34
35 public class AbstractTextZoomHandlerTest {
36
37 @Test
38 public void textZoomIsSupportedForAbstractTextEditor() {
39 IEditorPart part= new TestAbstractTextEditor();
40
41 assertZoomSupported(part, true);
42 }
43
44 @Test
45 public void textZoomIsNotSupportedForNonTextEditor() {
46 IEditorPart part= new TestNonTextEditor();
47
48 assertZoomSupported(part, false);
49 }
50
51 @Test
52 public void textZoomIsSupportedForMultiPageEditorPartWithAbstractTextEditorPage() {
53 EditorPart part= new TestMultiPageEditorPart(new TestAbstractTextEditor());
54
55 assertZoomSupported(part, true);
56 }
57
58 @Test
59 public void textZoomIsNotSupportedForMultiPageEditorPartWithNonTextPage() {
60 EditorPart part= new TestMultiPageEditorPart(new TestNonTextEditor());
61
62 assertZoomSupported(part, false);
63 }
64
65 @Test
66 public void textZoomIsSupportedForMultiEditorWithTextPage() {
67 EditorPart part= new TestMultiEditor(new TestAbstractTextEditor());
68
69 assertZoomSupported(part, true);
70 }
71
72 @Test
73 public void textZoomIsNotSupportedForMultiEditorWithNonTextPage() {
74 EditorPart part= new TestMultiEditor(new TestNonTextEditor());
75
76 assertZoomSupported(part, false);
77 }
78
79 @Test
80 public void textZoomIsSupportedForAdaptableToAbstractTextEditor() {
81 IEditorPart part= new TestAdaptableToAbstractTestEditor();
82
83 assertZoomSupported(part, true);
84 }
85
86 @Test
87 public void textZoomIsNotSupportedForGenericObject() {
88 assertZoomSupported(new Object(), false);
89 }
90
91 private void assertZoomSupported(Object receiver, boolean expectedEnabled) {
92 TextZoomInHandler textZoomHandler= new TextZoomInHandler();
93
94 EvaluationContext evaluationContext= new EvaluationContext(null, new Object());
95 evaluationContext.addVariable(ISources.ACTIVE_EDITOR_NAME, receiver);
96
97 textZoomHandler.setEnabled(evaluationContext);
98
99 boolean actualEnabled= textZoomHandler.isEnabled();
100
101 assertEquals(expectedEnabled, actualEnabled);
102 }
103
104 private static class TestAbstractTextEditor extends AbstractTextEditor {
105
106 @Override
107 public <T> T getAdapter(Class<T> adapter) {
108 return null;
109 }
110
111 @Override
112 public void init(IEditorSite site, IEditorInput input) throws PartInitException { //
113 }
114 }
115
116 private static class TestNonTextEditor extends EditorPart {
117
118 @Override
119 public <T> T getAdapter(Class<T> adapter) {
120 return null;
121 }
122
123 @Override
124 public void doSave(IProgressMonitor monitor) { //
125 }
126
127 @Override
128 public void doSaveAs() { //
129 }
130
131 @Override
132 public void init(IEditorSite site, IEditorInput input) throws PartInitException { //
133 }
134
135 @Override
136 public boolean isDirty() { //
137 return false;
138 }
139
140 @Override
141 public boolean isSaveAsAllowed() { //
142 return false;
143 }
144
145 @Override
146 public void createPartControl(Composite parent) { //
147 }
148
149 @Override
150 public void setFocus() { //
151 }
152 }
153
154 private static class TestAdaptableToAbstractTestEditor extends TestNonTextEditor {
155
156 @Override
157 public <T> T getAdapter(Class<T> adapter) {
158 if (adapter == AbstractTextEditor.class) {
159 return adapter.cast(new TestAbstractTextEditor());
160 }
161 return null;
162 }
163 }
164
165 private static class TestMultiEditor extends AbstractMultiEditor {
166
167 @Override
168 public <T> T getAdapter(Class<T> adapter) {
169 return null;
170 }
171
172 public TestMultiEditor(IEditorPart child) {
173 setChildren(new IEditorPart[] { child });
174 }
175
176 @Override
177 public void createPartControl(Composite parent) { //
178 }
179
180 @Override
181 protected void innerEditorsCreated() { //
182 }
183
184 @Override
185 public Composite getInnerEditorContainer(IEditorReference innerEditorReference) {
186 return null;
187 }
188 }
189
190 private static class TestMultiPageEditorPart extends MultiPageEditorPart {
191
192 private IEditorPart child;
193
194 public TestMultiPageEditorPart(IEditorPart child) {
195 this.child= child;
196 }
197
198 @Override
199 public <T> T getAdapter(Class<T> adapter) {
200 return null;
201 }
202
203 @Override
204 public boolean isSaveAsAllowed() {
205 return false;
206 }
207
208 @Override
209 public void doSaveAs() { //
210 }
211
212 @Override
213 public void doSave(IProgressMonitor monitor) { //
214 }
215
216 @Override
217 protected void createPages() { //
218 }
219
220 @Override
221 public void init(IEditorSite site, IEditorInput input) throws PartInitException { //
222 }
223
224 @Override
225 public Object getSelectedPage() {
226 return child;
227 }
228 }
229
230 }
3232 ChangeRegionTest.class,
3333 RulerTestSuite.class,
3434 HunkComputerTest.class,
35 ScreenshotTest.class
35 ScreenshotTest.class,
36 AbstractTextZoomHandlerTest.class
3637 })
3738 public class WorkbenchTextEditorTestSuite {
3839 // see @SuiteClasses
1414 <parent>
1515 <groupId>org.eclipse</groupId>
1616 <artifactId>eclipse-platform-parent</artifactId>
17 <version>4.7.3-SNAPSHOT</version>
17 <version>4.8.0-SNAPSHOT</version>
1818 <relativePath>../eclipse-platform-parent</relativePath>
1919 </parent>
2020
2121 <groupId>eclipse.platform.text</groupId>
2222 <artifactId>eclipse.platform.text</artifactId>
23 <version>4.7.3-SNAPSHOT</version>
23 <version>4.8.0-SNAPSHOT</version>
2424 <packaging>pom</packaging>
2525
2626 <properties>
6464 <module>org.eclipse.ui.editors</module>
6565 <module>org.eclipse.search</module>
6666 <module>org.eclipse.ui.examples.javaeditor</module>
67 <module>org.eclipse.jface.text.examples</module>
6768 <!-- Generic editor -->
6869 <module>org.eclipse.ui.genericeditor</module>
6970 <module>org.eclipse.ui.genericeditor.tests</module>
1313 <parent>
1414 <artifactId>eclipse.platform.text</artifactId>
1515 <groupId>eclipse.platform.text</groupId>
16 <version>4.7.3-SNAPSHOT</version>
16 <version>4.8.0-SNAPSHOT</version>
1717 </parent>
1818 <artifactId>tests-pom</artifactId>
19 <version>4.7.3-SNAPSHOT</version>
19 <version>4.8.0-SNAPSHOT</version>
2020 <packaging>pom</packaging>
2121 <properties>
2222 <code.ignoredWarnings>${tests.ignoredWarnings}</code.ignoredWarnings>