KStdAccel is now a namespace, not an object.
[kdbg.git] / kdbg / mainwndbase.cpp
blob7be28d49cf65b2605de4a5b0b1a863b665c10060
1 // $Id$
3 // Copyright by Johannes Sixt
4 // This file is under GPL, the GNU General Public Licence
6 #include <kapp.h>
7 #if QT_VERSION >= 200
8 #include <klocale.h> /* i18n */
9 #include <kconfig.h>
10 #include <kmessagebox.h>
11 #else
12 #include <kmsgbox.h>
13 #include <qkeycode.h>
14 #endif
15 #include <kiconloader.h>
16 #include <kstatusbar.h>
17 #include <ktoolbar.h>
18 #include <kfiledialog.h>
19 #include <qpainter.h>
20 #include <qtabdialog.h>
21 #include <qfileinfo.h>
22 #include "mainwndbase.h"
23 #include "debugger.h"
24 #include "gdbdriver.h"
25 #include "prefdebugger.h"
26 #include "prefmisc.h"
27 #include "ttywnd.h"
28 #include "updateui.h"
29 #include "commandids.h"
30 #include "valarray.h"
31 #ifdef HAVE_CONFIG
32 #include "config.h"
33 #endif
34 #include "mydebug.h"
35 #ifdef HAVE_SYS_STAT_H
36 #include <sys/stat.h> /* mknod(2) */
37 #endif
38 #ifdef HAVE_FCNTL_H
39 #include <fcntl.h> /* open(2) */
40 #endif
41 #ifdef HAVE_UNISTD_H
42 #include <unistd.h> /* getpid, unlink etc. */
43 #endif
45 #define MAX_RECENT_FILES 4
47 WatchWindow::WatchWindow(QWidget* parent, const char* name, WFlags f) :
48 QWidget(parent, name, f),
49 m_watchEdit(this, "watch_edit"),
50 m_watchAdd(i18n(" Add "), this, "watch_add"),
51 m_watchDelete(i18n(" Del "), this, "watch_delete"),
52 m_watchVariables(this, "watch_variables"),
53 m_watchV(this, 0),
54 m_watchH(0)
56 // setup the layout
57 m_watchAdd.setMinimumSize(m_watchAdd.sizeHint());
58 m_watchDelete.setMinimumSize(m_watchDelete.sizeHint());
59 m_watchV.addLayout(&m_watchH, 0);
60 m_watchV.addWidget(&m_watchVariables, 10);
61 m_watchH.addWidget(&m_watchEdit, 10);
62 m_watchH.addWidget(&m_watchAdd, 0);
63 m_watchH.addWidget(&m_watchDelete, 0);
65 connect(&m_watchEdit, SIGNAL(returnPressed()), SIGNAL(addWatch()));
66 connect(&m_watchAdd, SIGNAL(clicked()), SIGNAL(addWatch()));
67 connect(&m_watchDelete, SIGNAL(clicked()), SIGNAL(deleteWatch()));
68 connect(&m_watchVariables, SIGNAL(highlighted(int)), SLOT(slotWatchHighlighted(int)));
70 m_watchVariables.setMoveCurrentToSibling(true);
71 m_watchVariables.installEventFilter(this);
74 WatchWindow::~WatchWindow()
78 bool WatchWindow::eventFilter(QObject*, QEvent* ev)
80 if (ev->type() ==
81 #if QT_VERSION < 200
82 Event_KeyPress
83 #else
84 QEvent::KeyPress
85 #endif
88 QKeyEvent* kev = static_cast<QKeyEvent*>(ev);
89 if (kev->key() == Key_Delete) {
90 emit deleteWatch();
91 return true;
94 return false;
98 // place the text of the hightlighted watch expr in the edit field
99 void WatchWindow::slotWatchHighlighted(int idx)
101 QString text = m_watchVariables.exprStringAt(idx);
102 m_watchEdit.setText(text);
106 static void splitCmdStr(const QString& cmd, ValArray<QString>& parts)
108 QString str = cmd.simplifyWhiteSpace();
109 int start = 0;
110 int end;
111 while ((end = str.find(' ', start)) >= 0) {
112 parts.append(str.mid(start, end-start));
113 start = end+1;
115 parts.append(str.mid(start, str.length()-start));
119 const char defaultTermCmdStr[] = "xterm -name kdbgio -title %T -e sh -c %C";
120 const char defaultSourceFilter[] = "*.c *.cc *.cpp *.c++ *.C *.CC";
121 const char defaultHeaderFilter[] = "*.h *.hh *.hpp *.h++";
124 DebuggerMainWndBase::DebuggerMainWndBase() :
125 m_animationCounter(0),
126 m_outputTermCmdStr(defaultTermCmdStr),
127 m_outputTermProc(0),
128 m_ttyLevel(-1), /* no tty yet */
129 #ifdef GDB_TRANSCRIPT
130 m_transcriptFile(GDB_TRANSCRIPT),
131 #endif
132 m_popForeground(false),
133 m_backTimeout(1000),
134 m_tabWidth(0),
135 m_sourceFilter(defaultSourceFilter),
136 m_headerFilter(defaultHeaderFilter),
137 m_debugger(0)
139 m_statusActive = i18n("active");
140 m_recentExecList.setAutoDelete(true);
143 DebuggerMainWndBase::~DebuggerMainWndBase()
145 delete m_debugger;
147 // if the output window is open, close it
148 if (m_outputTermProc != 0) {
149 m_outputTermProc->disconnect(); /* ignore signals */
150 m_outputTermProc->kill();
151 shutdownTermWindow();
155 void DebuggerMainWndBase::setupDebugger(QWidget* parent,
156 ExprWnd* localVars,
157 ExprWnd* watchVars,
158 QListBox* backtrace)
160 GdbDriver* driver = new GdbDriver;
161 driver->setLogFileName(m_transcriptFile);
163 m_debugger = new KDebugger(parent, localVars, watchVars, backtrace, driver);
165 QObject::connect(m_debugger, SIGNAL(updateStatusMessage()),
166 parent, SLOT(slotNewStatusMsg()));
167 QObject::connect(m_debugger, SIGNAL(updateUI()),
168 parent, SLOT(updateUI()));
170 QObject::connect(m_debugger, SIGNAL(lineItemsChanged()),
171 parent, SLOT(updateLineItems()));
173 QObject::connect(m_debugger, SIGNAL(animationTimeout()),
174 parent, SLOT(slotAnimationTimeout()));
175 QObject::connect(m_debugger, SIGNAL(debuggerStarting()),
176 parent, SLOT(slotDebuggerStarting()));
178 m_debugger->setDebuggerCmd(m_debuggerCmdStr);
182 void DebuggerMainWndBase::setCoreFile(const QString& corefile)
184 assert(m_debugger != 0);
185 m_debugger->useCoreFile(corefile, true);
188 void DebuggerMainWndBase::setRemoteDevice(const QString& remoteDevice)
190 if (m_debugger != 0) {
191 m_debugger->setRemoteDevice(remoteDevice);
195 void DebuggerMainWndBase::setTranscript(const char* name)
197 m_transcriptFile = name;
198 if (m_debugger != 0)
199 m_debugger->driver()->setLogFileName(m_transcriptFile);
202 const char OutputWindowGroup[] = "OutputWindow";
203 const char TermCmdStr[] = "TermCmdStr";
204 const char KeepScript[] = "KeepScript";
205 const char DebuggerGroup[] = "Debugger";
206 const char DebuggerCmdStr[] = "DebuggerCmdStr";
207 const char PreferencesGroup[] = "Preferences";
208 const char PopForeground[] = "PopForeground";
209 const char BackTimeout[] = "BackTimeout";
210 const char TabWidth[] = "TabWidth";
211 const char FilesGroup[] = "Files";
212 const char RecentExecutables[] = "RecentExecutables";
213 const char SourceFileFilter[] = "SourceFileFilter";
214 const char HeaderFileFilter[] = "HeaderFileFilter";
216 void DebuggerMainWndBase::saveSettings(KConfig* config)
218 if (m_debugger != 0) {
219 m_debugger->saveSettings(config);
222 KConfigGroupSaver g(config, OutputWindowGroup);
223 config->writeEntry(TermCmdStr, m_outputTermCmdStr);
225 config->setGroup(DebuggerGroup);
226 config->writeEntry(DebuggerCmdStr, m_debuggerCmdStr);
228 config->setGroup(PreferencesGroup);
229 config->writeEntry(PopForeground, m_popForeground);
230 config->writeEntry(BackTimeout, m_backTimeout);
231 config->writeEntry(TabWidth, m_tabWidth);
232 config->writeEntry(SourceFileFilter, m_sourceFilter);
233 config->writeEntry(HeaderFileFilter, m_headerFilter);
235 config->setGroup(FilesGroup);
236 config->writeEntry(RecentExecutables, m_recentExecList, ',');
239 void DebuggerMainWndBase::restoreSettings(KConfig* config)
241 if (m_debugger != 0) {
242 m_debugger->restoreSettings(config);
245 KConfigGroupSaver g(config, OutputWindowGroup);
247 * For debugging and emergency purposes, let the config file override
248 * the shell script that is used to keep the output window open. This
249 * string must have EXACTLY 1 %s sequence in it.
251 setTerminalCmd(config->readEntry(TermCmdStr, defaultTermCmdStr));
252 m_outputTermKeepScript = config->readEntry(KeepScript);
254 config->setGroup(DebuggerGroup);
255 setDebuggerCmdStr(config->readEntry(DebuggerCmdStr));
257 config->setGroup(PreferencesGroup);
258 m_popForeground = config->readBoolEntry(PopForeground, false);
259 m_backTimeout = config->readNumEntry(BackTimeout, 1000);
260 m_tabWidth = config->readNumEntry(TabWidth, 0);
261 m_sourceFilter = config->readEntry(SourceFileFilter, m_sourceFilter);
262 m_headerFilter = config->readEntry(HeaderFileFilter, m_headerFilter);
264 config->setGroup(FilesGroup);
265 config->readListEntry(RecentExecutables, m_recentExecList,',');
268 bool DebuggerMainWndBase::debugProgram(const QString& executable)
270 assert(m_debugger != 0);
271 return m_debugger->debugProgram(executable);
274 // helper that gets a file name (it only differs in the caption of the dialog)
275 QString DebuggerMainWndBase::myGetFileName(QString caption,
276 QString dir, QString filter,
277 QWidget* parent)
279 QString filename;
280 KFileDialog dlg(dir, filter, parent, "filedialog", true);
282 dlg.setCaption(caption);
284 if (dlg.exec() == QDialog::Accepted)
285 filename = dlg.selectedFile();
287 return filename;
290 void DebuggerMainWndBase::updateUIItem(UpdateUI* item)
292 switch (item->id) {
293 case ID_FILE_EXECUTABLE:
294 item->enable(m_debugger->isIdle());
295 break;
296 case ID_FILE_PROG_SETTINGS:
297 item->enable(m_debugger->haveExecutable());
298 break;
299 case ID_FILE_COREFILE:
300 item->enable(m_debugger->canUseCoreFile());
301 break;
302 case ID_PROGRAM_STEP:
303 case ID_PROGRAM_STEPI:
304 case ID_PROGRAM_NEXT:
305 case ID_PROGRAM_NEXTI:
306 case ID_PROGRAM_FINISH:
307 case ID_PROGRAM_UNTIL:
308 case ID_PROGRAM_RUN_AGAIN:
309 item->enable(m_debugger->canSingleStep());
310 break;
311 case ID_PROGRAM_ATTACH:
312 case ID_PROGRAM_RUN:
313 item->enable(m_debugger->isReady());
314 break;
315 case ID_PROGRAM_KILL:
316 item->enable(m_debugger->haveExecutable() && m_debugger->isProgramActive());
317 break;
318 case ID_PROGRAM_BREAK:
319 item->enable(m_debugger->isProgramRunning());
320 break;
321 case ID_PROGRAM_ARGS:
322 item->enable(m_debugger->haveExecutable());
323 break;
326 // update statusbar
327 dbgStatusBar()->changeItem(m_debugger->isProgramActive() ?
328 static_cast<const char*>(m_statusActive) : "",
329 ID_STATUS_ACTIVE);
332 void DebuggerMainWndBase::updateLineItems()
336 void DebuggerMainWndBase::initAnimation()
338 #if QT_VERSION < 200
339 QString path = kapp->kde_datadir() + "/kfm/pics/";
340 QPixmap pixmap;
341 pixmap.load(path + "/kde1.xpm");
342 int numPix = 9;
343 #else
344 QPixmap pixmap = BarIcon("kde1");
345 int numPix = 6;
346 #endif
348 KToolBar* toolbar = dbgToolBar();
349 toolbar->insertButton(pixmap, ID_STATUS_BUSY);
350 toolbar->alignItemRight(ID_STATUS_BUSY, true);
352 // Load animated logo
353 m_animation.setAutoDelete(true);
354 QString n;
355 for (int i = 1; i <= numPix; i++) {
356 #if QT_VERSION < 200
357 n.sprintf("/kde%d.xpm", i);
358 QPixmap* p = new QPixmap();
359 p->load(path + n);
360 #else
361 n.sprintf("kde%d", i);
362 QPixmap* p = new QPixmap(BarIcon(n));
363 #endif
364 if (!p->isNull()) {
365 m_animation.append(p);
366 } else {
367 delete p;
370 // safeguard: if we did not find a single icon, add a dummy
371 if (m_animation.count() == 0) {
372 QPixmap* pix = new QPixmap(2,2);
373 QPainter p(pix);
374 #if QT_VERSION < 200
375 p.fillRect(0,0,2,2,QBrush(white));
376 #else
377 p.fillRect(0,0,2,2,QBrush(Qt::white));
378 #endif
379 m_animation.append(pix);
383 void DebuggerMainWndBase::slotAnimationTimeout()
385 assert(m_animation.count() > 0); /* must have been initialized */
386 m_animationCounter++;
387 if (m_animationCounter == m_animation.count())
388 m_animationCounter = 0;
389 dbgToolBar()->setButtonPixmap(ID_STATUS_BUSY,
390 *m_animation.at(m_animationCounter));
393 void DebuggerMainWndBase::slotNewStatusMsg()
395 QString msg = m_debugger->statusMessage();
396 dbgStatusBar()->changeItem(msg, ID_STATUS_MSG);
399 void DebuggerMainWndBase::doGlobalOptions(QWidget* parent)
401 QTabDialog dlg(parent, "global_options", true);
402 QString title = kapp->getCaption();
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();
484 #if QT_VERSION < 200
485 QString shellScript(strlen(fmt) + fifoName.length());
486 #else
487 QString shellScript;
488 #endif
489 shellScript.sprintf(fmt, fifoName.data());
490 TRACE("output window script is " + shellScript);
492 QString title = kapp->getCaption();
493 title += i18n(": Program output");
495 // parse the command line specified in the preferences
496 ValArray<QString> cmdParts;
497 splitCmdStr(m_outputTermCmdStr, cmdParts);
500 * Build the argv array. Thereby substitute special sequences:
502 struct {
503 char seq[4];
504 QString replace;
505 } substitute[] = {
506 { "%T", title },
507 { "%C", shellScript }
510 for (int i = 0; i < cmdParts.size(); i++) {
511 QString& str = cmdParts[i];
512 for (int j = sizeof(substitute)/sizeof(substitute[0])-1; j >= 0; j--) {
513 int pos = str.find(substitute[j].seq);
514 if (pos >= 0) {
515 str.replace(pos, 2, substitute[j].replace);
516 break; /* substitute only one sequence */
519 *m_outputTermProc << str;
524 if (m_outputTermProc->start())
526 // read the ttyname from the fifo
527 int f = ::open(fifoName, O_RDONLY);
528 if (f < 0) {
529 // error
530 ::unlink(fifoName);
531 return QString();
534 char ttyname[50];
535 int n = ::read(f, ttyname, sizeof(ttyname)-sizeof(char)); /* leave space for '\0' */
537 ::close(f);
538 ::unlink(fifoName);
540 if (n < 0) {
541 // error
542 return QString();
545 // remove whitespace
546 ttyname[n] = '\0';
547 QString tty = QString(ttyname).stripWhiteSpace();
548 TRACE("tty=" + tty);
549 return tty;
551 else
553 // error, could not start xterm
554 TRACE("fork failed for fifo " + fifoName);
555 ::unlink(fifoName);
556 shutdownTermWindow();
557 return QString();
561 void DebuggerMainWndBase::shutdownTermWindow()
563 delete m_outputTermProc;
564 m_outputTermProc = 0;
567 void DebuggerMainWndBase::setTerminalCmd(const QString& cmd)
569 m_outputTermCmdStr = cmd;
570 // revert to default if empty
571 if (m_outputTermCmdStr.isEmpty()) {
572 m_outputTermCmdStr = defaultTermCmdStr;
576 void DebuggerMainWndBase::slotDebuggerStarting()
578 if (m_debugger == 0) /* paranoia check */
579 return;
581 if (m_ttyLevel == m_debugger->ttyLevel())
584 else
586 // shut down terminal emulations we will not need
587 switch (m_ttyLevel) {
588 case KDebugger::ttySimpleOutputOnly:
589 ttyWindow()->deactivate();
590 break;
591 case KDebugger::ttyFull:
592 if (m_outputTermProc != 0) {
593 m_outputTermProc->kill();
594 // will be deleted in slot
596 break;
597 default: break;
600 m_ttyLevel = m_debugger->ttyLevel();
602 QString ttyName;
603 switch (m_ttyLevel) {
604 case KDebugger::ttySimpleOutputOnly:
605 ttyName = ttyWindow()->activate();
606 break;
607 case KDebugger::ttyFull:
608 if (m_outputTermProc == 0) {
609 // create an output window
610 ttyName = createOutputWindow();
611 TRACE(ttyName.isEmpty() ?
612 "createOuputWindow failed" : "successfully created output window");
614 break;
615 default: break;
618 m_debugger->setTerminal(ttyName);
622 void DebuggerMainWndBase::setDebuggerCmdStr(const QString& cmd)
624 m_debuggerCmdStr = cmd;
625 // make empty if it is the default
626 if (m_debuggerCmdStr == GdbDriver::defaultGdb()) {
627 m_debuggerCmdStr = QString();
629 if (m_debugger != 0) {
630 m_debugger->setDebuggerCmd(m_debuggerCmdStr);
634 void DebuggerMainWndBase::addRecentExec(const QString& executable)
636 int pos = m_recentExecList.find(executable);
637 if (pos != 0) {
638 // move to top
639 if (pos > 0)
640 m_recentExecList.remove(pos);
641 // else entry is new
643 // insert on top
644 m_recentExecList.insert(0, executable);
645 } // else pos == 0, which means we dont need to change the list
647 // shorten list
648 while (m_recentExecList.count() > MAX_RECENT_FILES) {
649 m_recentExecList.remove(MAX_RECENT_FILES);
653 void DebuggerMainWndBase::removeRecentExec(const QString& executable)
655 int pos = m_recentExecList.find(executable);
656 if (pos >= 0) {
657 m_recentExecList.remove(pos);
661 bool DebuggerMainWndBase::debugProgramInteractive(const QString& executable,
662 QWidget* parent)
664 // check the file name
665 QFileInfo fi(executable);
666 m_lastDirectory = fi.dirPath(true);
668 if (!fi.isFile()) {
669 QString msgFmt = i18n("`%s' is not a file or does not exist");
670 SIZED_QString(msg, msgFmt.length() + executable.length() + 20);
671 #if QT_VERSION < 200
672 msg.sprintf(msgFmt, executable.data());
673 KMsgBox::message(parent, kapp->appName(),
674 msg,
675 KMsgBox::STOP,
676 i18n("OK"));
677 #else
678 msg.sprintf(msgFmt, executable.latin1());
679 KMessageBox::sorry(parent, msg);
680 #endif
681 return false;
684 if (!m_debugger->debugProgram(executable)) {
685 QString msg = i18n("Could not start the debugger process.\n"
686 "Please shut down KDbg and resolve the problem.");
687 #if QT_VERSION < 200
688 KMsgBox::message(parent, kapp->appName(),
689 msg,
690 KMsgBox::STOP,
691 i18n("OK"));
692 #else
693 KMessageBox::sorry(parent, msg);
694 #endif
696 return true;
700 #include "mainwndbase.moc"