Convert application singleton, command line parser, and About data.
[kdbg.git] / kdbg / dbgmainwnd.cpp
blob0a3678a3e21cf8471fbce374c2a61add3aa89943
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 <klocale.h> /* i18n */
8 #include <kmessagebox.h>
9 #include <kconfig.h>
10 #include <kconfiggroup.h>
11 #include <kicon.h>
12 #include <kiconloader.h>
13 #include <kstandardaction.h>
14 #include <kstandardshortcut.h>
15 #include <kactioncollection.h>
16 #include <krecentfilesaction.h>
17 #include <ktoggleaction.h>
18 #include <kshortcutsdialog.h>
19 #include <kanimatedbutton.h>
20 #include <kwindowsystem.h>
21 #include <ksqueezedtextlabel.h>
22 #include <ktoolbar.h>
23 #include <kxmlguifactory.h>
24 #include <KPageDialog>
25 #include <QListWidget>
26 #include <QFile>
27 #include <QFileDialog>
28 #include <QFileInfo>
29 #include <QGuiApplication>
30 #include <QList>
31 #include <QDockWidget>
32 #include <QProcess>
33 #include <QStatusBar>
34 #include <QUrl>
35 #include "dbgmainwnd.h"
36 #include "debugger.h"
37 #include "winstack.h"
38 #include "brkpt.h"
39 #include "threadlist.h"
40 #include "memwindow.h"
41 #include "ttywnd.h"
42 #include "watchwindow.h"
43 #include "procattach.h"
44 #include "prefdebugger.h"
45 #include "prefmisc.h"
46 #include "gdbdriver.h"
47 #include "xsldbgdriver.h"
48 #include "mydebug.h"
49 #include <sys/stat.h> /* mknod(2) */
50 #include <unistd.h> /* getpid */
53 static const char defaultTermCmdStr[] = "xterm -name kdbgio -title %T -e sh -c %C";
54 static const char defaultSourceFilter[] = "*.c *.cc *.cpp *.c++ *.C *.CC";
55 static const char defaultHeaderFilter[] = "*.h *.hh *.hpp *.h++";
57 DebuggerMainWnd::DebuggerMainWnd() :
58 KXmlGuiWindow(),
59 m_debugger(0),
60 #ifdef GDB_TRANSCRIPT
61 m_transcriptFile(GDB_TRANSCRIPT),
62 #endif
63 m_outputTermCmdStr(defaultTermCmdStr),
64 m_outputTermProc(new QProcess),
65 m_ttyLevel(-1), /* no tty yet */
66 m_popForeground(false),
67 m_backTimeout(1000),
68 m_tabWidth(0),
69 m_sourceFilter(defaultSourceFilter),
70 m_headerFilter(defaultHeaderFilter),
71 m_statusActive(i18n("active"))
73 setDockNestingEnabled(true);
75 m_filesWindow = new WinStack(this);
76 setCentralWidget(m_filesWindow);
78 QDockWidget* dw1 = createDockWidget("Stack", i18n("Stack"));
79 m_btWindow = new QListWidget(dw1);
80 dw1->setWidget(m_btWindow);
81 QDockWidget* dw2 = createDockWidget("Locals", i18n("Locals"));
82 m_localVariables = new ExprWnd(dw2, i18n("Variable"));
83 dw2->setWidget(m_localVariables);
84 QDockWidget* dw3 = createDockWidget("Watches", i18n("Watches"));
85 m_watches = new WatchWindow(dw3);
86 dw3->setWidget(m_watches);
87 QDockWidget* dw4 = createDockWidget("Registers", i18n("Registers"));
88 m_registers = new RegisterView(dw4);
89 dw4->setWidget(m_registers);
90 QDockWidget* dw5 = createDockWidget("Breakpoints", i18n("Breakpoints"));
91 m_bpTable = new BreakpointTable(dw5);
92 dw5->setWidget(m_bpTable);
93 QDockWidget* dw6 = createDockWidget("Output", i18n("Output"));
94 m_ttyWindow = new TTYWindow(dw6);
95 dw6->setWidget(m_ttyWindow);
96 QDockWidget* dw7 = createDockWidget("Threads", i18n("Threads"));
97 m_threads = new ThreadList(dw7);
98 dw7->setWidget(m_threads);
99 QDockWidget* dw8 = createDockWidget("Memory", i18n("Memory"));
100 m_memoryWindow = new MemoryWindow(dw8);
101 dw8->setWidget(m_memoryWindow);
103 m_debugger = new KDebugger(this, m_localVariables, m_watches->watchVariables(), m_btWindow);
105 connect(m_debugger, SIGNAL(updateStatusMessage()), SLOT(slotNewStatusMsg()));
106 connect(m_debugger, SIGNAL(updateUI()), SLOT(updateUI()));
107 connect(m_debugger, SIGNAL(breakpointsChanged()), SLOT(updateLineItems()));
108 connect(m_debugger, SIGNAL(debuggerStarting()), SLOT(slotDebuggerStarting()));
109 m_bpTable->setDebugger(m_debugger);
110 m_memoryWindow->setDebugger(m_debugger);
112 setStandardToolBarMenuEnabled(true);
113 initKAction();
114 initStatusBar();
116 connect(m_watches, SIGNAL(addWatch()), SLOT(slotAddWatch()));
117 connect(m_watches, SIGNAL(deleteWatch()), m_debugger, SLOT(slotDeleteWatch()));
118 connect(m_watches, SIGNAL(textDropped(const QString&)), SLOT(slotAddWatch(const QString&)));
120 connect(&m_filesWindow->m_findDlg, SIGNAL(closed()), SLOT(updateUI()));
121 connect(m_filesWindow, SIGNAL(newFileLoaded()),
122 SLOT(slotNewFileLoaded()));
123 connect(m_filesWindow, SIGNAL(toggleBreak(const QString&,int,const DbgAddr&,bool)),
124 this, SLOT(slotToggleBreak(const QString&,int,const DbgAddr&,bool)));
125 connect(m_filesWindow, SIGNAL(enadisBreak(const QString&,int,const DbgAddr&)),
126 this, SLOT(slotEnaDisBreak(const QString&,int,const DbgAddr&)));
127 connect(m_debugger, SIGNAL(activateFileLine(const QString&,int,const DbgAddr&)),
128 m_filesWindow, SLOT(activate(const QString&,int,const DbgAddr&)));
129 connect(m_debugger, SIGNAL(executableUpdated()),
130 m_filesWindow, SLOT(reloadAllFiles()));
131 connect(m_debugger, SIGNAL(updatePC(const QString&,int,const DbgAddr&,int)),
132 m_filesWindow, SLOT(updatePC(const QString&,int,const DbgAddr&,int)));
133 // value popup communication
134 connect(m_filesWindow, SIGNAL(initiateValuePopup(const QString&)),
135 m_debugger, SLOT(slotValuePopup(const QString&)));
136 connect(m_debugger, SIGNAL(valuePopup(const QString&)),
137 m_filesWindow, SLOT(slotShowValueTip(const QString&)));
138 // disassembling
139 connect(m_filesWindow, SIGNAL(disassemble(const QString&, int)),
140 m_debugger, SLOT(slotDisassemble(const QString&, int)));
141 connect(m_debugger, SIGNAL(disassembled(const QString&,int,const std::list<DisassembledCode>&)),
142 m_filesWindow, SLOT(slotDisassembled(const QString&,int,const std::list<DisassembledCode>&)));
143 connect(m_filesWindow, SIGNAL(moveProgramCounter(const QString&,int,const DbgAddr&)),
144 m_debugger, SLOT(setProgramCounter(const QString&,int,const DbgAddr&)));
145 // program stopped
146 connect(m_debugger, SIGNAL(programStopped()), SLOT(slotProgramStopped()));
147 connect(&m_backTimer, SIGNAL(timeout()), SLOT(slotBackTimer()));
148 // tab width
149 connect(this, SIGNAL(setTabWidth(int)), m_filesWindow, SIGNAL(setTabWidth(int)));
151 // connect breakpoint table
152 connect(m_bpTable, SIGNAL(activateFileLine(const QString&,int,const DbgAddr&)),
153 m_filesWindow, SLOT(activate(const QString&,int,const DbgAddr&)));
154 connect(m_debugger, SIGNAL(updateUI()), m_bpTable, SLOT(updateUI()));
155 connect(m_debugger, SIGNAL(breakpointsChanged()), m_bpTable, SLOT(updateBreakList()));
156 connect(m_debugger, SIGNAL(breakpointsChanged()), m_bpTable, SLOT(updateUI()));
158 connect(m_debugger, SIGNAL(registersChanged(const std::list<RegisterInfo>&)),
159 m_registers, SLOT(updateRegisters(const std::list<RegisterInfo>&)));
161 connect(m_debugger, SIGNAL(memoryDumpChanged(const QString&, const std::list<MemoryDump>&)),
162 m_memoryWindow, SLOT(slotNewMemoryDump(const QString&, const std::list<MemoryDump>&)));
163 connect(m_debugger, SIGNAL(saveProgramSpecific(KConfigBase*)),
164 m_memoryWindow, SLOT(saveProgramSpecific(KConfigBase*)));
165 connect(m_debugger, SIGNAL(restoreProgramSpecific(KConfigBase*)),
166 m_memoryWindow, SLOT(restoreProgramSpecific(KConfigBase*)));
168 // thread window
169 connect(m_debugger, SIGNAL(threadsChanged(const std::list<ThreadInfo>&)),
170 m_threads, SLOT(updateThreads(const std::list<ThreadInfo>&)));
171 connect(m_threads, SIGNAL(setThread(int)),
172 m_debugger, SLOT(setThread(int)));
174 // popup menu of the local variables window
175 m_localVariables->setContextMenuPolicy(Qt::CustomContextMenu);
176 connect(m_localVariables, SIGNAL(customContextMenuRequested(const QPoint&)),
177 this, SLOT(slotLocalsPopup(const QPoint&)));
179 makeDefaultLayout();
180 setupGUI(KXmlGuiWindow::Default, "kdbgui.rc");
181 restoreSettings(KSharedConfig::openConfig());
183 // The animation button is not part of the restored window state.
184 // We must create it after the toolbar was loaded.
185 initAnimation();
187 updateUI();
188 m_bpTable->updateUI();
191 DebuggerMainWnd::~DebuggerMainWnd()
193 saveSettings(KSharedConfig::openConfig());
194 // must delete m_debugger early since it references our windows
195 delete m_debugger;
196 m_debugger = 0;
198 delete m_memoryWindow;
199 delete m_threads;
200 delete m_ttyWindow;
201 delete m_bpTable;
202 delete m_registers;
203 delete m_watches;
204 delete m_localVariables;
205 delete m_btWindow;
206 delete m_filesWindow;
208 delete m_outputTermProc;
211 QDockWidget* DebuggerMainWnd::createDockWidget(const char* name, const QString& title)
213 QDockWidget* w = new QDockWidget(title, this);
214 w->setObjectName(name);
215 // view menu changes when docking state changes
216 connect(w, SIGNAL(visibilityChanged(bool)), SLOT(updateUI()));
217 return w;
220 QAction* DebuggerMainWnd::createAction(const QString& text, const char* icon,
221 int shortcut, const QObject* receiver,
222 const char* slot, const char* name)
224 QAction* a = actionCollection()->addAction(name);
225 a->setText(text);
226 a->setIcon(KIcon(icon));
227 if (shortcut)
228 actionCollection()->setDefaultShortcut(a, QKeySequence(shortcut));
229 connect(a, SIGNAL(triggered()), receiver, slot);
230 return a;
233 QAction* DebuggerMainWnd::createAction(const QString& text,
234 int shortcut, const QObject* receiver,
235 const char* slot, const char* name)
237 QAction* a = actionCollection()->addAction(name);
238 a->setText(text);
239 if (shortcut)
240 actionCollection()->setDefaultShortcut(a, QKeySequence(shortcut));
241 connect(a, SIGNAL(triggered()), receiver, slot);
242 return a;
246 void DebuggerMainWnd::initKAction()
248 // file menu
249 QAction* open = KStandardAction::open(this, SLOT(slotFileOpen()),
250 actionCollection());
251 open->setText(i18n("&Open Source..."));
252 m_closeAction = KStandardAction::close(m_filesWindow, SLOT(slotClose()), actionCollection());
253 m_reloadAction = createAction(i18n("&Reload Source"), "view-refresh", 0,
254 m_filesWindow, SLOT(slotFileReload()), "file_reload");
255 m_fileExecAction = createAction(i18n("&Executable..."),
256 "document-open-executable", 0,
257 this, SLOT(slotFileExe()), "file_executable");
258 m_recentExecAction = KStandardAction::openRecent(this, SLOT(slotRecentExec(const QUrl&)),
259 actionCollection());
260 m_recentExecAction->setObjectName("file_executable_recent");
261 m_recentExecAction->setText(i18n("Recent E&xecutables"));
262 m_coreDumpAction = createAction(i18n("&Core dump..."), 0,
263 this, SLOT(slotFileCore()), "file_core_dump");
264 KStandardAction::quit(this, SLOT(close()), actionCollection());
266 // settings menu
267 m_settingsAction = createAction(i18n("This &Program..."), 0,
268 this, SLOT(slotFileProgSettings()), "settings_program");
269 createAction(i18n("&Global Options..."), 0,
270 this, SLOT(slotFileGlobalSettings()), "settings_global");
271 KStandardAction::keyBindings(this, SLOT(slotConfigureKeys()), actionCollection());
272 KStandardAction::showStatusbar(this, SLOT(slotViewStatusbar()), actionCollection());
274 // view menu
275 m_findAction = KStandardAction::find(m_filesWindow, SLOT(slotViewFind()), actionCollection());
276 KStandardAction::findNext(m_filesWindow, SLOT(slotFindForward()), actionCollection());
277 KStandardAction::findPrev(m_filesWindow, SLOT(slotFindBackward()), actionCollection());
279 i18n("Source &code");
280 struct { QString text; QWidget* w; QString id; QAction** act; } dw[] = {
281 { i18n("Stac&k"), m_btWindow, "view_stack", &m_btWindowAction },
282 { i18n("&Locals"), m_localVariables, "view_locals", &m_localVariablesAction },
283 { i18n("&Watched expressions"), m_watches, "view_watched_expressions", &m_watchesAction },
284 { i18n("&Registers"), m_registers, "view_registers", &m_registersAction },
285 { i18n("&Breakpoints"), m_bpTable, "view_breakpoints", &m_bpTableAction },
286 { i18n("T&hreads"), m_threads, "view_threads", &m_threadsAction },
287 { i18n("&Output"), m_ttyWindow, "view_output", &m_ttyWindowAction },
288 { i18n("&Memory"), m_memoryWindow, "view_memory", &m_memoryWindowAction }
290 for (unsigned i = 0; i < sizeof(dw)/sizeof(dw[0]); i++) {
291 QDockWidget* d = dockParent(dw[i].w);
292 *dw[i].act = new KToggleAction(dw[i].text, actionCollection());
293 actionCollection()->addAction(dw[i].id, *dw[i].act);
294 connect(*dw[i].act, SIGNAL(triggered()), d, SLOT(show()));
297 // execution menu
298 m_runAction = createAction(i18n("&Run"),
299 "debug-run", Qt::Key_F5,
300 m_debugger, SLOT(programRun()), "exec_run");
301 connect(m_runAction, SIGNAL(triggered()), this, SLOT(intoBackground()));
302 m_stepIntoAction = createAction(i18n("Step &into"),
303 "debug-step-into", Qt::Key_F8,
304 m_debugger, SLOT(programStep()), "exec_step_into");
305 connect(m_stepIntoAction, SIGNAL(triggered()), this, SLOT(intoBackground()));
306 m_stepOverAction = createAction(i18n("Step &over"),
307 "debug-step-over", Qt::Key_F10,
308 m_debugger, SLOT(programNext()), "exec_step_over");
309 connect(m_stepOverAction, SIGNAL(triggered()), this, SLOT(intoBackground()));
310 m_stepOutAction = createAction(i18n("Step o&ut"),
311 "debug-step-out", Qt::Key_F6,
312 m_debugger, SLOT(programFinish()), "exec_step_out");
313 connect(m_stepOutAction, SIGNAL(triggered()), this, SLOT(intoBackground()));
314 m_toCursorAction = createAction(i18n("Run to &cursor"),
315 "debug-execute-to-cursor", Qt::Key_F7,
316 this, SLOT(slotExecUntil()), "exec_run_to_cursor");
317 connect(m_toCursorAction, SIGNAL(triggered()), this, SLOT(intoBackground()));
318 m_stepIntoIAction = createAction(i18n("Step i&nto by instruction"),
319 "debug-step-into-instruction", Qt::SHIFT+Qt::Key_F8,
320 m_debugger, SLOT(programStepi()), "exec_step_into_by_insn");
321 connect(m_stepIntoIAction, SIGNAL(triggered()), this, SLOT(intoBackground()));
322 m_stepOverIAction = createAction(i18n("Step o&ver by instruction"),
323 "debug-step-instruction", Qt::SHIFT+Qt::Key_F10,
324 m_debugger, SLOT(programNexti()), "exec_step_over_by_insn");
325 connect(m_stepOverIAction, SIGNAL(triggered()), this, SLOT(intoBackground()));
326 m_execMovePCAction = createAction(i18n("&Program counter to current line"),
327 "debug-run-cursor", 0,
328 m_filesWindow, SLOT(slotMoveProgramCounter()), "exec_movepc");
329 m_breakAction = createAction(i18n("&Break"), 0,
330 m_debugger, SLOT(programBreak()), "exec_break");
331 m_killAction = createAction(i18n("&Kill"), 0,
332 m_debugger, SLOT(programKill()), "exec_kill");
333 m_restartAction = createAction(i18n("Re&start"), 0,
334 m_debugger, SLOT(programRunAgain()), "exec_restart");
335 m_attachAction = createAction(i18n("A&ttach..."), 0,
336 this, SLOT(slotExecAttach()), "exec_attach");
337 m_detachAction = createAction(i18n("&Detach"), 0,
338 m_debugger, SLOT(programDetach()), "exec_detach");
339 m_argumentsAction = createAction(i18n("&Arguments..."), 0,
340 this, SLOT(slotExecArgs()), "exec_arguments");
342 // breakpoint menu
343 m_bpSetAction = createAction(i18n("Set/Clear &breakpoint"), "brkpt", Qt::Key_F9,
344 m_filesWindow, SLOT(slotBrkptSet()), "breakpoint_set");
345 m_bpSetTempAction = createAction(i18n("Set &temporary breakpoint"), Qt::SHIFT+Qt::Key_F9,
346 m_filesWindow, SLOT(slotBrkptSetTemp()), "breakpoint_set_temporary");
347 m_bpEnableAction = createAction(i18n("&Enable/Disable breakpoint"), Qt::CTRL+Qt::Key_F9,
348 m_filesWindow, SLOT(slotBrkptEnable()), "breakpoint_enable");
350 // only in popup menus
351 createAction(i18n("Watch Expression"), 0,
352 this, SLOT(slotLocalsToWatch()), "watch_expression");
353 m_editValueAction = createAction(i18n("Edit Value"), Qt::Key_F2,
354 this, SLOT(slotEditValue()), "edit_value");
356 // all actions force an UI update
357 QList<QAction*> actions = actionCollection()->actions();
358 foreach(QAction* action, actions) {
359 connect(action, SIGNAL(triggered()), this, SLOT(updateUI()));
363 void DebuggerMainWnd::initAnimation()
365 KToolBar* toolbar = toolBar("mainToolBar");
366 m_animation = new KAnimatedButton(toolbar);
367 toolbar->addWidget(m_animation);
368 m_animation->setAnimationPath(KIconLoader::global()->moviePath("pulse", KIconLoader::Toolbar));
369 connect(m_animation, SIGNAL(clicked(bool)), m_debugger, SLOT(programBreak()));
370 m_animRunning = false;
373 void DebuggerMainWnd::initStatusBar()
375 QStatusBar* statusbar = statusBar();
376 m_statusActiveLabel = new KSqueezedTextLabel(statusbar);
377 m_statusActiveLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
378 statusbar->addPermanentWidget(m_statusActiveLabel);
379 m_statusActiveLabel->show();
380 m_lastActiveStatusText = m_statusActive;
382 /* message pane */
383 m_statusMsgLabel = new KSqueezedTextLabel(statusbar);
384 m_statusMsgLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
385 statusbar->addPermanentWidget(m_statusMsgLabel);
386 m_statusMsgLabel->show();
388 // reserve some translations
389 i18n("Restart");
390 i18n("Core dump");
393 bool DebuggerMainWnd::queryClose()
395 if (m_debugger != 0) {
396 m_debugger->shutdown();
398 return true;
402 // instance properties
403 void DebuggerMainWnd::saveProperties(KConfigGroup& cg)
405 // session management
406 QString executable = "";
407 if (m_debugger != 0) {
408 executable = m_debugger->executable();
410 cg.writeEntry("executable", executable);
413 void DebuggerMainWnd::readProperties(const KConfigGroup& cg)
415 // session management
416 QString execName = cg.readEntry("executable");
418 TRACE("readProperties: executable=" + execName);
419 if (!execName.isEmpty()) {
420 debugProgram(execName, "");
424 static const char RecentExecutables[] = "RecentExecutables";
425 static const char LastSession[] = "LastSession";
426 static const char OutputWindowGroup[] = "OutputWindow";
427 static const char TermCmdStr[] = "TermCmdStr";
428 static const char KeepScript[] = "KeepScript";
429 static const char DebuggerGroup[] = "Debugger";
430 static const char DebuggerCmdStr[] = "DebuggerCmdStr";
431 static const char PreferencesGroup[] = "Preferences";
432 static const char PopForeground[] = "PopForeground";
433 static const char BackTimeout[] = "BackTimeout";
434 static const char TabWidth[] = "TabWidth";
435 static const char SourceFileFilter[] = "SourceFileFilter";
436 static const char HeaderFileFilter[] = "HeaderFileFilter";
438 void DebuggerMainWnd::saveSettings(KSharedConfigPtr config)
440 m_recentExecAction->saveEntries(config->group(RecentExecutables));
442 KConfigGroup lg = config->group(LastSession);
443 lg.writeEntry("Width0Locals", m_localVariables->columnWidth(0));
444 lg.writeEntry("Width0Watches", m_watches->columnWidth(0));
446 if (m_debugger != 0) {
447 m_debugger->saveSettings(config.data());
450 config->group(OutputWindowGroup).writeEntry(TermCmdStr, m_outputTermCmdStr);
451 config->group(DebuggerGroup).writeEntry(DebuggerCmdStr, m_debuggerCmdStr);
453 KConfigGroup pg(config->group(PreferencesGroup));
454 pg.writeEntry(PopForeground, m_popForeground);
455 pg.writeEntry(BackTimeout, m_backTimeout);
456 pg.writeEntry(TabWidth, m_tabWidth);
457 pg.writeEntry(SourceFileFilter, m_sourceFilter);
458 pg.writeEntry(HeaderFileFilter, m_headerFilter);
461 void DebuggerMainWnd::restoreSettings(KSharedConfigPtr config)
463 m_recentExecAction->loadEntries(config->group(RecentExecutables));
465 KConfigGroup lg = config->group(LastSession);
466 int w;
467 w = lg.readEntry("Width0Locals", -1);
468 if (w >= 0 && w < 30000)
469 m_localVariables->setColumnWidth(0, w);
470 w = lg.readEntry("Width0Watches", -1);
471 if (w >= 0 && w < 30000)
472 m_watches->setColumnWidth(0, w);
474 if (m_debugger != 0) {
475 m_debugger->restoreSettings(config.data());
478 KConfigGroup og(config->group(OutputWindowGroup));
480 * For debugging and emergency purposes, let the config file override
481 * the shell script that is used to keep the output window open. This
482 * string must have EXACTLY 1 %s sequence in it.
484 setTerminalCmd(og.readEntry(TermCmdStr, defaultTermCmdStr));
485 m_outputTermKeepScript = og.readEntry(KeepScript);
487 setDebuggerCmdStr(config->group(DebuggerGroup).readEntry(DebuggerCmdStr));
489 KConfigGroup pg(config->group(PreferencesGroup));
490 m_popForeground = pg.readEntry(PopForeground, false);
491 m_backTimeout = pg.readEntry(BackTimeout, 1000);
492 m_tabWidth = pg.readEntry(TabWidth, 0);
493 m_sourceFilter = pg.readEntry(SourceFileFilter, m_sourceFilter);
494 m_headerFilter = pg.readEntry(HeaderFileFilter, m_headerFilter);
496 emit setTabWidth(m_tabWidth);
499 void DebuggerMainWnd::updateUI()
501 m_findAction->setChecked(m_filesWindow->m_findDlg.isVisible());
502 m_findAction->setEnabled(m_filesWindow->hasWindows());
503 m_bpSetAction->setEnabled(m_debugger->canChangeBreakpoints());
504 m_bpSetTempAction->setEnabled(m_debugger->canChangeBreakpoints());
505 m_bpEnableAction->setEnabled(m_debugger->canChangeBreakpoints());
506 m_bpTableAction->setChecked(isDockVisible(m_bpTable));
507 m_btWindowAction->setChecked(isDockVisible(m_btWindow));
508 m_localVariablesAction->setChecked(isDockVisible(m_localVariables));
509 m_watchesAction->setChecked(isDockVisible(m_watches));
510 m_registersAction->setChecked(isDockVisible(m_registers));
511 m_threadsAction->setChecked(isDockVisible(m_threads));
512 m_memoryWindowAction->setChecked(isDockVisible(m_memoryWindow));
513 m_ttyWindowAction->setChecked(isDockVisible(m_ttyWindow));
515 m_fileExecAction->setEnabled(m_debugger->isIdle());
516 m_settingsAction->setEnabled(m_debugger->haveExecutable());
517 m_coreDumpAction->setEnabled(m_debugger->canStart());
518 m_closeAction->setEnabled(m_filesWindow->hasWindows());
519 m_reloadAction->setEnabled(m_filesWindow->hasWindows());
520 m_stepIntoAction->setEnabled(m_debugger->canSingleStep());
521 m_stepIntoIAction->setEnabled(m_debugger->canSingleStep());
522 m_stepOverAction->setEnabled(m_debugger->canSingleStep());
523 m_stepOverIAction->setEnabled(m_debugger->canSingleStep());
524 m_stepOutAction->setEnabled(m_debugger->canSingleStep());
525 m_toCursorAction->setEnabled(m_debugger->canSingleStep());
526 m_execMovePCAction->setEnabled(m_debugger->canSingleStep());
527 m_restartAction->setEnabled(m_debugger->canSingleStep());
528 m_attachAction->setEnabled(m_debugger->isReady());
529 m_detachAction->setEnabled(m_debugger->canSingleStep());
530 m_runAction->setEnabled(m_debugger->canStart() || m_debugger->canSingleStep());
531 m_killAction->setEnabled(m_debugger->haveExecutable() && m_debugger->isProgramActive());
532 m_breakAction->setEnabled(m_debugger->isProgramRunning());
533 m_argumentsAction->setEnabled(m_debugger->haveExecutable());
534 m_editValueAction->setEnabled(m_debugger->canSingleStep());
536 // animation
537 if (m_debugger->isIdle()) {
538 if (m_animRunning && m_animation) {
539 m_animation->stop();
540 m_animRunning = false;
542 } else {
543 if (!m_animRunning && m_animation) {
544 m_animation->start();
545 m_animRunning = true;
549 // update statusbar
550 QString newStatus;
551 if (m_debugger->isProgramActive())
552 newStatus = m_statusActive;
553 if (newStatus != m_lastActiveStatusText) {
554 m_statusActiveLabel->setText(newStatus);
555 m_lastActiveStatusText = newStatus;
559 void DebuggerMainWnd::updateLineItems()
561 m_filesWindow->updateLineItems(m_debugger);
564 void DebuggerMainWnd::slotAddWatch()
566 if (m_debugger != 0) {
567 QString t = m_watches->watchText();
568 m_debugger->addWatch(t);
572 void DebuggerMainWnd::slotAddWatch(const QString& text)
574 if (m_debugger != 0) {
575 m_debugger->addWatch(text);
579 void DebuggerMainWnd::slotNewFileLoaded()
581 // updates program counter in the new file
582 if (m_debugger != 0)
583 m_filesWindow->updateLineItems(m_debugger);
586 QDockWidget* DebuggerMainWnd::dockParent(QWidget* w)
588 while ((w = w->parentWidget()) != 0) {
589 if (QDockWidget* dock = qobject_cast<QDockWidget*>(w))
590 return dock;
592 return 0;
595 bool DebuggerMainWnd::isDockVisible(QWidget* w)
597 QDockWidget* d = dockParent(w);
598 return d != 0 && d->isVisible();
601 void DebuggerMainWnd::makeDefaultLayout()
603 // +---------------+---------+
604 // | Source | Locals |
605 // | | |
606 // |---------------+---------+
607 // |Stack, Brkpts, | Watches |
608 // |Output,... | |
609 // +---------------+---------+
611 addDockWidget(Qt::RightDockWidgetArea, dockParent(m_localVariables));
612 addDockWidget(Qt::BottomDockWidgetArea, dockParent(m_memoryWindow));
613 splitDockWidget(dockParent(m_memoryWindow), dockParent(m_threads), Qt::Horizontal);
614 tabifyDockWidget(dockParent(m_memoryWindow), dockParent(m_registers));
615 tabifyDockWidget(dockParent(m_registers), dockParent(m_bpTable));
616 tabifyDockWidget(dockParent(m_bpTable), dockParent(m_ttyWindow));
617 tabifyDockWidget(dockParent(m_ttyWindow), dockParent(m_btWindow));
618 tabifyDockWidget(dockParent(m_threads), dockParent(m_watches));
619 dockParent(m_localVariables)->setVisible(true);
620 dockParent(m_ttyWindow)->setVisible(true);
621 dockParent(m_watches)->setVisible(true);
622 dockParent(m_btWindow)->setVisible(true);
623 dockParent(m_bpTable)->setVisible(true);
626 bool DebuggerMainWnd::debugProgram(const QString& exe, const QString& lang)
628 // check the file name
629 QFileInfo fi(exe);
631 bool success = fi.isFile();
632 if (!success)
634 QString msg = i18n("`%1' is not a file or does not exist");
635 KMessageBox::sorry(this, msg.arg(exe));
637 else
639 success = startDriver(fi.absoluteFilePath(), lang);
642 if (success)
644 m_recentExecAction->addUrl(QUrl::fromLocalFile(fi.absoluteFilePath()));
646 // keep the directory
647 m_lastDirectory = fi.absolutePath();
648 m_filesWindow->setExtraDirectory(m_lastDirectory);
650 // set caption to basename part of executable
651 QString caption = fi.fileName();
652 setCaption(caption);
654 else
656 m_recentExecAction->removeUrl(QUrl::fromLocalFile(fi.absoluteFilePath()));
659 return success;
662 static const char GeneralGroup[] = "General";
664 bool DebuggerMainWnd::startDriver(const QString& executable, QString lang)
666 assert(m_debugger != 0);
668 TRACE(QString("trying language '%1'...").arg(lang));
669 DebuggerDriver* driver = driverFromLang(lang);
671 if (driver == 0)
673 // see if there is a language in the per-program config file
674 QString configName = m_debugger->getConfigForExe(executable);
675 if (QFile::exists(configName))
677 KConfig c(configName, KConfig::SimpleConfig);
679 // Using "GDB" as default here is for backwards compatibility:
680 // The config file exists but doesn't have an entry,
681 // so it must have been created by an old version of KDbg
682 // that had only the GDB driver.
683 lang = c.group(GeneralGroup)
684 .readEntry(KDebugger::DriverNameEntry, "GDB");
686 TRACE(QString("...bad, trying config driver %1...").arg(lang));
687 driver = driverFromLang(lang);
691 if (driver == 0)
693 QString name = driverNameFromFile(executable);
695 TRACE(QString("...no luck, trying %1 derived"
696 " from file contents").arg(name));
697 driver = driverFromLang(name);
699 if (driver == 0)
701 // oops
702 QString msg = i18n("Don't know how to debug language `%1'");
703 KMessageBox::sorry(this, msg.arg(lang));
704 return false;
707 driver->setLogFileName(m_transcriptFile);
709 bool success = m_debugger->debugProgram(executable, driver);
711 if (!success)
713 delete driver;
715 QString msg = i18n("Could not start the debugger process.\n"
716 "Please shut down KDbg and resolve the problem.");
717 KMessageBox::sorry(this, msg);
720 return success;
723 // derive driver from language
724 DebuggerDriver* DebuggerMainWnd::driverFromLang(QString lang)
726 // lang is needed in all lowercase
727 lang = lang.toLower();
729 // The following table relates languages and debugger drivers
730 static const struct L {
731 const char* shortest; // abbreviated to this is still unique
732 const char* full; // full name of language
733 int driver;
734 } langs[] = {
735 { "c", "c++", 1 },
736 { "f", "fortran", 1 },
737 { "p", "python", 3 },
738 { "x", "xslt", 2 },
739 // the following are actually driver names
740 { "gdb", "gdb", 1 },
741 { "xsldbg", "xsldbg", 2 },
743 const int N = sizeof(langs)/sizeof(langs[0]);
745 // lookup the language name
746 int driverID = 0;
747 for (int i = 0; i < N; i++)
749 const L& l = langs[i];
751 // shortest must match
752 if (!lang.startsWith(l.shortest))
753 continue;
755 // lang must not be longer than the full name, and it must match
756 if (QString(l.full).startsWith(lang))
758 driverID = l.driver;
759 break;
762 DebuggerDriver* driver = 0;
763 switch (driverID) {
764 case 1:
766 GdbDriver* gdb = new GdbDriver;
767 gdb->setDefaultInvocation(m_debuggerCmdStr);
768 driver = gdb;
770 break;
771 case 2:
772 driver = new XsldbgDriver;
773 break;
774 default:
775 // unknown language
776 break;
778 return driver;
782 * Try to guess the language to use from the contents of the file.
784 QString DebuggerMainWnd::driverNameFromFile(const QString& exe)
786 /* Inprecise but simple test to see if file is in XSLT language */
787 if (exe.right(4).toLower() == ".xsl")
788 return "XSLT";
790 return "GDB";
793 void DebuggerMainWnd::setCoreFile(const QString& corefile)
795 assert(m_debugger != 0);
796 m_debugger->useCoreFile(corefile, true);
799 void DebuggerMainWnd::setRemoteDevice(const QString& remoteDevice)
801 if (m_debugger != 0) {
802 m_debugger->setRemoteDevice(remoteDevice);
806 void DebuggerMainWnd::overrideProgramArguments(const QString& args)
808 assert(m_debugger != 0);
809 m_debugger->overrideProgramArguments(args);
812 void DebuggerMainWnd::setTranscript(const QString& name)
814 m_transcriptFile = name;
815 if (m_debugger != 0 && m_debugger->driver() != 0)
816 m_debugger->driver()->setLogFileName(m_transcriptFile);
819 void DebuggerMainWnd::setAttachPid(const QString& pid)
821 assert(m_debugger != 0);
822 m_debugger->setAttachPid(pid);
825 void DebuggerMainWnd::slotNewStatusMsg()
827 QString msg = m_debugger->statusMessage();
828 m_statusMsgLabel->setText(msg.trimmed());
831 void DebuggerMainWnd::slotFileGlobalSettings()
833 int oldTabWidth = m_tabWidth;
835 KPageDialog dlg(this);
836 dlg.setWindowTitle(i18n("Global Options"));
838 PrefDebugger prefDebugger(&dlg);
839 prefDebugger.setDebuggerCmd(m_debuggerCmdStr.isEmpty() ?
840 GdbDriver::defaultGdb() : m_debuggerCmdStr);
841 prefDebugger.setTerminal(m_outputTermCmdStr);
843 PrefMisc prefMisc(&dlg);
844 prefMisc.setPopIntoForeground(m_popForeground);
845 prefMisc.setBackTimeout(m_backTimeout);
846 prefMisc.setTabWidth(m_tabWidth);
847 prefMisc.setSourceFilter(m_sourceFilter);
848 prefMisc.setHeaderFilter(m_headerFilter);
850 dlg.addPage(&prefDebugger, i18n("Debugger"));
851 dlg.addPage(&prefMisc, i18n("Miscellaneous"));
852 if (dlg.exec() == QDialog::Accepted)
854 setDebuggerCmdStr(prefDebugger.debuggerCmd());
855 setTerminalCmd(prefDebugger.terminal());
856 m_popForeground = prefMisc.popIntoForeground();
857 m_backTimeout = prefMisc.backTimeout();
858 m_tabWidth = prefMisc.tabWidth();
859 m_sourceFilter = prefMisc.sourceFilter();
860 if (m_sourceFilter.isEmpty())
861 m_sourceFilter = defaultSourceFilter;
862 m_headerFilter = prefMisc.headerFilter();
863 if (m_headerFilter.isEmpty())
864 m_headerFilter = defaultHeaderFilter;
867 if (m_tabWidth != oldTabWidth) {
868 emit setTabWidth(m_tabWidth);
872 void DebuggerMainWnd::setTerminalCmd(const QString& cmd)
874 m_outputTermCmdStr = cmd;
875 // revert to default if empty
876 if (m_outputTermCmdStr.isEmpty()) {
877 m_outputTermCmdStr = defaultTermCmdStr;
881 void DebuggerMainWnd::setDebuggerCmdStr(const QString& cmd)
883 m_debuggerCmdStr = cmd;
884 // make empty if it is the default
885 if (m_debuggerCmdStr == GdbDriver::defaultGdb()) {
886 m_debuggerCmdStr = QString();
890 void DebuggerMainWnd::slotDebuggerStarting()
892 if (m_debugger == 0) /* paranoia check */
893 return;
895 if (m_ttyLevel == m_debugger->ttyLevel())
896 return;
898 // shut down terminal emulations we will not need
899 switch (m_ttyLevel) {
900 case KDebugger::ttySimpleOutputOnly:
901 m_ttyWindow->deactivate();
902 break;
903 case KDebugger::ttyFull:
904 m_outputTermProc->kill();
905 break;
906 default: break;
909 m_ttyLevel = m_debugger->ttyLevel();
911 QString ttyName;
912 switch (m_ttyLevel) {
913 case KDebugger::ttySimpleOutputOnly:
914 ttyName = m_ttyWindow->activate();
915 break;
916 case KDebugger::ttyFull:
917 // create an output window
918 ttyName = createOutputWindow();
919 TRACE(ttyName.isEmpty() ?
920 "createOuputWindow failed" : "successfully created output window");
921 break;
922 default: break;
925 m_debugger->setTerminal(ttyName);
928 void DebuggerMainWnd::slotToggleBreak(const QString& fileName, int lineNo,
929 const DbgAddr& address, bool temp)
931 // lineNo is zero-based
932 if (m_debugger != 0) {
933 m_debugger->setBreakpoint(fileName, lineNo, address, temp);
937 void DebuggerMainWnd::slotEnaDisBreak(const QString& fileName, int lineNo,
938 const DbgAddr& address)
940 // lineNo is zero-based
941 if (m_debugger != 0) {
942 m_debugger->enableDisableBreakpoint(fileName, lineNo, address);
946 QString DebuggerMainWnd::createOutputWindow()
948 // create a name for a fifo
949 QString fifoName;
950 fifoName.sprintf("/tmp/kdbgttywin%05d", ::getpid());
952 // create a fifo that will pass in the tty name
953 QFile::remove(fifoName); // remove remnants
954 #ifdef HAVE_MKFIFO
955 if (::mkfifo(fifoName.toLocal8Bit(), S_IRUSR|S_IWUSR) < 0) {
956 // failed
957 TRACE("mkfifo " + fifoName + " failed");
958 return QString();
960 #else
961 if (::mknod(fifoName.toLocal8Bit(), S_IFIFO | S_IRUSR|S_IWUSR, 0) < 0) {
962 // failed
963 TRACE("mknod " + fifoName + " failed");
964 return QString();
966 #endif
969 * Spawn an xterm that in turn runs a shell script that passes us
970 * back the terminal name and then only sits and waits.
972 static const char shellScriptFmt[] =
973 "tty>%s;"
974 "trap \"\" INT QUIT TSTP;" /* ignore various signals */
975 "exec<&-;exec>&-;" /* close stdin and stdout */
976 "while :;do sleep 3600;done";
977 // let config file override this script
978 QString shellScript;
979 if (!m_outputTermKeepScript.isEmpty()) {
980 shellScript = m_outputTermKeepScript;
981 } else {
982 shellScript = shellScriptFmt;
985 shellScript.replace("%s", fifoName);
986 TRACE("output window script is " + shellScript);
988 QString title = QGuiApplication::applicationDisplayName();
989 title += i18n(": Program output");
991 // parse the command line specified in the preferences
992 QStringList cmdParts = m_outputTermCmdStr.split(' ');
995 * Build the argv array. Thereby substitute special sequences:
997 struct {
998 char seq[4];
999 QString replace;
1000 } substitute[] = {
1001 { "%T", title },
1002 { "%C", shellScript }
1005 for (QStringList::iterator i = cmdParts.begin(); i != cmdParts.end(); ++i)
1007 QString& str = *i;
1008 for (int j = sizeof(substitute)/sizeof(substitute[0])-1; j >= 0; j--) {
1009 int pos = str.indexOf(substitute[j].seq);
1010 if (pos >= 0) {
1011 str.replace(pos, 2, substitute[j].replace);
1012 break; /* substitute only one sequence */
1017 QString tty, pgm = cmdParts.takeFirst();
1019 m_outputTermProc->start(pgm, cmdParts);
1020 if (m_outputTermProc->waitForStarted())
1022 // read the ttyname from the fifo
1023 QFile f(fifoName);
1024 if (f.open(QIODevice::ReadOnly))
1026 QByteArray t = f.readAll();
1027 tty = QString::fromLocal8Bit(t, t.size());
1028 f.close();
1030 f.remove();
1032 // remove whitespace
1033 tty = tty.trimmed();
1034 TRACE("tty=" + tty);
1036 else
1038 // error, could not start xterm
1039 TRACE("fork failed for fifo " + fifoName);
1040 QFile::remove(fifoName);
1043 return tty;
1046 void DebuggerMainWnd::slotProgramStopped()
1048 // when the program stopped, move the window to the foreground
1049 if (m_popForeground) {
1050 // unfortunately, this requires quite some force to work :-(
1051 KWindowSystem::raiseWindow(winId());
1052 KWindowSystem::forceActiveWindow(winId());
1054 m_backTimer.stop();
1057 void DebuggerMainWnd::intoBackground()
1059 if (m_popForeground) {
1060 m_backTimer.setSingleShot(true);
1061 m_backTimer.start(m_backTimeout);
1065 void DebuggerMainWnd::slotBackTimer()
1067 lower();
1070 void DebuggerMainWnd::slotRecentExec(const QUrl& url)
1072 QString exe = url.toLocalFile();
1073 debugProgram(exe, "");
1076 QString DebuggerMainWnd::makeSourceFilter()
1078 QString f;
1079 f = i18n("All source files") + " (" + m_sourceFilter + " " + m_headerFilter + ")";
1080 f += ";;" + i18n("Source files") + " (" + m_sourceFilter + ")";
1081 f += ";;" + i18n("Header files") + " (" + m_headerFilter + ")";
1082 f += ";;" + i18n("All files") + " (*)";
1083 return f;
1087 * Pop up the context menu in the locals window
1089 void DebuggerMainWnd::slotLocalsPopup(const QPoint& pt)
1091 QMenu* popup = static_cast<QMenu*>(factory()->container("popup_locals", this));
1092 if (popup == 0) {
1093 return;
1095 if (popup->isVisible()) {
1096 popup->hide();
1097 } else {
1098 popup->popup(m_localVariables->viewport()->mapToGlobal(pt));
1103 * Copies the currently selected item to the watch window.
1105 void DebuggerMainWnd::slotLocalsToWatch()
1107 VarTree* item = m_localVariables->selectedItem();
1109 if (item != 0 && m_debugger != 0) {
1110 QString text = item->computeExpr();
1111 m_debugger->addWatch(text);
1116 * Starts editing a value in a value display
1118 void DebuggerMainWnd::slotEditValue()
1120 // does one of the value trees have the focus
1121 QWidget* f = QApplication::focusWidget();
1122 ExprWnd* wnd;
1123 if (f == m_localVariables) {
1124 wnd = m_localVariables;
1125 } else if (f == m_watches->watchVariables()) {
1126 wnd = m_watches->watchVariables();
1127 } else {
1128 return;
1131 if (m_localVariables->isEditing() ||
1132 m_watches->watchVariables()->isEditing())
1134 return; /* don't edit twice */
1137 VarTree* expr = wnd->selectedItem();
1138 if (expr != 0 && m_debugger != 0 && m_debugger->canSingleStep())
1140 TRACE("edit value");
1141 // determine the text to edit
1142 QString text = m_debugger->driver()->editableValue(expr);
1143 wnd->editValue(expr, text);
1147 void DebuggerMainWnd::slotFileOpen()
1149 // start browsing in the active file's directory
1150 // fall back to last used directory (executable)
1151 QString dir = m_lastDirectory;
1152 QString fileName = m_filesWindow->activeFileName();
1153 if (!fileName.isEmpty()) {
1154 QFileInfo fi(fileName);
1155 dir = fi.path();
1158 fileName = QFileDialog::getOpenFileName(this,
1159 i18n("Open"), dir, makeSourceFilter());
1161 if (!fileName.isEmpty())
1163 QFileInfo fi(fileName);
1164 m_lastDirectory = fi.path();
1165 m_filesWindow->setExtraDirectory(m_lastDirectory);
1166 m_filesWindow->activateFile(fileName);
1170 void DebuggerMainWnd::slotFileExe()
1172 if (m_debugger->isIdle())
1174 // open a new executable
1175 QString executable = QFileDialog::getOpenFileName(this,
1176 i18n("Select the Executable to Debug"),
1177 m_lastDirectory);
1178 if (executable.isEmpty())
1179 return;
1181 debugProgram(executable, "");
1185 void DebuggerMainWnd::slotFileCore()
1187 if (m_debugger->canStart())
1189 QString corefile = QFileDialog::getOpenFileName(this,
1190 i18n("Select Core Dump"),
1191 m_lastDirectory);
1192 if (!corefile.isEmpty()) {
1193 m_debugger->useCoreFile(corefile, false);
1198 void DebuggerMainWnd::slotFileProgSettings()
1200 if (m_debugger != 0) {
1201 m_debugger->programSettings(this);
1205 void DebuggerMainWnd::slotViewStatusbar()
1207 if (statusBar()->isVisible())
1208 statusBar()->hide();
1209 else
1210 statusBar()->show();
1211 setSettingsDirty();
1214 void DebuggerMainWnd::slotExecUntil()
1216 if (m_debugger != 0)
1218 QString file;
1219 int lineNo;
1220 if (m_filesWindow->activeLine(file, lineNo))
1221 m_debugger->runUntil(file, lineNo);
1225 void DebuggerMainWnd::slotExecAttach()
1227 #ifdef PS_COMMAND
1228 ProcAttachPS dlg(this);
1229 // seed filter with executable name
1230 QFileInfo fi = m_debugger->executable();
1231 dlg.setFilterText(fi.fileName());
1232 #else
1233 ProcAttach dlg(this);
1234 dlg.setText(m_debugger->attachedPid());
1235 #endif
1236 if (dlg.exec()) {
1237 m_debugger->attachProgram(dlg.text());
1241 void DebuggerMainWnd::slotExecArgs()
1243 if (m_debugger != 0) {
1244 m_debugger->programArgs(this);
1248 void DebuggerMainWnd::slotConfigureKeys()
1250 KShortcutsDialog::configure(actionCollection());
1253 #include "dbgmainwnd.moc"