2 // Copyright 2005 The Android Open Source Project
4 // Display runtime log output.
7 // For compilers that support precompilation, include "wx/wx.h".
10 // Otherwise, include all standard headers
14 #include "wx/image.h" // needed for Windows build
15 #include "wx/dcbuffer.h"
17 #include "LogWindow.h"
18 #include "LogMessage.h"
19 #include "LogPrefsDialog.h"
21 #include "Preferences.h"
23 #include "UserEventMessage.h"
27 static int android_snprintfBuffer(char** pBuf, int bufLen, const char* format, ...);
28 static int android_vsnprintfBuffer(char** pBuf, int bufLen, const char* format, va_list args);
31 using namespace android;
33 #if 0 // experiment -- works on Win32, but not with GTK
34 class MyTextCtrl : public wxTextCtrl {
36 MyTextCtrl(wxWindow* parent, wxWindowID id, const wxString& value,
37 const wxPoint& pos, const wxSize& size, int style = 0)
38 : wxTextCtrl(parent, id, value, pos, size, style)
40 printf("***************** MyTextCtrl!\n");
43 void OnScroll(wxScrollWinEvent& event);
44 void OnScrollBottom(wxScrollWinEvent& event);
50 BEGIN_EVENT_TABLE(MyTextCtrl, wxTextCtrl)
51 EVT_SCROLLWIN(MyTextCtrl::OnScroll)
52 EVT_SCROLLWIN_BOTTOM(MyTextCtrl::OnScrollBottom)
55 void MyTextCtrl::OnScroll(wxScrollWinEvent& event)
57 printf("OnScroll!\n");
60 void MyTextCtrl::OnScrollBottom(wxScrollWinEvent& event)
62 printf("OnScrollBottom!\n");
67 BEGIN_EVENT_TABLE(LogWindow, wxDialog)
68 EVT_CLOSE(LogWindow::OnClose)
69 EVT_MOVE(LogWindow::OnMove)
70 EVT_COMBOBOX(IDC_LOG_LEVEL, LogWindow::OnLogLevel)
71 EVT_BUTTON(IDC_LOG_CLEAR, LogWindow::OnLogClear)
72 EVT_BUTTON(IDC_LOG_PAUSE, LogWindow::OnLogPause)
73 EVT_BUTTON(IDC_LOG_PREFS, LogWindow::OnLogPrefs)
77 * Information about log levels.
79 * Each entry here corresponds to an entry in the combo box. The first
80 * letter of each name should be unique.
84 android_LogPriority priority;
86 { wxT("Verbose"), ANDROID_LOG_VERBOSE },
87 { wxT("Debug"), ANDROID_LOG_DEBUG },
88 { wxT("Info"), ANDROID_LOG_INFO },
89 { wxT("Warn"), ANDROID_LOG_WARN },
90 { wxT("Error"), ANDROID_LOG_ERROR }
95 * Create a new LogWindow. This should be a child of the main frame.
97 LogWindow::LogWindow(wxWindow* parent)
98 : wxDialog(parent, wxID_ANY, wxT("Log Output"), wxDefaultPosition,
100 wxCAPTION | wxSYSTEM_MENU | wxCLOSE_BOX | wxRESIZE_BORDER),
101 mDisplayArray(NULL), mMaxDisplayMsgs(0), mPaused(false),
102 mMinPriority(ANDROID_LOG_VERBOSE),
103 mHeaderFormat(LogPrefsDialog::kHFFull),
104 mSingleLine(false), mExtraSpacing(0), mPointSize(10), mUseColor(true),
105 mFontMonospace(true), mWriteFile(false), mTruncateOld(true), mLogFp(NULL),
106 mNewlyShown(false), mLastPosition(wxDefaultPosition), mVisible(false)
110 Preferences* pPrefs = ((MyApp*)wxTheApp)->GetPrefs();
112 int poolSize = 10240; // 10MB
113 pPrefs->GetInt("log-pool-size-kbytes", &poolSize);
114 assert(poolSize > 0);
115 mPool.Resize(poolSize * 1024);
117 mMaxDisplayMsgs = 1000;
118 pPrefs->GetInt("log-display-msg-count", &mMaxDisplayMsgs);
119 assert(mMaxDisplayMsgs > 0);
120 mDisplayArray = new LogMessage*[mMaxDisplayMsgs];
121 memset(mDisplayArray, 0, sizeof(LogMessage*) * mMaxDisplayMsgs);
125 int tmpInt = (int) mHeaderFormat;
126 pPrefs->GetInt("log-header-format", &tmpInt);
127 mHeaderFormat = (LogPrefsDialog::HeaderFormat) tmpInt;
128 pPrefs->GetBool("log-single-line", &mSingleLine);
129 pPrefs->GetInt("log-extra-spacing", &mExtraSpacing);
130 pPrefs->GetInt("log-point-size", &mPointSize);
131 pPrefs->GetBool("log-use-color", &mUseColor);
132 pPrefs->SetBool("log-font-monospace", &mFontMonospace);
135 mFileName = wxT("/tmp/android-log.txt");
136 pPrefs->GetBool("log-write-file", &mWriteFile);
137 pPrefs->GetString("log-filename", /*ref*/mFileName);
138 pPrefs->GetBool("log-truncate-old", &mTruncateOld);
144 * Destroy everything we own.
146 LogWindow::~LogWindow(void)
149 delete[] mDisplayArray;
156 * Set the text style, based on our preferences.
158 void LogWindow::SetTextStyle(void)
160 wxTextCtrl* pTextCtrl;
161 pTextCtrl = (wxTextCtrl*) FindWindow(IDC_LOG_TEXT);
163 style = pTextCtrl->GetDefaultStyle();
165 if (mFontMonospace) {
166 wxFont font(mPointSize, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL,
167 wxFONTWEIGHT_NORMAL);
170 wxFont font(mPointSize, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL,
171 wxFONTWEIGHT_NORMAL);
175 pTextCtrl->SetDefaultStyle(style);
179 * Set up the goodies in the window.
181 * Also initializes mMinPriority.
183 void LogWindow::ConstructControls(void)
185 Preferences* pPrefs = ((MyApp*)wxTheApp)->GetPrefs();
186 wxPanel* base = new wxPanel(this, wxID_ANY);
187 wxBoxSizer* masterSizer = new wxBoxSizer(wxVERTICAL);
188 wxBoxSizer* indentSizer = new wxBoxSizer(wxHORIZONTAL);
189 wxBoxSizer* configPrioritySizer = new wxBoxSizer(wxHORIZONTAL);
190 wxGridSizer* configSizer = new wxGridSizer(4, 1);
193 * Configure log level combo box.
195 wxComboBox* logLevel;
196 int defaultLogLevel = 1;
197 pPrefs->GetInt("log-display-level", &defaultLogLevel);
198 logLevel = new wxComboBox(base, IDC_LOG_LEVEL, wxT(""),
199 wxDefaultPosition, wxDefaultSize, 0, NULL,
200 wxCB_READONLY /*| wxSUNKEN_BORDER*/);
201 for (int i = 0; i < NELEM(gLogLevels); i++) {
202 logLevel->Append(gLogLevels[i].name);
203 logLevel->SetClientData(i, (void*) gLogLevels[i].priority);
205 logLevel->SetSelection(defaultLogLevel);
206 mMinPriority = gLogLevels[defaultLogLevel].priority;
209 * Set up stuff at the bottom, starting with the options
210 * at the bottom left.
212 configPrioritySizer->Add(new wxStaticText(base, wxID_ANY, wxT("Log level:"),
213 wxDefaultPosition, wxDefaultSize, wxALIGN_LEFT),
214 0, wxALIGN_CENTER_VERTICAL);
215 configPrioritySizer->AddSpacer(kInterSpacing);
216 configPrioritySizer->Add(logLevel);
218 wxButton* clear = new wxButton(base, IDC_LOG_CLEAR, wxT("&Clear"),
219 wxDefaultPosition, wxDefaultSize, 0);
220 wxButton* pause = new wxButton(base, IDC_LOG_PAUSE, wxT("&Pause"),
221 wxDefaultPosition, wxDefaultSize, 0);
222 wxButton* prefs = new wxButton(base, IDC_LOG_PREFS, wxT("C&onfigure"),
223 wxDefaultPosition, wxDefaultSize, 0);
225 configSizer->Add(configPrioritySizer, 0, wxALIGN_LEFT);
226 configSizer->Add(clear, 0, wxALIGN_CENTER);
227 configSizer->Add(pause, 0, wxALIGN_CENTER);
228 configSizer->Add(prefs, 0, wxALIGN_RIGHT);
233 wxTextCtrl* pTextCtrl;
234 pTextCtrl = new wxTextCtrl(base, IDC_LOG_TEXT, wxT(""),
235 wxDefaultPosition, wxDefaultSize,
236 wxTE_MULTILINE | wxTE_READONLY | wxTE_RICH2 | wxTE_NOHIDESEL |
240 * Add components to master sizer.
242 masterSizer->AddSpacer(kEdgeSpacing);
243 masterSizer->Add(pTextCtrl, 1, wxEXPAND);
244 masterSizer->AddSpacer(kInterSpacing);
245 masterSizer->Add(configSizer, 0, wxEXPAND);
246 masterSizer->AddSpacer(kEdgeSpacing);
251 indentSizer->AddSpacer(kEdgeSpacing);
252 indentSizer->Add(masterSizer, 1, wxEXPAND);
253 indentSizer->AddSpacer(kEdgeSpacing);
255 base->SetSizer(indentSizer);
257 indentSizer->Fit(this); // shrink-to-fit
258 indentSizer->SetSizeHints(this); // define minimum size
262 * In some cases, this means the user has clicked on our "close" button.
263 * We don't really even want one, but both WinXP and KDE put one on our
264 * window whether we want it or not. So, we make it work as a "hide"
267 * This also gets called when the app is shutting down, and we do want
268 * to destroy ourselves then, saving various information about our state.
270 void LogWindow::OnClose(wxCloseEvent& event)
272 /* just hide the window, unless we're shutting down */
273 if (event.CanVeto()) {
280 * Save some preferences.
284 /* if we can't veto the Close(), destroy ourselves */
289 * Save all of our preferences to the config file.
291 void LogWindow::SaveWindowPrefs(void)
293 Preferences* pPrefs = ((MyApp*)wxTheApp)->GetPrefs();
296 * Save shown/hidden state.
298 pPrefs->SetBool("window-log-show", IsShown());
301 * Limits and formatting prefs.
303 pPrefs->SetInt("log-display-msg-count", mMaxDisplayMsgs);
304 pPrefs->SetInt("log-pool-size-kbytes", mPool.GetMaxSize() / 1024);
306 pPrefs->SetInt("log-header-format", mHeaderFormat);
307 pPrefs->SetBool("log-single-line", mSingleLine);
308 pPrefs->SetInt("log-extra-spacing", mExtraSpacing);
309 pPrefs->SetInt("log-point-size", mPointSize);
310 pPrefs->SetBool("log-use-color", mUseColor);
311 pPrefs->SetBool("log-font-monospace", mFontMonospace);
313 pPrefs->SetBool("log-write-file", mWriteFile);
314 pPrefs->SetString("log-filename", mFileName.ToAscii());
315 pPrefs->SetBool("log-truncate-old", mTruncateOld);
318 * Save window size and position.
323 assert(pPrefs != NULL);
325 posn = GetPosition();
328 pPrefs->SetInt("window-log-x", posn.x);
329 pPrefs->SetInt("window-log-y", posn.y);
330 pPrefs->SetInt("window-log-width", size.GetWidth());
331 pPrefs->SetInt("window-log-height", size.GetHeight());
334 * Save current setting of debug level combo box.
338 pCombo = (wxComboBox*) FindWindow(IDC_LOG_LEVEL);
339 selection = pCombo->GetSelection();
340 pPrefs->SetInt("log-display-level", selection);
344 * Return the desired position and size.
346 /*static*/ wxRect LogWindow::GetPrefWindowRect(void)
348 Preferences* pPrefs = ((MyApp*)wxTheApp)->GetPrefs();
349 int x, y, width, height;
351 assert(pPrefs != NULL);
357 /* these don't modify the arg if the pref doesn't exist */
358 pPrefs->GetInt("window-log-x", &x);
359 pPrefs->GetInt("window-log-y", &y);
360 pPrefs->GetInt("window-log-width", &width);
361 pPrefs->GetInt("window-log-height", &height);
363 return wxRect(x, y, width, height);
367 * Under Linux+GTK, the first time you show the window, it appears where
368 * it's supposed to. If you then hide it and show it again, it gets
369 * moved on top of the parent window. After that, you can reposition it
370 * and it remembers its position across hide/show.
372 * To counter this annoyance, we save the position when we hide, and
373 * reset the position after a show. The "newly shown" flag ensures that
374 * we only reposition the window as the result of a Show(true) call.
376 * Sometimes, something helpful will shift the window over if it's
377 * partially straddling a seam between two monitors. I don't see an easy
378 * way to block this, and I'm not sure I want to anyway.
380 void LogWindow::OnMove(wxMoveEvent& event)
383 point = event.GetPosition();
384 //printf("Sim: log window is at (%d,%d) (new=%d)\n", point.x, point.y,
388 if (mLastPosition == wxDefaultPosition) {
389 //printf("Sim: no last position established\n");
399 * Set the "newly shown" flag.
401 bool LogWindow::Show(bool show)
407 mLastPosition = GetPosition();
411 return wxDialog::Show(show);
415 * User has adjusted the log level. Update the display appropriately.
417 * This is a wxEVT_COMMAND_COMBOBOX_SELECTED event.
419 void LogWindow::OnLogLevel(wxCommandEvent& event)
422 android_LogPriority priority;
424 selection = event.GetInt();
425 wxComboBox* pCombo = (wxComboBox*) FindWindow(IDC_LOG_LEVEL);
426 priority = (android_LogPriority) (long)pCombo->GetClientData(event.GetInt());
428 printf("Sim: log level selected: %d (%s)\n", (int) priority,
429 (const char*) gLogLevels[selection].name.ToAscii());
430 mMinPriority = priority;
437 void LogWindow::OnLogClear(wxCommandEvent& event)
444 * Handle the pause/resume button.
446 * If we're un-pausing, we need to get caught up.
448 void LogWindow::OnLogPause(wxCommandEvent& event)
452 wxButton* pButton = (wxButton*) FindWindow(IDC_LOG_PAUSE);
454 pButton->SetLabel(wxT("&Resume"));
458 pButton->SetLabel(wxT("&Pause"));
460 LogMessage* pMsg = mPool.GetBookmark();
462 /* bookmarked item fell out of pool */
463 printf("--- bookmark was lost, redisplaying\n");
467 * The bookmark points to the last item added to the display.
468 * We want to chase its "prev" pointer to walk toward the head
469 * of the list, adding items from oldest to newest.
471 pMsg = pMsg->GetPrev();
472 while (pMsg != NULL) {
473 if (FilterMatches(pMsg))
475 pMsg = pMsg->GetPrev();
482 * Open log preferences dialog.
484 void LogWindow::OnLogPrefs(wxCommandEvent& event)
486 LogPrefsDialog dialog(this);
491 dialog.mHeaderFormat = mHeaderFormat;
492 dialog.mSingleLine = mSingleLine;
493 dialog.mExtraSpacing = mExtraSpacing;
494 dialog.mPointSize = mPointSize;
495 dialog.mUseColor = mUseColor;
496 dialog.mFontMonospace = mFontMonospace;
498 dialog.mDisplayMax = mMaxDisplayMsgs;
499 dialog.mPoolSizeKB = mPool.GetMaxSize() / 1024;
501 dialog.mWriteFile = mWriteFile;
502 dialog.mFileName = mFileName;
503 dialog.mTruncateOld = mTruncateOld;
506 * Show it. If they hit "OK", copy the updated values out, and
507 * re-display the log output.
509 if (dialog.ShowModal() == wxID_OK) {
510 /* discard old display arra */
512 delete[] mDisplayArray;
514 mHeaderFormat = dialog.mHeaderFormat;
515 mSingleLine = dialog.mSingleLine;
516 mExtraSpacing = dialog.mExtraSpacing;
517 mPointSize = dialog.mPointSize;
518 mUseColor = dialog.mUseColor;
519 mFontMonospace = dialog.mFontMonospace;
521 assert(dialog.mDisplayMax > 0);
522 assert(dialog.mPoolSizeKB > 0);
523 mMaxDisplayMsgs = dialog.mDisplayMax;
524 mPool.Resize(dialog.mPoolSizeKB * 1024);
526 mWriteFile = dialog.mWriteFile;
527 if (mLogFp != NULL && mFileName != dialog.mFileName) {
528 printf("--- log file name changed, closing\n");
532 mFileName = dialog.mFileName;
533 mTruncateOld = dialog.mTruncateOld;
535 mDisplayArray = new LogMessage*[mMaxDisplayMsgs];
536 memset(mDisplayArray, 0, sizeof(LogMessage*) * mMaxDisplayMsgs);
544 * Handle a log message "user event". This should only be called in
545 * the main UI thread.
547 * We take ownership of "*pLogMessage".
549 void LogWindow::AddLogMessage(LogMessage* pLogMessage)
551 mPool.Add(pLogMessage);
553 if (!mPaused && mVisible && FilterMatches(pLogMessage)) {
555 * Thought: keep a reference to the previous message. If it
556 * matches in most fields (all except timestamp?), hold it and
557 * increment a counter. If we get a message that doesn't match,
558 * or a timer elapses, synthesize a "previous message repeated N
561 AddToDisplay(pLogMessage);
564 // release the initial ref caused by allocation
565 pLogMessage->Release();
568 LogToFile(pLogMessage);
572 * Clear out the display, releasing any log messages held in the display
575 void LogWindow::ClearDisplay(void)
577 wxTextCtrl* pTextCtrl;
578 pTextCtrl = (wxTextCtrl*) FindWindow(IDC_LOG_TEXT);
582 * Just run through the entire array.
584 for (int i = 0; i < mMaxDisplayMsgs; i++) {
585 if (mDisplayArray[i] != NULL) {
586 mDisplayArray[i]->Release();
587 mDisplayArray[i] = NULL;
595 * Clear the current display and regenerate it from the log pool. We need
596 * to do this whenever we change filters or log message formatting.
598 void LogWindow::Redisplay(void)
601 * Freeze output rendering so it doesn't flash during update. Doesn't
602 * seem to help for GTK, and it leaves garbage on the screen in WinXP,
603 * so I'm leaving it commented out.
605 //wxTextCtrl* pText = (wxTextCtrl*) FindWindow(IDC_LOG_TEXT);
608 //printf("--- redisplay\n");
612 * Set up the default wxWidgets text style stuff.
618 * - Start at the head of the pool (where the most recently added
620 * - Check to see if the current item passes our filter. If it does,
621 * increment the "found count".
622 * - Continue in this manner until we run out of pool or have
623 * sufficient items to fill the screen.
624 * - Starting from the current position, walk back toward the head,
625 * adding the items that meet the current filter criteria.
627 * Don't forget that the log pool could be empty.
629 LogMessage* pMsg = mPool.GetHead();
634 // note this stops before it runs off the end
635 while (pMsg->GetNext() != NULL && foundCount < mMaxDisplayMsgs) {
636 if (FilterMatches(pMsg))
638 pMsg = pMsg->GetNext();
641 while (pMsg != NULL) {
642 if (FilterMatches(pMsg))
644 pMsg = pMsg->GetPrev();
653 * Returns "true" if the currently specified filters would allow this
654 * message to be shown.
656 bool LogWindow::FilterMatches(const LogMessage* pLogMessage)
658 if (pLogMessage->GetPriority() >= mMinPriority)
665 * Realloc the array of pointers, and remove anything from the display
666 * that should no longer be there.
668 void LogWindow::SetMaxDisplayMsgs(int max)
670 Preferences* pPrefs = ((MyApp*)wxTheApp)->GetPrefs();
672 pPrefs->SetInt("log-display-msg-count", max);
676 * Add the message to the display array and to the screen.
678 void LogWindow::AddToDisplay(LogMessage* pLogMessage)
680 wxTextCtrl* pTextCtrl;
681 pTextCtrl = (wxTextCtrl*) FindWindow(IDC_LOG_TEXT);
683 if (mNextPtr == mTopPtr) {
685 * The display array is full.
687 * We need to eliminate the topmost entry. This requires removing
688 * it from the array and removing the text from the wxTextCtrl.
690 pTextCtrl->Remove(0, mDisplayArray[mTopPtr]->GetTextCtrlLen());
691 mDisplayArray[mTopPtr]->Release();
692 mTopPtr = (mTopPtr + 1) % mMaxDisplayMsgs;
696 * Add formatted text to the text ctrl. Track how much actual space
697 * is required. The space may be different on Win32 (CRLF-based) vs.
698 * GTK (LF-based), so we need to measure it, not compute it from the
701 long lastBefore, lastAfter;
703 //insertBefore = pTextCtrl->GetInsertionPoint();
704 lastBefore = pTextCtrl->GetLastPosition();
705 FormatMessage(pLogMessage, pTextCtrl);
706 lastAfter = pTextCtrl->GetLastPosition();
707 pLogMessage->SetTextCtrlLen(lastAfter - lastBefore);
710 * If we restore the old insertion point, we will be glued to where
711 * we were. This is okay until we start deleting text from the top,
712 * at which point we need to adjust it to retain our position.
714 * If we set the insertion point to the bottom, we effectively
715 * implement "scroll to bottom on output".
717 * If we don't set it at all, we get slightly strange behavior out
718 * of GTK, which seems to be par for the course here.
720 //pTextCtrl->SetInsertionPoint(insertBefore); // restore insertion pt
721 pTextCtrl->SetInsertionPoint(lastAfter);
723 /* add it to array, claim ownership */
724 mDisplayArray[mNextPtr] = pLogMessage;
725 pLogMessage->Acquire();
727 /* adjust pointers */
728 if (mTopPtr < 0) // first time only
730 mNextPtr = (mNextPtr + 1) % mMaxDisplayMsgs;
735 * Return a human-readable string for the priority level. Always returns
738 static const wxCharBuffer GetPriorityString(android_LogPriority priority)
742 idx = (int) priority - (int) ANDROID_LOG_VERBOSE;
743 if (idx < 0 || idx >= NELEM(gLogLevels))
745 return gLogLevels[idx].name.ToAscii();
749 * Format a message and write it to the text control.
751 void LogWindow::FormatMessage(const LogMessage* pLogMessage,
752 wxTextCtrl* pTextCtrl)
754 #if defined(HAVE_LOCALTIME_R)
763 LogPrefsDialog::HeaderFormat headerFmt;
765 headerFmt = mHeaderFormat;
766 if (pLogMessage->GetInternal())
767 headerFmt = LogPrefsDialog::kHFInternal;
769 priChar = ((const char*)GetPriorityString(pLogMessage->GetPriority()))[0];
772 * Get the current date/time in pretty form
774 * It's often useful when examining a log with "less" to jump to
775 * a specific point in the file by searching for the date/time stamp.
776 * For this reason it's very annoying to have regexp meta characters
777 * in the time stamp. Don't use forward slashes, parenthesis,
778 * brackets, asterisks, or other special chars here.
780 time_t when = pLogMessage->GetWhen();
781 const char* fmt = NULL;
782 #if defined(HAVE_LOCALTIME_R)
783 ptm = localtime_r(&when, &tmBuf);
785 ptm = localtime(&when);
788 case LogPrefsDialog::kHFFull:
789 case LogPrefsDialog::kHFInternal:
790 fmt = "%m-%d %H:%M:%S";
792 case LogPrefsDialog::kHFBrief:
793 case LogPrefsDialog::kHFMinimal:
800 strftime(timeBuf, sizeof(timeBuf), fmt, ptm);
802 strcpy(timeBuf, "-");
804 const int kMaxExtraNewlines = 2;
806 char finalNewlines[kMaxExtraNewlines+1 +1];
811 hdrNewline[0] = '\n';
812 hdrNewline[1] = '\0';
814 assert(mExtraSpacing <= kMaxExtraNewlines);
816 for (i = 0; i < mExtraSpacing+1; i++)
817 finalNewlines[i] = '\n';
818 finalNewlines[i] = '\0';
821 switch (pLogMessage->GetPriority()) {
822 case ANDROID_LOG_WARN:
823 msgColor.SetTextColour(*wxBLUE);
825 case ANDROID_LOG_ERROR:
826 msgColor.SetTextColour(*wxRED);
828 case ANDROID_LOG_VERBOSE:
829 case ANDROID_LOG_DEBUG:
830 case ANDROID_LOG_INFO:
832 msgColor.SetTextColour(*wxBLACK);
835 if (pLogMessage->GetInternal())
836 msgColor.SetTextColour(*wxGREEN);
839 * Construct a buffer containing the log header.
841 bool splitHeader = true;
844 case LogPrefsDialog::kHFFull:
846 msgLen = android_snprintfBuffer(&outBuf, sizeof(msgBuf),
847 "[ %s %5d %c/%-6.6s]%s",
848 timeBuf, pLogMessage->GetPid(), priChar,
849 pLogMessage->GetTag(), hdrNewline);
851 case LogPrefsDialog::kHFBrief:
853 msgLen = android_snprintfBuffer(&outBuf, sizeof(msgBuf),
855 timeBuf, pLogMessage->GetPid(), hdrNewline);
857 case LogPrefsDialog::kHFMinimal:
859 msgLen = android_snprintfBuffer(&outBuf, sizeof(msgBuf),
861 timeBuf, pLogMessage->GetPid(), pLogMessage->GetMsg());
863 case LogPrefsDialog::kHFInternal:
865 msgLen = android_snprintfBuffer(&outBuf, sizeof(msgBuf),
866 "[%s] %s", timeBuf, pLogMessage->GetMsg());
869 fprintf(stderr, "Sim: unexpected header format %d\n", headerFmt);
875 fprintf(stderr, "WHOOPS\n");
876 assert(outBuf == msgBuf);
882 pTextCtrl->SetDefaultStyle(wxTextAttr(*wxLIGHT_GREY));
883 pTextCtrl->AppendText(wxString::FromAscii(outBuf));
885 pTextCtrl->SetDefaultStyle(msgColor);
886 pTextCtrl->AppendText(wxString::FromAscii(pLogMessage->GetMsg()));
888 pTextCtrl->SetDefaultStyle(*wxBLACK);
889 pTextCtrl->AppendText(wxString::FromAscii(finalNewlines));
892 pTextCtrl->SetDefaultStyle(msgColor);
893 pTextCtrl->AppendText(wxString::FromAscii(outBuf));
895 pTextCtrl->SetDefaultStyle(*wxBLACK);
896 pTextCtrl->AppendText(wxString::FromAscii(finalNewlines));
899 /* if we allocated storage for this message, free it */
900 if (outBuf != msgBuf)
905 * Write the message to the log file.
907 * We can't just do this in FormatMessage(), because that re-writes all
908 * messages on the display whenever the output format or filter changes.
910 * Use a one-log-per-line format here to make "grep" useful.
912 void LogWindow::LogToFile(const LogMessage* pLogMessage)
914 #if defined(HAVE_LOCALTIME_R)
924 assert(mLogFp != NULL);
926 time_t when = pLogMessage->GetWhen();
927 #if defined(HAVE_LOCALTIME_R)
928 ptm = localtime_r(&when, &tmBuf);
930 ptm = localtime(&when);
933 strftime(timeBuf, sizeof(timeBuf), "%m-%d %H:%M:%S", ptm);
934 priChar = ((const char*)GetPriorityString(pLogMessage->GetPriority()))[0];
937 if (pLogMessage->GetInternal()) {
938 msgLen = android_snprintfBuffer(&outBuf, sizeof(msgBuf),
940 timeBuf, pLogMessage->GetPid(), pLogMessage->GetMsg());
942 msgLen = android_snprintfBuffer(&outBuf, sizeof(msgBuf),
944 timeBuf, pLogMessage->GetPid(), priChar,
945 pLogMessage->GetMsg());
947 if (fwrite(outBuf, msgLen, 1, mLogFp) != 1)
948 fprintf(stderr, "Sim: WARNING: partial log write\n");
951 /* if we allocated storage for this message, free it */
952 if (outBuf != msgBuf)
957 * Get the modification date of a file.
959 static bool GetFileModDate(const char* fileName, time_t* pModWhen)
963 if (stat(fileName, &sb) < 0)
966 *pModWhen = sb.st_mtime;
971 * Open or close the log file as appropriate.
973 void LogWindow::PrepareLogFile(void)
975 const int kLogFileMaxAge = 8 * 60 * 60; // 8 hours
977 if (!mWriteFile && mLogFp != NULL) {
978 printf("Sim: closing log file\n");
981 } else if (mWriteFile && mLogFp == NULL) {
982 printf("Sim: opening log file '%s'\n", (const char*)mFileName.ToAscii());
983 time_t now, modWhen = 0;
984 const char* openFlags;
988 (GetFileModDate(mFileName.ToAscii(), &modWhen) &&
989 modWhen + kLogFileMaxAge > now))
992 printf("--- log file is %.3f hours old, appending\n",
993 (now - modWhen) / 3600.0);
995 openFlags = "a"; // open for append (text mode)
998 printf("--- log file is %.3f hours old, truncating\n",
999 (now - modWhen) / 3600.0);
1001 openFlags = "w"; // open for writing, truncate (text mode)
1004 mLogFp = fopen(mFileName.ToAscii(), openFlags);
1005 if (mLogFp == NULL) {
1006 fprintf(stderr, "Sim: failed opening log file '%s': %s\n",
1007 (const char*) mFileName.ToAscii(), strerror(errno));
1009 fprintf(mLogFp, "\n\n");
1016 * Add a new log message.
1018 * This function can be called from any thread. It makes a copy of the
1019 * stuff in "*pBundle" and sends it to the main UI thread.
1021 /*static*/ void LogWindow::PostLogMsg(const android_LogBundle* pBundle)
1023 LogMessage* pNewMessage = LogMessage::Create(pBundle);
1025 SendToWindow(pNewMessage);
1029 * Post a simple string to the log.
1031 /*static*/ void LogWindow::PostLogMsg(const char* msg)
1033 LogMessage* pNewMessage = LogMessage::Create(msg);
1035 SendToWindow(pNewMessage);
1039 * Post a simple wxString to the log.
1041 /*static*/ void LogWindow::PostLogMsg(const wxString& msg)
1043 LogMessage* pNewMessage = LogMessage::Create(msg.ToAscii());
1045 SendToWindow(pNewMessage);
1049 * Send a log message to the log window.
1051 /*static*/ void LogWindow::SendToWindow(LogMessage* pMessage)
1053 if (pMessage != NULL) {
1054 wxWindow* pMainFrame = ((MyApp*)wxTheApp)->GetMainFrame();
1055 UserEventMessage* pUem = new UserEventMessage;
1056 pUem->CreateLogMessage(pMessage);
1058 UserEvent uev(0, (void*) pUem);
1060 pMainFrame->AddPendingEvent(uev);
1062 fprintf(stderr, "Sim: failed to add new log message\n");
1068 * This is a sanity check. We need to stop somewhere to avoid trashing
1069 * the system on bad input.
1071 #define kMaxLen 65536
1073 #define VSNPRINTF vsnprintf // used to worry about _vsnprintf
1077 * Print a formatted message into a buffer. Pass in a buffer to try to use.
1079 * If the buffer isn't big enough to hold the message, allocate storage
1080 * with malloc() and return that instead. The caller is responsible for
1081 * freeing the storage.
1083 * Returns the length of the string, or -1 if the printf call failed.
1085 static int android_vsnprintfBuffer(char** pBuf, int bufLen, const char* format, va_list args)
1088 char* localBuf = NULL;
1090 assert(pBuf != NULL && *pBuf != NULL);
1092 assert(format != NULL);
1096 * In some versions of libc, vsnprintf only returns 0 or -1, where
1097 * -1 indicates the the buffer wasn't big enough. In glibc 2.1
1098 * and later, it returns the actual size needed.
1100 * MinGW is just returning -1, so we have to retry there.
1104 charsOut = VSNPRINTF(*pBuf, bufLen, format, args);
1106 if (charsOut >= 0 && charsOut < bufLen)
1109 //fprintf(stderr, "EXCEED: %d vs %d\n", charsOut, bufLen);
1111 /* exact size not known, double previous size */
1113 if (bufLen > kMaxLen)
1116 /* exact size known, just use that */
1118 bufLen = charsOut + 1;
1120 //fprintf(stderr, "RETRY at %d\n", bufLen);
1122 newBuf = (char*) realloc(localBuf, bufLen);
1125 *pBuf = localBuf = newBuf;
1128 // On platforms where snprintf() doesn't return the number of
1129 // characters output, we would need to call strlen() here.
1134 if (localBuf != NULL) {
1142 * Variable-arg form of the above.
1144 static int android_snprintfBuffer(char** pBuf, int bufLen, const char* format, ...)
1149 va_start(args, format);
1150 result = android_vsnprintfBuffer(pBuf, bufLen, format, args);