~quadrispro/codelite/trunk

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
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//
// copyright            : (C) 2008 by Eran Ifrah
// file name            : buidltab.cpp
//
// -------------------------------------------------------------------------
// A
//              _____           _      _     _ _
//             /  __ \         | |    | |   (_) |
//             | /  \/ ___   __| | ___| |    _| |_ ___
//             | |    / _ \ / _  |/ _ \ |   | | __/ _ )
//             | \__/\ (_) | (_| |  __/ |___| | ||  __/
//              \____/\___/ \__,_|\___\_____/_|\__\___|
//
//                                                  F i l e
//
//    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.
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
#include "editor_config.h"
#include "frame.h"
#include "precompiled_header.h"
#include "frame.h"
#include "wx/regex.h"
#include "buildtabsettingsdata.h"
#include "regex_processor.h"
#include "macros.h"
#include "wx/xrc/xmlres.h"
#include "build_settings_config.h"
#include "compiler.h"
#include "manager.h"
#include "project.h"
#include "wx/wxscintilla.h"
#include "buidltab.h"

#ifndef wxScintillaEventHandler
#define wxScintillaEventHandler(func) \
	(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxScintillaEventFunction, &func)
#endif

BEGIN_EVENT_TABLE(BuildTab, wxPanel)
	EVT_MENU(XRCID("next_error"), BuildTab::OnNextBuildError)
END_EVENT_TABLE()

//----------------------------------------------------
//decide whether to colour gcc as warning or error
//return:
//0 - dont colour this line
//1 - colour as error
//2 - colour as warning
//----------------------------------------------------

BuildTab::BuildTab(wxWindow *parent, wxWindowID id, const wxString &name)
		: OutputTabWindow(parent, id, name)
		, m_nextBuildError_lastLine(wxNOT_FOUND)
{
	//set some colours to our styles
	m_sci->MarkerDefine(0x7, wxSCI_MARK_ARROW);
	m_sci->SetMarginWidth(1, 0);
	Initialize();
}

BuildTab::~BuildTab()
{
}

void BuildTab::Initialize()
{
	BuildTabSettingsData options;
	EditorConfigST::Get()->ReadObject(wxT("build_tab_settings"), &options);
	m_skipWarnings = options.GetSkipWarnings();

	wxFont defFont = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);
	wxFont font(defFont.GetPointSize(), wxFONTFAMILY_TELETYPE, wxNORMAL, wxNORMAL);

	m_sci->SetLexer(wxSCI_LEX_GCC);
	m_sci->MarkerSetBackground(0x7, wxT("PINK"));
	m_sci->MarkerSetForeground(0x7, wxT("BLACK"));

	m_sci->StyleSetForeground(wxSCI_LEX_GCC_WARNING, options.GetWarnColour());
	m_sci->StyleSetBackground(wxSCI_LEX_GCC_WARNING, options.GetWarnColourBg());

	m_sci->StyleSetForeground(wxSCI_LEX_GCC_ERROR, options.GetErrorColour());
	m_sci->StyleSetBackground(wxSCI_LEX_GCC_ERROR, options.GetErrorColourBg());

	font.SetWeight(options.GetBoldWarnFont() ? wxBOLD : wxNORMAL);
	m_sci->StyleSetFont(wxSCI_LEX_GCC_WARNING, font);

	font.SetWeight(wxNORMAL);
	m_sci->StyleSetFont(wxSCI_LEX_GCC_DEFAULT, font);

	m_sci->StyleSetForeground(wxSCI_LEX_GCC_FILE_LINK, wxT("BLUE"));
	m_sci->StyleSetFont(wxSCI_LEX_GCC_FILE_LINK, font);

	font.SetWeight(options.GetBoldErrFont() ? wxBOLD : wxNORMAL);
	m_sci->StyleSetFont(wxSCI_LEX_GCC_ERROR, font);

	font.SetWeight(wxBOLD);
	m_sci->StyleSetFont(wxSCI_LEX_GCC_BUILDING, font);
	m_sci->StyleSetHotSpot(wxSCI_LEX_GCC_FILE_LINK, true);
}

void BuildTab::AppendText(const wxString &text)
{
	// Parse the text and keep information
	//----------------------------------------------
	//Keep information about this line
	if (text.Contains(BUILD_PROJECT_PREFIX)) {
		LineInfo info;

		wxString projectName = text.AfterFirst(wxT('['));
		projectName = projectName.Trim(false).Trim();
		int where = projectName.Find(wxT(" - "));

		if (where != wxNOT_FOUND) {
			info.project = projectName.Mid(0, where);
			TrimString(info.project);

			info.configuration = text.AfterFirst(wxT('['));
			info.configuration = info.configuration.AfterFirst(wxT('-'));
			info.configuration = info.configuration.BeforeFirst(wxT(']'));
			TrimString(info.configuration);

			//keep the information about this line
			//we use here GetLineCount()-1 since an empty docuement contains
			//1 line, but scintilla refers to lines from 0
			m_lineInfo[m_sci->GetLineCount()-1] = info;
		} else {
			// do the fallback
			//set this line with the previous project
			int lineno = m_sci->GetLineCount()-1;
			std::map<int, LineInfo>::iterator iter = m_lineInfo.find(lineno-1);
			if (iter != m_lineInfo.end()) {
				m_lineInfo[lineno] = iter->second;
			}
		}

	} else {
		//set this line with the previous project
		int lineno = m_sci->GetLineCount()-1;
		std::map<int, LineInfo>::iterator iter = m_lineInfo.find(lineno-1);
		if (iter != m_lineInfo.end()) {
			m_lineInfo[lineno] = iter->second;
		}
	}

	OutputTabWindow::AppendText(text);
}

void BuildTab::OnMouseDClick(wxScintillaEvent &event)
{
	long pos = event.GetPosition();
	int line = m_sci->LineFromPosition(pos);
	wxString lineText = m_sci->GetLine(line);

	//remove selection
	m_sci->SetSelectionStart(pos);
	m_sci->SetSelectionEnd(pos);

	lineText.Replace(wxT("\\"), wxT("/"));
	OnBuildWindowDClick(lineText, line);
}

CompilerPtr BuildTab::GetCompilerByLine(int lineClicked)
{
	//lineClicked is zero based.
	//Get the project name that we are currently compiling:
	LineInfo info;
	wxString compilerType(wxEmptyString);

	std::map<int, LineInfo>::iterator iter = m_lineInfo.find(lineClicked);
	if (iter != m_lineInfo.end()) {
		info = iter->second;

		//get the project
		ProjectPtr proj = ManagerST::Get()->GetProject(info.project);
		if (proj) {
			ProjectSettingsPtr settings = proj->GetSettings();
			if (settings) {
				BuildConfigPtr bldConf = settings->GetBuildConfiguration(info.configuration);
				if (bldConf) {
					compilerType = bldConf->GetCompilerType();
				} else {
					//try to get the first build configuration
					ProjectSettingsCookie cookie;
					bldConf = settings->GetFirstBuildConfiguration(cookie);
					if (bldConf) {
						compilerType = bldConf->GetCompilerType();
					}
				}
			}
		}
	}

	//get the selected compiler for the current line that was DClicked
	//find the project selected build configuration for the workspace selected
	//configuration
	return BuildSettingsConfigST::Get()->GetCompiler(compilerType);
}

bool BuildTab::OnBuildWindowDClick(const wxString &line, int lineClicked)
{
	wxString fileName, strLineNumber;
	bool match = false;

	//get the selected compiler for the current line that was DClicked
	//find the project selected build configuration for the workspace selected
	//configuration
	CompilerPtr cmp = GetCompilerByLine(lineClicked);
	if (!cmp) {
		return false;
	}

	long idx;
	RegexProcessor re(cmp->GetWarnPattern());
	cmp->GetWarnFileNameIndex().ToLong(&idx);
	if (re.GetGroup(line, idx, fileName)) {
		//we found the file name, get the line number
		cmp->GetWarnLineNumberIndex().ToLong(&idx);
		re.GetGroup(line, idx, strLineNumber);
		match = true;
	}

	//try to match warning pattern
	if (!match) {
		//try to match an error pattern to the line
		RegexProcessor re(cmp->GetErrPattern());
		cmp->GetErrFileNameIndex().ToLong(&idx);
		if (re.GetGroup(line, idx, fileName)) {
			//we found the file name, get the line number
			cmp->GetErrLineNumberIndex().ToLong(&idx);
			re.GetGroup(line, idx, strLineNumber);
			match = true;
		}
	} else {
		//match was of a warning,
		//incase of the user is not interesting in warnings, skip it
		if (m_skipWarnings) {
			match = false;
		}
	}

	if (match) {
		long lineNumber = -1;
		strLineNumber.ToLong(&lineNumber);

		//do an educated guess for the reason why this failed
		wxFileName fn(fileName);

		Manager *mgr = ManagerST::Get();
		wxArrayString files;
		bool fileOpened(false);

		//try to open the file in context of the project
		wxString project_name = ProjectFromLine(lineClicked);
		if (project_name.IsEmpty() == false) {
			wxArrayString project_files;
			mgr->GetProjectFiles(project_name, project_files);
			fileOpened = DoTryOpenFile(project_files, fn, lineNumber, lineClicked);
		}


		mgr->GetWorkspaceFiles(files);
		
		// Ok no success in the project area... wider the search to workspace level
		if ( !fileOpened ) {
			fileOpened = DoTryOpenFile(files, fn, lineNumber, lineClicked);
		}

		if ( !fileOpened ) {
			// try to open the file as is
			// we have a match
			mgr->OpenFile(fn.GetFullPath(), wxEmptyString, (int)lineNumber-1);
			if (lineClicked != wxNOT_FOUND || m_nextBuildError_lastLine != wxNOT_FOUND) {
				if (lineClicked != wxNOT_FOUND) {
					
					// the call came from mouse double click, update
					// the m_nextBuildError_lastLine member
					m_nextBuildError_lastLine = lineClicked;
				}

				m_sci->MarkerDeleteAll(0x7);
				m_sci->MarkerAdd(m_nextBuildError_lastLine, 0x7);
				m_sci->GotoLine(m_nextBuildError_lastLine);
				m_sci->EnsureVisible(m_nextBuildError_lastLine);
			}
		}
	}

	return match;
}

void BuildTab::OnNextBuildError(wxCommandEvent &event)
{
	wxUnusedVar(event);
	// get handle to the build window

	if ( m_sci->GetLineCount() <= 0 ) {
		return;
	}

	// iterate through the lines, keeping the last known one
	// and pass the text on to OnBuildWindowDClick
	int startAt;
	if ((m_nextBuildError_lastLine < 0) ||
	        (m_nextBuildError_lastLine >= m_sci->GetLineCount()))
		startAt = 0;
	else startAt = m_nextBuildError_lastLine+1;

	bool match(false);
	for (m_nextBuildError_lastLine = startAt; m_nextBuildError_lastLine < m_sci->GetLineCount(); 	++m_nextBuildError_lastLine) {
		wxString lineText = m_sci->GetLine(m_nextBuildError_lastLine);
		lineText.Replace(wxT("\\"), wxT("/"));
		if (OnBuildWindowDClick(lineText, m_nextBuildError_lastLine)) {
			match = true;
			break;
		}
	}

	//no match? try from top again
	if (!match && startAt > 0) {
		for (m_nextBuildError_lastLine = 0; m_nextBuildError_lastLine < startAt; 	++m_nextBuildError_lastLine) {
			wxString lineText = m_sci->GetLine(m_nextBuildError_lastLine);
			lineText.Replace(wxT("\\"), wxT("/"));
			if (OnBuildWindowDClick(lineText, m_nextBuildError_lastLine)) {
				match = true;
				break;
			}
		}
	}
}

void BuildTab::Clear()
{
	OutputTabWindow::Clear();
	Initialize();
	m_lineInfo.clear();
	m_nextBuildError_lastLine = wxNOT_FOUND;
}

void BuildTab::OnBuildEnded()
{
}

void BuildTab::ReloadSettings()
{
	Initialize();
}

int BuildTab::LineFromPosition(int pos)
{
	return m_sci->LineFromPosition(pos);
}

void BuildTab::OnCompilerColours(wxCommandEvent &e)
{
	wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, XRCID("advance_settings"));
	event.SetEventObject(this);
	event.SetInt(1);
	Frame::Get()->ProcessEvent(event);
}

void BuildTab::OnHotspotClicked(wxScintillaEvent &event)
{
	OnMouseDClick(event);
}

int BuildTab::ColourGccLine(int startLine, const char *line, size_t &fileNameStart, size_t &fileNameLen)
{
	BuildTab *bt = Frame::Get()->GetOutputPane()->GetBuildTab();

	wxString fileName, strLineNumber;
	long idx;

	// search for the compiler definition for the current line
	int lineNumber = bt->LineFromPosition(startLine);
	CompilerPtr cmp = bt->GetCompilerByLine(lineNumber);
	if (!cmp) {
		return 0;
	}

	wxString lineText = _U(line);
	//check if this is a 'Building:' line
	if (lineText.StartsWith(wxT("Building:"))) {
		return wxSCI_LEX_GCC_BUILDING;
	}
	
	static wxRegEx reSummary(wxT("[0-9]+ errors, [0-9]+ warnings"));
	if(reSummary.IsValid() && reSummary.Matches(lineText)){
		return wxSCI_LEX_GCC_BUILDING;
	}
	
	wxRegEx re(cmp->GetWarnPattern());
	if (re.IsValid()) {
		cmp->GetWarnFileNameIndex().ToLong(&idx);
		if (re.Matches(lineText)) {
			re.GetMatch(&fileNameStart, &fileNameLen, 0);
			return wxSCI_LEX_GCC_WARNING;
		}
	}

	wxRegEx ere(cmp->GetErrPattern());
	if (re.IsValid()) {
		cmp->GetErrFileNameIndex().ToLong(&idx);
		if (ere.Matches(lineText)) {
			ere.GetMatch(&fileNameStart, &fileNameLen, 0);
			return wxSCI_LEX_GCC_ERROR;
		}
	}

	return wxSCI_LEX_GCC_DEFAULT;
}

wxString BuildTab::ProjectFromLine(int line)
{
	//return the project name
	//from given line number
	std::map<int, LineInfo>::iterator iter = m_lineInfo.find(line);
	if (iter == m_lineInfo.end()) {
		return wxEmptyString;
	}
	return iter->second.project;
}

int BuildTab::GetErrorCount()
{
	int errorCount(0);
	wxString txt = m_sci->GetText();
	for (int i=0; i<m_sci->GetLineCount(); i++) {
		const wxCharBuffer line = _C(m_sci->GetLine(i));
		size_t dummy;
		int res = ColourGccLine(m_sci->PositionFromLine(i), line.data(), dummy, dummy);
		if (res == wxSCI_LEX_GCC_ERROR) {
			errorCount++;
		}
	}
	return errorCount;
}

int BuildTab::GetWarningCount()
{
	int warnCount(0);
	wxString txt = m_sci->GetText();
	for (int i=0; i<m_sci->GetLineCount(); i++) {
		const wxCharBuffer line = _C(m_sci->GetLine(i));
		size_t dummy;
		int res = ColourGccLine(m_sci->PositionFromLine(i), line.data(), dummy, dummy);
		if (res == wxSCI_LEX_GCC_WARNING) {
			warnCount++;
		}
	}
	return warnCount;
}

bool BuildTab::DoTryOpenFile(const wxArrayString& files, const wxFileName &fn, int lineNumber, int lineClicked)
{
	// Iterate over the files twice:
	// first, try to full path
	// if the first iteration failes, iterate the files again
	// and compare full name only
	if(fn.IsAbsolute() && !fn.GetFullPath().Contains(wxT(".."))){
		return DoOpenFile(fn, lineNumber, lineClicked);
	}
	
/*	
	// try to convert it to absolute path
	wxFileName f1(fn);
	if(f1.MakeAbsolute() && !f1.GetFullPath().Contains(wxT(".."))){
		return DoOpenFile(f1, lineNumber, lineClicked);
	}
i*/	
	for (size_t i=0; i< files.GetCount(); i++) {
		wxFileName tmpFileName( files.Item(i) );
		if (tmpFileName.GetFullPath() == fn.GetFullPath()) {
			wxFileName tt(tmpFileName);
			if(tt.MakeAbsolute()){
				return DoOpenFile(tt, lineNumber, lineClicked);
			}else{
				return DoOpenFile(tmpFileName, lineNumber, lineClicked);
			}
		}
	}
	
	std::vector<wxFileName> matches;
	
	for (size_t i=0; i< files.GetCount(); i++) {
		wxFileName tmpFileName( files.Item(i) );
		if (tmpFileName.GetFullName() == fn.GetFullName()) {
			matches.push_back(tmpFileName);
		}
	}
	
	wxString lastDir;
	wxArrayString dirs = fn.GetDirs();
	if(dirs.GetCount() > 0){
		lastDir = dirs.Last();
	}
	
	if(matches.size() == 1){
		wxFileName tt(matches.at(0));
		if(tt.MakeAbsolute()){
			return DoOpenFile(tt, lineNumber, lineClicked);
		}else{
			return DoOpenFile(matches.at(0), lineNumber, lineClicked);
		}
		
	} else if(matches.size() > 1){
		// take the best match
		std::vector<wxFileName> betterMatches;
		for(size_t i=0; i<matches.size(); i++){
			
			wxFileName filename(matches.at(i));
			wxArrayString tmpdirs = filename.GetDirs();
			if(tmpdirs.GetCount() > 0){
				if(tmpdirs.Last() == lastDir){
					betterMatches.push_back(filename);
				}
			}		
		}
		
		if(betterMatches.size() == 1){
			wxFileName tt(betterMatches.at(0));
			if(tt.MakeAbsolute()){
				return DoOpenFile(tt, lineNumber, lineClicked);
			}else{
				return DoOpenFile(betterMatches.at(0), lineNumber, lineClicked);
			}
		} else {
			// open the first match
			wxFileName tt(matches.at(0));
			if(tt.MakeAbsolute()){
				return DoOpenFile(tt, lineNumber, lineClicked);
			}else{
				return DoOpenFile(matches.at(0), lineNumber, lineClicked);
			}
		}
	}
	return false;
}

bool BuildTab::DoOpenFile(const wxFileName& fn, int lineNumber, int lineClicked)
{
	//we got a match
	ManagerST::Get()->OpenFile(fn.GetFullPath(), wxEmptyString, (int)lineNumber-1);
	if (lineClicked != wxNOT_FOUND || m_nextBuildError_lastLine != wxNOT_FOUND) {
		if (lineClicked != wxNOT_FOUND) {
			//the call came from mouse double click, update
			//the m_nextBuildError_lastLine member
			m_nextBuildError_lastLine = lineClicked;
		}

		m_sci->MarkerDeleteAll(0x7);
		m_sci->MarkerAdd(m_nextBuildError_lastLine, 0x7);
		m_sci->GotoLine(m_nextBuildError_lastLine);
		m_sci->EnsureVisible(m_nextBuildError_lastLine);
	}
	return true;
}