Generate and install scalable icons.
[kdbg.git] / kdbg / dbgmainwnd.cpp
blob8f0ab876f4c0cd23b74f844657cd09ed9dc39593
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 <kiconengine.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 <QIcon>
31 #include <QList>
32 #include <QDockWidget>
33 #include <QProcess>
34 #include <QStatusBar>
35 #include <QUrl>
36 #include "dbgmainwnd.h"
37 #include "debugger.h"
38 #include "winstack.h"
39 #include "brkpt.h"
40 #include "threadlist.h"
41 #include "memwindow.h"
42 #include "ttywnd.h"
43 #include "watchwindow.h"
44 #include "procattach.h"
45 #include "prefdebugger.h"
46 #include "prefmisc.h"
47 #include "gdbdriver.h"
48 #include "xsldbgdriver.h"
49 #include "mydebug.h"
50 #include <sys/stat.h> /* mknod(2) */
51 #include <unistd.h> /* getpid */
54 static const char defaultTermCmdStr[] = "xterm -name kdbgio -title %T -e sh -c %C";
55 static const char defaultSourceFilter[] = "*.c *.cc *.cpp *.c++ *.C *.CC";
56 static const char defaultHeaderFilter[] = "*.h *.hh *.hpp *.h++";
58 DebuggerMainWnd::DebuggerMainWnd() :
59 KXmlGuiWindow(),
60 m_debugger(0),
61 #ifdef GDB_TRANSCRIPT
62 m_transcriptFile(GDB_TRANSCRIPT),
63 #endif
64 m_outputTermCmdStr(defaultTermCmdStr),
65 m_outputTermProc(new QProcess),
66 m_ttyLevel(-1), /* no tty yet */
67 m_popForeground(false),
68 m_backTimeout(1000),
69 m_tabWidth(0),
70 m_sourceFilter(defaultSourceFilter),
71 m_headerFilter(defaultHeaderFilter),
72 m_statusActive(i18n("active"))
74 setDockNestingEnabled(true);
76 m_filesWindow = new WinStack(this);
77 setCentralWidget(m_filesWindow);
79 QDockWidget* dw1 = createDockWidget("Stack", i18n("Stack"));
80 m_btWindow = new QListWidget(dw1);
81 dw1->setWidget(m_btWindow);
82 QDockWidget* dw2 = createDockWidget("Locals", i18n("Locals"));
83 m_localVariables = new ExprWnd(dw2, i18n("Variable"));
84 dw2->setWidget(m_localVariables);
85 QDockWidget* dw3 = createDockWidget("Watches", i18n("Watches"));
86 m_watches = new WatchWindow(dw3);
87 dw3->setWidget(m_watches);
88 QDockWidget* dw4 = createDockWidget("Registers", i18n("Registers"));
89 m_registers = new RegisterView(dw4);
90 dw4->setWidget(m_registers);
91 QDockWidget* dw5 = createDockWidget("Breakpoints", i18n("Breakpoints"));
92 m_bpTable = new BreakpointTable(dw5);
93 dw5->setWidget(m_bpTable);
94 QDockWidget* dw6 = createDockWidget("Output", i18n("Output"));
95 m_ttyWindow = new TTYWindow(dw6);
96 dw6->setWidget(m_ttyWindow);
97 QDockWidget* dw7 = createDockWidget("Threads", i18n("Threads"));
98 m_threads = new ThreadList(dw7);
99 dw7->setWidget(m_threads);
100 QDockWidget* dw8 = createDockWidget("Memory", i18n("Memory"));
101 m_memoryWindow = new MemoryWindow(dw8);
102 dw8->setWidget(m_memoryWindow);
104 m_debugger = new KDebugger(this, m_localVariables, m_watches->watchVariables(), m_btWindow);
106 connect(m_debugger, SIGNAL(updateStatusMessage()), SLOT(slotNewStatusMsg()));
107 connect(m_debugger, SIGNAL(updateUI()), SLOT(updateUI()));
108 connect(m_debugger, SIGNAL(breakpointsChanged()), SLOT(updateLineItems()));
109 connect(m_debugger, SIGNAL(debuggerStarting()), SLOT(slotDebuggerStarting()));
110 m_bpTable->setDebugger(m_debugger);
111 m_memoryWindow->setDebugger(m_debugger);
113 setStandardToolBarMenuEnabled(true);
114 initKAction();
115 initStatusBar();
117 connect(m_watches, SIGNAL(addWatch()), SLOT(slotAddWatch()));
118 connect(m_watches, SIGNAL(deleteWatch()), m_debugger, SLOT(slotDeleteWatch()));
119 connect(m_watches, SIGNAL(textDropped(const QString&)), SLOT(slotAddWatch(const QString&)));
121 connect(&m_filesWindow->m_findDlg, SIGNAL(closed()), SLOT(updateUI()));
122 connect(m_filesWindow, SIGNAL(newFileLoaded()),
123 SLOT(slotNewFileLoaded()));
124 connect(m_filesWindow, SIGNAL(toggleBreak(const QString&,int,const DbgAddr&,bool)),
125 this, SLOT(slotToggleBreak(const QString&,int,const DbgAddr&,bool)));
126 connect(m_filesWindow, SIGNAL(enadisBreak(const QString&,int,const DbgAddr&)),
127 this, SLOT(slotEnaDisBreak(const QString&,int,const DbgAddr&)));
128 connect(m_debugger, SIGNAL(activateFileLine(const QString&,int,const DbgAddr&)),
129 m_filesWindow, SLOT(activate(const QString&,int,const DbgAddr&)));
130 connect(m_debugger, SIGNAL(executableUpdated()),
131 m_filesWindow, SLOT(reloadAllFiles()));
132 connect(m_debugger, SIGNAL(updatePC(const QString&,int,const DbgAddr&,int)),
133 m_filesWindow, SLOT(updatePC(const QString&,int,const DbgAddr&,int)));
134 // value popup communication
135 connect(m_filesWindow, SIGNAL(initiateValuePopup(const QString&)),
136 m_debugger, SLOT(slotValuePopup(const QString&)));
137 connect(m_debugger, SIGNAL(valuePopup(const QString&)),
138 m_filesWindow, SLOT(slotShowValueTip(const QString&)));
139 // disassembling
140 connect(m_filesWindow, SIGNAL(disassemble(const QString&, int)),
141 m_debugger, SLOT(slotDisassemble(const QString&, int)));
142 connect(m_debugger, SIGNAL(disassembled(const QString&,int,const std::list<DisassembledCode>&)),
143 m_filesWindow, SLOT(slotDisassembled(const QString&,int,const std::list<DisassembledCode>&)));
144 connect(m_filesWindow, SIGNAL(moveProgramCounter(const QString&,int,const DbgAddr&)),
145 m_debugger, SLOT(setProgramCounter(const QString&,int,const DbgAddr&)));
146 // program stopped
147 connect(m_debugger, SIGNAL(programStopped()), SLOT(slotProgramStopped()));
148 connect(&m_backTimer, SIGNAL(timeout()), SLOT(slotBackTimer()));
149 // tab width
150 connect(this, SIGNAL(setTabWidth(int)), m_filesWindow, SIGNAL(setTabWidth(int)));
152 // connect breakpoint table
153 connect(m_bpTable, SIGNAL(activateFileLine(const QString&,int,const DbgAddr&)),
154 m_filesWindow, SLOT(activate(const QString&,int,const DbgAddr&)));
155 connect(m_debugger, SIGNAL(updateUI()), m_bpTable, SLOT(updateUI()));
156 connect(m_debugger, SIGNAL(breakpointsChanged()), m_bpTable, SLOT(updateBreakList()));
157 connect(m_debugger, SIGNAL(breakpointsChanged()), m_bpTable, SLOT(updateUI()));
159 connect(m_debugger, SIGNAL(registersChanged(const std::list<RegisterInfo>&)),
160 m_registers, SLOT(updateRegisters(const std::list<RegisterInfo>&)));
162 connect(m_debugger, SIGNAL(memoryDumpChanged(const QString&, const std::list<MemoryDump>&)),
163 m_memoryWindow, SLOT(slotNewMemoryDump(const QString&, const std::list<MemoryDump>&)));
164 connect(m_debugger, SIGNAL(saveProgramSpecific(KConfigBase*)),
165 m_memoryWindow, SLOT(saveProgramSpecific(KConfigBase*)));
166 connect(m_debugger, SIGNAL(restoreProgramSpecific(KConfigBase*)),
167 m_memoryWindow, SLOT(restoreProgramSpecific(KConfigBase*)));
169 // thread window
170 connect(m_debugger, SIGNAL(threadsChanged(const std::list<ThreadInfo>&)),
171 m_threads, SLOT(updateThreads(const std::list<ThreadInfo>&)));
172 connect(m_threads, SIGNAL(setThread(int)),
173 m_debugger, SLOT(setThread(int)));
175 // popup menu of the local variables window
176 m_localVariables->setContextMenuPolicy(Qt::CustomContextMenu);
177 connect(m_localVariables, SIGNAL(customContextMenuRequested(const QPoint&)),
178 this, SLOT(slotLocalsPopup(const QPoint&)));
180 makeDefaultLayout();
181 setupGUI(KXmlGuiWindow::Default, "kdbgui.rc");
182 restoreSettings(KSharedConfig::openConfig());
184 // The animation button is not part of the restored window state.
185 // We must create it after the toolbar was loaded.
186 initAnimation();
188 updateUI();
189 m_bpTable->updateUI();
192 DebuggerMainWnd::~DebuggerMainWnd()
194 saveSettings(KSharedConfig::openConfig());
195 // must delete m_debugger early since it references our windows
196 delete m_debugger;
197 m_debugger = 0;
199 delete m_memoryWindow;
200 delete m_threads;
201 delete m_ttyWindow;
202 delete m_bpTable;
203 delete m_registers;
204 delete m_watches;
205 delete m_localVariables;
206 delete m_btWindow;
207 delete m_filesWindow;
209 delete m_outputTermProc;
212 QDockWidget* DebuggerMainWnd::createDockWidget(const char* name, const QString& title)
214 QDockWidget* w = new QDockWidget(title, this);
215 w->setObjectName(name);
216 // view menu changes when docking state changes
217 connect(w, SIGNAL(visibilityChanged(bool)), SLOT(updateUI()));
218 return w;
221 QAction* DebuggerMainWnd::createAction(const QString& text, const char* icon,
222 int shortcut, const QObject* receiver,
223 const char* slot, const char* name)
225 QAction* a = actionCollection()->addAction(name);
226 a->setText(text);
227 a->setIcon(QIcon(new KIconEngine(icon, KIconLoader::global())));
228 if (shortcut)
229 actionCollection()->setDefaultShortcut(a, QKeySequence(shortcut));
230 connect(a, SIGNAL(triggered()), receiver, slot);
231 return a;
234 QAction* DebuggerMainWnd::createAction(const QString& text,
235 int shortcut, const QObject* receiver,
236 const char* slot, const char* name)
238 QAction* a = actionCollection()->addAction(name);
239 a->setText(text);
240 if (shortcut)
241 actionCollection()->setDefaultShortcut(a, QKeySequence(shortcut));
242 connect(a, SIGNAL(triggered()), receiver, slot);
243 return a;
247 void DebuggerMainWnd::initKAction()
249 // file menu
250 QAction* open = KStandardAction::open(this, SLOT(slotFileOpen()),
251 actionCollection());
252 open->setText(i18n("&Open Source..."));
253 m_closeAction = KStandardAction::close(m_filesWindow, SLOT(slotClose()), actionCollection());
254 m_reloadAction = createAction(i18n("&Reload Source"), "view-refresh", 0,
255 m_filesWindow, SLOT(slotFileReload()), "file_reload");
256 m_fileExecAction = createAction(i18n("&Executable..."),
257 "document-open-executable", 0,
258 this, SLOT(slotFileExe()), "file_executable");
259 m_recentExecAction = KStandardAction::openRecent(this, SLOT(slotRecentExec(const QUrl&)),
260 actionCollection());
261 m_recentExecAction->setObjectName("file_executable_recent");
262 m_recentExecAction->setText(i18n("Recent E&xecutables"));
263 m_coreDumpAction = createAction(i18n("&Core dump..."), 0,
264 this, SLOT(slotFileCore()), "file_core_dump");
265 KStandardAction::quit(this, SLOT(close()), actionCollection());
267 // settings menu
268 m_settingsAction = createAction(i18n("This &Program..."), 0,
269 this, SLOT(slotFileProgSettings()), "settings_program");
270 createAction(i18n("&Global Options..."), 0,
271 this, SLOT(slotFileGlobalSettings()), "settings_global");
272 KStandardAction::keyBindings(this, SLOT(slotConfigureKeys()), actionCollection());
273 KStandardAction::showStatusbar(this, SLOT(slotViewStatusbar()), actionCollection());
275 // view menu
276 m_findAction = KStandardAction::find(m_filesWindow, SLOT(slotViewFind()), actionCollection());
277 KStandardAction::findNext(m_filesWindow, SLOT(slotFindForward()), actionCollection());
278 KStandardAction::findPrev(m_filesWindow, SLOT(slotFindBackward()), actionCollection());
280 i18n("Source &code");
281 struct { QString text; QWidget* w; QString id; QAction** act; } dw[] = {
282 { i18n("Stac&k"), m_btWindow, "view_stack", &m_btWindowAction },
283 { i18n("&Locals"), m_localVariables, "view_locals", &m_localVariablesAction },
284 { i18n("&Watched expressions"), m_watches, "view_watched_expressions", &m_watchesAction },
285 { i18n("&Registers"), m_registers, "view_registers", &m_registersAction },
286 { i18n("&Breakpoints"), m_bpTable, "view_breakpoints", &m_bpTableAction },
287 { i18n("T&hreads"), m_threads, "view_threads", &m_threadsAction },
288 { i18n("&Output"), m_ttyWindow, "view_output", &m_ttyWindowAction },
289 { i18n("&Memory"), m_memoryWindow, "view_memory", &m_memoryWindowAction }
291 for (unsigned i = 0; i < sizeof(dw)/sizeof(dw[0]); i++) {
292 QDockWidget* d = dockParent(dw[i].w);
293 *dw[i].act = new KToggleAction(dw[i].text, actionCollection());
294 actionCollection()->addAction(dw[i].id, *dw[i].act);
295 connect(*dw[i].act, SIGNAL(triggered()), d, SLOT(show()));
298 // execution menu
299 m_runAction = createAction(i18n("&Run"),
300 "debug-run", Qt::Key_F5,
301 m_debugger, SLOT(programRun()), "exec_run");
302 connect(m_runAction, SIGNAL(triggered()), this, SLOT(intoBackground()));
303 m_stepIntoAction = createAction(i18n("Step &into"),
304 "debug-step-into", Qt::Key_F8,
305 m_debugger, SLOT(programStep()), "exec_step_into");
306 connect(m_stepIntoAction, SIGNAL(triggered()), this, SLOT(intoBackground()));
307 m_stepOverAction = createAction(i18n("Step &over"),
308 "debug-step-over", Qt::Key_F10,
309 m_debugger, SLOT(programNext()), "exec_step_over");
310 connect(m_stepOverAction, SIGNAL(triggered()), this, SLOT(intoBackground()));
311 m_stepOutAction = createAction(i18n("Step o&ut"),
312 "debug-step-out", Qt::Key_F6,
313 m_debugger, SLOT(programFinish()), "exec_step_out");
314 connect(m_stepOutAction, SIGNAL(triggered()), this, SLOT(intoBackground()));
315 m_toCursorAction = createAction(i18n("Run to &cursor"),
316 "debug-execute-to-cursor", Qt::Key_F7,
317 this, SLOT(slotExecUntil()), "exec_run_to_cursor");
318 connect(m_toCursorAction, SIGNAL(triggered()), this, SLOT(intoBackground()));
319 m_stepIntoIAction = createAction(i18n("Step i&nto by instruction"),
320 "debug-step-into-instruction", Qt::SHIFT+Qt::Key_F8,
321 m_debugger, SLOT(programStepi()), "exec_step_into_by_insn");
322 connect(m_stepIntoIAction, SIGNAL(triggered()), this, SLOT(intoBackground()));
323 m_stepOverIAction = createAction(i18n("Step o&ver by instruction"),
324 "debug-step-instruction", Qt::SHIFT+Qt::Key_F10,
325 m_debugger, SLOT(programNexti()), "exec_step_over_by_insn");
326 connect(m_stepOverIAction, SIGNAL(triggered()), this, SLOT(intoBackground()));
327 m_execMovePCAction = createAction(i18n("&Program counter to current line"),
328 "debug-run-cursor", 0,
329 m_filesWindow, SLOT(slotMoveProgramCounter()), "exec_movepc");
330 m_breakAction = createAction(i18n("&Break"), 0,
331 m_debugger, SLOT(programBreak()), "exec_break");
332 m_killAction = createAction(i18n("&Kill"), 0,
333 m_debugger, SLOT(programKill()), "exec_kill");
334 m_restartAction = createAction(i18n("Re&start"), 0,
335 m_debugger, SLOT(programRunAgain()), "exec_restart");
336 m_attachAction = createAction(i18n("A&ttach..."), 0,
337 this, SLOT(slotExecAttach()), "exec_attach");
338 m_detachAction = createAction(i18n("&Detach"), 0,
339 m_debugger, SLOT(programDetach()), "exec_detach");
340 m_argumentsAction = createAction(i18n("&Arguments..."), 0,
341 this, SLOT(slotExecArgs()), "exec_arguments");
343 // breakpoint menu
344 m_bpSetAction = createAction(i18n("Set/Clear &breakpoint"), "brkpt", Qt::Key_F9,
345 m_filesWindow, SLOT(slotBrkptSet()), "breakpoint_set");
346 m_bpSetTempAction = createAction(i18n("Set &temporary breakpoint"), Qt::SHIFT+Qt::Key_F9,
347 m_filesWindow, SLOT(slotBrkptSetTemp()), "breakpoint_set_temporary");
348 m_bpEnableAction = createAction(i18n("&Enable/Disable breakpoint"), Qt::CTRL+Qt::Key_F9,
349 m_filesWindow, SLOT(slotBrkptEnable()), "breakpoint_enable");
351 // only in popup menus
352 createAction(i18n("Watch Expression"), 0,
353 this, SLOT(slotLocalsToWatch()), "watch_expression");
354 m_editValueAction = createAction(i18n("Edit Value"), Qt::Key_F2,
355 this, SLOT(slotEditValue()), "edit_value");
357 // all actions force an UI update
358 QList<QAction*> actions = actionCollection()->actions();
359 foreach(QAction* action, actions) {
360 connect(action, SIGNAL(triggered()), this, SLOT(updateUI()));
364 void DebuggerMainWnd::initAnimation()
366 KToolBar* toolbar = toolBar("mainToolBar");
367 m_animation = new KAnimatedButton(toolbar);
368 toolbar->addWidget(m_animation);
369 m_animation->setAnimationPath(KIconLoader::global()->moviePath("pulse", KIconLoader::Toolbar));
370 connect(m_animation, SIGNAL(clicked(bool)), m_debugger, SLOT(programBreak()));
371 m_animRunning = false;
374 void DebuggerMainWnd::initStatusBar()
376 QStatusBar* statusbar = statusBar();
377 m_statusActiveLabel = new KSqueezedTextLabel(statusbar);
378 m_statusActiveLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
379 statusbar->addPermanentWidget(m_statusActiveLabel);
380 m_statusActiveLabel->show();
381 m_lastActiveStatusText = m_statusActive;
383 /* message pane */
384 m_statusMsgLabel = new KSqueezedTextLabel(statusbar);
385 m_statusMsgLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
386 statusbar->addPermanentWidget(m_statusMsgLabel);
387 m_statusMsgLabel->show();
389 // reserve some translations
390 i18n("Restart");
391 i18n("Core dump");
394 bool DebuggerMainWnd::queryClose()
396 if (m_debugger != 0) {
397 m_debugger->shutdown();
399 return true;
403 // instance properties
404 void DebuggerMainWnd::saveProperties(KConfigGroup& cg)
406 // session management
407 QString executable = "";
408 if (m_debugger != 0) {
409 executable = m_debugger->executable();
411 cg.writeEntry("executable", executable);
414 void DebuggerMainWnd::readProperties(const KConfigGroup& cg)
416 // session management
417 QString execName = cg.readEntry("executable");
419 TRACE("readProperties: executable=" + execName);
420 if (!execName.isEmpty()) {
421 debugProgram(execName, "");
425 static const char RecentExecutables[] = "RecentExecutables";
426 static const char LastSession[] = "LastSession";
427 static const char OutputWindowGroup[] = "OutputWindow";
428 static const char TermCmdStr[] = "TermCmdStr";
429 static const char KeepScript[] = "KeepScript";
430 static const char DebuggerGroup[] = "Debugger";
431 static const char DebuggerCmdStr[] = "DebuggerCmdStr";
432 static const char PreferencesGroup[] = "Preferences";
433 static const char PopForeground[] = "PopForeground";
434 static const char BackTimeout[] = "BackTimeout";
435 static const char TabWidth[] = "TabWidth";
436 static const char SourceFileFilter[] = "SourceFileFilter";
437 static const char HeaderFileFilter[] = "HeaderFileFilter";
439 void DebuggerMainWnd::saveSettings(KSharedConfigPtr config)
441 m_recentExecAction->saveEntries(config->group(RecentExecutables));
443 KConfigGroup lg = config->group(LastSession);
444 lg.writeEntry("Width0Locals", m_localVariables->columnWidth(0));
445 lg.writeEntry("Width0Watches", m_watches->columnWidth(0));
447 if (m_debugger != 0) {
448 m_debugger->saveSettings(config.data());
451 config->group(OutputWindowGroup).writeEntry(TermCmdStr, m_outputTermCmdStr);
452 config->group(DebuggerGroup).writeEntry(DebuggerCmdStr, m_debuggerCmdStr);
454 KConfigGroup pg(config->group(PreferencesGroup));
455 pg.writeEntry(PopForeground, m_popForeground);
456 pg.writeEntry(BackTimeout, m_backTimeout);
457 pg.writeEntry(TabWidth, m_tabWidth);
458 pg.writeEntry(SourceFileFilter, m_sourceFilter);
459 pg.writeEntry(HeaderFileFilter, m_headerFilter);
462 void DebuggerMainWnd::restoreSettings(KSharedConfigPtr config)
464 m_recentExecAction->loadEntries(config->group(RecentExecutables));
466 KConfigGroup lg = config->group(LastSession);
467 int w;
468 w = lg.readEntry("Width0Locals", -1);
469 if (w >= 0 && w < 30000)
470 m_localVariables->setColumnWidth(0, w);
471 w = lg.readEntry("Width0Watches", -1);
472 if (w >= 0 && w < 30000)
473 m_watches->setColumnWidth(0, w);
475 if (m_debugger != 0) {
476 m_debugger->restoreSettings(config.data());
479 KConfigGroup og(config->group(OutputWindowGroup));
481 * For debugging and emergency purposes, let the config file override
482 * the shell script that is used to keep the output window open. This
483 * string must have EXACTLY 1 %s sequence in it.
485 setTerminalCmd(og.readEntry(TermCmdStr, defaultTermCmdStr));
486 m_outputTermKeepScript = og.readEntry(KeepScript);
488 setDebuggerCmdStr(config->group(DebuggerGroup).readEntry(DebuggerCmdStr));
490 KConfigGroup pg(config->group(PreferencesGroup));
491 m_popForeground = pg.readEntry(PopForeground, false);
492 m_backTimeout = pg.readEntry(BackTimeout, 1000);
493 m_tabWidth = pg.readEntry(TabWidth, 0);
494 m_sourceFilter = pg.readEntry(SourceFileFilter, m_sourceFilter);
495 m_headerFilter = pg.readEntry(HeaderFileFilter, m_headerFilter);
497 emit setTabWidth(m_tabWidth);
500 void DebuggerMainWnd::updateUI()
502 m_findAction->setChecked(m_filesWindow->m_findDlg.isVisible());
503 m_findAction->setEnabled(m_filesWindow->hasWindows());
504 m_bpSetAction->setEnabled(m_debugger->canChangeBreakpoints());
505 m_bpSetTempAction->setEnabled(m_debugger->canChangeBreakpoints());
506 m_bpEnableAction->setEnabled(m_debugger->canChangeBreakpoints());
507 m_bpTableAction->setChecked(isDockVisible(m_bpTable));
508 m_btWindowAction->setChecked(isDockVisible(m_btWindow));
509 m_localVariablesAction->setChecked(isDockVisible(m_localVariables));
510 m_watchesAction->setChecked(isDockVisible(m_watches));
511 m_registersAction->setChecked(isDockVisible(m_registers));
512 m_threadsAction->setChecked(isDockVisible(m_threads));
513 m_memoryWindowAction->setChecked(isDockVisible(m_memoryWindow));
514 m_ttyWindowAction->setChecked(isDockVisible(m_ttyWindow));
516 m_fileExecAction->setEnabled(m_debugger->isIdle());
517 m_settingsAction->setEnabled(m_debugger->haveExecutable());
518 m_coreDumpAction->setEnabled(m_debugger->canStart());
519 m_closeAction->setEnabled(m_filesWindow->hasWindows());
520 m_reloadAction->setEnabled(m_filesWindow->hasWindows());
521 m_stepIntoAction->setEnabled(m_debugger->canSingleStep());
522 m_stepIntoIAction->setEnabled(m_debugger->canSingleStep());
523 m_stepOverAction->setEnabled(m_debugger->canSingleStep());
524 m_stepOverIAction->setEnabled(m_debugger->canSingleStep());
525 m_stepOutAction->setEnabled(m_debugger->canSingleStep());
526 m_toCursorAction->setEnabled(m_debugger->canSingleStep());
527 m_execMovePCAction->setEnabled(m_debugger->canSingleStep());
528 m_restartAction->setEnabled(m_debugger->canSingleStep());
529 m_attachAction->setEnabled(m_debugger->isReady());
530 m_detachAction->setEnabled(m_debugger->canSingleStep());
531 m_runAction->setEnabled(m_debugger->canStart() || m_debugger->canSingleStep());
532 m_killAction->setEnabled(m_debugger->haveExecutable() && m_debugger->isProgramActive());
533 m_breakAction->setEnabled(m_debugger->isProgramRunning());
534 m_argumentsAction->setEnabled(m_debugger->haveExecutable());
535 m_editValueAction->setEnabled(m_debugger->canSingleStep());
537 // animation
538 if (m_debugger->isIdle()) {
539 if (m_animRunning && m_animation) {
540 m_animation->stop();
541 m_animRunning = false;
543 } else {
544 if (!m_animRunning && m_animation) {
545 m_animation->start();
546 m_animRunning = true;
550 // update statusbar
551 QString newStatus;
552 if (m_debugger->isProgramActive())
553 newStatus = m_statusActive;
554 if (newStatus != m_lastActiveStatusText) {
555 m_statusActiveLabel->setText(newStatus);
556 m_lastActiveStatusText = newStatus;
560 void DebuggerMainWnd::updateLineItems()
562 m_filesWindow->updateLineItems(m_debugger);
565 void DebuggerMainWnd::slotAddWatch()
567 if (m_debugger != 0) {
568 QString t = m_watches->watchText();
569 m_debugger->addWatch(t);
573 void DebuggerMainWnd::slotAddWatch(const QString& text)
575 if (m_debugger != 0) {
576 m_debugger->addWatch(text);
580 void DebuggerMainWnd::slotNewFileLoaded()
582 // updates program counter in the new file
583 if (m_debugger != 0)
584 m_filesWindow->updateLineItems(m_debugger);
587 QDockWidget* DebuggerMainWnd::dockParent(QWidget* w)
589 while ((w = w->parentWidget()) != 0) {
590 if (QDockWidget* dock = qobject_cast<QDockWidget*>(w))
591 return dock;
593 return 0;
596 bool DebuggerMainWnd::isDockVisible(QWidget* w)
598 QDockWidget* d = dockParent(w);
599 return d != 0 && d->isVisible();
602 void DebuggerMainWnd::makeDefaultLayout()
604 // +---------------+---------+
605 // | Source | Locals |
606 // | | |
607 // |---------------+---------+
608 // |Stack, Brkpts, | Watches |
609 // |Output,... | |
610 // +---------------+---------+
612 addDockWidget(Qt::RightDockWidgetArea, dockParent(m_localVariables));
613 addDockWidget(Qt::BottomDockWidgetArea, dockParent(m_memoryWindow));
614 splitDockWidget(dockParent(m_memoryWindow), dockParent(m_threads), Qt::Horizontal);
615 tabifyDockWidget(dockParent(m_memoryWindow), dockParent(m_registers));
616 tabifyDockWidget(dockParent(m_registers), dockParent(m_bpTable));
617 tabifyDockWidget(dockParent(m_bpTable), dockParent(m_ttyWindow));
618 tabifyDockWidget(dockParent(m_ttyWindow), dockParent(m_btWindow));
619 tabifyDockWidget(dockParent(m_threads), dockParent(m_watches));
620 dockParent(m_localVariables)->setVisible(true);
621 dockParent(m_ttyWindow)->setVisible(true);
622 dockParent(m_watches)->setVisible(true);
623 dockParent(m_btWindow)->setVisible(true);
624 dockParent(m_bpTable)->setVisible(true);
627 bool DebuggerMainWnd::debugProgram(const QString& exe, const QString& lang)
629 // check the file name
630 QFileInfo fi(exe);
632 bool success = fi.isFile();
633 if (!success)
635 QString msg = i18n("`%1' is not a file or does not exist");
636 KMessageBox::sorry(this, msg.arg(exe));
638 else
640 success = startDriver(fi.absoluteFilePath(), lang);
643 if (success)
645 m_recentExecAction->addUrl(QUrl::fromLocalFile(fi.absoluteFilePath()));
647 // keep the directory
648 m_lastDirectory = fi.absolutePath();
649 m_filesWindow->setExtraDirectory(m_lastDirectory);
651 // set caption to basename part of executable
652 QString caption = fi.fileName();
653 setCaption(caption);
655 else
657 m_recentExecAction->removeUrl(QUrl::fromLocalFile(fi.absoluteFilePath()));
660 return success;
663 static const char GeneralGroup[] = "General";
665 bool DebuggerMainWnd::startDriver(const QString& executable, QString lang)
667 assert(m_debugger != 0);
669 TRACE(QString("trying language '%1'...").arg(lang));
670 DebuggerDriver* driver = driverFromLang(lang);
672 if (driver == 0)
674 // see if there is a language in the per-program config file
675 QString configName = m_debugger->getConfigForExe(executable);
676 if (QFile::exists(configName))
678 KConfig c(configName, KConfig::SimpleConfig);
680 // Using "GDB" as default here is for backwards compatibility:
681 // The config file exists but doesn't have an entry,
682 // so it must have been created by an old version of KDbg
683 // that had only the GDB driver.
684 lang = c.group(GeneralGroup)
685 .readEntry(KDebugger::DriverNameEntry, "GDB");
687 TRACE(QString("...bad, trying config driver %1...").arg(lang));
688 driver = driverFromLang(lang);
692 if (driver == 0)
694 QString name = driverNameFromFile(executable);
696 TRACE(QString("...no luck, trying %1 derived"
697 " from file contents").arg(name));
698 driver = driverFromLang(name);
700 if (driver == 0)
702 // oops
703 QString msg = i18n("Don't know how to debug language `%1'");
704 KMessageBox::sorry(this, msg.arg(lang));
705 return false;
708 driver->setLogFileName(m_transcriptFile);
710 bool success = m_debugger->debugProgram(executable, driver);
712 if (!success)
714 delete driver;
716 QString msg = i18n("Could not start the debugger process.\n"
717 "Please shut down KDbg and resolve the problem.");
718 KMessageBox::sorry(this, msg);
721 return success;
724 // derive driver from language
725 DebuggerDriver* DebuggerMainWnd::driverFromLang(QString lang)
727 // lang is needed in all lowercase
728 lang = lang.toLower();
730 // The following table relates languages and debugger drivers
731 static const struct L {
732 const char* shortest; // abbreviated to this is still unique
733 const char* full; // full name of language
734 int driver;
735 } langs[] = {
736 { "c", "c++", 1 },
737 { "f", "fortran", 1 },
738 { "p", "python", 3 },
739 { "x", "xslt", 2 },
740 // the following are actually driver names
741 { "gdb", "gdb", 1 },
742 { "xsldbg", "xsldbg", 2 },
744 const int N = sizeof(langs)/sizeof(langs[0]);
746 // lookup the language name
747 int driverID = 0;
748 for (int i = 0; i < N; i++)
750 const L& l = langs[i];
752 // shortest must match
753 if (!lang.startsWith(l.shortest))
754 continue;
756 // lang must not be longer than the full name, and it must match
757 if (QString(l.full).startsWith(lang))
759 driverID = l.driver;
760 break;
763 DebuggerDriver* driver = 0;
764 switch (driverID) {
765 case 1:
767 GdbDriver* gdb = new GdbDriver;
768 gdb->setDefaultInvocation(m_debuggerCmdStr);
769 driver = gdb;
771 break;
772 case 2:
773 driver = new XsldbgDriver;
774 break;
775 default:
776 // unknown language
777 break;
779 return driver;
783 * Try to guess the language to use from the contents of the file.
785 QString DebuggerMainWnd::driverNameFromFile(const QString& exe)
787 /* Inprecise but simple test to see if file is in XSLT language */
788 if (exe.right(4).toLower() == ".xsl")
789 return "XSLT";
791 return "GDB";
794 void DebuggerMainWnd::setCoreFile(const QString& corefile)
796 assert(m_debugger != 0);
797 m_debugger->useCoreFile(corefile, true);
800 void DebuggerMainWnd::setRemoteDevice(const QString& remoteDevice)
802 if (m_debugger != 0) {
803 m_debugger->setRemoteDevice(remoteDevice);
807 void DebuggerMainWnd::overrideProgramArguments(const QString& args)
809 assert(m_debugger != 0);
810 m_debugger->overrideProgramArguments(args);
813 void DebuggerMainWnd::setTranscript(const QString& name)
815 m_transcriptFile = name;
816 if (m_debugger != 0 && m_debugger->driver() != 0)
817 m_debugger->driver()->setLogFileName(m_transcriptFile);
820 void DebuggerMainWnd::setAttachPid(const QString& pid)
822 assert(m_debugger != 0);
823 m_debugger->setAttachPid(pid);
826 void DebuggerMainWnd::slotNewStatusMsg()
828 QString msg = m_debugger->statusMessage();
829 m_statusMsgLabel->setText(msg.trimmed());
832 void DebuggerMainWnd::slotFileGlobalSettings()
834 int oldTabWidth = m_tabWidth;
836 KPageDialog dlg(this);
837 dlg.setWindowTitle(i18n("Global Options"));
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 = QGuiApplication::applicationDisplayName();
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 QUrl& url)
1073 QString exe = url.toLocalFile();
1074 debugProgram(exe, "");
1077 QString DebuggerMainWnd::makeSourceFilter()
1079 QString f;
1080 f = i18n("All source files") + " (" + m_sourceFilter + " " + m_headerFilter + ")";
1081 f += ";;" + i18n("Source files") + " (" + m_sourceFilter + ")";
1082 f += ";;" + i18n("Header files") + " (" + m_headerFilter + ")";
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 = QApplication::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 void DebuggerMainWnd::slotFileOpen()
1150 // start browsing in the active file's directory
1151 // fall back to last used directory (executable)
1152 QString dir = m_lastDirectory;
1153 QString fileName = m_filesWindow->activeFileName();
1154 if (!fileName.isEmpty()) {
1155 QFileInfo fi(fileName);
1156 dir = fi.path();
1159 fileName = QFileDialog::getOpenFileName(this,
1160 i18n("Open"), dir, makeSourceFilter());
1162 if (!fileName.isEmpty())
1164 QFileInfo fi(fileName);
1165 m_lastDirectory = fi.path();
1166 m_filesWindow->setExtraDirectory(m_lastDirectory);
1167 m_filesWindow->activateFile(fileName);
1171 void DebuggerMainWnd::slotFileExe()
1173 if (m_debugger->isIdle())
1175 // open a new executable
1176 QString executable = QFileDialog::getOpenFileName(this,
1177 i18n("Select the Executable to Debug"),
1178 m_lastDirectory);
1179 if (executable.isEmpty())
1180 return;
1182 debugProgram(executable, "");
1186 void DebuggerMainWnd::slotFileCore()
1188 if (m_debugger->canStart())
1190 QString corefile = QFileDialog::getOpenFileName(this,
1191 i18n("Select Core Dump"),
1192 m_lastDirectory);
1193 if (!corefile.isEmpty()) {
1194 m_debugger->useCoreFile(corefile, false);
1199 void DebuggerMainWnd::slotFileProgSettings()
1201 if (m_debugger != 0) {
1202 m_debugger->programSettings(this);
1206 void DebuggerMainWnd::slotViewStatusbar()
1208 if (statusBar()->isVisible())
1209 statusBar()->hide();
1210 else
1211 statusBar()->show();
1212 setSettingsDirty();
1215 void DebuggerMainWnd::slotExecUntil()
1217 if (m_debugger != 0)
1219 QString file;
1220 int lineNo;
1221 if (m_filesWindow->activeLine(file, lineNo))
1222 m_debugger->runUntil(file, lineNo);
1226 void DebuggerMainWnd::slotExecAttach()
1228 #ifdef PS_COMMAND
1229 ProcAttachPS dlg(this);
1230 // seed filter with executable name
1231 QFileInfo fi = m_debugger->executable();
1232 dlg.setFilterText(fi.fileName());
1233 #else
1234 ProcAttach dlg(this);
1235 dlg.setText(m_debugger->attachedPid());
1236 #endif
1237 if (dlg.exec()) {
1238 m_debugger->attachProgram(dlg.text());
1242 void DebuggerMainWnd::slotExecArgs()
1244 if (m_debugger != 0) {
1245 m_debugger->programArgs(this);
1249 void DebuggerMainWnd::slotConfigureKeys()
1251 KShortcutsDialog::configure(actionCollection());
1254 #include "dbgmainwnd.moc"