Address status bar text boxes by pointer instead of "command IDs".
[kdbg.git] / kdbg / dbgmainwnd.cpp
blob63675963d8ee8af4693037c138dc8cb2ae1d170c
1 /*
2 * Copyright Johannes Sixt
3 * This file is licensed under the GNU General Public License Version 2.
4 * See the file COPYING in the toplevel directory of the source directory.
5 */
7 #include <kapplication.h>
8 #include <klocale.h> /* i18n */
9 #include <kmessagebox.h>
10 #include <kconfig.h>
11 #include <kstatusbar.h>
12 #include <kicon.h>
13 #include <kstandardaction.h>
14 #include <kstandardshortcut.h>
15 #include <kaction.h>
16 #include <kactioncollection.h>
17 #include <krecentfilesaction.h>
18 #include <ktoggleaction.h>
19 #include <kfiledialog.h>
20 #include <kshortcutsdialog.h>
21 #include <kanimatedbutton.h>
22 #include <kwindowsystem.h>
23 #include <ksqueezedtextlabel.h>
24 #include <ktoolbar.h>
25 #include <kurl.h>
26 #include <kxmlguifactory.h>
27 #include <KPageDialog>
28 #include <QListWidget>
29 #include <QFile>
30 #include <QFileInfo>
31 #include <QList>
32 #include <QDockWidget>
33 #include <QProcess>
34 #include "dbgmainwnd.h"
35 #include "debugger.h"
36 #include "winstack.h"
37 #include "brkpt.h"
38 #include "threadlist.h"
39 #include "memwindow.h"
40 #include "ttywnd.h"
41 #include "watchwindow.h"
42 #include "procattach.h"
43 #include "prefdebugger.h"
44 #include "prefmisc.h"
45 #include "gdbdriver.h"
46 #include "xsldbgdriver.h"
47 #include "mydebug.h"
48 #include <sys/stat.h> /* mknod(2) */
49 #include <unistd.h> /* getpid */
52 static const char defaultTermCmdStr[] = "xterm -name kdbgio -title %T -e sh -c %C";
53 static const char defaultSourceFilter[] = "*.c *.cc *.cpp *.c++ *.C *.CC";
54 static const char defaultHeaderFilter[] = "*.h *.hh *.hpp *.h++";
56 DebuggerMainWnd::DebuggerMainWnd() :
57 KXmlGuiWindow(),
58 m_debugger(0),
59 #ifdef GDB_TRANSCRIPT
60 m_transcriptFile(GDB_TRANSCRIPT),
61 #endif
62 m_outputTermCmdStr(defaultTermCmdStr),
63 m_outputTermProc(new QProcess),
64 m_ttyLevel(-1), /* no tty yet */
65 m_popForeground(false),
66 m_backTimeout(1000),
67 m_tabWidth(0),
68 m_sourceFilter(defaultSourceFilter),
69 m_headerFilter(defaultHeaderFilter),
70 m_statusActive(i18n("active"))
72 setDockNestingEnabled(true);
74 m_filesWindow = new WinStack(this);
75 setCentralWidget(m_filesWindow);
77 QDockWidget* dw1 = createDockWidget("Stack", i18n("Stack"));
78 m_btWindow = new QListWidget(dw1);
79 dw1->setWidget(m_btWindow);
80 QDockWidget* dw2 = createDockWidget("Locals", i18n("Locals"));
81 m_localVariables = new ExprWnd(dw2, i18n("Variable"));
82 dw2->setWidget(m_localVariables);
83 QDockWidget* dw3 = createDockWidget("Watches", i18n("Watches"));
84 m_watches = new WatchWindow(dw3);
85 dw3->setWidget(m_watches);
86 QDockWidget* dw4 = createDockWidget("Registers", i18n("Registers"));
87 m_registers = new RegisterView(dw4);
88 dw4->setWidget(m_registers);
89 QDockWidget* dw5 = createDockWidget("Breakpoints", i18n("Breakpoints"));
90 m_bpTable = new BreakpointTable(dw5);
91 dw5->setWidget(m_bpTable);
92 QDockWidget* dw6 = createDockWidget("Output", i18n("Output"));
93 m_ttyWindow = new TTYWindow(dw6);
94 dw6->setWidget(m_ttyWindow);
95 QDockWidget* dw7 = createDockWidget("Threads", i18n("Threads"));
96 m_threads = new ThreadList(dw7);
97 dw7->setWidget(m_threads);
98 QDockWidget* dw8 = createDockWidget("Memory", i18n("Memory"));
99 m_memoryWindow = new MemoryWindow(dw8);
100 dw8->setWidget(m_memoryWindow);
102 m_debugger = new KDebugger(this, m_localVariables, m_watches->watchVariables(), m_btWindow);
104 connect(m_debugger, SIGNAL(updateStatusMessage()), SLOT(slotNewStatusMsg()));
105 connect(m_debugger, SIGNAL(updateUI()), SLOT(updateUI()));
106 connect(m_debugger, SIGNAL(breakpointsChanged()), SLOT(updateLineItems()));
107 connect(m_debugger, SIGNAL(debuggerStarting()), SLOT(slotDebuggerStarting()));
108 m_bpTable->setDebugger(m_debugger);
109 m_memoryWindow->setDebugger(m_debugger);
111 setStandardToolBarMenuEnabled(true);
112 initKAction();
113 initStatusBar();
115 connect(m_watches, SIGNAL(addWatch()), SLOT(slotAddWatch()));
116 connect(m_watches, SIGNAL(deleteWatch()), m_debugger, SLOT(slotDeleteWatch()));
117 connect(m_watches, SIGNAL(textDropped(const QString&)), SLOT(slotAddWatch(const QString&)));
119 connect(&m_filesWindow->m_findDlg, SIGNAL(closed()), SLOT(updateUI()));
120 connect(m_filesWindow, SIGNAL(newFileLoaded()),
121 SLOT(slotNewFileLoaded()));
122 connect(m_filesWindow, SIGNAL(toggleBreak(const QString&,int,const DbgAddr&,bool)),
123 this, SLOT(slotToggleBreak(const QString&,int,const DbgAddr&,bool)));
124 connect(m_filesWindow, SIGNAL(enadisBreak(const QString&,int,const DbgAddr&)),
125 this, SLOT(slotEnaDisBreak(const QString&,int,const DbgAddr&)));
126 connect(m_debugger, SIGNAL(activateFileLine(const QString&,int,const DbgAddr&)),
127 m_filesWindow, SLOT(activate(const QString&,int,const DbgAddr&)));
128 connect(m_debugger, SIGNAL(executableUpdated()),
129 m_filesWindow, SLOT(reloadAllFiles()));
130 connect(m_debugger, SIGNAL(updatePC(const QString&,int,const DbgAddr&,int)),
131 m_filesWindow, SLOT(updatePC(const QString&,int,const DbgAddr&,int)));
132 // value popup communication
133 connect(m_filesWindow, SIGNAL(initiateValuePopup(const QString&)),
134 m_debugger, SLOT(slotValuePopup(const QString&)));
135 connect(m_debugger, SIGNAL(valuePopup(const QString&)),
136 m_filesWindow, SLOT(slotShowValueTip(const QString&)));
137 // disassembling
138 connect(m_filesWindow, SIGNAL(disassemble(const QString&, int)),
139 m_debugger, SLOT(slotDisassemble(const QString&, int)));
140 connect(m_debugger, SIGNAL(disassembled(const QString&,int,const std::list<DisassembledCode>&)),
141 m_filesWindow, SLOT(slotDisassembled(const QString&,int,const std::list<DisassembledCode>&)));
142 connect(m_filesWindow, SIGNAL(moveProgramCounter(const QString&,int,const DbgAddr&)),
143 m_debugger, SLOT(setProgramCounter(const QString&,int,const DbgAddr&)));
144 // program stopped
145 connect(m_debugger, SIGNAL(programStopped()), SLOT(slotProgramStopped()));
146 connect(&m_backTimer, SIGNAL(timeout()), SLOT(slotBackTimer()));
147 // tab width
148 connect(this, SIGNAL(setTabWidth(int)), m_filesWindow, SIGNAL(setTabWidth(int)));
150 // connect breakpoint table
151 connect(m_bpTable, SIGNAL(activateFileLine(const QString&,int,const DbgAddr&)),
152 m_filesWindow, SLOT(activate(const QString&,int,const DbgAddr&)));
153 connect(m_debugger, SIGNAL(updateUI()), m_bpTable, SLOT(updateUI()));
154 connect(m_debugger, SIGNAL(breakpointsChanged()), m_bpTable, SLOT(updateBreakList()));
155 connect(m_debugger, SIGNAL(breakpointsChanged()), m_bpTable, SLOT(updateUI()));
157 connect(m_debugger, SIGNAL(registersChanged(const std::list<RegisterInfo>&)),
158 m_registers, SLOT(updateRegisters(const std::list<RegisterInfo>&)));
160 connect(m_debugger, SIGNAL(memoryDumpChanged(const QString&, const std::list<MemoryDump>&)),
161 m_memoryWindow, SLOT(slotNewMemoryDump(const QString&, const std::list<MemoryDump>&)));
162 connect(m_debugger, SIGNAL(saveProgramSpecific(KConfigBase*)),
163 m_memoryWindow, SLOT(saveProgramSpecific(KConfigBase*)));
164 connect(m_debugger, SIGNAL(restoreProgramSpecific(KConfigBase*)),
165 m_memoryWindow, SLOT(restoreProgramSpecific(KConfigBase*)));
167 // thread window
168 connect(m_debugger, SIGNAL(threadsChanged(const std::list<ThreadInfo>&)),
169 m_threads, SLOT(updateThreads(const std::list<ThreadInfo>&)));
170 connect(m_threads, SIGNAL(setThread(int)),
171 m_debugger, SLOT(setThread(int)));
173 // popup menu of the local variables window
174 m_localVariables->setContextMenuPolicy(Qt::CustomContextMenu);
175 connect(m_localVariables, SIGNAL(customContextMenuRequested(const QPoint&)),
176 this, SLOT(slotLocalsPopup(const QPoint&)));
178 makeDefaultLayout();
179 setupGUI(KXmlGuiWindow::Default, "kdbgui.rc");
180 restoreSettings(KGlobal::config());
182 // The animation button is not part of the restored window state.
183 // We must create it after the toolbar was loaded.
184 initAnimation();
186 updateUI();
187 m_bpTable->updateUI();
190 DebuggerMainWnd::~DebuggerMainWnd()
192 saveSettings(KGlobal::config());
193 // must delete m_debugger early since it references our windows
194 delete m_debugger;
195 m_debugger = 0;
197 delete m_memoryWindow;
198 delete m_threads;
199 delete m_ttyWindow;
200 delete m_bpTable;
201 delete m_registers;
202 delete m_watches;
203 delete m_localVariables;
204 delete m_btWindow;
205 delete m_filesWindow;
207 delete m_outputTermProc;
210 QDockWidget* DebuggerMainWnd::createDockWidget(const char* name, const QString& title)
212 QDockWidget* w = new QDockWidget(title, this);
213 w->setObjectName(name);
214 // view menu changes when docking state changes
215 connect(w, SIGNAL(visibilityChanged(bool)), SLOT(updateUI()));
216 return w;
219 QAction* DebuggerMainWnd::createAction(const QString& text, const char* icon,
220 int shortcut, const QObject* receiver,
221 const char* slot, const char* name)
223 KAction* a = actionCollection()->addAction(name);
224 a->setText(text);
225 a->setIcon(KIcon(icon));
226 if (shortcut)
227 a->setShortcut(KShortcut(shortcut));
228 connect(a, SIGNAL(triggered()), receiver, slot);
229 return a;
232 QAction* DebuggerMainWnd::createAction(const QString& text,
233 int shortcut, const QObject* receiver,
234 const char* slot, const char* name)
236 KAction* a = actionCollection()->addAction(name);
237 a->setText(text);
238 if (shortcut)
239 a->setShortcut(KShortcut(shortcut));
240 connect(a, SIGNAL(triggered()), receiver, slot);
241 return a;
245 void DebuggerMainWnd::initKAction()
247 // file menu
248 KAction* open = KStandardAction::open(this, SLOT(slotFileOpen()),
249 actionCollection());
250 open->setText(i18n("&Open Source..."));
251 m_closeAction = KStandardAction::close(m_filesWindow, SLOT(slotClose()), actionCollection());
252 m_reloadAction = createAction(i18n("&Reload Source"), "view-refresh", 0,
253 m_filesWindow, SLOT(slotFileReload()), "file_reload");
254 m_fileExecAction = createAction(i18n("&Executable..."),
255 "document-open-executable", 0,
256 this, SLOT(slotFileExe()), "file_executable");
257 m_recentExecAction = KStandardAction::openRecent(this, SLOT(slotRecentExec(const KUrl&)),
258 actionCollection());
259 m_recentExecAction->setObjectName("file_executable_recent");
260 m_recentExecAction->setText(i18n("Recent E&xecutables"));
261 m_coreDumpAction = createAction(i18n("&Core dump..."), 0,
262 this, SLOT(slotFileCore()), "file_core_dump");
263 KStandardAction::quit(kapp, SLOT(closeAllWindows()), actionCollection());
265 // settings menu
266 m_settingsAction = createAction(i18n("This &Program..."), 0,
267 this, SLOT(slotFileProgSettings()), "settings_program");
268 createAction(i18n("&Global Options..."), 0,
269 this, SLOT(slotFileGlobalSettings()), "settings_global");
270 KStandardAction::keyBindings(this, SLOT(slotConfigureKeys()), actionCollection());
271 KStandardAction::showStatusbar(this, SLOT(slotViewStatusbar()), actionCollection());
273 // view menu
274 m_findAction = KStandardAction::find(m_filesWindow, SLOT(slotViewFind()), actionCollection());
275 KStandardAction::findNext(m_filesWindow, SLOT(slotFindForward()), actionCollection());
276 KStandardAction::findPrev(m_filesWindow, SLOT(slotFindBackward()), actionCollection());
278 i18n("Source &code");
279 struct { QString text; QWidget* w; QString id; QAction** act; } dw[] = {
280 { i18n("Stac&k"), m_btWindow, "view_stack", &m_btWindowAction },
281 { i18n("&Locals"), m_localVariables, "view_locals", &m_localVariablesAction },
282 { i18n("&Watched expressions"), m_watches, "view_watched_expressions", &m_watchesAction },
283 { i18n("&Registers"), m_registers, "view_registers", &m_registersAction },
284 { i18n("&Breakpoints"), m_bpTable, "view_breakpoints", &m_bpTableAction },
285 { i18n("T&hreads"), m_threads, "view_threads", &m_threadsAction },
286 { i18n("&Output"), m_ttyWindow, "view_output", &m_ttyWindowAction },
287 { i18n("&Memory"), m_memoryWindow, "view_memory", &m_memoryWindowAction }
289 for (unsigned i = 0; i < sizeof(dw)/sizeof(dw[0]); i++) {
290 QDockWidget* d = dockParent(dw[i].w);
291 *dw[i].act = new KToggleAction(dw[i].text, actionCollection());
292 actionCollection()->addAction(dw[i].id, *dw[i].act);
293 connect(*dw[i].act, SIGNAL(triggered()), d, SLOT(show()));
296 // execution menu
297 m_runAction = createAction(i18n("&Run"),
298 "debug-run", Qt::Key_F5,
299 m_debugger, SLOT(programRun()), "exec_run");
300 connect(m_runAction, SIGNAL(triggered()), this, SLOT(intoBackground()));
301 m_stepIntoAction = createAction(i18n("Step &into"),
302 "debug-step-into", Qt::Key_F8,
303 m_debugger, SLOT(programStep()), "exec_step_into");
304 connect(m_stepIntoAction, SIGNAL(triggered()), this, SLOT(intoBackground()));
305 m_stepOverAction = createAction(i18n("Step &over"),
306 "debug-step-over", Qt::Key_F10,
307 m_debugger, SLOT(programNext()), "exec_step_over");
308 connect(m_stepOverAction, SIGNAL(triggered()), this, SLOT(intoBackground()));
309 m_stepOutAction = createAction(i18n("Step o&ut"),
310 "debug-step-out", Qt::Key_F6,
311 m_debugger, SLOT(programFinish()), "exec_step_out");
312 connect(m_stepOutAction, SIGNAL(triggered()), this, SLOT(intoBackground()));
313 m_toCursorAction = createAction(i18n("Run to &cursor"),
314 "debug-execute-to-cursor", Qt::Key_F7,
315 this, SLOT(slotExecUntil()), "exec_run_to_cursor");
316 connect(m_toCursorAction, SIGNAL(triggered()), this, SLOT(intoBackground()));
317 m_stepIntoIAction = createAction(i18n("Step i&nto by instruction"),
318 "debug-step-into-instruction", Qt::SHIFT+Qt::Key_F8,
319 m_debugger, SLOT(programStepi()), "exec_step_into_by_insn");
320 connect(m_stepIntoIAction, SIGNAL(triggered()), this, SLOT(intoBackground()));
321 m_stepOverIAction = createAction(i18n("Step o&ver by instruction"),
322 "debug-step-instruction", Qt::SHIFT+Qt::Key_F10,
323 m_debugger, SLOT(programNexti()), "exec_step_over_by_insn");
324 connect(m_stepOverIAction, SIGNAL(triggered()), this, SLOT(intoBackground()));
325 m_execMovePCAction = createAction(i18n("&Program counter to current line"),
326 "debug-run-cursor", 0,
327 m_filesWindow, SLOT(slotMoveProgramCounter()), "exec_movepc");
328 m_breakAction = createAction(i18n("&Break"), 0,
329 m_debugger, SLOT(programBreak()), "exec_break");
330 m_killAction = createAction(i18n("&Kill"), 0,
331 m_debugger, SLOT(programKill()), "exec_kill");
332 m_restartAction = createAction(i18n("Re&start"), 0,
333 m_debugger, SLOT(programRunAgain()), "exec_restart");
334 m_attachAction = createAction(i18n("A&ttach..."), 0,
335 this, SLOT(slotExecAttach()), "exec_attach");
336 m_detachAction = createAction(i18n("&Detach"), 0,
337 m_debugger, SLOT(programDetach()), "exec_detach");
338 m_argumentsAction = createAction(i18n("&Arguments..."), 0,
339 this, SLOT(slotExecArgs()), "exec_arguments");
341 // breakpoint menu
342 m_bpSetAction = createAction(i18n("Set/Clear &breakpoint"), "brkpt", Qt::Key_F9,
343 m_filesWindow, SLOT(slotBrkptSet()), "breakpoint_set");
344 m_bpSetTempAction = createAction(i18n("Set &temporary breakpoint"), Qt::SHIFT+Qt::Key_F9,
345 m_filesWindow, SLOT(slotBrkptSetTemp()), "breakpoint_set_temporary");
346 m_bpEnableAction = createAction(i18n("&Enable/Disable breakpoint"), Qt::CTRL+Qt::Key_F9,
347 m_filesWindow, SLOT(slotBrkptEnable()), "breakpoint_enable");
349 // only in popup menus
350 createAction(i18n("Watch Expression"), 0,
351 this, SLOT(slotLocalsToWatch()), "watch_expression");
352 m_editValueAction = createAction(i18n("Edit Value"), Qt::Key_F2,
353 this, SLOT(slotEditValue()), "edit_value");
355 // all actions force an UI update
356 QList<QAction*> actions = actionCollection()->actions();
357 foreach(QAction* action, actions) {
358 connect(action, SIGNAL(triggered()), this, SLOT(updateUI()));
362 void DebuggerMainWnd::initAnimation()
364 KToolBar* toolbar = toolBar("mainToolBar");
365 m_animation = new KAnimatedButton(toolbar);
366 toolbar->addWidget(m_animation);
367 m_animation->setIcons("pulse");
368 connect(m_animation, SIGNAL(clicked(bool)), m_debugger, SLOT(programBreak()));
369 m_animRunning = false;
372 void DebuggerMainWnd::initStatusBar()
374 KStatusBar* statusbar = statusBar();
375 m_statusActiveLabel = new KSqueezedTextLabel(statusbar);
376 m_statusActiveLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
377 statusbar->addPermanentWidget(m_statusActiveLabel);
378 m_statusActiveLabel->show();
379 m_lastActiveStatusText = m_statusActive;
381 /* message pane */
382 m_statusMsgLabel = new KSqueezedTextLabel(statusbar);
383 m_statusMsgLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
384 statusbar->addPermanentWidget(m_statusMsgLabel);
385 m_statusMsgLabel->show();
387 // reserve some translations
388 i18n("Restart");
389 i18n("Core dump");
392 bool DebuggerMainWnd::queryClose()
394 if (m_debugger != 0) {
395 m_debugger->shutdown();
397 return true;
401 // instance properties
402 void DebuggerMainWnd::saveProperties(KConfigGroup& cg)
404 // session management
405 QString executable = "";
406 if (m_debugger != 0) {
407 executable = m_debugger->executable();
409 cg.writeEntry("executable", executable);
412 void DebuggerMainWnd::readProperties(const KConfigGroup& cg)
414 // session management
415 QString execName = cg.readEntry("executable");
417 TRACE("readProperties: executable=" + execName);
418 if (!execName.isEmpty()) {
419 debugProgram(execName, "");
423 static const char RecentExecutables[] = "RecentExecutables";
424 static const char LastSession[] = "LastSession";
425 static const char OutputWindowGroup[] = "OutputWindow";
426 static const char TermCmdStr[] = "TermCmdStr";
427 static const char KeepScript[] = "KeepScript";
428 static const char DebuggerGroup[] = "Debugger";
429 static const char DebuggerCmdStr[] = "DebuggerCmdStr";
430 static const char PreferencesGroup[] = "Preferences";
431 static const char PopForeground[] = "PopForeground";
432 static const char BackTimeout[] = "BackTimeout";
433 static const char TabWidth[] = "TabWidth";
434 static const char SourceFileFilter[] = "SourceFileFilter";
435 static const char HeaderFileFilter[] = "HeaderFileFilter";
437 void DebuggerMainWnd::saveSettings(KSharedConfigPtr config)
439 m_recentExecAction->saveEntries(config->group(RecentExecutables));
441 KConfigGroup lg = config->group(LastSession);
442 lg.writeEntry("Width0Locals", m_localVariables->columnWidth(0));
443 lg.writeEntry("Width0Watches", m_watches->columnWidth(0));
445 if (m_debugger != 0) {
446 m_debugger->saveSettings(config.data());
449 config->group(OutputWindowGroup).writeEntry(TermCmdStr, m_outputTermCmdStr);
450 config->group(DebuggerGroup).writeEntry(DebuggerCmdStr, m_debuggerCmdStr);
452 KConfigGroup pg(config->group(PreferencesGroup));
453 pg.writeEntry(PopForeground, m_popForeground);
454 pg.writeEntry(BackTimeout, m_backTimeout);
455 pg.writeEntry(TabWidth, m_tabWidth);
456 pg.writeEntry(SourceFileFilter, m_sourceFilter);
457 pg.writeEntry(HeaderFileFilter, m_headerFilter);
460 void DebuggerMainWnd::restoreSettings(KSharedConfigPtr config)
462 m_recentExecAction->loadEntries(config->group(RecentExecutables));
464 KConfigGroup lg = config->group(LastSession);
465 int w;
466 w = lg.readEntry("Width0Locals", -1);
467 if (w >= 0 && w < 30000)
468 m_localVariables->setColumnWidth(0, w);
469 w = lg.readEntry("Width0Watches", -1);
470 if (w >= 0 && w < 30000)
471 m_watches->setColumnWidth(0, w);
473 if (m_debugger != 0) {
474 m_debugger->restoreSettings(config.data());
477 KConfigGroup og(config->group(OutputWindowGroup));
479 * For debugging and emergency purposes, let the config file override
480 * the shell script that is used to keep the output window open. This
481 * string must have EXACTLY 1 %s sequence in it.
483 setTerminalCmd(og.readEntry(TermCmdStr, defaultTermCmdStr));
484 m_outputTermKeepScript = og.readEntry(KeepScript);
486 setDebuggerCmdStr(config->group(DebuggerGroup).readEntry(DebuggerCmdStr));
488 KConfigGroup pg(config->group(PreferencesGroup));
489 m_popForeground = pg.readEntry(PopForeground, false);
490 m_backTimeout = pg.readEntry(BackTimeout, 1000);
491 m_tabWidth = pg.readEntry(TabWidth, 0);
492 m_sourceFilter = pg.readEntry(SourceFileFilter, m_sourceFilter);
493 m_headerFilter = pg.readEntry(HeaderFileFilter, m_headerFilter);
495 emit setTabWidth(m_tabWidth);
498 void DebuggerMainWnd::updateUI()
500 m_findAction->setChecked(m_filesWindow->m_findDlg.isVisible());
501 m_findAction->setEnabled(m_filesWindow->hasWindows());
502 m_bpSetAction->setEnabled(m_debugger->canChangeBreakpoints());
503 m_bpSetTempAction->setEnabled(m_debugger->canChangeBreakpoints());
504 m_bpEnableAction->setEnabled(m_debugger->canChangeBreakpoints());
505 m_bpTableAction->setChecked(isDockVisible(m_bpTable));
506 m_btWindowAction->setChecked(isDockVisible(m_btWindow));
507 m_localVariablesAction->setChecked(isDockVisible(m_localVariables));
508 m_watchesAction->setChecked(isDockVisible(m_watches));
509 m_registersAction->setChecked(isDockVisible(m_registers));
510 m_threadsAction->setChecked(isDockVisible(m_threads));
511 m_memoryWindowAction->setChecked(isDockVisible(m_memoryWindow));
512 m_ttyWindowAction->setChecked(isDockVisible(m_ttyWindow));
514 m_fileExecAction->setEnabled(m_debugger->isIdle());
515 m_settingsAction->setEnabled(m_debugger->haveExecutable());
516 m_coreDumpAction->setEnabled(m_debugger->canStart());
517 m_closeAction->setEnabled(m_filesWindow->hasWindows());
518 m_reloadAction->setEnabled(m_filesWindow->hasWindows());
519 m_stepIntoAction->setEnabled(m_debugger->canSingleStep());
520 m_stepIntoIAction->setEnabled(m_debugger->canSingleStep());
521 m_stepOverAction->setEnabled(m_debugger->canSingleStep());
522 m_stepOverIAction->setEnabled(m_debugger->canSingleStep());
523 m_stepOutAction->setEnabled(m_debugger->canSingleStep());
524 m_toCursorAction->setEnabled(m_debugger->canSingleStep());
525 m_execMovePCAction->setEnabled(m_debugger->canSingleStep());
526 m_restartAction->setEnabled(m_debugger->canSingleStep());
527 m_attachAction->setEnabled(m_debugger->isReady());
528 m_detachAction->setEnabled(m_debugger->canSingleStep());
529 m_runAction->setEnabled(m_debugger->canStart() || m_debugger->canSingleStep());
530 m_killAction->setEnabled(m_debugger->haveExecutable() && m_debugger->isProgramActive());
531 m_breakAction->setEnabled(m_debugger->isProgramRunning());
532 m_argumentsAction->setEnabled(m_debugger->haveExecutable());
533 m_editValueAction->setEnabled(m_debugger->canSingleStep());
535 // animation
536 if (m_debugger->isIdle()) {
537 if (m_animRunning && m_animation) {
538 m_animation->stop();
539 m_animRunning = false;
541 } else {
542 if (!m_animRunning && m_animation) {
543 m_animation->start();
544 m_animRunning = true;
548 // update statusbar
549 QString newStatus;
550 if (m_debugger->isProgramActive())
551 newStatus = m_statusActive;
552 if (newStatus != m_lastActiveStatusText) {
553 m_statusActiveLabel->setText(newStatus);
554 m_lastActiveStatusText = newStatus;
558 void DebuggerMainWnd::updateLineItems()
560 m_filesWindow->updateLineItems(m_debugger);
563 void DebuggerMainWnd::slotAddWatch()
565 if (m_debugger != 0) {
566 QString t = m_watches->watchText();
567 m_debugger->addWatch(t);
571 void DebuggerMainWnd::slotAddWatch(const QString& text)
573 if (m_debugger != 0) {
574 m_debugger->addWatch(text);
578 void DebuggerMainWnd::slotNewFileLoaded()
580 // updates program counter in the new file
581 if (m_debugger != 0)
582 m_filesWindow->updateLineItems(m_debugger);
585 QDockWidget* DebuggerMainWnd::dockParent(QWidget* w)
587 while ((w = w->parentWidget()) != 0) {
588 if (QDockWidget* dock = qobject_cast<QDockWidget*>(w))
589 return dock;
591 return 0;
594 bool DebuggerMainWnd::isDockVisible(QWidget* w)
596 QDockWidget* d = dockParent(w);
597 return d != 0 && d->isVisible();
600 void DebuggerMainWnd::makeDefaultLayout()
602 // +---------------+---------+
603 // | Source | Locals |
604 // | | |
605 // |---------------+---------+
606 // |Stack, Brkpts, | Watches |
607 // |Output,... | |
608 // +---------------+---------+
610 addDockWidget(Qt::RightDockWidgetArea, dockParent(m_localVariables));
611 addDockWidget(Qt::BottomDockWidgetArea, dockParent(m_memoryWindow));
612 splitDockWidget(dockParent(m_memoryWindow), dockParent(m_threads), Qt::Horizontal);
613 tabifyDockWidget(dockParent(m_memoryWindow), dockParent(m_registers));
614 tabifyDockWidget(dockParent(m_registers), dockParent(m_bpTable));
615 tabifyDockWidget(dockParent(m_bpTable), dockParent(m_ttyWindow));
616 tabifyDockWidget(dockParent(m_ttyWindow), dockParent(m_btWindow));
617 tabifyDockWidget(dockParent(m_threads), dockParent(m_watches));
618 dockParent(m_localVariables)->setVisible(true);
619 dockParent(m_ttyWindow)->setVisible(true);
620 dockParent(m_watches)->setVisible(true);
621 dockParent(m_btWindow)->setVisible(true);
622 dockParent(m_bpTable)->setVisible(true);
625 bool DebuggerMainWnd::debugProgram(const QString& exe, const QString& lang)
627 // check the file name
628 QFileInfo fi(exe);
630 bool success = fi.isFile();
631 if (!success)
633 QString msg = i18n("`%1' is not a file or does not exist");
634 KMessageBox::sorry(this, msg.arg(exe));
636 else
638 success = startDriver(fi.absoluteFilePath(), lang);
641 if (success)
643 m_recentExecAction->addUrl(KUrl(fi.absoluteFilePath()));
645 // keep the directory
646 m_lastDirectory = fi.absolutePath();
647 m_filesWindow->setExtraDirectory(m_lastDirectory);
649 // set caption to basename part of executable
650 QString caption = fi.fileName();
651 setCaption(caption);
653 else
655 m_recentExecAction->removeUrl(KUrl(fi.absoluteFilePath()));
658 return success;
661 static const char GeneralGroup[] = "General";
663 bool DebuggerMainWnd::startDriver(const QString& executable, QString lang)
665 assert(m_debugger != 0);
667 TRACE(QString("trying language '%1'...").arg(lang));
668 DebuggerDriver* driver = driverFromLang(lang);
670 if (driver == 0)
672 // see if there is a language in the per-program config file
673 QString configName = m_debugger->getConfigForExe(executable);
674 if (QFile::exists(configName))
676 KConfig c(configName, KConfig::SimpleConfig);
678 // Using "GDB" as default here is for backwards compatibility:
679 // The config file exists but doesn't have an entry,
680 // so it must have been created by an old version of KDbg
681 // that had only the GDB driver.
682 lang = c.group(GeneralGroup)
683 .readEntry(KDebugger::DriverNameEntry, "GDB");
685 TRACE(QString("...bad, trying config driver %1...").arg(lang));
686 driver = driverFromLang(lang);
690 if (driver == 0)
692 QString name = driverNameFromFile(executable);
694 TRACE(QString("...no luck, trying %1 derived"
695 " from file contents").arg(name));
696 driver = driverFromLang(name);
698 if (driver == 0)
700 // oops
701 QString msg = i18n("Don't know how to debug language `%1'");
702 KMessageBox::sorry(this, msg.arg(lang));
703 return false;
706 driver->setLogFileName(m_transcriptFile);
708 bool success = m_debugger->debugProgram(executable, driver);
710 if (!success)
712 delete driver;
714 QString msg = i18n("Could not start the debugger process.\n"
715 "Please shut down KDbg and resolve the problem.");
716 KMessageBox::sorry(this, msg);
719 return success;
722 // derive driver from language
723 DebuggerDriver* DebuggerMainWnd::driverFromLang(QString lang)
725 // lang is needed in all lowercase
726 lang = lang.toLower();
728 // The following table relates languages and debugger drivers
729 static const struct L {
730 const char* shortest; // abbreviated to this is still unique
731 const char* full; // full name of language
732 int driver;
733 } langs[] = {
734 { "c", "c++", 1 },
735 { "f", "fortran", 1 },
736 { "p", "python", 3 },
737 { "x", "xslt", 2 },
738 // the following are actually driver names
739 { "gdb", "gdb", 1 },
740 { "xsldbg", "xsldbg", 2 },
742 const int N = sizeof(langs)/sizeof(langs[0]);
744 // lookup the language name
745 int driverID = 0;
746 for (int i = 0; i < N; i++)
748 const L& l = langs[i];
750 // shortest must match
751 if (!lang.startsWith(l.shortest))
752 continue;
754 // lang must not be longer than the full name, and it must match
755 if (QString(l.full).startsWith(lang))
757 driverID = l.driver;
758 break;
761 DebuggerDriver* driver = 0;
762 switch (driverID) {
763 case 1:
765 GdbDriver* gdb = new GdbDriver;
766 gdb->setDefaultInvocation(m_debuggerCmdStr);
767 driver = gdb;
769 break;
770 case 2:
771 driver = new XsldbgDriver;
772 break;
773 default:
774 // unknown language
775 break;
777 return driver;
781 * Try to guess the language to use from the contents of the file.
783 QString DebuggerMainWnd::driverNameFromFile(const QString& exe)
785 /* Inprecise but simple test to see if file is in XSLT language */
786 if (exe.right(4).toLower() == ".xsl")
787 return "XSLT";
789 return "GDB";
792 void DebuggerMainWnd::setCoreFile(const QString& corefile)
794 assert(m_debugger != 0);
795 m_debugger->useCoreFile(corefile, true);
798 void DebuggerMainWnd::setRemoteDevice(const QString& remoteDevice)
800 if (m_debugger != 0) {
801 m_debugger->setRemoteDevice(remoteDevice);
805 void DebuggerMainWnd::overrideProgramArguments(const QString& args)
807 assert(m_debugger != 0);
808 m_debugger->overrideProgramArguments(args);
811 void DebuggerMainWnd::setTranscript(const QString& name)
813 m_transcriptFile = name;
814 if (m_debugger != 0 && m_debugger->driver() != 0)
815 m_debugger->driver()->setLogFileName(m_transcriptFile);
818 void DebuggerMainWnd::setAttachPid(const QString& pid)
820 assert(m_debugger != 0);
821 m_debugger->setAttachPid(pid);
824 void DebuggerMainWnd::slotNewStatusMsg()
826 QString msg = m_debugger->statusMessage();
827 m_statusMsgLabel->setText(msg.trimmed());
830 void DebuggerMainWnd::slotFileGlobalSettings()
832 int oldTabWidth = m_tabWidth;
834 KPageDialog dlg(this);
835 QString title = KGlobal::caption();
836 title += i18n(": Global options");
837 dlg.setWindowTitle(title);
839 PrefDebugger prefDebugger(&dlg);
840 prefDebugger.setDebuggerCmd(m_debuggerCmdStr.isEmpty() ?
841 GdbDriver::defaultGdb() : m_debuggerCmdStr);
842 prefDebugger.setTerminal(m_outputTermCmdStr);
844 PrefMisc prefMisc(&dlg);
845 prefMisc.setPopIntoForeground(m_popForeground);
846 prefMisc.setBackTimeout(m_backTimeout);
847 prefMisc.setTabWidth(m_tabWidth);
848 prefMisc.setSourceFilter(m_sourceFilter);
849 prefMisc.setHeaderFilter(m_headerFilter);
851 dlg.addPage(&prefDebugger, i18n("Debugger"));
852 dlg.addPage(&prefMisc, i18n("Miscellaneous"));
853 if (dlg.exec() == QDialog::Accepted)
855 setDebuggerCmdStr(prefDebugger.debuggerCmd());
856 setTerminalCmd(prefDebugger.terminal());
857 m_popForeground = prefMisc.popIntoForeground();
858 m_backTimeout = prefMisc.backTimeout();
859 m_tabWidth = prefMisc.tabWidth();
860 m_sourceFilter = prefMisc.sourceFilter();
861 if (m_sourceFilter.isEmpty())
862 m_sourceFilter = defaultSourceFilter;
863 m_headerFilter = prefMisc.headerFilter();
864 if (m_headerFilter.isEmpty())
865 m_headerFilter = defaultHeaderFilter;
868 if (m_tabWidth != oldTabWidth) {
869 emit setTabWidth(m_tabWidth);
873 void DebuggerMainWnd::setTerminalCmd(const QString& cmd)
875 m_outputTermCmdStr = cmd;
876 // revert to default if empty
877 if (m_outputTermCmdStr.isEmpty()) {
878 m_outputTermCmdStr = defaultTermCmdStr;
882 void DebuggerMainWnd::setDebuggerCmdStr(const QString& cmd)
884 m_debuggerCmdStr = cmd;
885 // make empty if it is the default
886 if (m_debuggerCmdStr == GdbDriver::defaultGdb()) {
887 m_debuggerCmdStr = QString();
891 void DebuggerMainWnd::slotDebuggerStarting()
893 if (m_debugger == 0) /* paranoia check */
894 return;
896 if (m_ttyLevel == m_debugger->ttyLevel())
897 return;
899 // shut down terminal emulations we will not need
900 switch (m_ttyLevel) {
901 case KDebugger::ttySimpleOutputOnly:
902 m_ttyWindow->deactivate();
903 break;
904 case KDebugger::ttyFull:
905 m_outputTermProc->kill();
906 break;
907 default: break;
910 m_ttyLevel = m_debugger->ttyLevel();
912 QString ttyName;
913 switch (m_ttyLevel) {
914 case KDebugger::ttySimpleOutputOnly:
915 ttyName = m_ttyWindow->activate();
916 break;
917 case KDebugger::ttyFull:
918 // create an output window
919 ttyName = createOutputWindow();
920 TRACE(ttyName.isEmpty() ?
921 "createOuputWindow failed" : "successfully created output window");
922 break;
923 default: break;
926 m_debugger->setTerminal(ttyName);
929 void DebuggerMainWnd::slotToggleBreak(const QString& fileName, int lineNo,
930 const DbgAddr& address, bool temp)
932 // lineNo is zero-based
933 if (m_debugger != 0) {
934 m_debugger->setBreakpoint(fileName, lineNo, address, temp);
938 void DebuggerMainWnd::slotEnaDisBreak(const QString& fileName, int lineNo,
939 const DbgAddr& address)
941 // lineNo is zero-based
942 if (m_debugger != 0) {
943 m_debugger->enableDisableBreakpoint(fileName, lineNo, address);
947 QString DebuggerMainWnd::createOutputWindow()
949 // create a name for a fifo
950 QString fifoName;
951 fifoName.sprintf("/tmp/kdbgttywin%05d", ::getpid());
953 // create a fifo that will pass in the tty name
954 QFile::remove(fifoName); // remove remnants
955 #ifdef HAVE_MKFIFO
956 if (::mkfifo(fifoName.toLocal8Bit(), S_IRUSR|S_IWUSR) < 0) {
957 // failed
958 TRACE("mkfifo " + fifoName + " failed");
959 return QString();
961 #else
962 if (::mknod(fifoName.toLocal8Bit(), S_IFIFO | S_IRUSR|S_IWUSR, 0) < 0) {
963 // failed
964 TRACE("mknod " + fifoName + " failed");
965 return QString();
967 #endif
970 * Spawn an xterm that in turn runs a shell script that passes us
971 * back the terminal name and then only sits and waits.
973 static const char shellScriptFmt[] =
974 "tty>%s;"
975 "trap \"\" INT QUIT TSTP;" /* ignore various signals */
976 "exec<&-;exec>&-;" /* close stdin and stdout */
977 "while :;do sleep 3600;done";
978 // let config file override this script
979 QString shellScript;
980 if (!m_outputTermKeepScript.isEmpty()) {
981 shellScript = m_outputTermKeepScript;
982 } else {
983 shellScript = shellScriptFmt;
986 shellScript.replace("%s", fifoName);
987 TRACE("output window script is " + shellScript);
989 QString title = KGlobal::caption();
990 title += i18n(": Program output");
992 // parse the command line specified in the preferences
993 QStringList cmdParts = m_outputTermCmdStr.split(' ');
996 * Build the argv array. Thereby substitute special sequences:
998 struct {
999 char seq[4];
1000 QString replace;
1001 } substitute[] = {
1002 { "%T", title },
1003 { "%C", shellScript }
1006 for (QStringList::iterator i = cmdParts.begin(); i != cmdParts.end(); ++i)
1008 QString& str = *i;
1009 for (int j = sizeof(substitute)/sizeof(substitute[0])-1; j >= 0; j--) {
1010 int pos = str.indexOf(substitute[j].seq);
1011 if (pos >= 0) {
1012 str.replace(pos, 2, substitute[j].replace);
1013 break; /* substitute only one sequence */
1018 QString tty, pgm = cmdParts.takeFirst();
1020 m_outputTermProc->start(pgm, cmdParts);
1021 if (m_outputTermProc->waitForStarted())
1023 // read the ttyname from the fifo
1024 QFile f(fifoName);
1025 if (f.open(QIODevice::ReadOnly))
1027 QByteArray t = f.readAll();
1028 tty = QString::fromLocal8Bit(t, t.size());
1029 f.close();
1031 f.remove();
1033 // remove whitespace
1034 tty = tty.trimmed();
1035 TRACE("tty=" + tty);
1037 else
1039 // error, could not start xterm
1040 TRACE("fork failed for fifo " + fifoName);
1041 QFile::remove(fifoName);
1044 return tty;
1047 void DebuggerMainWnd::slotProgramStopped()
1049 // when the program stopped, move the window to the foreground
1050 if (m_popForeground) {
1051 // unfortunately, this requires quite some force to work :-(
1052 KWindowSystem::raiseWindow(winId());
1053 KWindowSystem::forceActiveWindow(winId());
1055 m_backTimer.stop();
1058 void DebuggerMainWnd::intoBackground()
1060 if (m_popForeground) {
1061 m_backTimer.setSingleShot(true);
1062 m_backTimer.start(m_backTimeout);
1066 void DebuggerMainWnd::slotBackTimer()
1068 lower();
1071 void DebuggerMainWnd::slotRecentExec(const KUrl& url)
1073 QString exe = url.path();
1074 debugProgram(exe, "");
1077 QString DebuggerMainWnd::makeSourceFilter()
1079 QString f;
1080 f = m_sourceFilter + " " + m_headerFilter + i18n("|All source files\n");
1081 f += m_sourceFilter + i18n("|Source files\n");
1082 f += m_headerFilter + i18n("|Header files\n");
1083 f += i18n("*|All files");
1084 return f;
1088 * Pop up the context menu in the locals window
1090 void DebuggerMainWnd::slotLocalsPopup(const QPoint& pt)
1092 QMenu* popup = static_cast<QMenu*>(factory()->container("popup_locals", this));
1093 if (popup == 0) {
1094 return;
1096 if (popup->isVisible()) {
1097 popup->hide();
1098 } else {
1099 popup->popup(m_localVariables->viewport()->mapToGlobal(pt));
1104 * Copies the currently selected item to the watch window.
1106 void DebuggerMainWnd::slotLocalsToWatch()
1108 VarTree* item = m_localVariables->selectedItem();
1110 if (item != 0 && m_debugger != 0) {
1111 QString text = item->computeExpr();
1112 m_debugger->addWatch(text);
1117 * Starts editing a value in a value display
1119 void DebuggerMainWnd::slotEditValue()
1121 // does one of the value trees have the focus
1122 QWidget* f = kapp->focusWidget();
1123 ExprWnd* wnd;
1124 if (f == m_localVariables) {
1125 wnd = m_localVariables;
1126 } else if (f == m_watches->watchVariables()) {
1127 wnd = m_watches->watchVariables();
1128 } else {
1129 return;
1132 if (m_localVariables->isEditing() ||
1133 m_watches->watchVariables()->isEditing())
1135 return; /* don't edit twice */
1138 VarTree* expr = wnd->selectedItem();
1139 if (expr != 0 && m_debugger != 0 && m_debugger->canSingleStep())
1141 TRACE("edit value");
1142 // determine the text to edit
1143 QString text = m_debugger->driver()->editableValue(expr);
1144 wnd->editValue(expr, text);
1148 // helper that gets a file name (it only differs in the caption of the dialog)
1149 static QString myGetFileName(QString caption,
1150 QString dir, QString filter,
1151 QWidget* parent)
1153 QString filename;
1154 KFileDialog dlg(dir, filter, parent);
1156 dlg.setWindowTitle(caption);
1158 if (dlg.exec() == QDialog::Accepted)
1159 filename = dlg.selectedFile();
1161 return filename;
1164 void DebuggerMainWnd::slotFileOpen()
1166 // start browsing in the active file's directory
1167 // fall back to last used directory (executable)
1168 QString dir = m_lastDirectory;
1169 QString fileName = m_filesWindow->activeFileName();
1170 if (!fileName.isEmpty()) {
1171 QFileInfo fi(fileName);
1172 dir = fi.path();
1175 fileName = myGetFileName(i18n("Open"),
1176 dir,
1177 makeSourceFilter(), this);
1179 if (!fileName.isEmpty())
1181 QFileInfo fi(fileName);
1182 m_lastDirectory = fi.path();
1183 m_filesWindow->setExtraDirectory(m_lastDirectory);
1184 m_filesWindow->activateFile(fileName);
1188 void DebuggerMainWnd::slotFileExe()
1190 if (m_debugger->isIdle())
1192 // open a new executable
1193 QString executable = myGetFileName(i18n("Select the executable to debug"),
1194 m_lastDirectory, 0, this);
1195 if (executable.isEmpty())
1196 return;
1198 debugProgram(executable, "");
1202 void DebuggerMainWnd::slotFileCore()
1204 if (m_debugger->canStart())
1206 QString corefile = myGetFileName(i18n("Select core dump"),
1207 m_lastDirectory, 0, this);
1208 if (!corefile.isEmpty()) {
1209 m_debugger->useCoreFile(corefile, false);
1214 void DebuggerMainWnd::slotFileProgSettings()
1216 if (m_debugger != 0) {
1217 m_debugger->programSettings(this);
1221 void DebuggerMainWnd::slotViewStatusbar()
1223 if (statusBar()->isVisible())
1224 statusBar()->hide();
1225 else
1226 statusBar()->show();
1227 setSettingsDirty();
1230 void DebuggerMainWnd::slotExecUntil()
1232 if (m_debugger != 0)
1234 QString file;
1235 int lineNo;
1236 if (m_filesWindow->activeLine(file, lineNo))
1237 m_debugger->runUntil(file, lineNo);
1241 void DebuggerMainWnd::slotExecAttach()
1243 #ifdef PS_COMMAND
1244 ProcAttachPS dlg(this);
1245 // seed filter with executable name
1246 QFileInfo fi = m_debugger->executable();
1247 dlg.setFilterText(fi.fileName());
1248 #else
1249 ProcAttach dlg(this);
1250 dlg.setText(m_debugger->attachedPid());
1251 #endif
1252 if (dlg.exec()) {
1253 m_debugger->attachProgram(dlg.text());
1257 void DebuggerMainWnd::slotExecArgs()
1259 if (m_debugger != 0) {
1260 m_debugger->programArgs(this);
1264 void DebuggerMainWnd::slotConfigureKeys()
1266 KShortcutsDialog::configure(actionCollection());
1269 #include "dbgmainwnd.moc"