Don't start with a tiny window when started for the first time.
[kdbg.git] / kdbg / mainwndbase.cpp
blobac3613840f7b302652c91365e9d143e7138e2feb
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 <kstatusbar.h>
11 #include <kfiledialog.h>
12 #include <qtabdialog.h>
13 #include <qfile.h>
14 #include "mainwndbase.h"
15 #include "debugger.h"
16 #include "gdbdriver.h"
17 #include "xsldbgdriver.h"
18 #include "prefdebugger.h"
19 #include "prefmisc.h"
20 #include "ttywnd.h"
21 #include "commandids.h"
22 #include "valarray.h"
23 #ifdef HAVE_CONFIG
24 #include "config.h"
25 #endif
26 #include "mydebug.h"
27 #ifdef HAVE_SYS_STAT_H
28 #include <sys/stat.h> /* mknod(2) */
29 #endif
30 #ifdef HAVE_FCNTL_H
31 #include <fcntl.h> /* open(2) */
32 #endif
33 #ifdef HAVE_UNISTD_H
34 #include <unistd.h> /* getpid, unlink etc. */
35 #endif
37 #define MAX_RECENT_FILES 4
39 WatchWindow::WatchWindow(QWidget* parent, const char* name, WFlags f) :
40 QWidget(parent, name, f),
41 m_watchEdit(this, "watch_edit"),
42 m_watchAdd(i18n(" Add "), this, "watch_add"),
43 m_watchDelete(i18n(" Del "), this, "watch_delete"),
44 m_watchVariables(this, "watch_variables"),
45 m_watchV(this, 0),
46 m_watchH(0)
48 // setup the layout
49 m_watchAdd.setMinimumSize(m_watchAdd.sizeHint());
50 m_watchDelete.setMinimumSize(m_watchDelete.sizeHint());
51 m_watchV.addLayout(&m_watchH, 0);
52 m_watchV.addWidget(&m_watchVariables, 10);
53 m_watchH.addWidget(&m_watchEdit, 10);
54 m_watchH.addWidget(&m_watchAdd, 0);
55 m_watchH.addWidget(&m_watchDelete, 0);
57 connect(&m_watchEdit, SIGNAL(returnPressed()), SIGNAL(addWatch()));
58 connect(&m_watchAdd, SIGNAL(clicked()), SIGNAL(addWatch()));
59 connect(&m_watchDelete, SIGNAL(clicked()), SIGNAL(deleteWatch()));
60 connect(&m_watchVariables, SIGNAL(highlighted(int)), SLOT(slotWatchHighlighted(int)));
62 m_watchVariables.setMoveCurrentToSibling(true);
63 m_watchVariables.installEventFilter(this);
66 WatchWindow::~WatchWindow()
70 bool WatchWindow::eventFilter(QObject*, QEvent* ev)
72 if (ev->type() == QEvent::KeyPress)
74 QKeyEvent* kev = static_cast<QKeyEvent*>(ev);
75 if (kev->key() == Key_Delete) {
76 emit deleteWatch();
77 return true;
80 return false;
84 // place the text of the hightlighted watch expr in the edit field
85 void WatchWindow::slotWatchHighlighted(int idx)
87 QString text = m_watchVariables.exprStringAt(idx);
88 m_watchEdit.setText(text);
92 static void splitCmdStr(const QString& cmd, ValArray<QString>& parts)
94 QString str = cmd.simplifyWhiteSpace();
95 int start = 0;
96 int end;
97 while ((end = str.find(' ', start)) >= 0) {
98 parts.append(str.mid(start, end-start));
99 start = end+1;
101 parts.append(str.mid(start, str.length()-start));
105 const char defaultTermCmdStr[] = "xterm -name kdbgio -title %T -e sh -c %C";
106 const char defaultSourceFilter[] = "*.c *.cc *.cpp *.c++ *.C *.CC";
107 const char defaultHeaderFilter[] = "*.h *.hh *.hpp *.h++";
110 DebuggerMainWndBase::DebuggerMainWndBase() :
111 m_outputTermCmdStr(defaultTermCmdStr),
112 m_outputTermProc(0),
113 m_ttyLevel(-1), /* no tty yet */
114 #ifdef GDB_TRANSCRIPT
115 m_transcriptFile(GDB_TRANSCRIPT),
116 #endif
117 m_popForeground(false),
118 m_backTimeout(1000),
119 m_tabWidth(0),
120 m_sourceFilter(defaultSourceFilter),
121 m_headerFilter(defaultHeaderFilter),
122 m_debugger(0)
124 m_statusActive = i18n("active");
127 DebuggerMainWndBase::~DebuggerMainWndBase()
129 delete m_debugger;
131 // if the output window is open, close it
132 if (m_outputTermProc != 0) {
133 m_outputTermProc->disconnect(); /* ignore signals */
134 m_outputTermProc->kill();
135 shutdownTermWindow();
139 void DebuggerMainWndBase::setupDebugger(QWidget* parent,
140 ExprWnd* localVars,
141 ExprWnd* watchVars,
142 QListBox* backtrace)
144 m_debugger = new KDebugger(parent, localVars, watchVars, backtrace);
146 QObject::connect(m_debugger, SIGNAL(updateStatusMessage()),
147 parent, SLOT(slotNewStatusMsg()));
148 QObject::connect(m_debugger, SIGNAL(updateUI()),
149 parent, SLOT(updateUI()));
151 QObject::connect(m_debugger, SIGNAL(breakpointsChanged()),
152 parent, SLOT(updateLineItems()));
154 QObject::connect(m_debugger, SIGNAL(debuggerStarting()),
155 parent, SLOT(slotDebuggerStarting()));
159 void DebuggerMainWndBase::setCoreFile(const QString& corefile)
161 assert(m_debugger != 0);
162 m_debugger->useCoreFile(corefile, true);
165 void DebuggerMainWndBase::setRemoteDevice(const QString& remoteDevice)
167 if (m_debugger != 0) {
168 m_debugger->setRemoteDevice(remoteDevice);
172 void DebuggerMainWndBase::setTranscript(const char* name)
174 m_transcriptFile = name;
175 if (m_debugger != 0 && m_debugger->driver() != 0)
176 m_debugger->driver()->setLogFileName(m_transcriptFile);
179 const char OutputWindowGroup[] = "OutputWindow";
180 const char TermCmdStr[] = "TermCmdStr";
181 const char KeepScript[] = "KeepScript";
182 const char DebuggerGroup[] = "Debugger";
183 const char DebuggerCmdStr[] = "DebuggerCmdStr";
184 const char PreferencesGroup[] = "Preferences";
185 const char PopForeground[] = "PopForeground";
186 const char BackTimeout[] = "BackTimeout";
187 const char TabWidth[] = "TabWidth";
188 const char FilesGroup[] = "Files";
189 const char SourceFileFilter[] = "SourceFileFilter";
190 const char HeaderFileFilter[] = "HeaderFileFilter";
191 const char GeneralGroup[] = "General";
193 void DebuggerMainWndBase::saveSettings(KConfig* config)
195 if (m_debugger != 0) {
196 m_debugger->saveSettings(config);
199 KConfigGroupSaver g(config, OutputWindowGroup);
200 config->writeEntry(TermCmdStr, m_outputTermCmdStr);
202 config->setGroup(DebuggerGroup);
203 config->writeEntry(DebuggerCmdStr, m_debuggerCmdStr);
205 config->setGroup(PreferencesGroup);
206 config->writeEntry(PopForeground, m_popForeground);
207 config->writeEntry(BackTimeout, m_backTimeout);
208 config->writeEntry(TabWidth, m_tabWidth);
209 config->writeEntry(SourceFileFilter, m_sourceFilter);
210 config->writeEntry(HeaderFileFilter, m_headerFilter);
213 void DebuggerMainWndBase::restoreSettings(KConfig* config)
215 if (m_debugger != 0) {
216 m_debugger->restoreSettings(config);
219 KConfigGroupSaver g(config, OutputWindowGroup);
221 * For debugging and emergency purposes, let the config file override
222 * the shell script that is used to keep the output window open. This
223 * string must have EXACTLY 1 %s sequence in it.
225 setTerminalCmd(config->readEntry(TermCmdStr, defaultTermCmdStr));
226 m_outputTermKeepScript = config->readEntry(KeepScript);
228 config->setGroup(DebuggerGroup);
229 setDebuggerCmdStr(config->readEntry(DebuggerCmdStr));
231 config->setGroup(PreferencesGroup);
232 m_popForeground = config->readBoolEntry(PopForeground, false);
233 m_backTimeout = config->readNumEntry(BackTimeout, 1000);
234 m_tabWidth = config->readNumEntry(TabWidth, 0);
235 m_sourceFilter = config->readEntry(SourceFileFilter, m_sourceFilter);
236 m_headerFilter = config->readEntry(HeaderFileFilter, m_headerFilter);
239 void DebuggerMainWndBase::setAttachPid(const QString& pid)
241 assert(m_debugger != 0);
242 m_debugger->setAttachPid(pid);
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::newStatusMsg(KStatusBar* statusbar)
395 QString msg = m_debugger->statusMessage();
396 statusbar->changeItem(msg, ID_STATUS_MSG);
399 void DebuggerMainWndBase::doGlobalOptions(QWidget* parent)
401 QTabDialog dlg(parent, "global_options", true);
402 QString title = kapp->caption();
403 title += i18n(": Global options");
404 dlg.setCaption(title);
405 dlg.setCancelButton(i18n("Cancel"));
406 dlg.setOKButton(i18n("OK"));
408 PrefDebugger prefDebugger(&dlg);
409 prefDebugger.setDebuggerCmd(m_debuggerCmdStr.isEmpty() ?
410 GdbDriver::defaultGdb() : m_debuggerCmdStr);
411 prefDebugger.setTerminal(m_outputTermCmdStr);
413 PrefMisc prefMisc(&dlg);
414 prefMisc.setPopIntoForeground(m_popForeground);
415 prefMisc.setBackTimeout(m_backTimeout);
416 prefMisc.setTabWidth(m_tabWidth);
417 prefMisc.setSourceFilter(m_sourceFilter);
418 prefMisc.setHeaderFilter(m_headerFilter);
420 dlg.addTab(&prefDebugger, i18n("&Debugger"));
421 dlg.addTab(&prefMisc, i18n("&Miscellaneous"));
422 if (dlg.exec() == QDialog::Accepted)
424 setDebuggerCmdStr(prefDebugger.debuggerCmd());
425 setTerminalCmd(prefDebugger.terminal());
426 m_popForeground = prefMisc.popIntoForeground();
427 m_backTimeout = prefMisc.backTimeout();
428 m_tabWidth = prefMisc.tabWidth();
429 m_sourceFilter = prefMisc.sourceFilter();
430 if (m_sourceFilter.isEmpty())
431 m_sourceFilter = defaultSourceFilter;
432 m_headerFilter = prefMisc.headerFilter();
433 if (m_headerFilter.isEmpty())
434 m_headerFilter = defaultHeaderFilter;
438 const char fifoNameBase[] = "/tmp/kdbgttywin%05d";
441 * We use the scope operator :: in this function, so that we don't
442 * accidentally use the wrong close() function (I've been bitten ;-),
443 * outch!) (We use it for all the libc functions, to be consistent...)
445 QString DebuggerMainWndBase::createOutputWindow()
447 // create a name for a fifo
448 QString fifoName;
449 fifoName.sprintf(fifoNameBase, ::getpid());
451 // create a fifo that will pass in the tty name
452 ::unlink(fifoName); /* remove remnants */
453 #ifdef HAVE_MKFIFO
454 if (::mkfifo(fifoName, S_IRUSR|S_IWUSR) < 0) {
455 // failed
456 TRACE("mkfifo " + fifoName + " failed");
457 return QString();
459 #else
460 if (::mknod(fifoName, S_IFIFO | S_IRUSR|S_IWUSR, 0) < 0) {
461 // failed
462 TRACE("mknod " + fifoName + " failed");
463 return QString();
465 #endif
467 m_outputTermProc = new KProcess;
471 * Spawn an xterm that in turn runs a shell script that passes us
472 * back the terminal name and then only sits and waits.
474 static const char shellScriptFmt[] =
475 "tty>%s;"
476 "trap \"\" INT QUIT TSTP;" /* ignore various signals */
477 "exec<&-;exec>&-;" /* close stdin and stdout */
478 "while :;do sleep 3600;done";
479 // let config file override this script
480 const char* fmt = shellScriptFmt;
481 if (m_outputTermKeepScript.length() != 0) {
482 fmt = m_outputTermKeepScript.data();
485 QString shellScript;
486 shellScript.sprintf(fmt, fifoName.data());
487 TRACE("output window script is " + shellScript);
489 QString title = kapp->caption();
490 title += i18n(": Program output");
492 // parse the command line specified in the preferences
493 ValArray<QString> cmdParts;
494 splitCmdStr(m_outputTermCmdStr, cmdParts);
497 * Build the argv array. Thereby substitute special sequences:
499 struct {
500 char seq[4];
501 QString replace;
502 } substitute[] = {
503 { "%T", title },
504 { "%C", shellScript }
507 for (int i = 0; i < cmdParts.size(); i++) {
508 QString& str = cmdParts[i];
509 for (int j = sizeof(substitute)/sizeof(substitute[0])-1; j >= 0; j--) {
510 int pos = str.find(substitute[j].seq);
511 if (pos >= 0) {
512 str.replace(pos, 2, substitute[j].replace);
513 break; /* substitute only one sequence */
516 *m_outputTermProc << str;
521 if (m_outputTermProc->start())
523 // read the ttyname from the fifo
524 int f = ::open(fifoName, O_RDONLY);
525 if (f < 0) {
526 // error
527 ::unlink(fifoName);
528 return QString();
531 char ttyname[50];
532 int n = ::read(f, ttyname, sizeof(ttyname)-sizeof(char)); /* leave space for '\0' */
534 ::close(f);
535 ::unlink(fifoName);
537 if (n < 0) {
538 // error
539 return QString();
542 // remove whitespace
543 ttyname[n] = '\0';
544 QString tty = QString(ttyname).stripWhiteSpace();
545 TRACE("tty=" + tty);
546 return tty;
548 else
550 // error, could not start xterm
551 TRACE("fork failed for fifo " + fifoName);
552 ::unlink(fifoName);
553 shutdownTermWindow();
554 return QString();
558 void DebuggerMainWndBase::shutdownTermWindow()
560 delete m_outputTermProc;
561 m_outputTermProc = 0;
564 void DebuggerMainWndBase::setTerminalCmd(const QString& cmd)
566 m_outputTermCmdStr = cmd;
567 // revert to default if empty
568 if (m_outputTermCmdStr.isEmpty()) {
569 m_outputTermCmdStr = defaultTermCmdStr;
573 void DebuggerMainWndBase::slotDebuggerStarting()
575 if (m_debugger == 0) /* paranoia check */
576 return;
578 if (m_ttyLevel == m_debugger->ttyLevel())
581 else
583 // shut down terminal emulations we will not need
584 switch (m_ttyLevel) {
585 case KDebugger::ttySimpleOutputOnly:
586 ttyWindow()->deactivate();
587 break;
588 case KDebugger::ttyFull:
589 if (m_outputTermProc != 0) {
590 m_outputTermProc->kill();
591 // will be deleted in slot
593 break;
594 default: break;
597 m_ttyLevel = m_debugger->ttyLevel();
599 QString ttyName;
600 switch (m_ttyLevel) {
601 case KDebugger::ttySimpleOutputOnly:
602 ttyName = ttyWindow()->activate();
603 break;
604 case KDebugger::ttyFull:
605 if (m_outputTermProc == 0) {
606 // create an output window
607 ttyName = createOutputWindow();
608 TRACE(ttyName.isEmpty() ?
609 "createOuputWindow failed" : "successfully created output window");
611 break;
612 default: break;
615 m_debugger->setTerminal(ttyName);
619 void DebuggerMainWndBase::setDebuggerCmdStr(const QString& cmd)
621 m_debuggerCmdStr = cmd;
622 // make empty if it is the default
623 if (m_debuggerCmdStr == GdbDriver::defaultGdb()) {
624 m_debuggerCmdStr = QString();
629 #include "mainwndbase.moc"