summaryrefslogtreecommitdiffstats
path: root/languages/cpp/cppsupportpart.h
blob: 906a2694a4be594e2a1e5c4b1b35684665882361 (plain)
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
/***************************************************************************
*   Copyright (C) 1999 by Jonas Nordin                                    *
*   [email protected]                                                *
*   Copyright (C) 2000-2001 by Bernd Gehrmann                             *
*   [email protected]                                                    *
*   Copyright (C) 2002-2003 by Roberto Raggi                              *
*   [email protected]                                                  *
*   Copyright (C) 2003-2004 by Alexander Dymo                             *
*   [email protected]                                                       *
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU General Public License as published by  *
*   the Free Software Foundation; either version 2 of the License, or     *
*   (at your option) any later version.                                   *
*                                                                         *
***************************************************************************/

#ifndef _CPPSUPPORTPART_H_
#define _CPPSUPPORTPART_H_

#include <kdevcore.h>
#include <kdevlanguagesupport.h>

#include <tqthread.h>
#include <tqmutex.h>
#include <tqtimer.h>
#include <kdialogbase.h>
#include <tqguardedptr.h>
#include <tqstring.h>
#include <tqwaitcondition.h>
#include <tqdatetime.h>
#include <tqdir.h>
#include <tqprogressbar.h>
#include <kdebug.h>
#include <ext/hash_map>
#include "driver.h"


///A class that helps detecting what exactly makes the UI block. To use it, just place a breakpoint on UIBlockTester::lockup() and inspect the execution-position of the main thread
class UIBlockTester : public TQObject {
	Q_OBJECT
  TQ_OBJECT
    class UIBlockTesterThread : public TQThread {
    public:
      UIBlockTesterThread( UIBlockTester& parent );
      void run();
      void stop();
    private:
      UIBlockTester& m_parent;
      bool m_stop;
    };
  friend class UIBlockTesterThread;
public:
    
  ///@param milliseconds when the ui locks for .. milliseconds, lockup() is called
  UIBlockTester( uint milliseconds );
  ~UIBlockTester();
	
private slots:
  void timer();
	
protected:
  virtual void lockup();

private:
    UIBlockTesterThread m_thread;
	TQDateTime m_lastTime;
	TQMutex m_timeMutex;
	TQTimer * m_timer;
	uint m_msecs;
};

class Context;
class CppCodeCompletion;
class CppCodeCompletionConfig;
class CppSplitHeaderSourceConfig;
class CreateGetterSetterConfiguration;
class QtBuildConfig;
class ProblemReporter;
class BackgroundParser;
class Catalog;
class TQLabel;
class TQProgressBar;
class TQStringList;
class TQListViewItem;
class TranslationUnitAST;
class TQTimer;
class KListView;
class Driver;
class KPopupMenu;
class BackgroundParserConfig;
class KAction;

namespace KParts
{
	class Part;
}
namespace KTextEditor
{
	class Document;
	class View;
	class EditInterface;
	class SelectionInterface;
	class ViewCursorInterface;
}


class SynchronizedFileSet
{
public:
    typedef __gnu_cxx::hash_set< HashedString > SetType;
    SynchronizedFileSet()
	{}
	
	bool isEmpty() const
	{
		TQMutexLocker locker( &m_mutex );
		return m_fileSet.empty();
	}
	
	uint count() const
	{
		TQMutexLocker locker( &m_mutex );
		return m_fileSet.size();
	}
	
	void clear()
	{
		TQMutexLocker locker( &m_mutex );
		m_fileSet.clear();
	}

    void setFiles( const SetType& files ) {
		TQMutexLocker locker( &m_mutex );
        m_fileSet = files;
    }
	
	void insert( const HashedString& str )
	{
        HashedString s( TQString::fromUtf8(str.str().utf8()) );
		TQMutexLocker locker( &m_mutex );
          
		m_fileSet.insert( s );
	}

    bool contains( const HashedString& str ) const {
		TQMutexLocker locker( &m_mutex );
        return m_fileSet.find( str ) != m_fileSet.end();
    }

private:
	mutable TQMutex m_mutex;
	SetType m_fileSet;
};

class CppSupportPart : public KDevLanguageSupport
{
	Q_OBJECT
  TQ_OBJECT

public:
	CppSupportPart( TQObject *parent, const char *name, const TQStringList &args );
	virtual ~CppSupportPart();

	bool isValid() const
	{
		return m_valid;
	}

	TQString specialHeaderName( bool local = false ) const;
	void updateParserConfiguration();
	void updateBackgroundParserConfig();
	
	// @fixme - isValid is used to avoid using the problem reporter
	// when a project is first parsed. This because the problem reporter
	// is currently a great slowdown for large projects (see bug #73671)
    ProblemReporter* problemReporter() const
	{
 		return isValid() ? static_cast<ProblemReporter *>( m_problemReporter ) : 0;
	}

    /** parses the file and all files that belong to it using the background-parser */
    int parseFileAndDependencies( const TQString& fileName, bool background = true, bool parseFirst = false, bool silent = false );
    int parseFilesAndDependencies( TQStringList files, bool background = true, bool parseFirst = false, bool silent = false );
    
    BackgroundParser* backgroundParser() const
	{
		return m_backgroundParser;
	}
    CppCodeCompletion* codeCompletion() const
	{
		return m_pCompletion;
	}
    CppCodeCompletionConfig* codeCompletionConfig() const
	{
		return m_pCompletionConfig;
	}
    CppSplitHeaderSourceConfig* splitHeaderSourceConfig() const
    {
        return m_pSplitHeaderSourceConfig;
    }
    CreateGetterSetterConfiguration* createGetterSetterConfiguration() const
	{
		return m_pCreateGetterSetterConfiguration;
	}
	
	/**
		Get a pointer to the QtBuildConfig object
		@return A pointer to the QtBuildConfig object.
	*/
	inline QtBuildConfig* qtBuildConfig() const { return m_qtBuildConfig; }

    const TQPtrList<Catalog>& catalogList() const
	{
		return m_catalogList;
	}
	void addCatalog( Catalog* catalog );
	void removeCatalog( const TQString& dbName );

	bool isValidSource( const TQString& fileName ) const;

	virtual void customEvent( TQCustomEvent* ev );

	virtual TQStringList subclassWidget( const TQString& formName );
	virtual TQStringList updateWidget( const TQString& formName, const TQString& fileName );

	FunctionDefinitionDom currentFunctionDefinition();
	FunctionDefinitionDom functionDefinitionAt( int line, int column );


	KTextEditor::Document* findDocument( const KURL& url );
	static KConfig *config();

	virtual TQString formatTag( const Tag& tag );
	virtual TQString formatModelItem( const CodeModelItem *item, bool shortDescription = false );
	virtual void addClass();

	TQString extractInterface( const ClassDom& klass );

	bool isHeader( const TQString& fileName ) const;
	bool isSource( const TQString& fileName ) const;

    //uses the old simple algorithm to find the header
    TQString findHeaderSimple( const TQString &header );
  
	virtual KDevDesignerIntegration *designer( KInterfaceDesigner::DesignerType type );

	void setTyping( bool typing );
	
	/**
	 * Add a new method to a class.
	 * @param aClass The class to which the method should be added.
	 * @param name The name of the method.
	 * @param type The return type of the method.
	 * @param parameters A string containing the parameters
	 * (including names, default values, but no '(' , ')', e.g.: "int, const TQString& aString").
	 * @param accessType The access specifier e.g. CodeModelItem::PUBLIC.
	 * @param isConst true if method is const.
	 * @param isInline true if method should be declared inline.
	 * @param isVirtual true if method is virtual(this is ignored if isPureVirtual is true)
	 * @param isPureVirtual true if method is pure virtual (this overrides any value of isVirtual)
	 * @param implementation a optional implementation, if this is not set the method body will be empty.
	 * @author Jonas Jacobi <[email protected]>
	 */
	virtual void addMethod( ClassDom aClass, const TQString& name, const TQString type, const TQString& parameters, CodeModelItem::Access accessType, bool isConst, bool isInline, bool isVirtual, bool isPureVirtual, const TQString& implementation = "" );

	void createAccessMethods( ClassDom theClass, VariableDom theVariable );

    bool isQueued( const TQString& file ) const;
    bool switchHeaderImpl( const TQString& file, int line, int col, bool scrollOnly = false );

    const Driver* driver() const;

    Driver* driver();

    ///thread-safe, returns the thread-safe set of all files that do not need to be parsed when being included, either because they are part of the project and parsed anyway, or because they are already in the code-repository
    const SynchronizedFileSet& safeFileSet() const;
    SynchronizedFileSet& safeFileSet();
signals:
	void fileParsed( const TQString& fileName );
    ///Emitted whenever a file was parsed, but the code-model could be updated(the file in the code-model did not have to be replaced)
	void codeModelUpdated( const TQString& fileName );
	///Emitted whenever a translation-unit was parsed in the main thread
	void synchronousParseReady( const TQString& file, ParsedFilePointer unit );
    
protected:
	virtual KDevLanguageSupport::Features features();
	virtual KMimeType::List mimeTypes();
	virtual TQString formatClassName( const TQString &name );
	virtual TQString unformatClassName( const TQString &name );
    virtual bool shouldSplitDocument( const KURL &url );
    virtual Qt::Orientation splitOrientation() const;
	virtual void addMethod( ClassDom klass );
	virtual void addAttribute( ClassDom klass );

private slots:
	void activePartChanged( KParts::Part *part );
	void partRemoved( KParts::Part* part );
	void projectOpened();
	void projectClosed();
	void savedFile( const KURL &fileName );
	void configWidget( KDialogBase *dlg );
	void projectConfigWidget( KDialogBase *dlg );
	void contextMenu( TQPopupMenu *popup, const Context *context );
	void addedFilesToProject( const TQStringList &fileList );
	void removedFilesFromProject( const TQStringList &fileList );
	void changedFilesInProject( const TQStringList & fileList );
	void slotProjectCompiled();
	void setupCatalog();
    void codeCompletionConfigStored();
    void splitHeaderSourceConfigStored();
    //	void recomputeCodeModel( const TQString& fileName );
	void slotNavigate();
	void slotNewClass();
	void slotSwitchHeader( bool scrollOnly = false );
	void slotCompleteText();
	void slotMakeMember();
	void slotExtractInterface();
	void slotCursorPositionChanged();
// 	void slotFunctionHint();
	void gotoLine( int line );
	void gotoDeclarationLine( int line );
    void emitFileParsed( TQStringList l );
	void slotParseFiles();
	void slotCreateSubclass();
	void slotCreateAccessMethods();
	void slotDeleteParserStore();
    void slotSaveMemory();
	void slotTextChanged();
	void slotCursorMoved();
	void slotParseCurrentFile();
	void embedProblemReporter( bool force = false );
	void removeProblemReporter();
	

	void slotNeedTextHint( int, int, TQString& );

	/**
	 * loads, parses and creates both classstores needed
	 */
	void initialParse( );

	/**
	 * only parses the current project
	 */
	bool parseProject( bool force = false );

private:

	void resetParserStoreTimer();
	/**
	 * Get a linenumber in which a new method with a specific access specifier can be inserted.
	 * If there isn't a "section" with access, such a "section" gets inserted and the resulting place is returned.
	 * @param aClass the class one wants to insert a method to.
	 * @param access the access specifier the new method should have.
	 * @return A linenumber where the new method can be inserted 
	 * or -1 if partController()->activePart() is no KTextEditorInterface.
	 * @author Jonas Jacobi <[email protected]>
	 */
	int findInsertionLineMethod( ClassDom aClass, CodeModelItem::Access access );
	/**
	 * Same as above, just returns a insertion line for a variable instead of a method
	 */
	int findInsertionLineVariable( ClassDom aClass, CodeModelItem::Access access );


	/**
	 * Get a class declaration which is "around" the current cursor position.
	 * @return The class declaration which is "around" the current cursor position,
	 * in the case of nested classes this is the innermost fitting class. If there is no
	 * class declared at the current cursor position, 0 is returned.
	 * @author Jonas Jacobi <[email protected]>
	 */
	ClassDom currentClass() const;
	/**
	 * Get the class attribute of curClass, which is declared at the current cursor position.
	 * @param curClass the class to search for attributes.
	 * @return the attribute declared at the current cursor position or 0, if no attribute is declared there.
	 * @author Jonas Jacobi <[email protected]>
	 */
	VariableDom currentAttribute( ClassDom curClass ) const;

	/**
	 * checks if a file has to be parsed
	 */
    FileDom fileByName( const TQString& name);
	void maybeParse( const TQString& fileName, bool background = true );
	void removeWithReferences( const TQString& fileName );
	void createIgnorePCSFile();

	void MakeMemberHelper( TQString& text, int& atline, int& atcol );

    TQString sourceOrHeaderCandidate( const KURL &url = KURL() );

	FunctionDom findFunction( const FunctionDom& def );
	FunctionDom findFunctionInNamespace( const NamespaceDom& ns, const FunctionDom& def, const std::set<NamespaceImportModel>& nsImports,
	                                     const TQString& candidateFile, int scopeIndex, FunctionDom& bestMatch );
	FunctionDom findFunctionInClass( const ClassDom& cs, const FunctionDom& def, const std::set<NamespaceImportModel>& nsImports,
	                                 const TQString& candidateFile, int scopeIndex, FunctionDom& bestMatch );
	FunctionDom findFunctionDefinition( const FunctionDom& decl );

	void jumpToCodeModelItem( const ItemDom& item, bool scrollOnly );

	TQStringList modifiedFileList();
	TQString findSourceFile();
	int pcsVersion();
	void setPcsVersion( int version );

	void saveProjectSourceInfo();
	TQStringList reorder( const TQStringList& list );

	CppCodeCompletion* m_pCompletion;
	CppCodeCompletionConfig* m_pCompletionConfig;
    CppSplitHeaderSourceConfig* m_pSplitHeaderSourceConfig;

	CreateGetterSetterConfiguration* m_pCreateGetterSetterConfiguration;
	KAction * m_createGetterSetterAction;
	KAction * m_switchHeaderSourceAction;
	
	QtBuildConfig* m_qtBuildConfig;

	bool withcpp;
	TQString m_contextFileName;

	VariableDom m_curAttribute;
	ClassDom m_curClass;
	TQGuardedPtr< ProblemReporter > m_problemReporter;
	BackgroundParser* m_backgroundParser;
    UIBlockTester* m_lockupTester;

	KTextEditor::Document* m_activeDocument;
	KTextEditor::View* m_activeView;
	KTextEditor::SelectionInterface* m_activeSelection;
	KTextEditor::EditInterface* m_activeEditor;
	KTextEditor::ViewCursorInterface* m_activeViewCursor;
	TQString m_activeFileName;

	TQMap<KInterfaceDesigner::DesignerType, KDevDesignerIntegration*> m_designers;

	TQWaitCondition m_eventConsumed;
	bool m_projectClosed;
	bool m_projectClosing;

	TQMap<TQString, TQDateTime> m_timestamp;
	bool m_valid;
	bool m_isTyping;
	bool m_hadErrors; ///Whether there were already errors when the user started typing
	
	TQPtrList<Catalog> m_catalogList;
	Driver* m_driver;
	TQString m_projectDirectory;
	TQStringList m_projectFileList;

	ClassDom m_activeClass;
	FunctionDom m_activeFunction;
	VariableDom m_activeVariable;

	TQGuardedPtr<KPopupMenu> m_navigationMenu;

// 	TQTimer* m_functionHintTimer;
// 	TQTimer* m_deleteParserStoreTimer;
	TQTimer* m_saveMemoryTimer;
	TQTimer * m_textChangedTimer;
	TQTimer * m_cursorMovedTimer;
    TQTimer* m_buildSafeFileSetTimer;
    
    class ParseEmitWaiting {
    public:
	    enum Flags {
		    None = 0,
			HadErrors = 1,
			HadQueueProblem = 2,
            Silent = 4
	    };
    private:
	    struct Item {
		    TQStringList first;
		    TQStringList second;
		    Flags flags;
	    	Item() : flags(None) {
		    }
			Item( TQStringList f, TQStringList s, Flags fl = None ) : first( f ), second( s ), flags( fl )
		    {
		    }
	    };
	    //typedef TQPair<TQStringList, TQStringList> Item; ///The files we are waiting fore, and the files we already got
        typedef TQValueList< Item > List;
        List m_waiting;
        
        
        TQStringList harvestUntil( List::iterator targIt ) {
            List::iterator it = m_waiting.begin();
            TQStringList ret;
            while( it != targIt && it != m_waiting.end() ) {
                ret += (*it).first;
                it = m_waiting.erase( it );
            }
            return ret;
        }
        
    public:
        void addGroup( TQStringList& files, Flags flag = None ) {
            m_waiting << Item(files, TQStringList(), flag);
        }
        void addGroupFront( TQStringList& files, Flags flag = None ) {
            m_waiting.push_front( Item(files, TQStringList(), flag) );
        }
        void clear() {
            m_waiting.clear();
        }
        
        ///files that were not requested must not be processed, since they maybe do not respect the group-relationships.
        bool reject( TQString file ) {
            for( List::iterator it = m_waiting.begin(); it != m_waiting.end(); ++it) {
                if( (*it).first.find( file ) !=  (*it).first.end() ) {
                    return false;
                }
            }
            return true;
        }

        bool waiting( TQString file, Flags forbidFlags = None, int count = 1 ) const {
            int hits = 0;
            for( List::const_iterator it = m_waiting.begin(); it != m_waiting.end(); ++it) {
                if( (*it).first.find( file ) !=  (*it).first.end() ) {
                    if( ((Flags)((*it).flags & forbidFlags )) == None ) {
                        hits++;
                        if( hits >= count ) return true;
                    }
                }
            }
            return false;
        }
        
	    struct Processed {
		    TQStringList res;
		    Flags flag;
			Processed() : flag(None) {
			}
			Processed(const TQStringList& l , Flags f = None ) : res( l ), flag( f ) {
			}
		    operator TQStringList() {
			    return res;
		    }

		    bool hadQueueProblem() {
			    return flag & HadQueueProblem;
		    }

		    bool hasFlag( Flags f ) const {
			    return f & flag;
		    }
		    // surely a copy paste implementation?
/*		    
    	    bool hasFlag( Flags flag ) const {
        	    return flag & HadQueueProblem;
    	    }
*/
	    };


    private:
        ///Just return all files that have been parsed
	    Processed errorRecover( TQString currentFile ) {
		    TQStringList ret;
	    kdDebug( 9007 ) << "ParseEmitWaiting: error in the waiting-chain" << endl;
		    for( List::iterator it = m_waiting.begin(); it != m_waiting.end(); ++it) {
			    ret += (*it).second;
		    }
		    if( !currentFile.isEmpty() ) ret << currentFile;
		    m_waiting.clear();
		    return Processed( ret, HadQueueProblem );
	    }
    public:
	    
        ///returns the parsed-messages that should be emitted
		Processed processFile( TQString file, Flags flag = None ) {
            TQStringList ret;
            for( List::iterator it = m_waiting.begin(); it != m_waiting.end(); ++it) {
                if( (*it).first.find( file ) !=  (*it).first.end() ) {
                    if( (*it).second.find( file ) == (*it).second.end() ) {
	                    (*it).flags = (Flags) ((*it).flags | flag);
                        (*it).second << file;
                        if( (*it).second.count() == (*it).first.count() ) {
	                        Flags f = (*it).flags;
                            if( it != m_waiting.begin() ) {
                                kdDebug( 9007 ) << "ParseEmitWaiting: the chain has multiple groups waiting, they are flushed" << endl;
	                            f = (Flags)(f | HadQueueProblem);
                            }
	                        return Processed( harvestUntil( ++it ), f );
                        } else {
                            ///The file was registered, now wait for the next
                            return TQStringList();
                        }
                    } else {
                        ///The file has already been parsed
                    	kdDebug( 9007 ) << "ParseEmitWaiting: file has been parsed twice" << endl;
	                    return errorRecover( file );
                    }
                }
            }
            
            kdDebug( 9007 ) << "ParseEmitWaiting: file \"" << file << "\" has no group waiting for it" << endl;
            ret << file;
			return Processed( ret, HadQueueProblem );
        }
    };
    
    ParseEmitWaiting m_parseEmitWaiting;
    ParseEmitWaiting m_fileParsedEmitWaiting;

private slots:
	void parseEmit( ParseEmitWaiting::Processed files );
    void  buildSafeFileSet();
private:

    SynchronizedFileSet m_safeProjectFiles;
	BackgroundParserConfig * m_backgroundParserConfig;
	
	static TQStringList m_sourceMimeTypes;
	static TQStringList m_headerMimeTypes;

	static TQStringList m_sourceExtensions;
	static TQStringList m_headerExtensions;

	friend class KDevCppSupportIface;
	friend class CppDriver;

	// we need something to plug actions that are not in any menu 
	// into in order for their shortcuts to work
	TQWidget m_DummyActionWidget;

    void addToRepository( ParsedFilePointer );
	void emitSynchronousParseReady( const TQString& file, ParsedFilePointer unit );

	struct JobData
	{
		TQDir dir;
		TQGuardedPtr<TQProgressBar> progressBar;
		TQStringList::Iterator it;
		TQStringList files;
		int cycle;
		int backgroundCount;
		int lastBackgroundState;
		int backgroundState;
		TQStringList reparseList;
		TQMap< TQString, TQPair<uint, uint> > pcs;
		TQDataStream stream;
		TQFile file;
		TQTime lastParse;

		~JobData()
		{
			delete progressBar;
		}
	};

	JobData * _jd;
};

#endif 
// kate: indent-mode csands; tab-width 4;