Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: fd7fed1a295681f5f5ae1164e8a5e0360de38ca4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
/*******************************************************************************
 * Copyright (c) 2004, 2006 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corp. - Rational Software - initial implementation
 *******************************************************************************/

package org.eclipse.cdt.internal.ui.search.actions;

import java.io.IOException;

import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.dom.ast.IASTFileLocation;
import org.eclipse.cdt.core.dom.ast.IASTName;
import org.eclipse.cdt.core.model.CoreModel;
import org.eclipse.cdt.core.model.IWorkingCopy;
import org.eclipse.cdt.core.parser.CodeReader;
import org.eclipse.cdt.core.parser.IParser;
import org.eclipse.cdt.core.parser.IScannerInfo;
import org.eclipse.cdt.core.parser.IScannerInfoProvider;
import org.eclipse.cdt.core.parser.Keywords;
import org.eclipse.cdt.core.parser.NullSourceElementRequestor;
import org.eclipse.cdt.core.parser.ParserFactory;
import org.eclipse.cdt.core.parser.ParserFactoryError;
import org.eclipse.cdt.core.parser.ParserLanguage;
import org.eclipse.cdt.core.parser.ParserMode;
import org.eclipse.cdt.core.parser.ParserUtil;
import org.eclipse.cdt.core.parser.ScannerInfo;
import org.eclipse.cdt.core.resources.FileStorage;
import org.eclipse.cdt.internal.ui.editor.CEditor;
import org.eclipse.cdt.internal.ui.editor.ExternalSearchEditor;
import org.eclipse.cdt.internal.ui.search.CSearchMessages;
import org.eclipse.cdt.internal.ui.util.ExternalEditorInput;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.search.ui.NewSearchUI;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.ITextEditor;

/**
 * @author aniefer
 * Created on Jun 2, 2004
 */
public class SelectionParseAction extends Action {
	private static final String OPERATOR = "operator"; //$NON-NLS-1$
	protected static final String CSEARCH_OPERATION_NO_NAMES_SELECTED_MESSAGE = "CSearchOperation.noNamesSelected.message"; //$NON-NLS-1$
	protected static final String CSEARCH_OPERATION_OPERATION_UNAVAILABLE_MESSAGE = "CSearchOperation.operationUnavailable.message"; //$NON-NLS-1$
    protected static final String CSEARCH_OPERATION_NO_DEFINITION_MESSAGE = "CSearchOperation.noDefinitionFound.message"; //$NON-NLS-1$
    protected static final String CSEARCH_OPERATION_NO_DECLARATION_MESSAGE = "CSearchOperation.noDeclarationFound.message"; //$NON-NLS-1$
        
	protected IWorkbenchSite fSite;
	protected CEditor fEditor;

	public SelectionParseAction() {
		super();
	}
	
	public SelectionParseAction( CEditor editor ) {
		super();
		fEditor=editor;
		fSite=editor.getSite();
	}
	
	public SelectionParseAction(IWorkbenchSite site){
		super();
		fSite=site;
	}

	protected IParser setupParser(IFile resourceFile) {
		

		//Get the scanner info
		IProject currentProject = resourceFile.getProject();
		IScannerInfo scanInfo = new ScannerInfo();
		IScannerInfoProvider provider = CCorePlugin.getDefault().getScannerInfoProvider(currentProject);
		if (provider != null){
		  IScannerInfo buildScanInfo = provider.getScannerInformation(resourceFile);
		  if (buildScanInfo != null){
			scanInfo = new ScannerInfo(buildScanInfo.getDefinedSymbols(), buildScanInfo.getIncludePaths());
		  }
		}
		
		//C or CPP?
		ParserLanguage language = CoreModel.hasCCNature(currentProject) ? ParserLanguage.CPP : ParserLanguage.C;
		
		IWorkingCopy workingCopy = null;
		if( fEditor.isDirty() ){
			IWorkingCopy [] workingCopies = CUIPlugin.getSharedWorkingCopies();
			if( workingCopies != null ){
				for( int i = 0; i < workingCopies.length; i++ ){
					if( workingCopies[i].getUnderlyingResource().equals( resourceFile ) ){
						workingCopy = workingCopies[i];
						break;
					}
				}
			}
		}
		
		IParser parser = null;
		CodeReader reader = null;
		try {
			if( workingCopy == null )
				reader = new CodeReader(resourceFile.getLocation().toOSString(), resourceFile.getCharset() );
			else 
				reader = new CodeReader(resourceFile.getLocation().toOSString(), workingCopy.getContents());
		} catch (IOException e) {
			e.printStackTrace();
		} catch ( CoreException e ) {
            e.printStackTrace();
        }
		
		try
		{
			parser = ParserFactory.createParser( 
							ParserFactory.createScanner( reader, scanInfo, ParserMode.SELECTION_PARSE, language, new NullSourceElementRequestor(), ParserUtil.getScannerLogService(), null ), 
							new NullSourceElementRequestor(), ParserMode.SELECTION_PARSE, language, ParserUtil.getParserLogService() );
			
		} catch( ParserFactoryError pfe ){}
		
	   return parser;
	 }

	protected void operationNotAvailable(final String message) {
		// run the code to update the status line on the Display thread
		// this way any other thread can invoke operationNotAvailable(String)
		CUIPlugin.getStandardDisplay().asyncExec(new Runnable(){
			/* (non-Javadoc)
			 * @see java.lang.Runnable#run()
			 */
			public void run() {
				IStatusLineManager statusManager = null;
				 if (fSite instanceof IViewSite){
				 	statusManager = ((IViewSite) fSite).getActionBars().getStatusLineManager();
				 }
				 else if (fSite instanceof IEditorSite){
				 	statusManager = ((IEditorSite) fSite).getActionBars().getStatusLineManager();
				 }	
				 if( statusManager != null )
				 	statusManager.setErrorMessage(CSearchMessages.getString(message));//$NON-NLS-1$
			}
		});
	}
	protected void clearStatusLine() {
		// run the code to update the status line on the Display thread
		// this way any other thread can invoke clearStatusLine()
		CUIPlugin.getStandardDisplay().asyncExec(new Runnable(){
			/* (non-Javadoc)
			 * @see java.lang.Runnable#run()
			 */
			public void run() {
				IStatusLineManager statusManager = null;
				 if (fSite instanceof IViewSite){
				 	statusManager = ((IViewSite) fSite).getActionBars().getStatusLineManager();
				 }
				 else if (fSite instanceof IEditorSite){
				 	statusManager = ((IEditorSite) fSite).getActionBars().getStatusLineManager();
				 }	
				 if( statusManager != null )
				 	statusManager.setErrorMessage( "" ); //$NON-NLS-1$
			}
		});
	}

	//TODO: Change this to work with qualified identifiers
	public ITextSelection getSelection( int fPos ) {
 		IDocumentProvider prov = ( fEditor != null ) ? fEditor.getDocumentProvider() : null;
 		IDocument doc = ( prov != null ) ? prov.getDocument(fEditor.getEditorInput()) : null;
 		
 		if( doc == null )
 			return null;
 		 
		int pos= fPos;
		char c;
		int fStartPos =0, fEndPos=0;
        int nonJavaStart=-1, nonJavaEnd=-1;
		String selectedWord=null;
		
		try{
			while (pos >= 0) {
				c= doc.getChar(pos);

                // TODO this logic needs to be improved
                // ex: ~destr[cursor]uctors, p2->ope[cursor]rator=(zero), etc
                if (nonJavaStart == -1 && !Character.isJavaIdentifierPart(c)) {
                    nonJavaStart=pos+1;
                }
                    
                if (Character.isWhitespace(c))
                    break;

				--pos;
			}
			fStartPos= pos + 1;
			
			pos= fPos;
			int length= doc.getLength();
			while (pos < length) {
				c= doc.getChar(pos);

                if (nonJavaEnd == -1 && !Character.isJavaIdentifierPart(c)) {
                    nonJavaEnd=pos;
                }
                if (Character.isWhitespace(c))
                    break;
				++pos;
			}
			fEndPos= pos;
			selectedWord = doc.get(fStartPos, (fEndPos - fStartPos));
        }
        catch(BadLocationException e){
        }
        
        boolean selectedOperator=false;
        if (selectedWord != null && selectedWord.indexOf(OPERATOR) >= 0 && fPos >= fStartPos + selectedWord.indexOf(OPERATOR) && fPos < fStartPos + selectedWord.indexOf(OPERATOR) + OPERATOR.length()) {
            selectedOperator=true;
        }
    
        // if the operator was selected, get its proper bounds
        if (selectedOperator && fEditor.getEditorInput() instanceof IFileEditorInput &&  
                CoreModel.hasCCNature(((IFileEditorInput)fEditor.getEditorInput()).getFile().getProject())) {
            int actualStart=fStartPos + selectedWord.indexOf(OPERATOR);
            int actualEnd=getOperatorActualEnd(doc, fStartPos + selectedWord.indexOf(OPERATOR) + OPERATOR.length());
            
            actualEnd=(actualEnd>0?actualEnd:fEndPos);
            
            return new TextSelection(doc, actualStart, actualEnd - actualStart);
        // TODO Devin this only works for definitions of destructors right now
        // if there is a destructor and the cursor is in the destructor name's segment then get the entire destructor
        } else if (selectedWord != null && selectedWord.indexOf('~') >= 0 && fPos - 2 >= fStartPos + selectedWord.lastIndexOf(new String(Keywords.cpCOLONCOLON))) {
            int tildePos = selectedWord.indexOf('~');
            int actualStart=fStartPos + tildePos;
            int length=0;
            char temp;
            char[] lastSegment = selectedWord.substring(tildePos).toCharArray();
            for(int i=1; i<lastSegment.length; i++) {
                temp = lastSegment[i];
                if (!Character.isJavaIdentifierPart(temp)) {
                    length=i;
                    break;
                }
            }
            
            // if the cursor is after the destructor name then use the regular boundaries 
            if (fPos >= actualStart + length) {
            	return new TextSelection(doc, nonJavaStart, length);
            } else {
            	return new TextSelection(doc, actualStart, length);
            }
        } else {
            // otherwise use the non-java identifier parts as boundaries for the selection
        	return new TextSelection(doc, nonJavaStart, nonJavaEnd - nonJavaStart);
        }
	}
    
    private int getOperatorActualEnd(IDocument doc, int index) {
        char c1, c2;
        int actualEnd=-1;
        boolean multiComment=false;
        boolean singleComment=false;
        int possibleEnd=-1;
        while (actualEnd==-1) {
            try {
                c1=doc.getChar(index);
                c2=doc.getChar(index+1);
                
                // skip anything within a single-line comment
                if (singleComment) {
                    char c3=doc.getChar(index-1);
                    if (c3 != '\\' && (c1 == '\n' || c1 == '\r' && c2 == '\n' )) {
                        singleComment=false;
                    }
                    index++;
                    continue;
                }
                // skip anything within a multi-line comment
                if (multiComment) {
                    if (c1 == '*' && c2 == '/') {
                        multiComment=false;
                        index+=2;
                        continue;
                    }
                    index++;
                    continue;
                }
                
                switch(c1) {
                case '+': {
                    switch(c2) {
                    case '=':
                    case '+':
                        actualEnd=index+2;
                        break;
                    default:
                        actualEnd=index+1;
                        break;
                    }
                    break;
                }
                case '-': {
                    switch(c2) {
                    case '=':
                        actualEnd=index+2;
                        break;
                    case '-':
                        switch(doc.getChar(index+2)) {
                        case '>': {
                            switch(doc.getChar(index+3)) {
                            case '*':
                                actualEnd=index+4;
                                break;
                            default:
                                actualEnd=index+3;
                                break;
                            }
                            break;
                        }
                        default:
                            actualEnd=index+2;
                            break;                                
                        }
                        break;
                    default:
                        
                        break;
                    }
                    break;
                }
                case '|': {
                    switch(c2) {
                    case '=':
                    case '|':
                        actualEnd=index+2;
                        break;
                    default:
                        actualEnd=index+1;
                        break;
                    }
                    break;                  
                }
                case '&': {
                    switch(c2) {
                    case '=':
                    case '&':
                        actualEnd=index+2;
                        break;
                    default:
                        actualEnd=index+1;
                        break;
                    }
                    break;
                }
                case '/': {
                    switch(c2) {
                    case '/':
                        singleComment=true;
                        index+=2;
                        break;
                    case '*':
                        multiComment=true;
                        index+=2;
                        break;
                    case '=':
                        actualEnd=index+2;
                        break;
                    default:
                        actualEnd=index+1;
                        break;
                    }
                    break;
                }
                case '*':
                case '%': 
                case '^': 
                case '!': 
                case '=': {
                    switch(c2) {
                    case '=':
                        actualEnd=index+2;
                        break;
                    default:
                        actualEnd=index+1;
                        break;
                    }
                    break;
                }
                case '(': {
                    if (possibleEnd > 0)
                        actualEnd = possibleEnd;
                    
                    index++;
                    
                    break;
                }   
                case ']':
                case ')':
                case ',':
                case '~': {
                    actualEnd=index+1;
                    break;
                }
                case '<': {
                    switch(c2) {
                    case '=':
                    case '<':
                        switch(doc.getChar(index+2)) {
                        case '=':
                            actualEnd=index+3;
                            break;
                        default:
                            actualEnd=index+2;
                            break;
                        }
                        break;
                    default:
                        actualEnd=index;
                        break;
                    }
                    break;                  
                }
                case '>': {
                    switch(c2) {
                    case '=':
                    case '>':
                        switch(doc.getChar(index+2)) {
                        case '=':
                            actualEnd=index+3;
                            break;
                        default:
                            actualEnd=index+2;
                            break;
                        }
                        break;
                    default:
                        actualEnd=index;
                        break;
                    }
                    break;  
                }
                case 'n': { // start of "new"
                    while (doc.getChar(++index) != 'w') {}
                    possibleEnd=++index;
                    break;
                }
                case 'd': { // start of "delete"
                    while (doc.getChar(++index) != 't' && doc.getChar(index+1) != 'e'){}
                    index+=2;
                    possibleEnd=index;
                    break;
                }
                default:
                    index++;
                    break;
                }
            } catch (BadLocationException e) {
                // something went wrong
                return -1;
            }
        }
        
        return actualEnd;
    }
    
	/**
	  * Return the selected string from the editor
	  * @return The string currently selected, or null if there is no valid selection
	  */
	protected ITextSelection getSelection( ITextSelection textSelection ) {
		if( textSelection == null )
			return null;
		
		 if (textSelection.getLength() == 0) {
	 		 return getSelection(textSelection.getOffset());
		 } else {
			 return textSelection;
		 }
	}
	
	protected ISelection getSelection() {
		ISelection sel = null;
		if (fSite != null && fSite.getSelectionProvider() != null ){
			sel = fSite.getSelectionProvider().getSelection();
		}
		
		return sel;
	}
	
    protected ITextSelection getSelectedStringFromEditor() {
        ISelection selection = getSelection();
        if( selection == null || !(selection instanceof ITextSelection) ) 
             return null;

        return getSelection( (ITextSelection)selection );
    }
    
    /**
     * Open the editor on the given name.
     * 
     * @param name
     */
    protected void open(IASTName name) throws CoreException {
    	IASTFileLocation fileloc = name.getFileLocation();
    	if (fileloc == null)
    		// no source location - TODO spit out an error in the status bar
    		return;
    	int currentOffset = fileloc.getNodeOffset();
    	int currentLength = fileloc.getNodeLength();
    	
		IPath path = new Path(fileloc.getFileName());
		IFile[] files = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocation(path);
		if (files.length > 0) {
			IEditorPart editor = IDE.openEditor(CUIPlugin.getActivePage(), files[0]);
			try {
				IMarker marker = files[0].createMarker(NewSearchUI.SEARCH_MARKER);
				marker.setAttribute(IMarker.CHAR_START, currentOffset);
				marker.setAttribute(IMarker.CHAR_END, currentOffset + currentLength);
				IDE.gotoMarker(editor, marker);
				marker.delete();
			} catch (CoreException e) {
				CUIPlugin.getDefault().log(e);
			}
		} else {
			// external file
			IEditorInput input = new ExternalEditorInput(new FileStorage(path));
			IEditorPart editor = CUIPlugin.getActivePage().openEditor(input, ExternalSearchEditor.EDITOR_ID);
			if (editor instanceof ITextEditor) {
				ITextEditor textEditor = (ITextEditor)editor;
				textEditor.selectAndReveal(currentOffset, currentLength);
			}
		}

    }
    
    public void update() {
		setEnabled(getSelectedStringFromEditor() != null);
	}

}

Back to the top