Converted the array of breakpoints to a QPtrVector.
[kdbg.git] / kdbg / mainwndbase.cpp
blobb7c540ff8f097b48879bd39a00b173fe84132acd
1 // $Id$
3 // Copyright by Johannes Sixt
4 // This file is under GPL, the GNU General Public Licence
6 #include <kapp.h>
7 #include <klocale.h> /* i18n */
8 #include <kconfig.h>
9 #include <kmessagebox.h>
10 #include <kiconloader.h>
11 #include <kstatusbar.h>
12 #include <ktoolbar.h>
13 #include <kfiledialog.h>
14 #include <qpainter.h>
15 #include <qtabdialog.h>
16 #include <qfile.h>
17 #include "mainwndbase.h"
18 #include "debugger.h"
19 #include "gdbdriver.h"
20 #include "xsldbgdriver.h"
21 #include "prefdebugger.h"
22 #include "prefmisc.h"
23 #include "ttywnd.h"
24 #include "commandids.h"
25 #include "valarray.h"
26 #ifdef HAVE_CONFIG
27 #include "config.h"
28 #endif
29 #include "mydebug.h"
30 #ifdef HAVE_SYS_STAT_H
31 #include <sys/stat.h> /* mknod(2) */
32 #endif
33 #ifdef HAVE_FCNTL_H
34 #include <fcntl.h> /* open(2) */
35 #endif
36 #ifdef HAVE_UNISTD_H
37 #include <unistd.h> /* getpid, unlink etc. */
38 #endif
40 #define MAX_RECENT_FILES 4
42 WatchWindow::WatchWindow(QWidget* parent, const char* name, WFlags f) :
43 QWidget(parent, name, f),
44 m_watchEdit(this, "watch_edit"),
45 m_watchAdd(i18n(" Add "), this, "watch_add"),
46 m_watchDelete(i18n(" Del "), this, "watch_delete"),
47 m_watchVariables(this, "watch_variables"),
48 m_watchV(this, 0),
49 m_watchH(0)
51 // setup the layout
52 m_watchAdd.setMinimumSize(m_watchAdd.sizeHint());
53 m_watchDelete.setMinimumSize(m_watchDelete.sizeHint());
54 m_watchV.addLayout(&m_watchH, 0);
55 m_watchV.addWidget(&m_watchVariables, 10);
56 m_watchH.addWidget(&m_watchEdit, 10);
57 m_watchH.addWidget(&m_watchAdd, 0);
58 m_watchH.addWidget(&m_watchDelete, 0);
60 connect(&m_watchEdit, SIGNAL(returnPressed()), SIGNAL(addWatch()));
61 connect(&m_watchAdd, SIGNAL(clicked()), SIGNAL(addWatch()));
62 connect(&m_watchDelete, SIGNAL(clicked()), SIGNAL(deleteWatch()));
63 connect(&m_watchVariables, SIGNAL(highlighted(int)), SLOT(slotWatchHighlighted(int)));
65 m_watchVariables.setMoveCurrentToSibling(true);
66 m_watchVariables.installEventFilter(this);
69 WatchWindow::~WatchWindow()
73 bool WatchWindow::eventFilter(QObject*, QEvent* ev)
75 if (ev->type() == QEvent::KeyPress)
77 QKeyEvent* kev = static_cast<QKeyEvent*>(ev);
78 if (kev->key() == Key_Delete) {
79 emit deleteWatch();
80 return true;
83 return false;
87 // place the text of the hightlighted watch expr in the edit field
88 void WatchWindow::slotWatchHighlighted(int idx)
90 QString text = m_watchVariables.exprStringAt(idx);
91 m_watchEdit.setText(text);
95 static void splitCmdStr(const QString& cmd, ValArray<QString>& parts)
97 QString str = cmd.simplifyWhiteSpace();
98 int start = 0;
99 int end;
100 while ((end = str.find(' ', start)) >= 0) {
101 parts.append(str.mid(start, end-start));
102 start = end+1;
104 parts.append(str.mid(start, str.length()-start));
108 const char defaultTermCmdStr[] = "xterm -name kdbgio -title %T -e sh -c %C";
109 const char defaultSourceFilter[] = "*.c *.cc *.cpp *.c++ *.C *.CC";
110 const char defaultHeaderFilter[] = "*.h *.hh *.hpp *.h++";
113 DebuggerMainWndBase::DebuggerMainWndBase() :
114 m_animationCounter(0),
115 m_outputTermCmdStr(defaultTermCmdStr),
116 m_outputTermProc(0),
117 m_ttyLevel(-1), /* no tty yet */
118 #ifdef GDB_TRANSCRIPT
119 m_transcriptFile(GDB_TRANSCRIPT),
120 #endif
121 m_popForeground(false),
122 m_backTimeout(1000),
123 m_tabWidth(0),
124 m_sourceFilter(defaultSourceFilter),
125 m_headerFilter(defaultHeaderFilter),
126 m_debugger(0)
128 m_statusActive = i18n("active");
131 DebuggerMainWndBase::~DebuggerMainWndBase()
133 delete m_debugger;
135 // if the output window is open, close it
136 if (m_outputTermProc != 0) {
137 m_outputTermProc->disconnect(); /* ignore signals */
138 m_outputTermProc->kill();
139 shutdownTermWindow();
143 void DebuggerMainWndBase::setupDebugger(QWidget* parent,
144 ExprWnd* localVars,
145 ExprWnd* watchVars,
146 QListBox* backtrace)
148 m_debugger = new KDebugger(parent, localVars, watchVars, backtrace);
150 QObject::connect(m_debugger, SIGNAL(updateStatusMessage()),
151 parent, SLOT(slotNewStatusMsg()));
152 QObject::connect(m_debugger, SIGNAL(updateUI()),
153 parent, SLOT(updateUI()));
155 QObject::connect(m_debugger, SIGNAL(lineItemsChanged()),
156 parent, SLOT(updateLineItems()));
158 QObject::connect(m_debugger, SIGNAL(animationTimeout()),
159 parent, SLOT(slotAnimationTimeout()));
160 QObject::connect(m_debugger, SIGNAL(debuggerStarting()),
161 parent, SLOT(slotDebuggerStarting()));
165 void DebuggerMainWndBase::setCoreFile(const QString& corefile)
167 assert(m_debugger != 0);
168 m_debugger->useCoreFile(corefile, true);
171 void DebuggerMainWndBase::setRemoteDevice(const QString& remoteDevice)
173 if (m_debugger != 0) {
174 m_debugger->setRemoteDevice(remoteDevice);
178 void DebuggerMainWndBase::setTranscript(const char* name)
180 m_transcriptFile = name;
181 if (m_debugger != 0 && m_debugger->driver() != 0)
182 m_debugger->driver()->setLogFileName(m_transcriptFile);
185 const char OutputWindowGroup[] = "OutputWindow";
186 const char TermCmdStr[] = "TermCmdStr";
187 const char KeepScript[] = "KeepScript";
188 const char DebuggerGroup[] = "Debugger";
189 const char DebuggerCmdStr[] = "DebuggerCmdStr";
190 const char PreferencesGroup[] = "Preferences";
191 const char PopForeground[] = "PopForeground";
192 const char BackTimeout[] = "BackTimeout";
193 const char TabWidth[] = "TabWidth";
194 const char FilesGroup[] = "Files";
195 const char SourceFileFilter[] = "SourceFileFilter";
196 const char HeaderFileFilter[] = "HeaderFileFilter";
197 const char GeneralGroup[] = "General";
199 void DebuggerMainWndBase::saveSettings(KConfig* config)
201 if (m_debugger != 0) {
202 m_debugger->saveSettings(config);
205 KConfigGroupSaver g(config, OutputWindowGroup);
206 config->writeEntry(TermCmdStr, m_outputTermCmdStr);
208 config->setGroup(DebuggerGroup);
209 config->writeEntry(DebuggerCmdStr, m_debuggerCmdStr);
211 config->setGroup(PreferencesGroup);
212 config->writeEntry(PopForeground, m_popForeground);
213 config->writeEntry(BackTimeout, m_backTimeout);
214 config->writeEntry(TabWidth, m_tabWidth);
215 config->writeEntry(SourceFileFilter, m_sourceFilter);
216 config->writeEntry(HeaderFileFilter, m_headerFilter);
219 void DebuggerMainWndBase::restoreSettings(KConfig* config)
221 if (m_debugger != 0) {
222 m_debugger->restoreSettings(config);
225 KConfigGroupSaver g(config, OutputWindowGroup);
227 * For debugging and emergency purposes, let the config file override
228 * the shell script that is used to keep the output window open. This
229 * string must have EXACTLY 1 %s sequence in it.
231 setTerminalCmd(config->readEntry(TermCmdStr, defaultTermCmdStr));
232 m_outputTermKeepScript = config->readEntry(KeepScript);
234 config->setGroup(DebuggerGroup);
235 setDebuggerCmdStr(config->readEntry(DebuggerCmdStr));
237 config->setGroup(PreferencesGroup);
238 m_popForeground = config->readBoolEntry(PopForeground, false);
239 m_backTimeout = config->readNumEntry(BackTimeout, 1000);
240 m_tabWidth = config->readNumEntry(TabWidth, 0);
241 m_sourceFilter = config->readEntry(SourceFileFilter, m_sourceFilter);
242 m_headerFilter = config->readEntry(HeaderFileFilter, m_headerFilter);
245 bool DebuggerMainWndBase::debugProgram(const QString& executable,
246 QCString lang, QWidget* parent)
248 assert(m_debugger != 0);
250 TRACE(QString().sprintf("trying language '%s'...", lang.data()));
251 DebuggerDriver* driver = driverFromLang(lang);
253 if (driver == 0)
255 // see if there is a language in the per-program config file
256 QString configName = m_debugger->getConfigForExe(executable);
257 if (QFile::exists(configName))
259 KSimpleConfig c(configName, true); // read-only
260 c.setGroup(GeneralGroup);
262 // Using "GDB" as default here is for backwards compatibility:
263 // The config file exists but doesn't have an entry,
264 // so it must have been created by an old version of KDbg
265 // that had only the GDB driver.
266 lang = c.readEntry(KDebugger::DriverNameEntry, "GDB").latin1();
268 TRACE(QString().sprintf("...bad, trying config driver %s...",
269 lang.data()));
270 driver = driverFromLang(lang);
274 if (driver == 0)
276 QCString name = driverNameFromFile(executable);
278 TRACE(QString().sprintf("...no luck, trying %s derived"
279 " from file contents", name.data()));
280 driver = driverFromLang(name);
282 if (driver == 0)
284 // oops
285 QString msg = i18n("Don't know how to debug language `%1'");
286 KMessageBox::sorry(parent, msg.arg(lang));
287 return false;
290 driver->setLogFileName(m_transcriptFile);
292 bool success = m_debugger->debugProgram(executable, driver);
294 if (!success)
296 delete driver;
298 QString msg = i18n("Could not start the debugger process.\n"
299 "Please shut down KDbg and resolve the problem.");
300 KMessageBox::sorry(parent, msg);
303 return success;
306 // derive driver from language
307 DebuggerDriver* DebuggerMainWndBase::driverFromLang(QCString lang)
309 // lang is needed in all lowercase
310 lang = lang.lower();
312 // The following table relates languages and debugger drivers
313 static const struct L {
314 const char* shortest; // abbreviated to this is still unique
315 const char* full; // full name of language
316 int driver;
317 } langs[] = {
318 { "c", "c++", 1 },
319 { "f", "fortran", 1 },
320 { "p", "python", 3 },
321 { "x", "xslt", 2 },
322 // the following are actually driver names
323 { "gdb", "gdb", 1 },
324 { "xsldbg", "xsldbg", 2 },
326 const int N = sizeof(langs)/sizeof(langs[0]);
328 // lookup the language name
329 int driverID = 0;
330 for (int i = 0; i < N; i++)
332 const L& l = langs[i];
334 // shortest must match
335 if (strncmp(l.shortest, lang, strlen(l.shortest)) != 0)
336 continue;
338 // lang must not be longer than the full name, and it must match
339 if (lang.length() <= strlen(l.full) &&
340 strncmp(l.full, lang, lang.length()) == 0)
342 driverID = l.driver;
343 break;
346 DebuggerDriver* driver = 0;
347 switch (driverID) {
348 case 1:
350 GdbDriver* gdb = new GdbDriver;
351 gdb->setDefaultInvocation(m_debuggerCmdStr);
352 driver = gdb;
354 break;
355 case 2:
356 driver = new XsldbgDriver;
357 break;
358 default:
359 // unknown language
360 break;
362 return driver;
366 * Try to guess the language to use from the contents of the file.
368 QCString DebuggerMainWndBase::driverNameFromFile(const QString& exe)
370 /* Inprecise but simple test to see if file is in XSLT language */
371 if (exe.right(4).lower() == ".xsl")
372 return "XSLT";
374 return "GDB";
377 // helper that gets a file name (it only differs in the caption of the dialog)
378 QString DebuggerMainWndBase::myGetFileName(QString caption,
379 QString dir, QString filter,
380 QWidget* parent)
382 QString filename;
383 KFileDialog dlg(dir, filter, parent, "filedialog", true);
385 dlg.setCaption(caption);
387 if (dlg.exec() == QDialog::Accepted)
388 filename = dlg.selectedFile();
390 return filename;
393 void DebuggerMainWndBase::initAnimation(KToolBar* toolbar)
395 QPixmap pixmap = BarIcon("kde1");
396 int numPix = 6;
398 toolbar->insertButton(pixmap, ID_STATUS_BUSY);
399 toolbar->alignItemRight(ID_STATUS_BUSY, true);
401 // Load animated logo
402 m_animation.setAutoDelete(true);
403 QString n;
404 for (int i = 1; i <= numPix; i++) {
405 n.sprintf("kde%d", i);
406 QPixmap* p = new QPixmap(BarIcon(n));
407 if (!p->isNull()) {
408 m_animation.append(p);
409 } else {
410 delete p;
413 // safeguard: if we did not find a single icon, add a dummy
414 if (m_animation.count() == 0) {
415 QPixmap* pix = new QPixmap(2,2);
416 QPainter p(pix);
417 p.fillRect(0,0,2,2,QBrush(Qt::white));
418 m_animation.append(pix);
422 void DebuggerMainWndBase::nextAnimationFrame(KToolBar* toolbar)
424 assert(m_animation.count() > 0); /* must have been initialized */
425 m_animationCounter++;
426 if (m_animationCounter == m_animation.count())
427 m_animationCounter = 0;
428 toolbar->setButtonPixmap(ID_STATUS_BUSY,
429 *m_animation.at(m_animationCounter));
432 void DebuggerMainWndBase::newStatusMsg(KStatusBar* statusbar)
434 QString msg = m_debugger->statusMessage();
435 statusbar->changeItem(msg, ID_STATUS_MSG);
438 void DebuggerMainWndBase::doGlobalOptions(QWidget* parent)
440 QTabDialog dlg(parent, "global_options", true);
441 QString title = kapp->caption();
442 title += i18n(": Global options");
443 dlg.setCaption(title);
444 dlg.setCancelButton(i18n("Cancel"));
445 dlg.setOKButton(i18n("OK"));
447 PrefDebugger prefDebugger(&dlg);
448 prefDebugger.setDebuggerCmd(m_debuggerCmdStr.isEmpty() ?
449 GdbDriver::defaultGdb() : m_debuggerCmdStr);
450 prefDebugger.setTerminal(m_outputTermCmdStr);
452 PrefMisc prefMisc(&dlg);
453 prefMisc.setPopIntoForeground(m_popForeground);
454 prefMisc.setBackTimeout(m_backTimeout);
455 prefMisc.setTabWidth(m_tabWidth);
456 prefMisc.setSourceFilter(m_sourceFilter);
457 prefMisc.setHeaderFilter(m_headerFilter);
459 dlg.addTab(&prefDebugger, i18n("&Debugger"));
460 dlg.addTab(&prefMisc, i18n("&Miscellaneous"));
461 if (dlg.exec() == QDialog::Accepted)
463 setDebuggerCmdStr(prefDebugger.debuggerCmd());
464 setTerminalCmd(prefDebugger.terminal());
465 m_popForeground = prefMisc.popIntoForeground();
466 m_backTimeout = prefMisc.backTimeout();
467 m_tabWidth = prefMisc.tabWidth();
468 m_sourceFilter = prefMisc.sourceFilter();
469 if (m_sourceFilter.isEmpty())
470 m_sourceFilter = defaultSourceFilter;
471 m_headerFilter = prefMisc.headerFilter();
472 if (m_headerFilter.isEmpty())
473 m_headerFilter = defaultHeaderFilter;
477 const char fifoNameBase[] = "/tmp/kdbgttywin%05d";
480 * We use the scope operator :: in this function, so that we don't
481 * accidentally use the wrong close() function (I've been bitten ;-),
482 * outch!) (We use it for all the libc functions, to be consistent...)
484 QString DebuggerMainWndBase::createOutputWindow()
486 // create a name for a fifo
487 QString fifoName;
488 fifoName.sprintf(fifoNameBase, ::getpid());
490 // create a fifo that will pass in the tty name
491 ::unlink(fifoName); /* remove remnants */
492 #ifdef HAVE_MKFIFO
493 if (::mkfifo(fifoName, S_IRUSR|S_IWUSR) < 0) {
494 // failed
495 TRACE("mkfifo " + fifoName + " failed");
496 return QString();
498 #else
499 if (::mknod(fifoName, S_IFIFO | S_IRUSR|S_IWUSR, 0) < 0) {
500 // failed
501 TRACE("mknod " + fifoName + " failed");
502 return QString();
504 #endif
506 m_outputTermProc = new KProcess;
510 * Spawn an xterm that in turn runs a shell script that passes us
511 * back the terminal name and then only sits and waits.
513 static const char shellScriptFmt[] =
514 "tty>%s;"
515 "trap \"\" INT QUIT TSTP;" /* ignore various signals */
516 "exec<&-;exec>&-;" /* close stdin and stdout */
517 "while :;do sleep 3600;done";
518 // let config file override this script
519 const char* fmt = shellScriptFmt;
520 if (m_outputTermKeepScript.length() != 0) {
521 fmt = m_outputTermKeepScript.data();
524 QString shellScript;
525 shellScript.sprintf(fmt, fifoName.data());
526 TRACE("output window script is " + shellScript);
528 QString title = kapp->caption();
529 title += i18n(": Program output");
531 // parse the command line specified in the preferences
532 ValArray<QString> cmdParts;
533 splitCmdStr(m_outputTermCmdStr, cmdParts);
536 * Build the argv array. Thereby substitute special sequences:
538 struct {
539 char seq[4];
540 QString replace;
541 } substitute[] = {
542 { "%T", title },
543 { "%C", shellScript }
546 for (int i = 0; i < cmdParts.size(); i++) {
547 QString& str = cmdParts[i];
548 for (int j = sizeof(substitute)/sizeof(substitute[0])-1; j >= 0; j--) {
549 int pos = str.find(substitute[j].seq);
550 if (pos >= 0) {
551 str.replace(pos, 2, substitute[j].replace);
552 break; /* substitute only one sequence */
555 *m_outputTermProc << str;
560 if (m_outputTermProc->start())
562 // read the ttyname from the fifo
563 int f = ::open(fifoName, O_RDONLY);
564 if (f < 0) {
565 // error
566 ::unlink(fifoName);
567 return QString();
570 char ttyname[50];
571 int n = ::read(f, ttyname, sizeof(ttyname)-sizeof(char)); /* leave space for '\0' */
573 ::close(f);
574 ::unlink(fifoName);
576 if (n < 0) {
577 // error
578 return QString();
581 // remove whitespace
582 ttyname[n] = '\0';
583 QString tty = QString(ttyname).stripWhiteSpace();
584 TRACE("tty=" + tty);
585 return tty;
587 else
589 // error, could not start xterm
590 TRACE("fork failed for fifo " + fifoName);
591 ::unlink(fifoName);
592 shutdownTermWindow();
593 return QString();
597 void DebuggerMainWndBase::shutdownTermWindow()
599 delete m_outputTermProc;
600 m_outputTermProc = 0;
603 void DebuggerMainWndBase::setTerminalCmd(const QString& cmd)
605 m_outputTermCmdStr = cmd;
606 // revert to default if empty
607 if (m_outputTermCmdStr.isEmpty()) {
608 m_outputTermCmdStr = defaultTermCmdStr;
612 void DebuggerMainWndBase::slotDebuggerStarting()
614 if (m_debugger == 0) /* paranoia check */
615 return;
617 if (m_ttyLevel == m_debugger->ttyLevel())
620 else
622 // shut down terminal emulations we will not need
623 switch (m_ttyLevel) {
624 case KDebugger::ttySimpleOutputOnly:
625 ttyWindow()->deactivate();
626 break;
627 case KDebugger::ttyFull:
628 if (m_outputTermProc != 0) {
629 m_outputTermProc->kill();
630 // will be deleted in slot
632 break;
633 default: break;
636 m_ttyLevel = m_debugger->ttyLevel();
638 QString ttyName;
639 switch (m_ttyLevel) {
640 case KDebugger::ttySimpleOutputOnly:
641 ttyName = ttyWindow()->activate();
642 break;
643 case KDebugger::ttyFull:
644 if (m_outputTermProc == 0) {
645 // create an output window
646 ttyName = createOutputWindow();
647 TRACE(ttyName.isEmpty() ?
648 "createOuputWindow failed" : "successfully created output window");
650 break;
651 default: break;
654 m_debugger->setTerminal(ttyName);
658 void DebuggerMainWndBase::setDebuggerCmdStr(const QString& cmd)
660 m_debuggerCmdStr = cmd;
661 // make empty if it is the default
662 if (m_debuggerCmdStr == GdbDriver::defaultGdb()) {
663 m_debuggerCmdStr = QString();
668 #include "mainwndbase.moc"