1 //===-- IOHandler.cpp -------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lldb/Core/IOHandler.h"
13 #ifndef LLDB_DISABLE_CURSES
19 #if defined(__APPLE__)
24 // Other libraries and framework includes
26 #include "lldb/Core/Debugger.h"
27 #include "lldb/Core/StreamFile.h"
28 #include "lldb/Host/File.h" // for File
29 #include "lldb/Host/Predicate.h" // for Predicate, ::eBroad...
30 #include "lldb/Utility/Error.h" // for Error
31 #include "lldb/Utility/StreamString.h" // for StreamString
32 #include "lldb/Utility/StringList.h" // for StringList
33 #include "lldb/lldb-forward.h" // for StreamFileSP
35 #ifndef LLDB_DISABLE_LIBEDIT
36 #include "lldb/Host/Editline.h"
38 #include "lldb/Interpreter/CommandCompletions.h"
39 #include "lldb/Interpreter/CommandInterpreter.h"
40 #ifndef LLDB_DISABLE_CURSES
41 #include "lldb/Breakpoint/BreakpointLocation.h"
42 #include "lldb/Core/Module.h"
43 #include "lldb/Core/State.h"
44 #include "lldb/Core/ValueObject.h"
45 #include "lldb/Core/ValueObjectRegister.h"
46 #include "lldb/Symbol/Block.h"
47 #include "lldb/Symbol/Function.h"
48 #include "lldb/Symbol/Symbol.h"
49 #include "lldb/Symbol/VariableList.h"
50 #include "lldb/Target/Process.h"
51 #include "lldb/Target/RegisterContext.h"
52 #include "lldb/Target/StackFrame.h"
53 #include "lldb/Target/StopInfo.h"
54 #include "lldb/Target/Target.h"
55 #include "lldb/Target/Thread.h"
58 #include "llvm/ADT/StringRef.h" // for StringRef
64 #include <memory> // for shared_ptr
65 #include <mutex> // for recursive_mutex
67 #include <assert.h> // for assert
68 #include <ctype.h> // for isspace
69 #include <errno.h> // for EINTR, errno
70 #include <stdint.h> // for uint32_t, UINT32_MAX
71 #include <stdio.h> // for size_t, fprintf, feof
72 #include <string.h> // for strlen
73 #include <type_traits> // for move
76 using namespace lldb_private;
78 IOHandler::IOHandler(Debugger &debugger, IOHandler::Type type)
79 : IOHandler(debugger, type,
80 StreamFileSP(), // Adopt STDIN from top input reader
81 StreamFileSP(), // Adopt STDOUT from top input reader
82 StreamFileSP(), // Adopt STDERR from top input reader
86 IOHandler::IOHandler(Debugger &debugger, IOHandler::Type type,
87 const lldb::StreamFileSP &input_sp,
88 const lldb::StreamFileSP &output_sp,
89 const lldb::StreamFileSP &error_sp, uint32_t flags)
90 : m_debugger(debugger), m_input_sp(input_sp), m_output_sp(output_sp),
91 m_error_sp(error_sp), m_popped(false), m_flags(flags), m_type(type),
92 m_user_data(nullptr), m_done(false), m_active(false) {
93 // If any files are not specified, then adopt them from the top input reader.
94 if (!m_input_sp || !m_output_sp || !m_error_sp)
95 debugger.AdoptTopIOHandlerFilesIfInvalid(m_input_sp, m_output_sp,
99 IOHandler::~IOHandler() = default;
101 int IOHandler::GetInputFD() {
102 return (m_input_sp ? m_input_sp->GetFile().GetDescriptor() : -1);
105 int IOHandler::GetOutputFD() {
106 return (m_output_sp ? m_output_sp->GetFile().GetDescriptor() : -1);
109 int IOHandler::GetErrorFD() {
110 return (m_error_sp ? m_error_sp->GetFile().GetDescriptor() : -1);
113 FILE *IOHandler::GetInputFILE() {
114 return (m_input_sp ? m_input_sp->GetFile().GetStream() : nullptr);
117 FILE *IOHandler::GetOutputFILE() {
118 return (m_output_sp ? m_output_sp->GetFile().GetStream() : nullptr);
121 FILE *IOHandler::GetErrorFILE() {
122 return (m_error_sp ? m_error_sp->GetFile().GetStream() : nullptr);
125 StreamFileSP &IOHandler::GetInputStreamFile() { return m_input_sp; }
127 StreamFileSP &IOHandler::GetOutputStreamFile() { return m_output_sp; }
129 StreamFileSP &IOHandler::GetErrorStreamFile() { return m_error_sp; }
131 bool IOHandler::GetIsInteractive() {
132 return GetInputStreamFile()->GetFile().GetIsInteractive();
135 bool IOHandler::GetIsRealTerminal() {
136 return GetInputStreamFile()->GetFile().GetIsRealTerminal();
139 void IOHandler::SetPopped(bool b) { m_popped.SetValue(b, eBroadcastOnChange); }
141 void IOHandler::WaitForPop() { m_popped.WaitForValueEqualTo(true); }
143 void IOHandlerStack::PrintAsync(Stream *stream, const char *s, size_t len) {
145 std::lock_guard<std::recursive_mutex> guard(m_mutex);
147 m_top->PrintAsync(stream, s, len);
151 IOHandlerConfirm::IOHandlerConfirm(Debugger &debugger, llvm::StringRef prompt,
152 bool default_response)
154 debugger, IOHandler::Type::Confirm,
155 nullptr, // nullptr editline_name means no history loaded/saved
156 llvm::StringRef(), // No prompt
157 llvm::StringRef(), // No continuation prompt
159 false, // Don't colorize the prompt (i.e. the confirm message.)
161 m_default_response(default_response), m_user_response(default_response) {
162 StreamString prompt_stream;
163 prompt_stream.PutCString(prompt);
164 if (m_default_response)
165 prompt_stream.Printf(": [Y/n] ");
167 prompt_stream.Printf(": [y/N] ");
169 SetPrompt(prompt_stream.GetString());
172 IOHandlerConfirm::~IOHandlerConfirm() = default;
174 int IOHandlerConfirm::IOHandlerComplete(IOHandler &io_handler,
175 const char *current_line,
177 const char *last_char,
178 int skip_first_n_matches,
179 int max_matches, StringList &matches) {
180 if (current_line == cursor) {
181 if (m_default_response) {
182 matches.AppendString("y");
184 matches.AppendString("n");
187 return matches.GetSize();
190 void IOHandlerConfirm::IOHandlerInputComplete(IOHandler &io_handler,
193 // User just hit enter, set the response to the default
194 m_user_response = m_default_response;
195 io_handler.SetIsDone(true);
199 if (line.size() == 1) {
203 m_user_response = true;
204 io_handler.SetIsDone(true);
208 m_user_response = false;
209 io_handler.SetIsDone(true);
216 if (line == "yes" || line == "YES" || line == "Yes") {
217 m_user_response = true;
218 io_handler.SetIsDone(true);
219 } else if (line == "no" || line == "NO" || line == "No") {
220 m_user_response = false;
221 io_handler.SetIsDone(true);
225 int IOHandlerDelegate::IOHandlerComplete(IOHandler &io_handler,
226 const char *current_line,
228 const char *last_char,
229 int skip_first_n_matches,
230 int max_matches, StringList &matches) {
231 switch (m_completion) {
232 case Completion::None:
235 case Completion::LLDBCommand:
236 return io_handler.GetDebugger().GetCommandInterpreter().HandleCompletion(
237 current_line, cursor, last_char, skip_first_n_matches, max_matches,
240 case Completion::Expression: {
241 bool word_complete = false;
242 const char *word_start = cursor;
243 if (cursor > current_line)
245 while (word_start > current_line && !isspace(*word_start))
247 CommandCompletions::InvokeCommonCompletionCallbacks(
248 io_handler.GetDebugger().GetCommandInterpreter(),
249 CommandCompletions::eVariablePathCompletion, word_start,
250 skip_first_n_matches, max_matches, nullptr, word_complete, matches);
252 size_t num_matches = matches.GetSize();
253 if (num_matches > 0) {
254 std::string common_prefix;
255 matches.LongestCommonPrefix(common_prefix);
256 const size_t partial_name_len = strlen(word_start);
258 // If we matched a unique single command, add a space...
259 // Only do this if the completer told us this was a complete word,
261 if (num_matches == 1 && word_complete) {
262 common_prefix.push_back(' ');
264 common_prefix.erase(0, partial_name_len);
265 matches.InsertStringAtIndex(0, std::move(common_prefix));
274 IOHandlerEditline::IOHandlerEditline(
275 Debugger &debugger, IOHandler::Type type,
276 const char *editline_name, // Used for saving history files
277 llvm::StringRef prompt, llvm::StringRef continuation_prompt,
278 bool multi_line, bool color_prompts, uint32_t line_number_start,
279 IOHandlerDelegate &delegate)
280 : IOHandlerEditline(debugger, type,
281 StreamFileSP(), // Inherit input from top input reader
282 StreamFileSP(), // Inherit output from top input reader
283 StreamFileSP(), // Inherit error from top input reader
285 editline_name, // Used for saving history files
286 prompt, continuation_prompt, multi_line, color_prompts,
287 line_number_start, delegate) {}
289 IOHandlerEditline::IOHandlerEditline(
290 Debugger &debugger, IOHandler::Type type,
291 const lldb::StreamFileSP &input_sp, const lldb::StreamFileSP &output_sp,
292 const lldb::StreamFileSP &error_sp, uint32_t flags,
293 const char *editline_name, // Used for saving history files
294 llvm::StringRef prompt, llvm::StringRef continuation_prompt,
295 bool multi_line, bool color_prompts, uint32_t line_number_start,
296 IOHandlerDelegate &delegate)
297 : IOHandler(debugger, type, input_sp, output_sp, error_sp, flags),
298 #ifndef LLDB_DISABLE_LIBEDIT
301 m_delegate(delegate), m_prompt(), m_continuation_prompt(),
302 m_current_lines_ptr(nullptr), m_base_line_number(line_number_start),
303 m_curr_line_idx(UINT32_MAX), m_multi_line(multi_line),
304 m_color_prompts(color_prompts), m_interrupt_exits(true),
308 #ifndef LLDB_DISABLE_LIBEDIT
309 bool use_editline = false;
311 use_editline = m_input_sp->GetFile().GetIsRealTerminal();
314 m_editline_ap.reset(new Editline(editline_name, GetInputFILE(),
315 GetOutputFILE(), GetErrorFILE(),
317 m_editline_ap->SetIsInputCompleteCallback(IsInputCompleteCallback, this);
318 m_editline_ap->SetAutoCompleteCallback(AutoCompleteCallback, this);
319 // See if the delegate supports fixing indentation
320 const char *indent_chars = delegate.IOHandlerGetFixIndentationCharacters();
322 // The delegate does support indentation, hook it up so when any
324 // character is typed, the delegate gets a chance to fix it
325 m_editline_ap->SetFixIndentationCallback(FixIndentationCallback, this,
330 SetBaseLineNumber(m_base_line_number);
332 SetContinuationPrompt(continuation_prompt);
335 IOHandlerEditline::~IOHandlerEditline() {
336 #ifndef LLDB_DISABLE_LIBEDIT
337 m_editline_ap.reset();
341 void IOHandlerEditline::Activate() {
342 IOHandler::Activate();
343 m_delegate.IOHandlerActivated(*this);
346 void IOHandlerEditline::Deactivate() {
347 IOHandler::Deactivate();
348 m_delegate.IOHandlerDeactivated(*this);
351 bool IOHandlerEditline::GetLine(std::string &line, bool &interrupted) {
352 #ifndef LLDB_DISABLE_LIBEDIT
354 return m_editline_ap->GetLine(line, interrupted);
359 FILE *in = GetInputFILE();
361 if (GetIsInteractive()) {
362 const char *prompt = nullptr;
364 if (m_multi_line && m_curr_line_idx > 0)
365 prompt = GetContinuationPrompt();
367 if (prompt == nullptr)
368 prompt = GetPrompt();
370 if (prompt && prompt[0]) {
371 FILE *out = GetOutputFILE();
373 ::fprintf(out, "%s", prompt);
380 bool got_line = false;
383 if (fgets(buffer, sizeof(buffer), in) == nullptr) {
384 const int saved_errno = errno;
387 else if (ferror(in)) {
388 if (saved_errno != EINTR)
393 size_t buffer_len = strlen(buffer);
394 assert(buffer[buffer_len] == '\0');
395 char last_char = buffer[buffer_len - 1];
396 if (last_char == '\r' || last_char == '\n') {
398 // Strip trailing newlines
399 while (last_char == '\r' || last_char == '\n') {
403 last_char = buffer[buffer_len - 1];
406 line.append(buffer, buffer_len);
410 // We might have gotten a newline on a line by itself
411 // make sure to return true in this case.
414 // No more input file, we are done...
418 #ifndef LLDB_DISABLE_LIBEDIT
423 #ifndef LLDB_DISABLE_LIBEDIT
424 bool IOHandlerEditline::IsInputCompleteCallback(Editline *editline,
427 IOHandlerEditline *editline_reader = (IOHandlerEditline *)baton;
428 return editline_reader->m_delegate.IOHandlerIsInputComplete(*editline_reader,
432 int IOHandlerEditline::FixIndentationCallback(Editline *editline,
433 const StringList &lines,
436 IOHandlerEditline *editline_reader = (IOHandlerEditline *)baton;
437 return editline_reader->m_delegate.IOHandlerFixIndentation(
438 *editline_reader, lines, cursor_position);
441 int IOHandlerEditline::AutoCompleteCallback(const char *current_line,
443 const char *last_char,
444 int skip_first_n_matches,
446 StringList &matches, void *baton) {
447 IOHandlerEditline *editline_reader = (IOHandlerEditline *)baton;
449 return editline_reader->m_delegate.IOHandlerComplete(
450 *editline_reader, current_line, cursor, last_char, skip_first_n_matches,
451 max_matches, matches);
456 const char *IOHandlerEditline::GetPrompt() {
457 #ifndef LLDB_DISABLE_LIBEDIT
459 return m_editline_ap->GetPrompt();
462 if (m_prompt.empty())
464 #ifndef LLDB_DISABLE_LIBEDIT
467 return m_prompt.c_str();
470 bool IOHandlerEditline::SetPrompt(llvm::StringRef prompt) {
473 #ifndef LLDB_DISABLE_LIBEDIT
475 m_editline_ap->SetPrompt(m_prompt.empty() ? nullptr : m_prompt.c_str());
480 const char *IOHandlerEditline::GetContinuationPrompt() {
481 return (m_continuation_prompt.empty() ? nullptr
482 : m_continuation_prompt.c_str());
485 void IOHandlerEditline::SetContinuationPrompt(llvm::StringRef prompt) {
486 m_continuation_prompt = prompt;
488 #ifndef LLDB_DISABLE_LIBEDIT
490 m_editline_ap->SetContinuationPrompt(m_continuation_prompt.empty()
492 : m_continuation_prompt.c_str());
496 void IOHandlerEditline::SetBaseLineNumber(uint32_t line) {
497 m_base_line_number = line;
500 uint32_t IOHandlerEditline::GetCurrentLineIndex() const {
501 #ifndef LLDB_DISABLE_LIBEDIT
503 return m_editline_ap->GetCurrentLine();
505 return m_curr_line_idx;
508 bool IOHandlerEditline::GetLines(StringList &lines, bool &interrupted) {
509 m_current_lines_ptr = &lines;
511 bool success = false;
512 #ifndef LLDB_DISABLE_LIBEDIT
514 return m_editline_ap->GetLines(m_base_line_number, lines, interrupted);
521 // Show line numbers if we are asked to
523 if (m_base_line_number > 0 && GetIsInteractive()) {
524 FILE *out = GetOutputFILE();
526 ::fprintf(out, "%u%s", m_base_line_number + (uint32_t)lines.GetSize(),
527 GetPrompt() == nullptr ? " " : "");
530 m_curr_line_idx = lines.GetSize();
532 bool interrupted = false;
533 if (GetLine(line, interrupted) && !interrupted) {
534 lines.AppendString(line);
535 done = m_delegate.IOHandlerIsInputComplete(*this, lines);
540 success = lines.GetSize() > 0;
541 #ifndef LLDB_DISABLE_LIBEDIT
547 // Each IOHandler gets to run until it is done. It should read data
548 // from the "in" and place output into "out" and "err and return
550 void IOHandlerEditline::Run() {
553 bool interrupted = false;
556 if (GetLines(lines, interrupted)) {
558 m_done = m_interrupt_exits;
559 m_delegate.IOHandlerInputInterrupted(*this, line);
562 line = lines.CopyList();
563 m_delegate.IOHandlerInputComplete(*this, line);
569 if (GetLine(line, interrupted)) {
571 m_delegate.IOHandlerInputInterrupted(*this, line);
573 m_delegate.IOHandlerInputComplete(*this, line);
581 void IOHandlerEditline::Cancel() {
582 #ifndef LLDB_DISABLE_LIBEDIT
584 m_editline_ap->Cancel();
588 bool IOHandlerEditline::Interrupt() {
589 // Let the delgate handle it first
590 if (m_delegate.IOHandlerInterrupt(*this))
593 #ifndef LLDB_DISABLE_LIBEDIT
595 return m_editline_ap->Interrupt();
600 void IOHandlerEditline::GotEOF() {
601 #ifndef LLDB_DISABLE_LIBEDIT
603 m_editline_ap->Interrupt();
607 void IOHandlerEditline::PrintAsync(Stream *stream, const char *s, size_t len) {
608 #ifndef LLDB_DISABLE_LIBEDIT
610 m_editline_ap->PrintAsync(stream, s, len);
615 const char *prompt = GetPrompt();
617 // Back up over previous prompt using Windows API
618 CONSOLE_SCREEN_BUFFER_INFO screen_buffer_info;
619 HANDLE console_handle = GetStdHandle(STD_OUTPUT_HANDLE);
620 GetConsoleScreenBufferInfo(console_handle, &screen_buffer_info);
621 COORD coord = screen_buffer_info.dwCursorPosition;
622 coord.X -= strlen(prompt);
625 SetConsoleCursorPosition(console_handle, coord);
628 IOHandler::PrintAsync(stream, s, len);
631 IOHandler::PrintAsync(GetOutputStreamFile().get(), prompt,
637 // we may want curses to be disabled for some builds
638 // for instance, windows
639 #ifndef LLDB_DISABLE_CURSES
641 #define KEY_RETURN 10
642 #define KEY_ESCAPE 27
648 class WindowDelegate;
649 typedef std::shared_ptr<Menu> MenuSP;
650 typedef std::shared_ptr<MenuDelegate> MenuDelegateSP;
651 typedef std::shared_ptr<Window> WindowSP;
652 typedef std::shared_ptr<WindowDelegate> WindowDelegateSP;
653 typedef std::vector<MenuSP> Menus;
654 typedef std::vector<WindowSP> Windows;
655 typedef std::vector<WindowDelegateSP> WindowDelegates;
658 type summary add -s "x=${var.x}, y=${var.y}" curses::Point
659 type summary add -s "w=${var.width}, h=${var.height}" curses::Size
660 type summary add -s "${var.origin%S} ${var.size%S}" curses::Rect
667 Point(int _x = 0, int _y = 0) : x(_x), y(_y) {}
674 Point &operator+=(const Point &rhs) {
680 void Dump() { printf("(x=%i, y=%i)\n", x, y); }
683 bool operator==(const Point &lhs, const Point &rhs) {
684 return lhs.x == rhs.x && lhs.y == rhs.y;
687 bool operator!=(const Point &lhs, const Point &rhs) {
688 return lhs.x != rhs.x || lhs.y != rhs.y;
694 Size(int w = 0, int h = 0) : width(w), height(h) {}
701 void Dump() { printf("(w=%i, h=%i)\n", width, height); }
704 bool operator==(const Size &lhs, const Size &rhs) {
705 return lhs.width == rhs.width && lhs.height == rhs.height;
708 bool operator!=(const Size &lhs, const Size &rhs) {
709 return lhs.width != rhs.width || lhs.height != rhs.height;
716 Rect() : origin(), size() {}
718 Rect(const Point &p, const Size &s) : origin(p), size(s) {}
726 printf("(x=%i, y=%i), w=%i, h=%i)\n", origin.x, origin.y, size.width,
730 void Inset(int w, int h) {
731 if (size.width > w * 2)
735 if (size.height > h * 2)
736 size.height -= h * 2;
740 // Return a status bar rectangle which is the last line of
741 // this rectangle. This rectangle will be modified to not
742 // include the status bar area.
743 Rect MakeStatusBar() {
745 if (size.height > 1) {
746 status_bar.origin.x = origin.x;
747 status_bar.origin.y = size.height;
748 status_bar.size.width = size.width;
749 status_bar.size.height = 1;
755 // Return a menubar rectangle which is the first line of
756 // this rectangle. This rectangle will be modified to not
757 // include the menubar area.
760 if (size.height > 1) {
761 menubar.origin.x = origin.x;
762 menubar.origin.y = origin.y;
763 menubar.size.width = size.width;
764 menubar.size.height = 1;
771 void HorizontalSplitPercentage(float top_percentage, Rect &top,
772 Rect &bottom) const {
773 float top_height = top_percentage * size.height;
774 HorizontalSplit(top_height, top, bottom);
777 void HorizontalSplit(int top_height, Rect &top, Rect &bottom) const {
779 if (top_height < size.height) {
780 top.size.height = top_height;
781 bottom.origin.x = origin.x;
782 bottom.origin.y = origin.y + top.size.height;
783 bottom.size.width = size.width;
784 bottom.size.height = size.height - top.size.height;
790 void VerticalSplitPercentage(float left_percentage, Rect &left,
792 float left_width = left_percentage * size.width;
793 VerticalSplit(left_width, left, right);
796 void VerticalSplit(int left_width, Rect &left, Rect &right) const {
798 if (left_width < size.width) {
799 left.size.width = left_width;
800 right.origin.x = origin.x + left.size.width;
801 right.origin.y = origin.y;
802 right.size.width = size.width - left.size.width;
803 right.size.height = size.height;
810 bool operator==(const Rect &lhs, const Rect &rhs) {
811 return lhs.origin == rhs.origin && lhs.size == rhs.size;
814 bool operator!=(const Rect &lhs, const Rect &rhs) {
815 return lhs.origin != rhs.origin || lhs.size != rhs.size;
818 enum HandleCharResult {
824 enum class MenuActionResult {
827 Quit // Exit all menus and quit
832 const char *description;
835 class WindowDelegate {
837 virtual ~WindowDelegate() = default;
839 virtual bool WindowDelegateDraw(Window &window, bool force) {
840 return false; // Drawing not handled
843 virtual HandleCharResult WindowDelegateHandleChar(Window &window, int key) {
844 return eKeyNotHandled;
847 virtual const char *WindowDelegateGetHelpText() { return nullptr; }
849 virtual KeyHelp *WindowDelegateGetKeyHelp() { return nullptr; }
852 class HelpDialogDelegate : public WindowDelegate {
854 HelpDialogDelegate(const char *text, KeyHelp *key_help_array);
856 ~HelpDialogDelegate() override;
858 bool WindowDelegateDraw(Window &window, bool force) override;
860 HandleCharResult WindowDelegateHandleChar(Window &window, int key) override;
862 size_t GetNumLines() const { return m_text.GetSize(); }
864 size_t GetMaxLineLength() const { return m_text.GetMaxStringLength(); }
868 int m_first_visible_line;
873 Window(const char *name)
874 : m_name(name), m_window(nullptr), m_panel(nullptr), m_parent(nullptr),
875 m_subwindows(), m_delegate_sp(), m_curr_active_window_idx(UINT32_MAX),
876 m_prev_active_window_idx(UINT32_MAX), m_delete(false),
877 m_needs_update(true), m_can_activate(true), m_is_subwin(false) {}
879 Window(const char *name, WINDOW *w, bool del = true)
880 : m_name(name), m_window(nullptr), m_panel(nullptr), m_parent(nullptr),
881 m_subwindows(), m_delegate_sp(), m_curr_active_window_idx(UINT32_MAX),
882 m_prev_active_window_idx(UINT32_MAX), m_delete(del),
883 m_needs_update(true), m_can_activate(true), m_is_subwin(false) {
888 Window(const char *name, const Rect &bounds)
889 : m_name(name), m_window(nullptr), m_parent(nullptr), m_subwindows(),
890 m_delegate_sp(), m_curr_active_window_idx(UINT32_MAX),
891 m_prev_active_window_idx(UINT32_MAX), m_delete(true),
892 m_needs_update(true), m_can_activate(true), m_is_subwin(false) {
893 Reset(::newwin(bounds.size.height, bounds.size.width, bounds.origin.y,
902 void Reset(WINDOW *w = nullptr, bool del = true) {
907 ::del_panel(m_panel);
910 if (m_window && m_delete) {
917 m_panel = ::new_panel(m_window);
922 void AttributeOn(attr_t attr) { ::wattron(m_window, attr); }
923 void AttributeOff(attr_t attr) { ::wattroff(m_window, attr); }
924 void Box(chtype v_char = ACS_VLINE, chtype h_char = ACS_HLINE) {
925 ::box(m_window, v_char, h_char);
927 void Clear() { ::wclear(m_window); }
928 void Erase() { ::werase(m_window); }
930 return Rect(GetParentOrigin(), GetSize());
931 } // Get the rectangle in our parent window
932 int GetChar() { return ::wgetch(m_window); }
933 int GetCursorX() { return getcurx(m_window); }
934 int GetCursorY() { return getcury(m_window); }
936 return Rect(Point(), GetSize());
937 } // Get our rectangle in our own coordinate system
938 Point GetParentOrigin() { return Point(GetParentX(), GetParentY()); }
939 Size GetSize() { return Size(GetWidth(), GetHeight()); }
940 int GetParentX() { return getparx(m_window); }
941 int GetParentY() { return getpary(m_window); }
942 int GetMaxX() { return getmaxx(m_window); }
943 int GetMaxY() { return getmaxy(m_window); }
944 int GetWidth() { return GetMaxX(); }
945 int GetHeight() { return GetMaxY(); }
946 void MoveCursor(int x, int y) { ::wmove(m_window, y, x); }
947 void MoveWindow(int x, int y) { MoveWindow(Point(x, y)); }
948 void Resize(int w, int h) { ::wresize(m_window, h, w); }
949 void Resize(const Size &size) {
950 ::wresize(m_window, size.height, size.width);
952 void PutChar(int ch) { ::waddch(m_window, ch); }
953 void PutCString(const char *s, int len = -1) { ::waddnstr(m_window, s, len); }
954 void Refresh() { ::wrefresh(m_window); }
955 void DeferredRefresh() {
956 // We are using panels, so we don't need to call this...
957 //::wnoutrefresh(m_window);
959 void SetBackground(int color_pair_idx) {
960 ::wbkgd(m_window, COLOR_PAIR(color_pair_idx));
962 void UnderlineOn() { AttributeOn(A_UNDERLINE); }
963 void UnderlineOff() { AttributeOff(A_UNDERLINE); }
965 void PutCStringTruncated(const char *s, int right_pad) {
966 int bytes_left = GetWidth() - GetCursorX();
967 if (bytes_left > right_pad) {
968 bytes_left -= right_pad;
969 ::waddnstr(m_window, s, bytes_left);
973 void MoveWindow(const Point &origin) {
974 const bool moving_window = origin != GetParentOrigin();
975 if (m_is_subwin && moving_window) {
976 // Can't move subwindows, must delete and re-create
977 Size size = GetSize();
978 Reset(::subwin(m_parent->m_window, size.height, size.width, origin.y,
982 ::mvwin(m_window, origin.y, origin.x);
986 void SetBounds(const Rect &bounds) {
987 const bool moving_window = bounds.origin != GetParentOrigin();
988 if (m_is_subwin && moving_window) {
989 // Can't move subwindows, must delete and re-create
990 Reset(::subwin(m_parent->m_window, bounds.size.height, bounds.size.width,
991 bounds.origin.y, bounds.origin.x),
995 MoveWindow(bounds.origin);
1000 void Printf(const char *format, ...) __attribute__((format(printf, 2, 3))) {
1002 va_start(args, format);
1003 vwprintw(m_window, format, args);
1008 ::touchwin(m_window);
1013 WindowSP CreateSubWindow(const char *name, const Rect &bounds,
1015 WindowSP subwindow_sp;
1017 subwindow_sp.reset(new Window(
1018 name, ::subwin(m_window, bounds.size.height, bounds.size.width,
1019 bounds.origin.y, bounds.origin.x),
1021 subwindow_sp->m_is_subwin = true;
1024 new Window(name, ::newwin(bounds.size.height, bounds.size.width,
1025 bounds.origin.y, bounds.origin.x),
1027 subwindow_sp->m_is_subwin = false;
1029 subwindow_sp->m_parent = this;
1031 m_prev_active_window_idx = m_curr_active_window_idx;
1032 m_curr_active_window_idx = m_subwindows.size();
1034 m_subwindows.push_back(subwindow_sp);
1035 ::top_panel(subwindow_sp->m_panel);
1036 m_needs_update = true;
1037 return subwindow_sp;
1040 bool RemoveSubWindow(Window *window) {
1041 Windows::iterator pos, end = m_subwindows.end();
1043 for (pos = m_subwindows.begin(); pos != end; ++pos, ++i) {
1044 if ((*pos).get() == window) {
1045 if (m_prev_active_window_idx == i)
1046 m_prev_active_window_idx = UINT32_MAX;
1047 else if (m_prev_active_window_idx != UINT32_MAX &&
1048 m_prev_active_window_idx > i)
1049 --m_prev_active_window_idx;
1051 if (m_curr_active_window_idx == i)
1052 m_curr_active_window_idx = UINT32_MAX;
1053 else if (m_curr_active_window_idx != UINT32_MAX &&
1054 m_curr_active_window_idx > i)
1055 --m_curr_active_window_idx;
1057 m_subwindows.erase(pos);
1058 m_needs_update = true;
1069 WindowSP FindSubWindow(const char *name) {
1070 Windows::iterator pos, end = m_subwindows.end();
1072 for (pos = m_subwindows.begin(); pos != end; ++pos, ++i) {
1073 if ((*pos)->m_name.compare(name) == 0)
1079 void RemoveSubWindows() {
1080 m_curr_active_window_idx = UINT32_MAX;
1081 m_prev_active_window_idx = UINT32_MAX;
1082 for (Windows::iterator pos = m_subwindows.begin();
1083 pos != m_subwindows.end(); pos = m_subwindows.erase(pos)) {
1092 WINDOW *get() { return m_window; }
1094 operator WINDOW *() { return m_window; }
1096 //----------------------------------------------------------------------
1097 // Window drawing utilities
1098 //----------------------------------------------------------------------
1099 void DrawTitleBox(const char *title, const char *bottom_message = nullptr) {
1102 attr = A_BOLD | COLOR_PAIR(2);
1111 if (title && title[0]) {
1117 if (bottom_message && bottom_message[0]) {
1118 int bottom_message_length = strlen(bottom_message);
1119 int x = GetWidth() - 3 - (bottom_message_length + 2);
1122 MoveCursor(x, GetHeight() - 1);
1124 PutCString(bottom_message);
1127 MoveCursor(1, GetHeight() - 1);
1129 PutCStringTruncated(bottom_message, 1);
1136 virtual void Draw(bool force) {
1137 if (m_delegate_sp && m_delegate_sp->WindowDelegateDraw(*this, force))
1140 for (auto &subwindow_sp : m_subwindows)
1141 subwindow_sp->Draw(force);
1144 bool CreateHelpSubwindow() {
1145 if (m_delegate_sp) {
1146 const char *text = m_delegate_sp->WindowDelegateGetHelpText();
1147 KeyHelp *key_help = m_delegate_sp->WindowDelegateGetKeyHelp();
1148 if ((text && text[0]) || key_help) {
1149 std::auto_ptr<HelpDialogDelegate> help_delegate_ap(
1150 new HelpDialogDelegate(text, key_help));
1151 const size_t num_lines = help_delegate_ap->GetNumLines();
1152 const size_t max_length = help_delegate_ap->GetMaxLineLength();
1153 Rect bounds = GetBounds();
1155 if (max_length + 4 < static_cast<size_t>(bounds.size.width)) {
1156 bounds.origin.x += (bounds.size.width - max_length + 4) / 2;
1157 bounds.size.width = max_length + 4;
1159 if (bounds.size.width > 100) {
1160 const int inset_w = bounds.size.width / 4;
1161 bounds.origin.x += inset_w;
1162 bounds.size.width -= 2 * inset_w;
1166 if (num_lines + 2 < static_cast<size_t>(bounds.size.height)) {
1167 bounds.origin.y += (bounds.size.height - num_lines + 2) / 2;
1168 bounds.size.height = num_lines + 2;
1170 if (bounds.size.height > 100) {
1171 const int inset_h = bounds.size.height / 4;
1172 bounds.origin.y += inset_h;
1173 bounds.size.height -= 2 * inset_h;
1176 WindowSP help_window_sp;
1177 Window *parent_window = GetParent();
1179 help_window_sp = parent_window->CreateSubWindow("Help", bounds, true);
1181 help_window_sp = CreateSubWindow("Help", bounds, true);
1182 help_window_sp->SetDelegate(
1183 WindowDelegateSP(help_delegate_ap.release()));
1190 virtual HandleCharResult HandleChar(int key) {
1191 // Always check the active window first
1192 HandleCharResult result = eKeyNotHandled;
1193 WindowSP active_window_sp = GetActiveWindow();
1194 if (active_window_sp) {
1195 result = active_window_sp->HandleChar(key);
1196 if (result != eKeyNotHandled)
1200 if (m_delegate_sp) {
1201 result = m_delegate_sp->WindowDelegateHandleChar(*this, key);
1202 if (result != eKeyNotHandled)
1206 // Then check for any windows that want any keys
1207 // that weren't handled. This is typically only
1209 // Make a copy of the subwindows in case any HandleChar()
1210 // functions muck with the subwindows. If we don't do this,
1211 // we can crash when iterating over the subwindows.
1212 Windows subwindows(m_subwindows);
1213 for (auto subwindow_sp : subwindows) {
1214 if (!subwindow_sp->m_can_activate) {
1215 HandleCharResult result = subwindow_sp->HandleChar(key);
1216 if (result != eKeyNotHandled)
1221 return eKeyNotHandled;
1224 bool SetActiveWindow(Window *window) {
1225 const size_t num_subwindows = m_subwindows.size();
1226 for (size_t i = 0; i < num_subwindows; ++i) {
1227 if (m_subwindows[i].get() == window) {
1228 m_prev_active_window_idx = m_curr_active_window_idx;
1229 ::top_panel(window->m_panel);
1230 m_curr_active_window_idx = i;
1237 WindowSP GetActiveWindow() {
1238 if (!m_subwindows.empty()) {
1239 if (m_curr_active_window_idx >= m_subwindows.size()) {
1240 if (m_prev_active_window_idx < m_subwindows.size()) {
1241 m_curr_active_window_idx = m_prev_active_window_idx;
1242 m_prev_active_window_idx = UINT32_MAX;
1243 } else if (IsActive()) {
1244 m_prev_active_window_idx = UINT32_MAX;
1245 m_curr_active_window_idx = UINT32_MAX;
1247 // Find first window that wants to be active if this window is active
1248 const size_t num_subwindows = m_subwindows.size();
1249 for (size_t i = 0; i < num_subwindows; ++i) {
1250 if (m_subwindows[i]->GetCanBeActive()) {
1251 m_curr_active_window_idx = i;
1258 if (m_curr_active_window_idx < m_subwindows.size())
1259 return m_subwindows[m_curr_active_window_idx];
1264 bool GetCanBeActive() const { return m_can_activate; }
1266 void SetCanBeActive(bool b) { m_can_activate = b; }
1268 const WindowDelegateSP &GetDelegate() const { return m_delegate_sp; }
1270 void SetDelegate(const WindowDelegateSP &delegate_sp) {
1271 m_delegate_sp = delegate_sp;
1274 Window *GetParent() const { return m_parent; }
1276 bool IsActive() const {
1278 return m_parent->GetActiveWindow().get() == this;
1280 return true; // Top level window is always active
1283 void SelectNextWindowAsActive() {
1284 // Move active focus to next window
1285 const size_t num_subwindows = m_subwindows.size();
1286 if (m_curr_active_window_idx == UINT32_MAX) {
1288 for (auto subwindow_sp : m_subwindows) {
1289 if (subwindow_sp->GetCanBeActive()) {
1290 m_curr_active_window_idx = idx;
1295 } else if (m_curr_active_window_idx + 1 < num_subwindows) {
1296 bool handled = false;
1297 m_prev_active_window_idx = m_curr_active_window_idx;
1298 for (size_t idx = m_curr_active_window_idx + 1; idx < num_subwindows;
1300 if (m_subwindows[idx]->GetCanBeActive()) {
1301 m_curr_active_window_idx = idx;
1307 for (size_t idx = 0; idx <= m_prev_active_window_idx; ++idx) {
1308 if (m_subwindows[idx]->GetCanBeActive()) {
1309 m_curr_active_window_idx = idx;
1315 m_prev_active_window_idx = m_curr_active_window_idx;
1316 for (size_t idx = 0; idx < num_subwindows; ++idx) {
1317 if (m_subwindows[idx]->GetCanBeActive()) {
1318 m_curr_active_window_idx = idx;
1325 const char *GetName() const { return m_name.c_str(); }
1332 Windows m_subwindows;
1333 WindowDelegateSP m_delegate_sp;
1334 uint32_t m_curr_active_window_idx;
1335 uint32_t m_prev_active_window_idx;
1337 bool m_needs_update;
1338 bool m_can_activate;
1342 DISALLOW_COPY_AND_ASSIGN(Window);
1345 class MenuDelegate {
1347 virtual ~MenuDelegate() = default;
1349 virtual MenuActionResult MenuDelegateAction(Menu &menu) = 0;
1352 class Menu : public WindowDelegate {
1354 enum class Type { Invalid, Bar, Item, Separator };
1356 // Menubar or separator constructor
1359 // Menuitem constructor
1360 Menu(const char *name, const char *key_name, int key_value,
1361 uint64_t identifier);
1363 ~Menu() override = default;
1365 const MenuDelegateSP &GetDelegate() const { return m_delegate_sp; }
1367 void SetDelegate(const MenuDelegateSP &delegate_sp) {
1368 m_delegate_sp = delegate_sp;
1371 void RecalculateNameLengths();
1373 void AddSubmenu(const MenuSP &menu_sp);
1375 int DrawAndRunMenu(Window &window);
1377 void DrawMenuTitle(Window &window, bool highlight);
1379 bool WindowDelegateDraw(Window &window, bool force) override;
1381 HandleCharResult WindowDelegateHandleChar(Window &window, int key) override;
1383 MenuActionResult ActionPrivate(Menu &menu) {
1384 MenuActionResult result = MenuActionResult::NotHandled;
1385 if (m_delegate_sp) {
1386 result = m_delegate_sp->MenuDelegateAction(menu);
1387 if (result != MenuActionResult::NotHandled)
1389 } else if (m_parent) {
1390 result = m_parent->ActionPrivate(menu);
1391 if (result != MenuActionResult::NotHandled)
1394 return m_canned_result;
1397 MenuActionResult Action() {
1398 // Call the recursive action so it can try to handle it
1399 // with the menu delegate, and if not, try our parent menu
1400 return ActionPrivate(*this);
1403 void SetCannedResult(MenuActionResult result) { m_canned_result = result; }
1405 Menus &GetSubmenus() { return m_submenus; }
1407 const Menus &GetSubmenus() const { return m_submenus; }
1409 int GetSelectedSubmenuIndex() const { return m_selected; }
1411 void SetSelectedSubmenuIndex(int idx) { m_selected = idx; }
1413 Type GetType() const { return m_type; }
1415 int GetStartingColumn() const { return m_start_col; }
1417 void SetStartingColumn(int col) { m_start_col = col; }
1419 int GetKeyValue() const { return m_key_value; }
1421 void SetKeyValue(int key_value) { m_key_value = key_value; }
1423 std::string &GetName() { return m_name; }
1425 std::string &GetKeyName() { return m_key_name; }
1427 int GetDrawWidth() const {
1428 return m_max_submenu_name_length + m_max_submenu_key_name_length + 8;
1431 uint64_t GetIdentifier() const { return m_identifier; }
1433 void SetIdentifier(uint64_t identifier) { m_identifier = identifier; }
1437 std::string m_key_name;
1438 uint64_t m_identifier;
1442 int m_max_submenu_name_length;
1443 int m_max_submenu_key_name_length;
1447 WindowSP m_menu_window_sp;
1448 MenuActionResult m_canned_result;
1449 MenuDelegateSP m_delegate_sp;
1452 // Menubar or separator constructor
1453 Menu::Menu(Type type)
1454 : m_name(), m_key_name(), m_identifier(0), m_type(type), m_key_value(0),
1455 m_start_col(0), m_max_submenu_name_length(0),
1456 m_max_submenu_key_name_length(0), m_selected(0), m_parent(nullptr),
1457 m_submenus(), m_canned_result(MenuActionResult::NotHandled),
1460 // Menuitem constructor
1461 Menu::Menu(const char *name, const char *key_name, int key_value,
1462 uint64_t identifier)
1463 : m_name(), m_key_name(), m_identifier(identifier), m_type(Type::Invalid),
1464 m_key_value(key_value), m_start_col(0), m_max_submenu_name_length(0),
1465 m_max_submenu_key_name_length(0), m_selected(0), m_parent(nullptr),
1466 m_submenus(), m_canned_result(MenuActionResult::NotHandled),
1468 if (name && name[0]) {
1470 m_type = Type::Item;
1471 if (key_name && key_name[0])
1472 m_key_name = key_name;
1474 m_type = Type::Separator;
1478 void Menu::RecalculateNameLengths() {
1479 m_max_submenu_name_length = 0;
1480 m_max_submenu_key_name_length = 0;
1481 Menus &submenus = GetSubmenus();
1482 const size_t num_submenus = submenus.size();
1483 for (size_t i = 0; i < num_submenus; ++i) {
1484 Menu *submenu = submenus[i].get();
1485 if (static_cast<size_t>(m_max_submenu_name_length) < submenu->m_name.size())
1486 m_max_submenu_name_length = submenu->m_name.size();
1487 if (static_cast<size_t>(m_max_submenu_key_name_length) <
1488 submenu->m_key_name.size())
1489 m_max_submenu_key_name_length = submenu->m_key_name.size();
1493 void Menu::AddSubmenu(const MenuSP &menu_sp) {
1494 menu_sp->m_parent = this;
1495 if (static_cast<size_t>(m_max_submenu_name_length) < menu_sp->m_name.size())
1496 m_max_submenu_name_length = menu_sp->m_name.size();
1497 if (static_cast<size_t>(m_max_submenu_key_name_length) <
1498 menu_sp->m_key_name.size())
1499 m_max_submenu_key_name_length = menu_sp->m_key_name.size();
1500 m_submenus.push_back(menu_sp);
1503 void Menu::DrawMenuTitle(Window &window, bool highlight) {
1504 if (m_type == Type::Separator) {
1505 window.MoveCursor(0, window.GetCursorY());
1506 window.PutChar(ACS_LTEE);
1507 int width = window.GetWidth();
1510 for (int i = 0; i < width; ++i)
1511 window.PutChar(ACS_HLINE);
1513 window.PutChar(ACS_RTEE);
1515 const int shortcut_key = m_key_value;
1516 bool underlined_shortcut = false;
1517 const attr_t hilgight_attr = A_REVERSE;
1519 window.AttributeOn(hilgight_attr);
1520 if (isprint(shortcut_key)) {
1521 size_t lower_pos = m_name.find(tolower(shortcut_key));
1522 size_t upper_pos = m_name.find(toupper(shortcut_key));
1523 const char *name = m_name.c_str();
1524 size_t pos = std::min<size_t>(lower_pos, upper_pos);
1525 if (pos != std::string::npos) {
1526 underlined_shortcut = true;
1528 window.PutCString(name, pos);
1531 const attr_t shortcut_attr = A_UNDERLINE | A_BOLD;
1532 window.AttributeOn(shortcut_attr);
1533 window.PutChar(name[0]);
1534 window.AttributeOff(shortcut_attr);
1537 window.PutCString(name);
1541 if (!underlined_shortcut) {
1542 window.PutCString(m_name.c_str());
1546 window.AttributeOff(hilgight_attr);
1548 if (m_key_name.empty()) {
1549 if (!underlined_shortcut && isprint(m_key_value)) {
1550 window.AttributeOn(COLOR_PAIR(3));
1551 window.Printf(" (%c)", m_key_value);
1552 window.AttributeOff(COLOR_PAIR(3));
1555 window.AttributeOn(COLOR_PAIR(3));
1556 window.Printf(" (%s)", m_key_name.c_str());
1557 window.AttributeOff(COLOR_PAIR(3));
1562 bool Menu::WindowDelegateDraw(Window &window, bool force) {
1563 Menus &submenus = GetSubmenus();
1564 const size_t num_submenus = submenus.size();
1565 const int selected_idx = GetSelectedSubmenuIndex();
1566 Menu::Type menu_type = GetType();
1567 switch (menu_type) {
1568 case Menu::Type::Bar: {
1569 window.SetBackground(2);
1570 window.MoveCursor(0, 0);
1571 for (size_t i = 0; i < num_submenus; ++i) {
1572 Menu *menu = submenus[i].get();
1574 window.PutChar(' ');
1575 menu->SetStartingColumn(window.GetCursorX());
1576 window.PutCString("| ");
1577 menu->DrawMenuTitle(window, false);
1579 window.PutCString(" |");
1580 window.DeferredRefresh();
1583 case Menu::Type::Item: {
1590 window.SetBackground(2);
1592 for (size_t i = 0; i < num_submenus; ++i) {
1593 const bool is_selected = (i == static_cast<size_t>(selected_idx));
1594 window.MoveCursor(x, y + i);
1596 // Remember where we want the cursor to be
1600 submenus[i]->DrawMenuTitle(window, is_selected);
1602 window.MoveCursor(cursor_x, cursor_y);
1603 window.DeferredRefresh();
1607 case Menu::Type::Separator:
1610 return true; // Drawing handled...
1613 HandleCharResult Menu::WindowDelegateHandleChar(Window &window, int key) {
1614 HandleCharResult result = eKeyNotHandled;
1616 Menus &submenus = GetSubmenus();
1617 const size_t num_submenus = submenus.size();
1618 const int selected_idx = GetSelectedSubmenuIndex();
1619 Menu::Type menu_type = GetType();
1620 if (menu_type == Menu::Type::Bar) {
1625 // Show last menu or first menu
1626 if (selected_idx < static_cast<int>(num_submenus))
1627 run_menu_sp = submenus[selected_idx];
1628 else if (!submenus.empty())
1629 run_menu_sp = submenus.front();
1630 result = eKeyHandled;
1635 if (m_selected >= static_cast<int>(num_submenus))
1637 if (m_selected < static_cast<int>(num_submenus))
1638 run_menu_sp = submenus[m_selected];
1639 else if (!submenus.empty())
1640 run_menu_sp = submenus.front();
1641 result = eKeyHandled;
1647 m_selected = num_submenus - 1;
1648 if (m_selected < static_cast<int>(num_submenus))
1649 run_menu_sp = submenus[m_selected];
1650 else if (!submenus.empty())
1651 run_menu_sp = submenus.front();
1652 result = eKeyHandled;
1656 for (size_t i = 0; i < num_submenus; ++i) {
1657 if (submenus[i]->GetKeyValue() == key) {
1658 SetSelectedSubmenuIndex(i);
1659 run_menu_sp = submenus[i];
1660 result = eKeyHandled;
1668 // Run the action on this menu in case we need to populate the
1669 // menu with dynamic content and also in case check marks, and
1670 // any other menu decorations need to be calculated
1671 if (run_menu_sp->Action() == MenuActionResult::Quit)
1672 return eQuitApplication;
1675 menu_bounds.origin.x = run_menu_sp->GetStartingColumn();
1676 menu_bounds.origin.y = 1;
1677 menu_bounds.size.width = run_menu_sp->GetDrawWidth();
1678 menu_bounds.size.height = run_menu_sp->GetSubmenus().size() + 2;
1679 if (m_menu_window_sp)
1680 window.GetParent()->RemoveSubWindow(m_menu_window_sp.get());
1682 m_menu_window_sp = window.GetParent()->CreateSubWindow(
1683 run_menu_sp->GetName().c_str(), menu_bounds, true);
1684 m_menu_window_sp->SetDelegate(run_menu_sp);
1686 } else if (menu_type == Menu::Type::Item) {
1689 if (m_submenus.size() > 1) {
1690 const int start_select = m_selected;
1691 while (++m_selected != start_select) {
1692 if (static_cast<size_t>(m_selected) >= num_submenus)
1694 if (m_submenus[m_selected]->GetType() == Type::Separator)
1704 if (m_submenus.size() > 1) {
1705 const int start_select = m_selected;
1706 while (--m_selected != start_select) {
1707 if (m_selected < static_cast<int>(0))
1708 m_selected = num_submenus - 1;
1709 if (m_submenus[m_selected]->GetType() == Type::Separator)
1719 if (static_cast<size_t>(selected_idx) < num_submenus) {
1720 if (submenus[selected_idx]->Action() == MenuActionResult::Quit)
1721 return eQuitApplication;
1722 window.GetParent()->RemoveSubWindow(&window);
1727 case KEY_ESCAPE: // Beware: pressing escape key has 1 to 2 second delay in
1728 // case other chars are entered for escaped sequences
1729 window.GetParent()->RemoveSubWindow(&window);
1733 for (size_t i = 0; i < num_submenus; ++i) {
1734 Menu *menu = submenus[i].get();
1735 if (menu->GetKeyValue() == key) {
1736 SetSelectedSubmenuIndex(i);
1737 window.GetParent()->RemoveSubWindow(&window);
1738 if (menu->Action() == MenuActionResult::Quit)
1739 return eQuitApplication;
1745 } else if (menu_type == Menu::Type::Separator) {
1752 Application(FILE *in, FILE *out)
1753 : m_window_sp(), m_screen(nullptr), m_in(in), m_out(out) {}
1756 m_window_delegates.clear();
1757 m_window_sp.reset();
1759 ::delscreen(m_screen);
1765 ::setlocale(LC_ALL, "");
1766 ::setlocale(LC_CTYPE, "");
1770 m_screen = ::newterm(nullptr, m_out, m_in);
1775 ::keypad(stdscr, TRUE);
1778 void Terminate() { ::endwin(); }
1780 void Run(Debugger &debugger) {
1782 int delay_in_tenths_of_a_second = 1;
1784 // Alas the threading model in curses is a bit lame so we need to
1785 // resort to polling every 0.5 seconds. We could poll for stdin
1786 // ourselves and then pass the keys down but then we need to
1787 // translate all of the escape sequences ourselves. So we resort to
1788 // polling for input because we need to receive async process events
1789 // while in this loop.
1791 halfdelay(delay_in_tenths_of_a_second); // Poll using some number of tenths
1792 // of seconds seconds when calling
1793 // Window::GetChar()
1795 ListenerSP listener_sp(
1796 Listener::MakeListener("lldb.IOHandler.curses.Application"));
1797 ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass());
1798 ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass());
1799 ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass());
1800 debugger.EnableForwardEvents(listener_sp);
1803 #if defined(__APPLE__)
1804 std::deque<int> escape_chars;
1809 m_window_sp->Draw(false);
1810 // All windows should be calling Window::DeferredRefresh() instead
1811 // of Window::Refresh() so we can do a single update and avoid
1812 // any screen blinking
1815 // Cursor hiding isn't working on MacOSX, so hide it in the top left
1817 m_window_sp->MoveCursor(0, 0);
1823 #if defined(__APPLE__)
1824 // Terminal.app doesn't map its function keys correctly, F1-F4 default to:
1825 // \033OP, \033OQ, \033OR, \033OS, so lets take care of this here if
1828 if (escape_chars.empty())
1829 ch = m_window_sp->GetChar();
1831 ch = escape_chars.front();
1832 escape_chars.pop_front();
1834 if (ch == KEY_ESCAPE) {
1835 int ch2 = m_window_sp->GetChar();
1837 int ch3 = m_window_sp->GetChar();
1852 escape_chars.push_back(ch2);
1854 escape_chars.push_back(ch3);
1857 } else if (ch2 != -1)
1858 escape_chars.push_back(ch2);
1861 int ch = m_window_sp->GetChar();
1865 if (feof(m_in) || ferror(m_in)) {
1868 // Just a timeout from using halfdelay(), check for events
1870 while (listener_sp->PeekAtNextEvent()) {
1871 listener_sp->GetEvent(event_sp, std::chrono::seconds(0));
1874 Broadcaster *broadcaster = event_sp->GetBroadcaster();
1876 // uint32_t event_type = event_sp->GetType();
1877 ConstString broadcaster_class(
1878 broadcaster->GetBroadcasterClass());
1879 if (broadcaster_class == broadcaster_class_process) {
1880 debugger.GetCommandInterpreter().UpdateExecutionContext(
1883 continue; // Don't get any key, just update our view
1890 HandleCharResult key_result = m_window_sp->HandleChar(ch);
1891 switch (key_result) {
1893 debugger.GetCommandInterpreter().UpdateExecutionContext(nullptr);
1896 case eKeyNotHandled:
1898 case eQuitApplication:
1905 debugger.CancelForwardEvents(listener_sp);
1908 WindowSP &GetMainWindow() {
1910 m_window_sp.reset(new Window("main", stdscr, false));
1914 WindowDelegates &GetWindowDelegates() { return m_window_delegates; }
1917 WindowSP m_window_sp;
1918 WindowDelegates m_window_delegates;
1924 } // namespace curses
1926 using namespace curses;
1929 ValueObjectManager value;
1931 // The process stop ID when the children were calculated.
1932 uint32_t children_stop_id;
1936 bool might_have_children;
1938 bool calculated_children;
1939 std::vector<Row> children;
1941 Row(const ValueObjectSP &v, Row *p)
1942 : value(v, lldb::eDynamicDontRunTarget, true), parent(p), row_idx(0),
1943 x(1), y(1), might_have_children(v ? v->MightHaveChildren() : false),
1944 expanded(false), calculated_children(false), children() {}
1946 size_t GetDepth() const {
1948 return 1 + parent->GetDepth();
1956 std::vector<Row> &GetChildren() {
1957 ProcessSP process_sp = value.GetProcessSP();
1958 auto stop_id = process_sp->GetStopID();
1959 if (process_sp && stop_id != children_stop_id) {
1960 children_stop_id = stop_id;
1961 calculated_children = false;
1963 if (!calculated_children) {
1965 calculated_children = true;
1966 ValueObjectSP valobj = value.GetSP();
1968 const size_t num_children = valobj->GetNumChildren();
1969 for (size_t i = 0; i < num_children; ++i) {
1970 children.push_back(Row(valobj->GetChildAtIndex(i, true), this));
1979 calculated_children = false;
1983 void DrawTree(Window &window) {
1985 parent->DrawTreeForChild(window, this, 0);
1987 if (might_have_children) {
1988 // It we can get UTF8 characters to work we should try to use the "symbol"
1989 // UTF8 string below
1990 // const char *symbol = "";
1991 // if (row.expanded)
1992 // symbol = "\xe2\x96\xbd ";
1994 // symbol = "\xe2\x96\xb7 ";
1995 // window.PutCString (symbol);
1997 // The ACS_DARROW and ACS_RARROW don't look very nice they are just a
1998 // 'v' or '>' character...
2000 // window.PutChar (ACS_DARROW);
2002 // window.PutChar (ACS_RARROW);
2003 // Since we can't find any good looking right arrow/down arrow
2004 // symbols, just use a diamond...
2005 window.PutChar(ACS_DIAMOND);
2006 window.PutChar(ACS_HLINE);
2010 void DrawTreeForChild(Window &window, Row *child, uint32_t reverse_depth) {
2012 parent->DrawTreeForChild(window, this, reverse_depth + 1);
2014 if (&GetChildren().back() == child) {
2016 if (reverse_depth == 0) {
2017 window.PutChar(ACS_LLCORNER);
2018 window.PutChar(ACS_HLINE);
2020 window.PutChar(' ');
2021 window.PutChar(' ');
2024 if (reverse_depth == 0) {
2025 window.PutChar(ACS_LTEE);
2026 window.PutChar(ACS_HLINE);
2028 window.PutChar(ACS_VLINE);
2029 window.PutChar(' ');
2035 struct DisplayOptions {
2041 class TreeDelegate {
2043 TreeDelegate() = default;
2044 virtual ~TreeDelegate() = default;
2046 virtual void TreeDelegateDrawTreeItem(TreeItem &item, Window &window) = 0;
2047 virtual void TreeDelegateGenerateChildren(TreeItem &item) = 0;
2048 virtual bool TreeDelegateItemSelected(
2049 TreeItem &item) = 0; // Return true if we need to update views
2052 typedef std::shared_ptr<TreeDelegate> TreeDelegateSP;
2056 TreeItem(TreeItem *parent, TreeDelegate &delegate, bool might_have_children)
2057 : m_parent(parent), m_delegate(delegate), m_user_data(nullptr),
2058 m_identifier(0), m_row_idx(-1), m_children(),
2059 m_might_have_children(might_have_children), m_is_expanded(false) {}
2061 TreeItem &operator=(const TreeItem &rhs) {
2063 m_parent = rhs.m_parent;
2064 m_delegate = rhs.m_delegate;
2065 m_user_data = rhs.m_user_data;
2066 m_identifier = rhs.m_identifier;
2067 m_row_idx = rhs.m_row_idx;
2068 m_children = rhs.m_children;
2069 m_might_have_children = rhs.m_might_have_children;
2070 m_is_expanded = rhs.m_is_expanded;
2075 size_t GetDepth() const {
2077 return 1 + m_parent->GetDepth();
2081 int GetRowIndex() const { return m_row_idx; }
2083 void ClearChildren() { m_children.clear(); }
2085 void Resize(size_t n, const TreeItem &t) { m_children.resize(n, t); }
2087 TreeItem &operator[](size_t i) { return m_children[i]; }
2089 void SetRowIndex(int row_idx) { m_row_idx = row_idx; }
2091 size_t GetNumChildren() {
2092 m_delegate.TreeDelegateGenerateChildren(*this);
2093 return m_children.size();
2096 void ItemWasSelected() { m_delegate.TreeDelegateItemSelected(*this); }
2098 void CalculateRowIndexes(int &row_idx) {
2099 SetRowIndex(row_idx);
2102 const bool expanded = IsExpanded();
2104 // The root item must calculate its children,
2105 // or we must calculate the number of children
2106 // if the item is expanded
2107 if (m_parent == nullptr || expanded)
2110 for (auto &item : m_children) {
2112 item.CalculateRowIndexes(row_idx);
2114 item.SetRowIndex(-1);
2118 TreeItem *GetParent() { return m_parent; }
2120 bool IsExpanded() const { return m_is_expanded; }
2122 void Expand() { m_is_expanded = true; }
2124 void Unexpand() { m_is_expanded = false; }
2126 bool Draw(Window &window, const int first_visible_row,
2127 const uint32_t selected_row_idx, int &row_idx, int &num_rows_left) {
2128 if (num_rows_left <= 0)
2131 if (m_row_idx >= first_visible_row) {
2132 window.MoveCursor(2, row_idx + 1);
2135 m_parent->DrawTreeForChild(window, this, 0);
2137 if (m_might_have_children) {
2138 // It we can get UTF8 characters to work we should try to use the
2140 // UTF8 string below
2141 // const char *symbol = "";
2142 // if (row.expanded)
2143 // symbol = "\xe2\x96\xbd ";
2145 // symbol = "\xe2\x96\xb7 ";
2146 // window.PutCString (symbol);
2148 // The ACS_DARROW and ACS_RARROW don't look very nice they are just a
2149 // 'v' or '>' character...
2151 // window.PutChar (ACS_DARROW);
2153 // window.PutChar (ACS_RARROW);
2154 // Since we can't find any good looking right arrow/down arrow
2155 // symbols, just use a diamond...
2156 window.PutChar(ACS_DIAMOND);
2157 window.PutChar(ACS_HLINE);
2159 bool highlight = (selected_row_idx == static_cast<size_t>(m_row_idx)) &&
2163 window.AttributeOn(A_REVERSE);
2165 m_delegate.TreeDelegateDrawTreeItem(*this, window);
2168 window.AttributeOff(A_REVERSE);
2173 if (num_rows_left <= 0)
2174 return false; // We are done drawing...
2177 for (auto &item : m_children) {
2178 // If we displayed all the rows and item.Draw() returns
2179 // false we are done drawing and can exit this for loop
2180 if (!item.Draw(window, first_visible_row, selected_row_idx, row_idx,
2185 return num_rows_left >= 0; // Return true if not done drawing yet
2188 void DrawTreeForChild(Window &window, TreeItem *child,
2189 uint32_t reverse_depth) {
2191 m_parent->DrawTreeForChild(window, this, reverse_depth + 1);
2193 if (&m_children.back() == child) {
2195 if (reverse_depth == 0) {
2196 window.PutChar(ACS_LLCORNER);
2197 window.PutChar(ACS_HLINE);
2199 window.PutChar(' ');
2200 window.PutChar(' ');
2203 if (reverse_depth == 0) {
2204 window.PutChar(ACS_LTEE);
2205 window.PutChar(ACS_HLINE);
2207 window.PutChar(ACS_VLINE);
2208 window.PutChar(' ');
2213 TreeItem *GetItemForRowIndex(uint32_t row_idx) {
2214 if (static_cast<uint32_t>(m_row_idx) == row_idx)
2216 if (m_children.empty())
2219 for (auto &item : m_children) {
2220 TreeItem *selected_item_ptr = item.GetItemForRowIndex(row_idx);
2221 if (selected_item_ptr)
2222 return selected_item_ptr;
2228 void *GetUserData() const { return m_user_data; }
2230 void SetUserData(void *user_data) { m_user_data = user_data; }
2232 uint64_t GetIdentifier() const { return m_identifier; }
2234 void SetIdentifier(uint64_t identifier) { m_identifier = identifier; }
2236 void SetMightHaveChildren(bool b) { m_might_have_children = b; }
2240 TreeDelegate &m_delegate;
2242 uint64_t m_identifier;
2243 int m_row_idx; // Zero based visible row index, -1 if not visible or for the
2245 std::vector<TreeItem> m_children;
2246 bool m_might_have_children;
2250 class TreeWindowDelegate : public WindowDelegate {
2252 TreeWindowDelegate(Debugger &debugger, const TreeDelegateSP &delegate_sp)
2253 : m_debugger(debugger), m_delegate_sp(delegate_sp),
2254 m_root(nullptr, *delegate_sp, true), m_selected_item(nullptr),
2255 m_num_rows(0), m_selected_row_idx(0), m_first_visible_row(0),
2256 m_min_x(0), m_min_y(0), m_max_x(0), m_max_y(0) {}
2258 int NumVisibleRows() const { return m_max_y - m_min_y; }
2260 bool WindowDelegateDraw(Window &window, bool force) override {
2261 ExecutionContext exe_ctx(
2262 m_debugger.GetCommandInterpreter().GetExecutionContext());
2263 Process *process = exe_ctx.GetProcessPtr();
2265 bool display_content = false;
2267 StateType state = process->GetState();
2268 if (StateIsStoppedState(state, true)) {
2269 // We are stopped, so it is ok to
2270 display_content = true;
2271 } else if (StateIsRunningState(state)) {
2272 return true; // Don't do any updating when we are running
2278 m_max_x = window.GetWidth() - 1;
2279 m_max_y = window.GetHeight() - 1;
2282 window.DrawTitleBox(window.GetName());
2284 if (display_content) {
2285 const int num_visible_rows = NumVisibleRows();
2287 m_root.CalculateRowIndexes(m_num_rows);
2289 // If we unexpanded while having something selected our
2290 // total number of rows is less than the num visible rows,
2291 // then make sure we show all the rows by setting the first
2292 // visible row accordingly.
2293 if (m_first_visible_row > 0 && m_num_rows < num_visible_rows)
2294 m_first_visible_row = 0;
2296 // Make sure the selected row is always visible
2297 if (m_selected_row_idx < m_first_visible_row)
2298 m_first_visible_row = m_selected_row_idx;
2299 else if (m_first_visible_row + num_visible_rows <= m_selected_row_idx)
2300 m_first_visible_row = m_selected_row_idx - num_visible_rows + 1;
2303 int num_rows_left = num_visible_rows;
2304 m_root.Draw(window, m_first_visible_row, m_selected_row_idx, row_idx,
2306 // Get the selected row
2307 m_selected_item = m_root.GetItemForRowIndex(m_selected_row_idx);
2309 m_selected_item = nullptr;
2312 window.DeferredRefresh();
2314 return true; // Drawing handled
2317 const char *WindowDelegateGetHelpText() override {
2318 return "Thread window keyboard shortcuts:";
2321 KeyHelp *WindowDelegateGetKeyHelp() override {
2322 static curses::KeyHelp g_source_view_key_help[] = {
2323 {KEY_UP, "Select previous item"},
2324 {KEY_DOWN, "Select next item"},
2325 {KEY_RIGHT, "Expand the selected item"},
2327 "Unexpand the selected item or select parent if not expanded"},
2328 {KEY_PPAGE, "Page up"},
2329 {KEY_NPAGE, "Page down"},
2330 {'h', "Show help dialog"},
2331 {' ', "Toggle item expansion"},
2335 return g_source_view_key_help;
2338 HandleCharResult WindowDelegateHandleChar(Window &window, int c) override {
2343 if (m_first_visible_row > 0) {
2344 if (m_first_visible_row > m_max_y)
2345 m_first_visible_row -= m_max_y;
2347 m_first_visible_row = 0;
2348 m_selected_row_idx = m_first_visible_row;
2349 m_selected_item = m_root.GetItemForRowIndex(m_selected_row_idx);
2350 if (m_selected_item)
2351 m_selected_item->ItemWasSelected();
2358 if (m_num_rows > m_max_y) {
2359 if (m_first_visible_row + m_max_y < m_num_rows) {
2360 m_first_visible_row += m_max_y;
2361 m_selected_row_idx = m_first_visible_row;
2362 m_selected_item = m_root.GetItemForRowIndex(m_selected_row_idx);
2363 if (m_selected_item)
2364 m_selected_item->ItemWasSelected();
2370 if (m_selected_row_idx > 0) {
2371 --m_selected_row_idx;
2372 m_selected_item = m_root.GetItemForRowIndex(m_selected_row_idx);
2373 if (m_selected_item)
2374 m_selected_item->ItemWasSelected();
2379 if (m_selected_row_idx + 1 < m_num_rows) {
2380 ++m_selected_row_idx;
2381 m_selected_item = m_root.GetItemForRowIndex(m_selected_row_idx);
2382 if (m_selected_item)
2383 m_selected_item->ItemWasSelected();
2388 if (m_selected_item) {
2389 if (!m_selected_item->IsExpanded())
2390 m_selected_item->Expand();
2395 if (m_selected_item) {
2396 if (m_selected_item->IsExpanded())
2397 m_selected_item->Unexpand();
2398 else if (m_selected_item->GetParent()) {
2399 m_selected_row_idx = m_selected_item->GetParent()->GetRowIndex();
2400 m_selected_item = m_root.GetItemForRowIndex(m_selected_row_idx);
2401 if (m_selected_item)
2402 m_selected_item->ItemWasSelected();
2408 // Toggle expansion state when SPACE is pressed
2409 if (m_selected_item) {
2410 if (m_selected_item->IsExpanded())
2411 m_selected_item->Unexpand();
2413 m_selected_item->Expand();
2418 window.CreateHelpSubwindow();
2424 return eKeyNotHandled;
2428 Debugger &m_debugger;
2429 TreeDelegateSP m_delegate_sp;
2431 TreeItem *m_selected_item;
2433 int m_selected_row_idx;
2434 int m_first_visible_row;
2441 class FrameTreeDelegate : public TreeDelegate {
2443 FrameTreeDelegate() : TreeDelegate() {
2444 FormatEntity::Parse(
2445 "frame #${frame.index}: {${function.name}${function.pc-offset}}}",
2449 ~FrameTreeDelegate() override = default;
2451 void TreeDelegateDrawTreeItem(TreeItem &item, Window &window) override {
2452 Thread *thread = (Thread *)item.GetUserData();
2454 const uint64_t frame_idx = item.GetIdentifier();
2455 StackFrameSP frame_sp = thread->GetStackFrameAtIndex(frame_idx);
2458 const SymbolContext &sc =
2459 frame_sp->GetSymbolContext(eSymbolContextEverything);
2460 ExecutionContext exe_ctx(frame_sp);
2461 if (FormatEntity::Format(m_format, strm, &sc, &exe_ctx, nullptr,
2462 nullptr, false, false)) {
2464 window.PutCStringTruncated(strm.GetString().str().c_str(), right_pad);
2470 void TreeDelegateGenerateChildren(TreeItem &item) override {
2471 // No children for frames yet...
2474 bool TreeDelegateItemSelected(TreeItem &item) override {
2475 Thread *thread = (Thread *)item.GetUserData();
2477 thread->GetProcess()->GetThreadList().SetSelectedThreadByID(
2479 const uint64_t frame_idx = item.GetIdentifier();
2480 thread->SetSelectedFrameByIndex(frame_idx);
2487 FormatEntity::Entry m_format;
2490 class ThreadTreeDelegate : public TreeDelegate {
2492 ThreadTreeDelegate(Debugger &debugger)
2493 : TreeDelegate(), m_debugger(debugger), m_tid(LLDB_INVALID_THREAD_ID),
2494 m_stop_id(UINT32_MAX) {
2495 FormatEntity::Parse("thread #${thread.index}: tid = ${thread.id}{, stop "
2496 "reason = ${thread.stop-reason}}",
2500 ~ThreadTreeDelegate() override = default;
2502 ProcessSP GetProcess() {
2503 return m_debugger.GetCommandInterpreter()
2504 .GetExecutionContext()
2508 ThreadSP GetThread(const TreeItem &item) {
2509 ProcessSP process_sp = GetProcess();
2511 return process_sp->GetThreadList().FindThreadByID(item.GetIdentifier());
2515 void TreeDelegateDrawTreeItem(TreeItem &item, Window &window) override {
2516 ThreadSP thread_sp = GetThread(item);
2519 ExecutionContext exe_ctx(thread_sp);
2520 if (FormatEntity::Format(m_format, strm, nullptr, &exe_ctx, nullptr,
2521 nullptr, false, false)) {
2523 window.PutCStringTruncated(strm.GetString().str().c_str(), right_pad);
2528 void TreeDelegateGenerateChildren(TreeItem &item) override {
2529 ProcessSP process_sp = GetProcess();
2530 if (process_sp && process_sp->IsAlive()) {
2531 StateType state = process_sp->GetState();
2532 if (StateIsStoppedState(state, true)) {
2533 ThreadSP thread_sp = GetThread(item);
2535 if (m_stop_id == process_sp->GetStopID() &&
2536 thread_sp->GetID() == m_tid)
2537 return; // Children are already up to date
2538 if (!m_frame_delegate_sp) {
2539 // Always expand the thread item the first time we show it
2540 m_frame_delegate_sp.reset(new FrameTreeDelegate());
2543 m_stop_id = process_sp->GetStopID();
2544 m_tid = thread_sp->GetID();
2546 TreeItem t(&item, *m_frame_delegate_sp, false);
2547 size_t num_frames = thread_sp->GetStackFrameCount();
2548 item.Resize(num_frames, t);
2549 for (size_t i = 0; i < num_frames; ++i) {
2550 item[i].SetUserData(thread_sp.get());
2551 item[i].SetIdentifier(i);
2557 item.ClearChildren();
2560 bool TreeDelegateItemSelected(TreeItem &item) override {
2561 ProcessSP process_sp = GetProcess();
2562 if (process_sp && process_sp->IsAlive()) {
2563 StateType state = process_sp->GetState();
2564 if (StateIsStoppedState(state, true)) {
2565 ThreadSP thread_sp = GetThread(item);
2567 ThreadList &thread_list = thread_sp->GetProcess()->GetThreadList();
2568 std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex());
2569 ThreadSP selected_thread_sp = thread_list.GetSelectedThread();
2570 if (selected_thread_sp->GetID() != thread_sp->GetID()) {
2571 thread_list.SetSelectedThreadByID(thread_sp->GetID());
2581 Debugger &m_debugger;
2582 std::shared_ptr<FrameTreeDelegate> m_frame_delegate_sp;
2583 lldb::user_id_t m_tid;
2585 FormatEntity::Entry m_format;
2588 class ThreadsTreeDelegate : public TreeDelegate {
2590 ThreadsTreeDelegate(Debugger &debugger)
2591 : TreeDelegate(), m_thread_delegate_sp(), m_debugger(debugger),
2592 m_stop_id(UINT32_MAX) {
2593 FormatEntity::Parse("process ${process.id}{, name = ${process.name}}",
2597 ~ThreadsTreeDelegate() override = default;
2599 ProcessSP GetProcess() {
2600 return m_debugger.GetCommandInterpreter()
2601 .GetExecutionContext()
2605 void TreeDelegateDrawTreeItem(TreeItem &item, Window &window) override {
2606 ProcessSP process_sp = GetProcess();
2607 if (process_sp && process_sp->IsAlive()) {
2609 ExecutionContext exe_ctx(process_sp);
2610 if (FormatEntity::Format(m_format, strm, nullptr, &exe_ctx, nullptr,
2611 nullptr, false, false)) {
2613 window.PutCStringTruncated(strm.GetString().str().c_str(), right_pad);
2618 void TreeDelegateGenerateChildren(TreeItem &item) override {
2619 ProcessSP process_sp = GetProcess();
2620 if (process_sp && process_sp->IsAlive()) {
2621 StateType state = process_sp->GetState();
2622 if (StateIsStoppedState(state, true)) {
2623 const uint32_t stop_id = process_sp->GetStopID();
2624 if (m_stop_id == stop_id)
2625 return; // Children are already up to date
2627 m_stop_id = stop_id;
2629 if (!m_thread_delegate_sp) {
2630 // Always expand the thread item the first time we show it
2632 m_thread_delegate_sp.reset(new ThreadTreeDelegate(m_debugger));
2635 TreeItem t(&item, *m_thread_delegate_sp, false);
2636 ThreadList &threads = process_sp->GetThreadList();
2637 std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
2638 size_t num_threads = threads.GetSize();
2639 item.Resize(num_threads, t);
2640 for (size_t i = 0; i < num_threads; ++i) {
2641 item[i].SetIdentifier(threads.GetThreadAtIndex(i)->GetID());
2642 item[i].SetMightHaveChildren(true);
2647 item.ClearChildren();
2650 bool TreeDelegateItemSelected(TreeItem &item) override { return false; }
2653 std::shared_ptr<ThreadTreeDelegate> m_thread_delegate_sp;
2654 Debugger &m_debugger;
2656 FormatEntity::Entry m_format;
2659 class ValueObjectListDelegate : public WindowDelegate {
2661 ValueObjectListDelegate()
2662 : m_rows(), m_selected_row(nullptr),
2663 m_selected_row_idx(0), m_first_visible_row(0), m_num_rows(0),
2664 m_max_x(0), m_max_y(0) {}
2666 ValueObjectListDelegate(ValueObjectList &valobj_list)
2667 : m_rows(), m_selected_row(nullptr),
2668 m_selected_row_idx(0), m_first_visible_row(0), m_num_rows(0),
2669 m_max_x(0), m_max_y(0) {
2670 SetValues(valobj_list);
2673 ~ValueObjectListDelegate() override = default;
2675 void SetValues(ValueObjectList &valobj_list) {
2676 m_selected_row = nullptr;
2677 m_selected_row_idx = 0;
2678 m_first_visible_row = 0;
2681 for (auto &valobj_sp : valobj_list.GetObjects())
2682 m_rows.push_back(Row(valobj_sp, nullptr));
2685 bool WindowDelegateDraw(Window &window, bool force) override {
2689 m_max_x = window.GetWidth() - 1;
2690 m_max_y = window.GetHeight() - 1;
2693 window.DrawTitleBox(window.GetName());
2695 const int num_visible_rows = NumVisibleRows();
2696 const int num_rows = CalculateTotalNumberRows(m_rows);
2698 // If we unexpanded while having something selected our
2699 // total number of rows is less than the num visible rows,
2700 // then make sure we show all the rows by setting the first
2701 // visible row accordingly.
2702 if (m_first_visible_row > 0 && num_rows < num_visible_rows)
2703 m_first_visible_row = 0;
2705 // Make sure the selected row is always visible
2706 if (m_selected_row_idx < m_first_visible_row)
2707 m_first_visible_row = m_selected_row_idx;
2708 else if (m_first_visible_row + num_visible_rows <= m_selected_row_idx)
2709 m_first_visible_row = m_selected_row_idx - num_visible_rows + 1;
2711 DisplayRows(window, m_rows, g_options);
2713 window.DeferredRefresh();
2715 // Get the selected row
2716 m_selected_row = GetRowForRowIndex(m_selected_row_idx);
2717 // Keep the cursor on the selected row so the highlight and the cursor
2718 // are always on the same line
2720 window.MoveCursor(m_selected_row->x, m_selected_row->y);
2722 return true; // Drawing handled
2725 KeyHelp *WindowDelegateGetKeyHelp() override {
2726 static curses::KeyHelp g_source_view_key_help[] = {
2727 {KEY_UP, "Select previous item"},
2728 {KEY_DOWN, "Select next item"},
2729 {KEY_RIGHT, "Expand selected item"},
2730 {KEY_LEFT, "Unexpand selected item or select parent if not expanded"},
2731 {KEY_PPAGE, "Page up"},
2732 {KEY_NPAGE, "Page down"},
2733 {'A', "Format as annotated address"},
2734 {'b', "Format as binary"},
2735 {'B', "Format as hex bytes with ASCII"},
2736 {'c', "Format as character"},
2737 {'d', "Format as a signed integer"},
2738 {'D', "Format selected value using the default format for the type"},
2739 {'f', "Format as float"},
2740 {'h', "Show help dialog"},
2741 {'i', "Format as instructions"},
2742 {'o', "Format as octal"},
2743 {'p', "Format as pointer"},
2744 {'s', "Format as C string"},
2745 {'t', "Toggle showing/hiding type names"},
2746 {'u', "Format as an unsigned integer"},
2747 {'x', "Format as hex"},
2748 {'X', "Format as uppercase hex"},
2749 {' ', "Toggle item expansion"},
2753 return g_source_view_key_help;
2756 HandleCharResult WindowDelegateHandleChar(Window &window, int c) override {
2772 // Change the format for the currently selected item
2773 if (m_selected_row) {
2774 auto valobj_sp = m_selected_row->value.GetSP();
2776 valobj_sp->SetFormat(FormatForChar(c));
2781 // Toggle showing type names
2782 g_options.show_types = !g_options.show_types;
2788 if (m_first_visible_row > 0) {
2789 if (static_cast<int>(m_first_visible_row) > m_max_y)
2790 m_first_visible_row -= m_max_y;
2792 m_first_visible_row = 0;
2793 m_selected_row_idx = m_first_visible_row;
2800 if (m_num_rows > static_cast<size_t>(m_max_y)) {
2801 if (m_first_visible_row + m_max_y < m_num_rows) {
2802 m_first_visible_row += m_max_y;
2803 m_selected_row_idx = m_first_visible_row;
2809 if (m_selected_row_idx > 0)
2810 --m_selected_row_idx;
2814 if (m_selected_row_idx + 1 < m_num_rows)
2815 ++m_selected_row_idx;
2819 if (m_selected_row) {
2820 if (!m_selected_row->expanded)
2821 m_selected_row->Expand();
2826 if (m_selected_row) {
2827 if (m_selected_row->expanded)
2828 m_selected_row->Unexpand();
2829 else if (m_selected_row->parent)
2830 m_selected_row_idx = m_selected_row->parent->row_idx;
2835 // Toggle expansion state when SPACE is pressed
2836 if (m_selected_row) {
2837 if (m_selected_row->expanded)
2838 m_selected_row->Unexpand();
2840 m_selected_row->Expand();
2845 window.CreateHelpSubwindow();
2851 return eKeyNotHandled;
2855 std::vector<Row> m_rows;
2856 Row *m_selected_row;
2857 uint32_t m_selected_row_idx;
2858 uint32_t m_first_visible_row;
2859 uint32_t m_num_rows;
2865 static Format FormatForChar(int c) {
2870 return eFormatHexUppercase;
2872 return eFormatOctal;
2874 return eFormatCString;
2876 return eFormatUnsigned;
2878 return eFormatDecimal;
2880 return eFormatDefault;
2882 return eFormatInstruction;
2884 return eFormatAddressInfo;
2886 return eFormatPointer;
2890 return eFormatBinary;
2892 return eFormatBytesWithASCII;
2894 return eFormatFloat;
2896 return eFormatDefault;
2899 bool DisplayRowObject(Window &window, Row &row, DisplayOptions &options,
2900 bool highlight, bool last_child) {
2901 ValueObject *valobj = row.value.GetSP().get();
2903 if (valobj == nullptr)
2906 const char *type_name =
2907 options.show_types ? valobj->GetTypeName().GetCString() : nullptr;
2908 const char *name = valobj->GetName().GetCString();
2909 const char *value = valobj->GetValueAsCString();
2910 const char *summary = valobj->GetSummaryAsCString();
2912 window.MoveCursor(row.x, row.y);
2914 row.DrawTree(window);
2917 window.AttributeOn(A_REVERSE);
2919 if (type_name && type_name[0])
2920 window.Printf("(%s) ", type_name);
2922 if (name && name[0])
2923 window.PutCString(name);
2925 attr_t changd_attr = 0;
2926 if (valobj->GetValueDidChange())
2927 changd_attr = COLOR_PAIR(5) | A_BOLD;
2929 if (value && value[0]) {
2930 window.PutCString(" = ");
2932 window.AttributeOn(changd_attr);
2933 window.PutCString(value);
2935 window.AttributeOff(changd_attr);
2938 if (summary && summary[0]) {
2939 window.PutChar(' ');
2941 window.AttributeOn(changd_attr);
2942 window.PutCString(summary);
2944 window.AttributeOff(changd_attr);
2948 window.AttributeOff(A_REVERSE);
2953 void DisplayRows(Window &window, std::vector<Row> &rows,
2954 DisplayOptions &options) {
2958 bool window_is_active = window.IsActive();
2959 for (auto &row : rows) {
2960 const bool last_child = row.parent && &rows[rows.size() - 1] == &row;
2961 // Save the row index in each Row structure
2962 row.row_idx = m_num_rows;
2963 if ((m_num_rows >= m_first_visible_row) &&
2964 ((m_num_rows - m_first_visible_row) <
2965 static_cast<size_t>(NumVisibleRows()))) {
2967 row.y = m_num_rows - m_first_visible_row + 1;
2968 if (DisplayRowObject(window, row, options,
2970 m_num_rows == m_selected_row_idx,
2983 auto &children = row.GetChildren();
2984 if (row.expanded && !children.empty()) {
2985 DisplayRows(window, children, options);
2990 int CalculateTotalNumberRows(std::vector<Row> &rows) {
2992 for (auto &row : rows) {
2995 row_count += CalculateTotalNumberRows(row.GetChildren());
3000 static Row *GetRowForRowIndexImpl(std::vector<Row> &rows, size_t &row_index) {
3001 for (auto &row : rows) {
3006 auto &children = row.GetChildren();
3007 if (row.expanded && !children.empty()) {
3008 Row *result = GetRowForRowIndexImpl(children, row_index);
3017 Row *GetRowForRowIndex(size_t row_index) {
3018 return GetRowForRowIndexImpl(m_rows, row_index);
3021 int NumVisibleRows() const { return m_max_y - m_min_y; }
3023 static DisplayOptions g_options;
3026 class FrameVariablesWindowDelegate : public ValueObjectListDelegate {
3028 FrameVariablesWindowDelegate(Debugger &debugger)
3029 : ValueObjectListDelegate(), m_debugger(debugger),
3030 m_frame_block(nullptr) {}
3032 ~FrameVariablesWindowDelegate() override = default;
3034 const char *WindowDelegateGetHelpText() override {
3035 return "Frame variable window keyboard shortcuts:";
3038 bool WindowDelegateDraw(Window &window, bool force) override {
3039 ExecutionContext exe_ctx(
3040 m_debugger.GetCommandInterpreter().GetExecutionContext());
3041 Process *process = exe_ctx.GetProcessPtr();
3042 Block *frame_block = nullptr;
3043 StackFrame *frame = nullptr;
3046 StateType state = process->GetState();
3047 if (StateIsStoppedState(state, true)) {
3048 frame = exe_ctx.GetFramePtr();
3050 frame_block = frame->GetFrameBlock();
3051 } else if (StateIsRunningState(state)) {
3052 return true; // Don't do any updating when we are running
3056 ValueObjectList local_values;
3058 // Only update the variables if they have changed
3059 if (m_frame_block != frame_block) {
3060 m_frame_block = frame_block;
3062 VariableList *locals = frame->GetVariableList(true);
3064 const DynamicValueType use_dynamic = eDynamicDontRunTarget;
3065 const size_t num_locals = locals->GetSize();
3066 for (size_t i = 0; i < num_locals; ++i) {
3067 ValueObjectSP value_sp = frame->GetValueObjectForFrameVariable(
3068 locals->GetVariableAtIndex(i), use_dynamic);
3070 ValueObjectSP synthetic_value_sp = value_sp->GetSyntheticValue();
3071 if (synthetic_value_sp)
3072 local_values.Append(synthetic_value_sp);
3074 local_values.Append(value_sp);
3077 // Update the values
3078 SetValues(local_values);
3082 m_frame_block = nullptr;
3083 // Update the values with an empty list if there is no frame
3084 SetValues(local_values);
3087 return ValueObjectListDelegate::WindowDelegateDraw(window, force);
3091 Debugger &m_debugger;
3092 Block *m_frame_block;
3095 class RegistersWindowDelegate : public ValueObjectListDelegate {
3097 RegistersWindowDelegate(Debugger &debugger)
3098 : ValueObjectListDelegate(), m_debugger(debugger) {}
3100 ~RegistersWindowDelegate() override = default;
3102 const char *WindowDelegateGetHelpText() override {
3103 return "Register window keyboard shortcuts:";
3106 bool WindowDelegateDraw(Window &window, bool force) override {
3107 ExecutionContext exe_ctx(
3108 m_debugger.GetCommandInterpreter().GetExecutionContext());
3109 StackFrame *frame = exe_ctx.GetFramePtr();
3111 ValueObjectList value_list;
3113 if (frame->GetStackID() != m_stack_id) {
3114 m_stack_id = frame->GetStackID();
3115 RegisterContextSP reg_ctx(frame->GetRegisterContext());
3117 const uint32_t num_sets = reg_ctx->GetRegisterSetCount();
3118 for (uint32_t set_idx = 0; set_idx < num_sets; ++set_idx) {
3120 ValueObjectRegisterSet::Create(frame, reg_ctx, set_idx));
3123 SetValues(value_list);
3126 Process *process = exe_ctx.GetProcessPtr();
3127 if (process && process->IsAlive())
3128 return true; // Don't do any updating if we are running
3130 // Update the values with an empty list if there
3131 // is no process or the process isn't alive anymore
3132 SetValues(value_list);
3135 return ValueObjectListDelegate::WindowDelegateDraw(window, force);
3139 Debugger &m_debugger;
3143 static const char *CursesKeyToCString(int ch) {
3144 static char g_desc[32];
3145 if (ch >= KEY_F0 && ch < KEY_F0 + 64) {
3146 snprintf(g_desc, sizeof(g_desc), "F%u", ch - KEY_F0);
3163 return "delete-line";
3165 return "insert-line";
3167 return "delete-char";
3169 return "insert-char";
3173 return "clear-to-eos";
3175 return "clear-to-eol";
3177 return "scroll-forward";
3179 return "scroll-backward";
3189 return "clear-all-tabs";
3195 return "lower-left key";
3197 return "upper left of keypad";
3199 return "upper right of keypad";
3201 return "center of keypad";
3203 return "lower left of keypad";
3205 return "lower right of keypad";
3207 return "back-tab key";
3211 return "cancel key";
3215 return "command key";
3219 return "create key";
3231 return "message key";
3239 return "options key";
3241 return "previous key";
3245 return "reference key";
3247 return "refresh key";
3249 return "replace key";
3251 return "restart key";
3253 return "resume key";
3257 return "shifted begin key";
3259 return "shifted cancel key";
3261 return "shifted command key";
3263 return "shifted copy key";
3265 return "shifted create key";
3267 return "shifted delete-character key";
3269 return "shifted delete-line key";
3271 return "select key";
3273 return "shifted end key";
3275 return "shifted clear-to-end-of-line key";
3277 return "shifted exit key";
3279 return "shifted find key";
3281 return "shifted help key";
3283 return "shifted home key";
3285 return "shifted insert-character key";
3287 return "shifted left-arrow key";
3289 return "shifted message key";
3291 return "shifted move key";
3293 return "shifted next key";
3295 return "shifted options key";
3297 return "shifted previous key";
3299 return "shifted print key";
3301 return "shifted redo key";
3303 return "shifted replace key";
3305 return "shifted right-arrow key";
3307 return "shifted resume key";
3309 return "shifted save key";
3311 return "shifted suspend key";
3313 return "shifted undo key";
3315 return "suspend key";
3319 return "Mouse event has occurred";
3321 return "Terminal resize event";
3324 return "We were interrupted by an event";
3336 snprintf(g_desc, sizeof(g_desc), "%c", ch);
3338 snprintf(g_desc, sizeof(g_desc), "\\x%2.2x", ch);
3344 HelpDialogDelegate::HelpDialogDelegate(const char *text,
3345 KeyHelp *key_help_array)
3346 : m_text(), m_first_visible_line(0) {
3347 if (text && text[0]) {
3348 m_text.SplitIntoLines(text);
3349 m_text.AppendString("");
3351 if (key_help_array) {
3352 for (KeyHelp *key = key_help_array; key->ch; ++key) {
3353 StreamString key_description;
3354 key_description.Printf("%10s - %s", CursesKeyToCString(key->ch),
3356 m_text.AppendString(key_description.GetString());
3361 HelpDialogDelegate::~HelpDialogDelegate() = default;
3363 bool HelpDialogDelegate::WindowDelegateDraw(Window &window, bool force) {
3365 const int window_height = window.GetHeight();
3368 const int min_y = y;
3369 const int max_y = window_height - 1 - y;
3370 const size_t num_visible_lines = max_y - min_y + 1;
3371 const size_t num_lines = m_text.GetSize();
3372 const char *bottom_message;
3373 if (num_lines <= num_visible_lines)
3374 bottom_message = "Press any key to exit";
3376 bottom_message = "Use arrows to scroll, any other key to exit";
3377 window.DrawTitleBox(window.GetName(), bottom_message);
3378 while (y <= max_y) {
3379 window.MoveCursor(x, y);
3380 window.PutCStringTruncated(
3381 m_text.GetStringAtIndex(m_first_visible_line + y - min_y), 1);
3387 HandleCharResult HelpDialogDelegate::WindowDelegateHandleChar(Window &window,
3390 const size_t num_lines = m_text.GetSize();
3391 const size_t num_visible_lines = window.GetHeight() - 2;
3393 if (num_lines <= num_visible_lines) {
3395 // If we have all lines visible and don't need scrolling, then any
3396 // key press will cause us to exit
3400 if (m_first_visible_line > 0)
3401 --m_first_visible_line;
3405 if (m_first_visible_line + num_visible_lines < num_lines)
3406 ++m_first_visible_line;
3411 if (m_first_visible_line > 0) {
3412 if (static_cast<size_t>(m_first_visible_line) >= num_visible_lines)
3413 m_first_visible_line -= num_visible_lines;
3415 m_first_visible_line = 0;
3421 if (m_first_visible_line + num_visible_lines < num_lines) {
3422 m_first_visible_line += num_visible_lines;
3423 if (static_cast<size_t>(m_first_visible_line) > num_lines)
3424 m_first_visible_line = num_lines - num_visible_lines;
3434 window.GetParent()->RemoveSubWindow(&window);
3438 class ApplicationDelegate : public WindowDelegate, public MenuDelegate {
3446 eMenuID_TargetCreate,
3447 eMenuID_TargetDelete,
3450 eMenuID_ProcessAttach,
3451 eMenuID_ProcessDetach,
3452 eMenuID_ProcessLaunch,
3453 eMenuID_ProcessContinue,
3454 eMenuID_ProcessHalt,
3455 eMenuID_ProcessKill,
3458 eMenuID_ThreadStepIn,
3459 eMenuID_ThreadStepOver,
3460 eMenuID_ThreadStepOut,
3463 eMenuID_ViewBacktrace,
3464 eMenuID_ViewRegisters,
3466 eMenuID_ViewVariables,
3472 ApplicationDelegate(Application &app, Debugger &debugger)
3473 : WindowDelegate(), MenuDelegate(), m_app(app), m_debugger(debugger) {}
3475 ~ApplicationDelegate() override = default;
3477 bool WindowDelegateDraw(Window &window, bool force) override {
3478 return false; // Drawing not handled, let standard window drawing happen
3481 HandleCharResult WindowDelegateHandleChar(Window &window, int key) override {
3484 window.SelectNextWindowAsActive();
3488 window.CreateHelpSubwindow();
3492 return eQuitApplication;
3497 return eKeyNotHandled;
3500 const char *WindowDelegateGetHelpText() override {
3501 return "Welcome to the LLDB curses GUI.\n\n"
3502 "Press the TAB key to change the selected view.\n"
3503 "Each view has its own keyboard shortcuts, press 'h' to open a "
3504 "dialog to display them.\n\n"
3505 "Common key bindings for all views:";
3508 KeyHelp *WindowDelegateGetKeyHelp() override {
3509 static curses::KeyHelp g_source_view_key_help[] = {
3510 {'\t', "Select next view"},
3511 {'h', "Show help dialog with view specific key bindings"},
3514 {KEY_UP, "Select previous"},
3515 {KEY_DOWN, "Select next"},
3516 {KEY_LEFT, "Unexpand or select parent"},
3517 {KEY_RIGHT, "Expand"},
3518 {KEY_PPAGE, "Page up"},
3519 {KEY_NPAGE, "Page down"},
3521 return g_source_view_key_help;
3524 MenuActionResult MenuDelegateAction(Menu &menu) override {
3525 switch (menu.GetIdentifier()) {
3526 case eMenuID_ThreadStepIn: {
3527 ExecutionContext exe_ctx =
3528 m_debugger.GetCommandInterpreter().GetExecutionContext();
3529 if (exe_ctx.HasThreadScope()) {
3530 Process *process = exe_ctx.GetProcessPtr();
3531 if (process && process->IsAlive() &&
3532 StateIsStoppedState(process->GetState(), true))
3533 exe_ctx.GetThreadRef().StepIn(true);
3536 return MenuActionResult::Handled;
3538 case eMenuID_ThreadStepOut: {
3539 ExecutionContext exe_ctx =
3540 m_debugger.GetCommandInterpreter().GetExecutionContext();
3541 if (exe_ctx.HasThreadScope()) {
3542 Process *process = exe_ctx.GetProcessPtr();
3543 if (process && process->IsAlive() &&
3544 StateIsStoppedState(process->GetState(), true))
3545 exe_ctx.GetThreadRef().StepOut();
3548 return MenuActionResult::Handled;
3550 case eMenuID_ThreadStepOver: {
3551 ExecutionContext exe_ctx =
3552 m_debugger.GetCommandInterpreter().GetExecutionContext();
3553 if (exe_ctx.HasThreadScope()) {
3554 Process *process = exe_ctx.GetProcessPtr();
3555 if (process && process->IsAlive() &&
3556 StateIsStoppedState(process->GetState(), true))
3557 exe_ctx.GetThreadRef().StepOver(true);
3560 return MenuActionResult::Handled;
3562 case eMenuID_ProcessContinue: {
3563 ExecutionContext exe_ctx =
3564 m_debugger.GetCommandInterpreter().GetExecutionContext();
3565 if (exe_ctx.HasProcessScope()) {
3566 Process *process = exe_ctx.GetProcessPtr();
3567 if (process && process->IsAlive() &&
3568 StateIsStoppedState(process->GetState(), true))
3572 return MenuActionResult::Handled;
3574 case eMenuID_ProcessKill: {
3575 ExecutionContext exe_ctx =
3576 m_debugger.GetCommandInterpreter().GetExecutionContext();
3577 if (exe_ctx.HasProcessScope()) {
3578 Process *process = exe_ctx.GetProcessPtr();
3579 if (process && process->IsAlive())
3580 process->Destroy(false);
3583 return MenuActionResult::Handled;
3585 case eMenuID_ProcessHalt: {
3586 ExecutionContext exe_ctx =
3587 m_debugger.GetCommandInterpreter().GetExecutionContext();
3588 if (exe_ctx.HasProcessScope()) {
3589 Process *process = exe_ctx.GetProcessPtr();
3590 if (process && process->IsAlive())
3594 return MenuActionResult::Handled;
3596 case eMenuID_ProcessDetach: {
3597 ExecutionContext exe_ctx =
3598 m_debugger.GetCommandInterpreter().GetExecutionContext();
3599 if (exe_ctx.HasProcessScope()) {
3600 Process *process = exe_ctx.GetProcessPtr();
3601 if (process && process->IsAlive())
3602 process->Detach(false);
3605 return MenuActionResult::Handled;
3607 case eMenuID_Process: {
3608 // Populate the menu with all of the threads if the process is stopped
3610 // the Process menu gets selected and is about to display its submenu.
3611 Menus &submenus = menu.GetSubmenus();
3612 ExecutionContext exe_ctx =
3613 m_debugger.GetCommandInterpreter().GetExecutionContext();
3614 Process *process = exe_ctx.GetProcessPtr();
3615 if (process && process->IsAlive() &&
3616 StateIsStoppedState(process->GetState(), true)) {
3617 if (submenus.size() == 7)
3618 menu.AddSubmenu(MenuSP(new Menu(Menu::Type::Separator)));
3619 else if (submenus.size() > 8)
3620 submenus.erase(submenus.begin() + 8, submenus.end());
3622 ThreadList &threads = process->GetThreadList();
3623 std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
3624 size_t num_threads = threads.GetSize();
3625 for (size_t i = 0; i < num_threads; ++i) {
3626 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
3627 char menu_char = '\0';
3629 menu_char = '1' + i;
3630 StreamString thread_menu_title;
3631 thread_menu_title.Printf("Thread %u", thread_sp->GetIndexID());
3632 const char *thread_name = thread_sp->GetName();
3633 if (thread_name && thread_name[0])
3634 thread_menu_title.Printf(" %s", thread_name);
3636 const char *queue_name = thread_sp->GetQueueName();
3637 if (queue_name && queue_name[0])
3638 thread_menu_title.Printf(" %s", queue_name);
3641 MenuSP(new Menu(thread_menu_title.GetString().str().c_str(),
3642 nullptr, menu_char, thread_sp->GetID())));
3644 } else if (submenus.size() > 7) {
3645 // Remove the separator and any other thread submenu items
3646 // that were previously added
3647 submenus.erase(submenus.begin() + 7, submenus.end());
3649 // Since we are adding and removing items we need to recalculate the name
3651 menu.RecalculateNameLengths();
3653 return MenuActionResult::Handled;
3655 case eMenuID_ViewVariables: {
3656 WindowSP main_window_sp = m_app.GetMainWindow();
3657 WindowSP source_window_sp = main_window_sp->FindSubWindow("Source");
3658 WindowSP variables_window_sp = main_window_sp->FindSubWindow("Variables");
3659 WindowSP registers_window_sp = main_window_sp->FindSubWindow("Registers");
3660 const Rect source_bounds = source_window_sp->GetBounds();
3662 if (variables_window_sp) {
3663 const Rect variables_bounds = variables_window_sp->GetBounds();
3665 main_window_sp->RemoveSubWindow(variables_window_sp.get());
3667 if (registers_window_sp) {
3668 // We have a registers window, so give all the area back to the
3670 Rect registers_bounds = variables_bounds;
3671 registers_bounds.size.width = source_bounds.size.width;
3672 registers_window_sp->SetBounds(registers_bounds);
3674 // We have no registers window showing so give the bottom
3675 // area back to the source view
3676 source_window_sp->Resize(source_bounds.size.width,
3677 source_bounds.size.height +
3678 variables_bounds.size.height);
3681 Rect new_variables_rect;
3682 if (registers_window_sp) {
3683 // We have a registers window so split the area of the registers
3684 // window into two columns where the left hand side will be the
3685 // variables and the right hand side will be the registers
3686 const Rect variables_bounds = registers_window_sp->GetBounds();
3687 Rect new_registers_rect;
3688 variables_bounds.VerticalSplitPercentage(0.50, new_variables_rect,
3689 new_registers_rect);
3690 registers_window_sp->SetBounds(new_registers_rect);
3692 // No variables window, grab the bottom part of the source window
3693 Rect new_source_rect;
3694 source_bounds.HorizontalSplitPercentage(0.70, new_source_rect,
3695 new_variables_rect);
3696 source_window_sp->SetBounds(new_source_rect);
3698 WindowSP new_window_sp = main_window_sp->CreateSubWindow(
3699 "Variables", new_variables_rect, false);
3700 new_window_sp->SetDelegate(
3701 WindowDelegateSP(new FrameVariablesWindowDelegate(m_debugger)));
3705 return MenuActionResult::Handled;
3707 case eMenuID_ViewRegisters: {
3708 WindowSP main_window_sp = m_app.GetMainWindow();
3709 WindowSP source_window_sp = main_window_sp->FindSubWindow("Source");
3710 WindowSP variables_window_sp = main_window_sp->FindSubWindow("Variables");
3711 WindowSP registers_window_sp = main_window_sp->FindSubWindow("Registers");
3712 const Rect source_bounds = source_window_sp->GetBounds();
3714 if (registers_window_sp) {
3715 if (variables_window_sp) {
3716 const Rect variables_bounds = variables_window_sp->GetBounds();
3718 // We have a variables window, so give all the area back to the
3720 variables_window_sp->Resize(variables_bounds.size.width +
3721 registers_window_sp->GetWidth(),
3722 variables_bounds.size.height);
3724 // We have no variables window showing so give the bottom
3725 // area back to the source view
3726 source_window_sp->Resize(source_bounds.size.width,
3727 source_bounds.size.height +
3728 registers_window_sp->GetHeight());
3730 main_window_sp->RemoveSubWindow(registers_window_sp.get());
3733 if (variables_window_sp) {
3734 // We have a variables window, split it into two columns
3735 // where the left hand side will be the variables and the
3736 // right hand side will be the registers
3737 const Rect variables_bounds = variables_window_sp->GetBounds();
3739 variables_bounds.VerticalSplitPercentage(0.50, new_vars_rect,
3741 variables_window_sp->SetBounds(new_vars_rect);
3743 // No registers window, grab the bottom part of the source window
3744 Rect new_source_rect;
3745 source_bounds.HorizontalSplitPercentage(0.70, new_source_rect,
3747 source_window_sp->SetBounds(new_source_rect);
3749 WindowSP new_window_sp =
3750 main_window_sp->CreateSubWindow("Registers", new_regs_rect, false);
3751 new_window_sp->SetDelegate(
3752 WindowDelegateSP(new RegistersWindowDelegate(m_debugger)));
3756 return MenuActionResult::Handled;
3758 case eMenuID_HelpGUIHelp:
3759 m_app.GetMainWindow()->CreateHelpSubwindow();
3760 return MenuActionResult::Handled;
3766 return MenuActionResult::NotHandled;
3771 Debugger &m_debugger;
3774 class StatusBarWindowDelegate : public WindowDelegate {
3776 StatusBarWindowDelegate(Debugger &debugger) : m_debugger(debugger) {
3777 FormatEntity::Parse("Thread: ${thread.id%tid}", m_format);
3780 ~StatusBarWindowDelegate() override = default;
3782 bool WindowDelegateDraw(Window &window, bool force) override {
3783 ExecutionContext exe_ctx =
3784 m_debugger.GetCommandInterpreter().GetExecutionContext();
3785 Process *process = exe_ctx.GetProcessPtr();
3786 Thread *thread = exe_ctx.GetThreadPtr();
3787 StackFrame *frame = exe_ctx.GetFramePtr();
3789 window.SetBackground(2);
3790 window.MoveCursor(0, 0);
3792 const StateType state = process->GetState();
3793 window.Printf("Process: %5" PRIu64 " %10s", process->GetID(),
3794 StateAsCString(state));
3796 if (StateIsStoppedState(state, true)) {
3798 if (thread && FormatEntity::Format(m_format, strm, nullptr, &exe_ctx,
3799 nullptr, nullptr, false, false)) {
3800 window.MoveCursor(40, 0);
3801 window.PutCStringTruncated(strm.GetString().str().c_str(), 1);
3804 window.MoveCursor(60, 0);
3806 window.Printf("Frame: %3u PC = 0x%16.16" PRIx64,
3807 frame->GetFrameIndex(),
3808 frame->GetFrameCodeAddress().GetOpcodeLoadAddress(
3809 exe_ctx.GetTargetPtr()));
3810 } else if (state == eStateExited) {
3811 const char *exit_desc = process->GetExitDescription();
3812 const int exit_status = process->GetExitStatus();
3813 if (exit_desc && exit_desc[0])
3814 window.Printf(" with status = %i (%s)", exit_status, exit_desc);
3816 window.Printf(" with status = %i", exit_status);
3819 window.DeferredRefresh();
3824 Debugger &m_debugger;
3825 FormatEntity::Entry m_format;
3828 class SourceFileWindowDelegate : public WindowDelegate {
3830 SourceFileWindowDelegate(Debugger &debugger)
3831 : WindowDelegate(), m_debugger(debugger), m_sc(), m_file_sp(),
3832 m_disassembly_scope(nullptr), m_disassembly_sp(), m_disassembly_range(),
3833 m_title(), m_line_width(4), m_selected_line(0), m_pc_line(0),
3834 m_stop_id(0), m_frame_idx(UINT32_MAX), m_first_visible_line(0),
3835 m_min_x(0), m_min_y(0), m_max_x(0), m_max_y(0) {}
3837 ~SourceFileWindowDelegate() override = default;
3839 void Update(const SymbolContext &sc) { m_sc = sc; }
3841 uint32_t NumVisibleLines() const { return m_max_y - m_min_y; }
3843 const char *WindowDelegateGetHelpText() override {
3844 return "Source/Disassembly window keyboard shortcuts:";
3847 KeyHelp *WindowDelegateGetKeyHelp() override {
3848 static curses::KeyHelp g_source_view_key_help[] = {
3849 {KEY_RETURN, "Run to selected line with one shot breakpoint"},
3850 {KEY_UP, "Select previous source line"},
3851 {KEY_DOWN, "Select next source line"},
3852 {KEY_PPAGE, "Page up"},
3853 {KEY_NPAGE, "Page down"},
3854 {'b', "Set breakpoint on selected source/disassembly line"},
3855 {'c', "Continue process"},
3856 {'d', "Detach and resume process"},
3857 {'D', "Detach with process suspended"},
3858 {'h', "Show help dialog"},
3859 {'k', "Kill process"},
3860 {'n', "Step over (source line)"},
3861 {'N', "Step over (single instruction)"},
3863 {'s', "Step in (source line)"},
3864 {'S', "Step in (single instruction)"},
3868 return g_source_view_key_help;
3871 bool WindowDelegateDraw(Window &window, bool force) override {
3872 ExecutionContext exe_ctx =
3873 m_debugger.GetCommandInterpreter().GetExecutionContext();
3874 Process *process = exe_ctx.GetProcessPtr();
3875 Thread *thread = nullptr;
3877 bool update_location = false;
3879 StateType state = process->GetState();
3880 if (StateIsStoppedState(state, true)) {
3881 // We are stopped, so it is ok to
3882 update_location = true;
3888 m_max_x = window.GetMaxX() - 1;
3889 m_max_y = window.GetMaxY() - 1;
3891 const uint32_t num_visible_lines = NumVisibleLines();
3892 StackFrameSP frame_sp;
3893 bool set_selected_line_to_pc = false;
3895 if (update_location) {
3896 const bool process_alive = process ? process->IsAlive() : false;
3897 bool thread_changed = false;
3898 if (process_alive) {
3899 thread = exe_ctx.GetThreadPtr();
3901 frame_sp = thread->GetSelectedFrame();
3902 auto tid = thread->GetID();
3903 thread_changed = tid != m_tid;
3906 if (m_tid != LLDB_INVALID_THREAD_ID) {
3907 thread_changed = true;
3908 m_tid = LLDB_INVALID_THREAD_ID;
3912 const uint32_t stop_id = process ? process->GetStopID() : 0;
3913 const bool stop_id_changed = stop_id != m_stop_id;
3914 bool frame_changed = false;
3915 m_stop_id = stop_id;
3918 m_sc = frame_sp->GetSymbolContext(eSymbolContextEverything);
3919 if (m_sc.module_sp) {
3921 "%s", m_sc.module_sp->GetFileSpec().GetFilename().GetCString());
3922 ConstString func_name = m_sc.GetFunctionName();
3924 m_title.Printf("`%s", func_name.GetCString());
3926 const uint32_t frame_idx = frame_sp->GetFrameIndex();
3927 frame_changed = frame_idx != m_frame_idx;
3928 m_frame_idx = frame_idx;
3931 frame_changed = m_frame_idx != UINT32_MAX;
3932 m_frame_idx = UINT32_MAX;
3935 const bool context_changed =
3936 thread_changed || frame_changed || stop_id_changed;
3938 if (process_alive) {
3939 if (m_sc.line_entry.IsValid()) {
3940 m_pc_line = m_sc.line_entry.line;
3941 if (m_pc_line != UINT32_MAX)
3942 --m_pc_line; // Convert to zero based line number...
3943 // Update the selected line if the stop ID changed...
3944 if (context_changed)
3945 m_selected_line = m_pc_line;
3947 if (m_file_sp && m_file_sp->FileSpecMatches(m_sc.line_entry.file)) {
3948 // Same file, nothing to do, we should either have the
3949 // lines or not (source file missing)
3950 if (m_selected_line >= static_cast<size_t>(m_first_visible_line)) {
3951 if (m_selected_line >= m_first_visible_line + num_visible_lines)
3952 m_first_visible_line = m_selected_line - 10;
3954 if (m_selected_line > 10)
3955 m_first_visible_line = m_selected_line - 10;
3957 m_first_visible_line = 0;
3960 // File changed, set selected line to the line with the PC
3961 m_selected_line = m_pc_line;
3963 m_debugger.GetSourceManager().GetFile(m_sc.line_entry.file);
3965 const size_t num_lines = m_file_sp->GetNumLines();
3966 int m_line_width = 1;
3967 for (size_t n = num_lines; n >= 10; n = n / 10)
3970 snprintf(m_line_format, sizeof(m_line_format), " %%%iu ",
3972 if (num_lines < num_visible_lines ||
3973 m_selected_line < num_visible_lines)
3974 m_first_visible_line = 0;
3976 m_first_visible_line = m_selected_line - 10;
3983 if (!m_file_sp || m_file_sp->GetNumLines() == 0) {
3985 bool prefer_file_cache = false;
3986 if (m_sc.function) {
3987 if (m_disassembly_scope != m_sc.function) {
3988 m_disassembly_scope = m_sc.function;
3989 m_disassembly_sp = m_sc.function->GetInstructions(
3990 exe_ctx, nullptr, prefer_file_cache);
3991 if (m_disassembly_sp) {
3992 set_selected_line_to_pc = true;
3993 m_disassembly_range = m_sc.function->GetAddressRange();
3995 m_disassembly_range.Clear();
3998 set_selected_line_to_pc = context_changed;
4000 } else if (m_sc.symbol) {
4001 if (m_disassembly_scope != m_sc.symbol) {
4002 m_disassembly_scope = m_sc.symbol;
4003 m_disassembly_sp = m_sc.symbol->GetInstructions(
4004 exe_ctx, nullptr, prefer_file_cache);
4005 if (m_disassembly_sp) {
4006 set_selected_line_to_pc = true;
4007 m_disassembly_range.GetBaseAddress() =
4008 m_sc.symbol->GetAddress();
4009 m_disassembly_range.SetByteSize(m_sc.symbol->GetByteSize());
4011 m_disassembly_range.Clear();
4014 set_selected_line_to_pc = context_changed;
4019 m_pc_line = UINT32_MAX;
4023 const int window_width = window.GetWidth();
4025 window.DrawTitleBox("Sources");
4026 if (!m_title.GetString().empty()) {
4027 window.AttributeOn(A_REVERSE);
4028 window.MoveCursor(1, 1);
4029 window.PutChar(' ');
4030 window.PutCStringTruncated(m_title.GetString().str().c_str(), 1);
4031 int x = window.GetCursorX();
4032 if (x < window_width - 1) {
4033 window.Printf("%*s", window_width - x - 1, "");
4035 window.AttributeOff(A_REVERSE);
4038 Target *target = exe_ctx.GetTargetPtr();
4039 const size_t num_source_lines = GetNumSourceLines();
4040 if (num_source_lines > 0) {
4042 BreakpointLines bp_lines;
4044 BreakpointList &bp_list = target->GetBreakpointList();
4045 const size_t num_bps = bp_list.GetSize();
4046 for (size_t bp_idx = 0; bp_idx < num_bps; ++bp_idx) {
4047 BreakpointSP bp_sp = bp_list.GetBreakpointAtIndex(bp_idx);
4048 const size_t num_bps_locs = bp_sp->GetNumLocations();
4049 for (size_t bp_loc_idx = 0; bp_loc_idx < num_bps_locs; ++bp_loc_idx) {
4050 BreakpointLocationSP bp_loc_sp =
4051 bp_sp->GetLocationAtIndex(bp_loc_idx);
4052 LineEntry bp_loc_line_entry;
4053 if (bp_loc_sp->GetAddress().CalculateSymbolContextLineEntry(
4054 bp_loc_line_entry)) {
4055 if (m_file_sp->GetFileSpec() == bp_loc_line_entry.file) {
4056 bp_lines.insert(bp_loc_line_entry.line);
4063 const attr_t selected_highlight_attr = A_REVERSE;
4064 const attr_t pc_highlight_attr = COLOR_PAIR(1);
4066 for (size_t i = 0; i < num_visible_lines; ++i) {
4067 const uint32_t curr_line = m_first_visible_line + i;
4068 if (curr_line < num_source_lines) {
4069 const int line_y = m_min_y + i;
4070 window.MoveCursor(1, line_y);
4071 const bool is_pc_line = curr_line == m_pc_line;
4072 const bool line_is_selected = m_selected_line == curr_line;
4073 // Highlight the line as the PC line first, then if the selected line
4074 // isn't the same as the PC line, highlight it differently
4075 attr_t highlight_attr = 0;
4078 highlight_attr = pc_highlight_attr;
4079 else if (line_is_selected)
4080 highlight_attr = selected_highlight_attr;
4082 if (bp_lines.find(curr_line + 1) != bp_lines.end())
4083 bp_attr = COLOR_PAIR(2);
4086 window.AttributeOn(bp_attr);
4088 window.Printf(m_line_format, curr_line + 1);
4091 window.AttributeOff(bp_attr);
4093 window.PutChar(ACS_VLINE);
4094 // Mark the line with the PC with a diamond
4096 window.PutChar(ACS_DIAMOND);
4098 window.PutChar(' ');
4101 window.AttributeOn(highlight_attr);
4102 const uint32_t line_len =
4103 m_file_sp->GetLineLength(curr_line + 1, false);
4105 window.PutCString(m_file_sp->PeekLineData(curr_line + 1), line_len);
4107 if (is_pc_line && frame_sp &&
4108 frame_sp->GetConcreteFrameIndex() == 0) {
4109 StopInfoSP stop_info_sp;
4111 stop_info_sp = thread->GetStopInfo();
4113 const char *stop_description = stop_info_sp->GetDescription();
4114 if (stop_description && stop_description[0]) {
4115 size_t stop_description_len = strlen(stop_description);
4116 int desc_x = window_width - stop_description_len - 16;
4117 window.Printf("%*s", desc_x - window.GetCursorX(), "");
4118 // window.MoveCursor(window_width - stop_description_len - 15,
4120 window.Printf("<<< Thread %u: %s ", thread->GetIndexID(),
4124 window.Printf("%*s", window_width - window.GetCursorX() - 1, "");
4128 window.AttributeOff(highlight_attr);
4134 size_t num_disassembly_lines = GetNumDisassemblyLines();
4135 if (num_disassembly_lines > 0) {
4136 // Display disassembly
4137 BreakpointAddrs bp_file_addrs;
4138 Target *target = exe_ctx.GetTargetPtr();
4140 BreakpointList &bp_list = target->GetBreakpointList();
4141 const size_t num_bps = bp_list.GetSize();
4142 for (size_t bp_idx = 0; bp_idx < num_bps; ++bp_idx) {
4143 BreakpointSP bp_sp = bp_list.GetBreakpointAtIndex(bp_idx);
4144 const size_t num_bps_locs = bp_sp->GetNumLocations();
4145 for (size_t bp_loc_idx = 0; bp_loc_idx < num_bps_locs;
4147 BreakpointLocationSP bp_loc_sp =
4148 bp_sp->GetLocationAtIndex(bp_loc_idx);
4149 LineEntry bp_loc_line_entry;
4150 const lldb::addr_t file_addr =
4151 bp_loc_sp->GetAddress().GetFileAddress();
4152 if (file_addr != LLDB_INVALID_ADDRESS) {
4153 if (m_disassembly_range.ContainsFileAddress(file_addr))
4154 bp_file_addrs.insert(file_addr);
4160 const attr_t selected_highlight_attr = A_REVERSE;
4161 const attr_t pc_highlight_attr = COLOR_PAIR(1);
4165 InstructionList &insts = m_disassembly_sp->GetInstructionList();
4169 pc_address = frame_sp->GetFrameCodeAddress();
4170 const uint32_t pc_idx =
4171 pc_address.IsValid()
4172 ? insts.GetIndexOfInstructionAtAddress(pc_address)
4174 if (set_selected_line_to_pc) {
4175 m_selected_line = pc_idx;
4178 const uint32_t non_visible_pc_offset = (num_visible_lines / 5);
4179 if (static_cast<size_t>(m_first_visible_line) >= num_disassembly_lines)
4180 m_first_visible_line = 0;
4182 if (pc_idx < num_disassembly_lines) {
4183 if (pc_idx < static_cast<uint32_t>(m_first_visible_line) ||
4184 pc_idx >= m_first_visible_line + num_visible_lines)
4185 m_first_visible_line = pc_idx - non_visible_pc_offset;
4188 for (size_t i = 0; i < num_visible_lines; ++i) {
4189 const uint32_t inst_idx = m_first_visible_line + i;
4190 Instruction *inst = insts.GetInstructionAtIndex(inst_idx).get();
4194 const int line_y = m_min_y + i;
4195 window.MoveCursor(1, line_y);
4196 const bool is_pc_line = frame_sp && inst_idx == pc_idx;
4197 const bool line_is_selected = m_selected_line == inst_idx;
4198 // Highlight the line as the PC line first, then if the selected line
4199 // isn't the same as the PC line, highlight it differently
4200 attr_t highlight_attr = 0;
4203 highlight_attr = pc_highlight_attr;
4204 else if (line_is_selected)
4205 highlight_attr = selected_highlight_attr;
4207 if (bp_file_addrs.find(inst->GetAddress().GetFileAddress()) !=
4208 bp_file_addrs.end())
4209 bp_attr = COLOR_PAIR(2);
4212 window.AttributeOn(bp_attr);
4214 window.Printf(" 0x%16.16llx ",
4215 static_cast<unsigned long long>(
4216 inst->GetAddress().GetLoadAddress(target)));
4219 window.AttributeOff(bp_attr);
4221 window.PutChar(ACS_VLINE);
4222 // Mark the line with the PC with a diamond
4224 window.PutChar(ACS_DIAMOND);
4226 window.PutChar(' ');
4229 window.AttributeOn(highlight_attr);
4231 const char *mnemonic = inst->GetMnemonic(&exe_ctx);
4232 const char *operands = inst->GetOperands(&exe_ctx);
4233 const char *comment = inst->GetComment(&exe_ctx);
4235 if (mnemonic != nullptr && mnemonic[0] == '\0')
4237 if (operands != nullptr && operands[0] == '\0')
4239 if (comment != nullptr && comment[0] == '\0')
4244 if (mnemonic != nullptr && operands != nullptr && comment != nullptr)
4245 strm.Printf("%-8s %-25s ; %s", mnemonic, operands, comment);
4246 else if (mnemonic != nullptr && operands != nullptr)
4247 strm.Printf("%-8s %s", mnemonic, operands);
4248 else if (mnemonic != nullptr)
4249 strm.Printf("%s", mnemonic);
4252 window.PutCStringTruncated(strm.GetData(), right_pad);
4254 if (is_pc_line && frame_sp &&
4255 frame_sp->GetConcreteFrameIndex() == 0) {
4256 StopInfoSP stop_info_sp;
4258 stop_info_sp = thread->GetStopInfo();
4260 const char *stop_description = stop_info_sp->GetDescription();
4261 if (stop_description && stop_description[0]) {
4262 size_t stop_description_len = strlen(stop_description);
4263 int desc_x = window_width - stop_description_len - 16;
4264 window.Printf("%*s", desc_x - window.GetCursorX(), "");
4265 // window.MoveCursor(window_width - stop_description_len - 15,
4267 window.Printf("<<< Thread %u: %s ", thread->GetIndexID(),
4271 window.Printf("%*s", window_width - window.GetCursorX() - 1, "");
4275 window.AttributeOff(highlight_attr);
4279 window.DeferredRefresh();
4280 return true; // Drawing handled
4283 size_t GetNumLines() {
4284 size_t num_lines = GetNumSourceLines();
4286 num_lines = GetNumDisassemblyLines();
4290 size_t GetNumSourceLines() const {
4292 return m_file_sp->GetNumLines();
4296 size_t GetNumDisassemblyLines() const {
4297 if (m_disassembly_sp)
4298 return m_disassembly_sp->GetInstructionList().GetSize();
4302 HandleCharResult WindowDelegateHandleChar(Window &window, int c) override {
4303 const uint32_t num_visible_lines = NumVisibleLines();
4304 const size_t num_lines = GetNumLines();
4310 if (static_cast<uint32_t>(m_first_visible_line) > num_visible_lines)
4311 m_first_visible_line -= num_visible_lines;
4313 m_first_visible_line = 0;
4314 m_selected_line = m_first_visible_line;
4321 if (m_first_visible_line + num_visible_lines < num_lines)
4322 m_first_visible_line += num_visible_lines;
4323 else if (num_lines < num_visible_lines)
4324 m_first_visible_line = 0;
4326 m_first_visible_line = num_lines - num_visible_lines;
4327 m_selected_line = m_first_visible_line;
4332 if (m_selected_line > 0) {
4334 if (static_cast<size_t>(m_first_visible_line) > m_selected_line)
4335 m_first_visible_line = m_selected_line;
4340 if (m_selected_line + 1 < num_lines) {
4342 if (m_first_visible_line + num_visible_lines < m_selected_line)
4343 m_first_visible_line++;
4350 // Set a breakpoint and run to the line using a one shot breakpoint
4351 if (GetNumSourceLines() > 0) {
4352 ExecutionContext exe_ctx =
4353 m_debugger.GetCommandInterpreter().GetExecutionContext();
4354 if (exe_ctx.HasProcessScope() && exe_ctx.GetProcessRef().IsAlive()) {
4355 BreakpointSP bp_sp = exe_ctx.GetTargetRef().CreateBreakpoint(
4356 nullptr, // Don't limit the breakpoint to certain modules
4357 m_file_sp->GetFileSpec(), // Source file
4359 1, // Source line number (m_selected_line is zero based)
4361 eLazyBoolCalculate, // Check inlines using global setting
4362 eLazyBoolCalculate, // Skip prologue using global setting,
4364 false, // request_hardware
4365 eLazyBoolCalculate); // move_to_nearest_code
4366 // Make breakpoint one shot
4367 bp_sp->GetOptions()->SetOneShot(true);
4368 exe_ctx.GetProcessRef().Resume();
4370 } else if (m_selected_line < GetNumDisassemblyLines()) {
4371 const Instruction *inst = m_disassembly_sp->GetInstructionList()
4372 .GetInstructionAtIndex(m_selected_line)
4374 ExecutionContext exe_ctx =
4375 m_debugger.GetCommandInterpreter().GetExecutionContext();
4376 if (exe_ctx.HasTargetScope()) {
4377 Address addr = inst->GetAddress();
4378 BreakpointSP bp_sp = exe_ctx.GetTargetRef().CreateBreakpoint(
4379 addr, // lldb_private::Address
4381 false); // request_hardware
4382 // Make breakpoint one shot
4383 bp_sp->GetOptions()->SetOneShot(true);
4384 exe_ctx.GetProcessRef().Resume();
4389 case 'b': // 'b' == toggle breakpoint on currently selected line
4390 if (m_selected_line < GetNumSourceLines()) {
4391 ExecutionContext exe_ctx =
4392 m_debugger.GetCommandInterpreter().GetExecutionContext();
4393 if (exe_ctx.HasTargetScope()) {
4394 BreakpointSP bp_sp = exe_ctx.GetTargetRef().CreateBreakpoint(
4395 nullptr, // Don't limit the breakpoint to certain modules
4396 m_file_sp->GetFileSpec(), // Source file
4398 1, // Source line number (m_selected_line is zero based)
4400 eLazyBoolCalculate, // Check inlines using global setting
4401 eLazyBoolCalculate, // Skip prologue using global setting,
4403 false, // request_hardware
4404 eLazyBoolCalculate); // move_to_nearest_code
4406 } else if (m_selected_line < GetNumDisassemblyLines()) {
4407 const Instruction *inst = m_disassembly_sp->GetInstructionList()
4408 .GetInstructionAtIndex(m_selected_line)
4410 ExecutionContext exe_ctx =
4411 m_debugger.GetCommandInterpreter().GetExecutionContext();
4412 if (exe_ctx.HasTargetScope()) {
4413 Address addr = inst->GetAddress();
4414 BreakpointSP bp_sp = exe_ctx.GetTargetRef().CreateBreakpoint(
4415 addr, // lldb_private::Address
4417 false); // request_hardware
4422 case 'd': // 'd' == detach and let run
4423 case 'D': // 'D' == detach and keep stopped
4425 ExecutionContext exe_ctx =
4426 m_debugger.GetCommandInterpreter().GetExecutionContext();
4427 if (exe_ctx.HasProcessScope())
4428 exe_ctx.GetProcessRef().Detach(c == 'D');
4435 ExecutionContext exe_ctx =
4436 m_debugger.GetCommandInterpreter().GetExecutionContext();
4437 if (exe_ctx.HasProcessScope())
4438 exe_ctx.GetProcessRef().Destroy(false);
4445 ExecutionContext exe_ctx =
4446 m_debugger.GetCommandInterpreter().GetExecutionContext();
4447 if (exe_ctx.HasProcessScope())
4448 exe_ctx.GetProcessRef().Resume();
4455 ExecutionContext exe_ctx =
4456 m_debugger.GetCommandInterpreter().GetExecutionContext();
4457 if (exe_ctx.HasThreadScope() &&
4458 StateIsStoppedState(exe_ctx.GetProcessRef().GetState(), true)) {
4459 exe_ctx.GetThreadRef().StepOut();
4464 case 'n': // 'n' == step over
4465 case 'N': // 'N' == step over instruction
4467 ExecutionContext exe_ctx =
4468 m_debugger.GetCommandInterpreter().GetExecutionContext();
4469 if (exe_ctx.HasThreadScope() &&
4470 StateIsStoppedState(exe_ctx.GetProcessRef().GetState(), true)) {
4471 bool source_step = (c == 'n');
4472 exe_ctx.GetThreadRef().StepOver(source_step);
4477 case 's': // 's' == step into
4478 case 'S': // 'S' == step into instruction
4480 ExecutionContext exe_ctx =
4481 m_debugger.GetCommandInterpreter().GetExecutionContext();
4482 if (exe_ctx.HasThreadScope() &&
4483 StateIsStoppedState(exe_ctx.GetProcessRef().GetState(), true)) {
4484 bool source_step = (c == 's');
4485 exe_ctx.GetThreadRef().StepIn(source_step);
4491 window.CreateHelpSubwindow();
4497 return eKeyNotHandled;
4501 typedef std::set<uint32_t> BreakpointLines;
4502 typedef std::set<lldb::addr_t> BreakpointAddrs;
4504 Debugger &m_debugger;
4506 SourceManager::FileSP m_file_sp;
4507 SymbolContextScope *m_disassembly_scope;
4508 lldb::DisassemblerSP m_disassembly_sp;
4509 AddressRange m_disassembly_range;
4510 StreamString m_title;
4511 lldb::user_id_t m_tid;
4512 char m_line_format[8];
4514 uint32_t m_selected_line; // The selected line
4515 uint32_t m_pc_line; // The line with the PC
4517 uint32_t m_frame_idx;
4518 int m_first_visible_line;
4525 DisplayOptions ValueObjectListDelegate::g_options = {true};
4527 IOHandlerCursesGUI::IOHandlerCursesGUI(Debugger &debugger)
4528 : IOHandler(debugger, IOHandler::Type::Curses) {}
4530 void IOHandlerCursesGUI::Activate() {
4531 IOHandler::Activate();
4533 m_app_ap.reset(new Application(GetInputFILE(), GetOutputFILE()));
4535 // This is both a window and a menu delegate
4536 std::shared_ptr<ApplicationDelegate> app_delegate_sp(
4537 new ApplicationDelegate(*m_app_ap, m_debugger));
4539 MenuDelegateSP app_menu_delegate_sp =
4540 std::static_pointer_cast<MenuDelegate>(app_delegate_sp);
4541 MenuSP lldb_menu_sp(
4542 new Menu("LLDB", "F1", KEY_F(1), ApplicationDelegate::eMenuID_LLDB));
4543 MenuSP exit_menuitem_sp(
4544 new Menu("Exit", nullptr, 'x', ApplicationDelegate::eMenuID_LLDBExit));
4545 exit_menuitem_sp->SetCannedResult(MenuActionResult::Quit);
4546 lldb_menu_sp->AddSubmenu(MenuSP(new Menu(
4547 "About LLDB", nullptr, 'a', ApplicationDelegate::eMenuID_LLDBAbout)));
4548 lldb_menu_sp->AddSubmenu(MenuSP(new Menu(Menu::Type::Separator)));
4549 lldb_menu_sp->AddSubmenu(exit_menuitem_sp);
4551 MenuSP target_menu_sp(new Menu("Target", "F2", KEY_F(2),
4552 ApplicationDelegate::eMenuID_Target));
4553 target_menu_sp->AddSubmenu(MenuSP(new Menu(
4554 "Create", nullptr, 'c', ApplicationDelegate::eMenuID_TargetCreate)));
4555 target_menu_sp->AddSubmenu(MenuSP(new Menu(
4556 "Delete", nullptr, 'd', ApplicationDelegate::eMenuID_TargetDelete)));
4558 MenuSP process_menu_sp(new Menu("Process", "F3", KEY_F(3),
4559 ApplicationDelegate::eMenuID_Process));
4560 process_menu_sp->AddSubmenu(MenuSP(new Menu(
4561 "Attach", nullptr, 'a', ApplicationDelegate::eMenuID_ProcessAttach)));
4562 process_menu_sp->AddSubmenu(MenuSP(new Menu(
4563 "Detach", nullptr, 'd', ApplicationDelegate::eMenuID_ProcessDetach)));
4564 process_menu_sp->AddSubmenu(MenuSP(new Menu(
4565 "Launch", nullptr, 'l', ApplicationDelegate::eMenuID_ProcessLaunch)));
4566 process_menu_sp->AddSubmenu(MenuSP(new Menu(Menu::Type::Separator)));
4567 process_menu_sp->AddSubmenu(
4568 MenuSP(new Menu("Continue", nullptr, 'c',
4569 ApplicationDelegate::eMenuID_ProcessContinue)));
4570 process_menu_sp->AddSubmenu(MenuSP(new Menu(
4571 "Halt", nullptr, 'h', ApplicationDelegate::eMenuID_ProcessHalt)));
4572 process_menu_sp->AddSubmenu(MenuSP(new Menu(
4573 "Kill", nullptr, 'k', ApplicationDelegate::eMenuID_ProcessKill)));
4575 MenuSP thread_menu_sp(new Menu("Thread", "F4", KEY_F(4),
4576 ApplicationDelegate::eMenuID_Thread));
4577 thread_menu_sp->AddSubmenu(MenuSP(new Menu(
4578 "Step In", nullptr, 'i', ApplicationDelegate::eMenuID_ThreadStepIn)));
4579 thread_menu_sp->AddSubmenu(
4580 MenuSP(new Menu("Step Over", nullptr, 'v',
4581 ApplicationDelegate::eMenuID_ThreadStepOver)));
4582 thread_menu_sp->AddSubmenu(MenuSP(new Menu(
4583 "Step Out", nullptr, 'o', ApplicationDelegate::eMenuID_ThreadStepOut)));
4585 MenuSP view_menu_sp(
4586 new Menu("View", "F5", KEY_F(5), ApplicationDelegate::eMenuID_View));
4587 view_menu_sp->AddSubmenu(
4588 MenuSP(new Menu("Backtrace", nullptr, 'b',
4589 ApplicationDelegate::eMenuID_ViewBacktrace)));
4590 view_menu_sp->AddSubmenu(
4591 MenuSP(new Menu("Registers", nullptr, 'r',
4592 ApplicationDelegate::eMenuID_ViewRegisters)));
4593 view_menu_sp->AddSubmenu(MenuSP(new Menu(
4594 "Source", nullptr, 's', ApplicationDelegate::eMenuID_ViewSource)));
4595 view_menu_sp->AddSubmenu(
4596 MenuSP(new Menu("Variables", nullptr, 'v',
4597 ApplicationDelegate::eMenuID_ViewVariables)));
4599 MenuSP help_menu_sp(
4600 new Menu("Help", "F6", KEY_F(6), ApplicationDelegate::eMenuID_Help));
4601 help_menu_sp->AddSubmenu(MenuSP(new Menu(
4602 "GUI Help", nullptr, 'g', ApplicationDelegate::eMenuID_HelpGUIHelp)));
4604 m_app_ap->Initialize();
4605 WindowSP &main_window_sp = m_app_ap->GetMainWindow();
4607 MenuSP menubar_sp(new Menu(Menu::Type::Bar));
4608 menubar_sp->AddSubmenu(lldb_menu_sp);
4609 menubar_sp->AddSubmenu(target_menu_sp);
4610 menubar_sp->AddSubmenu(process_menu_sp);
4611 menubar_sp->AddSubmenu(thread_menu_sp);
4612 menubar_sp->AddSubmenu(view_menu_sp);
4613 menubar_sp->AddSubmenu(help_menu_sp);
4614 menubar_sp->SetDelegate(app_menu_delegate_sp);
4616 Rect content_bounds = main_window_sp->GetFrame();
4617 Rect menubar_bounds = content_bounds.MakeMenuBar();
4618 Rect status_bounds = content_bounds.MakeStatusBar();
4620 Rect variables_bounds;
4621 Rect threads_bounds;
4622 Rect source_variables_bounds;
4623 content_bounds.VerticalSplitPercentage(0.80, source_variables_bounds,
4625 source_variables_bounds.HorizontalSplitPercentage(0.70, source_bounds,
4628 WindowSP menubar_window_sp =
4629 main_window_sp->CreateSubWindow("Menubar", menubar_bounds, false);
4630 // Let the menubar get keys if the active window doesn't handle the
4631 // keys that are typed so it can respond to menubar key presses.
4632 menubar_window_sp->SetCanBeActive(
4633 false); // Don't let the menubar become the active window
4634 menubar_window_sp->SetDelegate(menubar_sp);
4636 WindowSP source_window_sp(
4637 main_window_sp->CreateSubWindow("Source", source_bounds, true));
4638 WindowSP variables_window_sp(
4639 main_window_sp->CreateSubWindow("Variables", variables_bounds, false));
4640 WindowSP threads_window_sp(
4641 main_window_sp->CreateSubWindow("Threads", threads_bounds, false));
4642 WindowSP status_window_sp(
4643 main_window_sp->CreateSubWindow("Status", status_bounds, false));
4644 status_window_sp->SetCanBeActive(
4645 false); // Don't let the status bar become the active window
4646 main_window_sp->SetDelegate(
4647 std::static_pointer_cast<WindowDelegate>(app_delegate_sp));
4648 source_window_sp->SetDelegate(
4649 WindowDelegateSP(new SourceFileWindowDelegate(m_debugger)));
4650 variables_window_sp->SetDelegate(
4651 WindowDelegateSP(new FrameVariablesWindowDelegate(m_debugger)));
4652 TreeDelegateSP thread_delegate_sp(new ThreadsTreeDelegate(m_debugger));
4653 threads_window_sp->SetDelegate(WindowDelegateSP(
4654 new TreeWindowDelegate(m_debugger, thread_delegate_sp)));
4655 status_window_sp->SetDelegate(
4656 WindowDelegateSP(new StatusBarWindowDelegate(m_debugger)));
4658 // Show the main help window once the first time the curses GUI is launched
4659 static bool g_showed_help = false;
4660 if (!g_showed_help) {
4661 g_showed_help = true;
4662 main_window_sp->CreateHelpSubwindow();
4665 init_pair(1, COLOR_WHITE, COLOR_BLUE);
4666 init_pair(2, COLOR_BLACK, COLOR_WHITE);
4667 init_pair(3, COLOR_MAGENTA, COLOR_WHITE);
4668 init_pair(4, COLOR_MAGENTA, COLOR_BLACK);
4669 init_pair(5, COLOR_RED, COLOR_BLACK);
4673 void IOHandlerCursesGUI::Deactivate() { m_app_ap->Terminate(); }
4675 void IOHandlerCursesGUI::Run() {
4676 m_app_ap->Run(m_debugger);
4680 IOHandlerCursesGUI::~IOHandlerCursesGUI() = default;
4682 void IOHandlerCursesGUI::Cancel() {}
4684 bool IOHandlerCursesGUI::Interrupt() { return false; }
4686 void IOHandlerCursesGUI::GotEOF() {}
4688 #endif // LLDB_DISABLE_CURSES