aboutsummaryrefslogtreecommitdiff
path: root/dep/g3dlite/source/debugAssert.cpp
blob: cfccf9a0cc564190cb707fdae2080df4f30c29a5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
/**
 @file debugAssert.cpp

 Windows implementation of assertion routines.

 @maintainer Morgan McGuire, graphics3d.com
 
 @created 2001-08-26
 @edited  2009-06-02
 */

#include "G3D/debugAssert.h"
#include "G3D/platform.h"
#ifdef G3D_WINDOWS
    #include <tchar.h>
#endif
#include "G3D/format.h"
#include "G3D/prompt.h"
#include <string>
#include "G3D/debugPrintf.h"
#include "G3D/Log.h"

#include <cstdlib>

#ifdef _MSC_VER
    // disable: "C++ exception handler used"
#   pragma warning (push)
#   pragma warning (disable : 4530)
#endif

using namespace std;

namespace G3D { namespace _internal {

ConsolePrintHook _consolePrintHook;
AssertionHook _debugHook = _handleDebugAssert_;
AssertionHook _failureHook = _handleErrorCheck_;

#ifdef G3D_LINUX
#if 0 /* G3DFIX: Disabled to avoid requirement for X11 libraries */
    Display*      x11Display = NULL;
    Window        x11Window  = 0;
#endif
#endif


#ifdef G3D_WINDOWS
static void postToClipboard(const char *text) {
    if (OpenClipboard(NULL)) {
        HGLOBAL hMem = GlobalAlloc(GHND | GMEM_DDESHARE, strlen(text) + 1);
        if (hMem) {
            char *pMem = (char*)GlobalLock(hMem);
            strcpy(pMem, text);
            GlobalUnlock(hMem);

            EmptyClipboard();
            SetClipboardData(CF_TEXT, hMem);
        }

        CloseClipboard();
        GlobalFree(hMem);
    }
}
#endif

/**
 outTitle should be set before the call
 */
static void createErrorMessage(
    const char*         expression,
    const std::string&  message,
    const char*         filename,
    int                 lineNumber,
    std::string&        outTitle,
    std::string&        outMessage) {

    std::string le = "";
    const char* newline = "\n";

    #ifdef G3D_WINDOWS
        newline = "\r\n";

        // The last error value.  (Which is preserved across the call).
        DWORD lastErr = GetLastError();
    
        // The decoded message from FormatMessage
        LPTSTR formatMsg = NULL;

        if (NULL == formatMsg) {
            FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
                          FORMAT_MESSAGE_IGNORE_INSERTS |
                          FORMAT_MESSAGE_FROM_SYSTEM,
                            NULL,
                            lastErr,
                            0,
                            (LPTSTR)&formatMsg,
                            0,
                            NULL);
        }

        // Make sure the message got translated into something.
        LPTSTR realLastErr;
        if (NULL != formatMsg) {
            realLastErr = formatMsg;
        } else {
            realLastErr = _T("Last error code does not exist.");
        }

        if (lastErr != 0) {
            le = G3D::format("Last Error (0x%08X): %s\r\n\r\n", lastErr, (LPCSTR)realLastErr);
        }

        // Get rid of the allocated memory from FormatMessage.
        if (NULL != formatMsg) {
            LocalFree((LPVOID)formatMsg);
        }

        char modulePath[MAX_PATH];
        GetModuleFileNameA(NULL, modulePath, MAX_PATH);

        const char* moduleName = strrchr(modulePath, '\\');
        outTitle = outTitle + string(" - ") + string(moduleName ? (moduleName + 1) : modulePath);

    #else
        (void)outTitle;
    #endif

    // Build the message.
    outMessage =
        G3D::format("%s%s%sExpression: %s%s%s:%d%s%s%s", 
                 message.c_str(), newline, newline, expression, newline, 
                 filename, lineNumber, newline, newline, le.c_str());
}


bool _handleDebugAssert_(
    const char*         expression,
    const std::string&  message,
    const char*         filename,
    int                 lineNumber,
    bool                useGuiPrompt) {

    std::string dialogTitle = "Assertion Failure";
    std::string dialogText = "";
    createErrorMessage(expression, message, filename, lineNumber, dialogTitle, dialogText);

    #ifdef G3D_WINDOWS
        DWORD lastErr = GetLastError();
        postToClipboard(dialogText.c_str());
        debugPrintf("\n%s\n", dialogText.c_str());
    #endif

    const int cBreak        = 0;
    const int cIgnore       = 1;
    const int cAbort        = 2;

    static const char* choices[] = {"Debug", "Ignore", "Exit"};

    // Log the error
    Log::common()->print(std::string("\n**************************\n\n") + dialogTitle + "\n" + dialogText);

    int result = G3D::prompt(dialogTitle.c_str(), dialogText.c_str(), (const char**)choices, 3, useGuiPrompt);

#    ifdef G3D_WINDOWS
        // Put the incoming last error back.
        SetLastError(lastErr);
#    endif

    switch (result) {
    // -1 shouldn't actually occur because it means 
    // that we're in release mode.
    case -1:
    case cBreak:
        return true;
        break;

    case cIgnore:
        return false;
        break;
   
    case cAbort:
        exit(-1);
        break;
    }

    // Should never get here
    return false;
}


bool _handleErrorCheck_(
    const char*         expression,
    const std::string&  message,
    const char*         filename,
    int                 lineNumber,
    bool                useGuiPrompt) {

    std::string dialogTitle = "Critical Error";
    std::string dialogText = "";

    createErrorMessage(expression, message, filename, lineNumber, dialogTitle, dialogText);

    // Log the error
    Log::common()->print(std::string("\n**************************\n\n") + dialogTitle + "\n" + dialogText);
    #ifdef G3D_WINDOWS
        DWORD lastErr = GetLastError();
        (void)lastErr;
        postToClipboard(dialogText.c_str());
        debugPrintf("\n%s\n", dialogText.c_str());
    #endif

    static const char* choices[] = {"Ok"};

    const std::string& m = 
        std::string("An internal error has occured in this program and it will now close.  "
        "The specific error is below. More information has been saved in \"") +
            Log::getCommonLogFilename() + "\".\n\n" + dialogText;

    int result = G3D::prompt("Error", m.c_str(), (const char**)choices, 1, useGuiPrompt);
    (void)result;

    return true;
}


#ifdef G3D_WINDOWS
static HCURSOR oldCursor;
static RECT    oldCursorRect;
static POINT   oldCursorPos;
static int     oldShowCursorCount;
#endif

void _releaseInputGrab_() {
    #ifdef G3D_WINDOWS

        GetCursorPos(&oldCursorPos);

        // Stop hiding the cursor if the application hid it.
        oldShowCursorCount = ShowCursor(true) - 1;

        if (oldShowCursorCount < -1) {
            for (int c = oldShowCursorCount; c < -1; ++c) {
                ShowCursor(true);
            }
        }

        // Set the default cursor in case the application
        // set the cursor to NULL.
        oldCursor = GetCursor();
        SetCursor(LoadCursor(NULL, IDC_ARROW));

        // Allow the cursor full access to the screen
        GetClipCursor(&oldCursorRect);
        ClipCursor(NULL);
        
    #elif defined(G3D_LINUX)
#if 0 /* G3DFIX: Disabled to avoid requirement for X11 libraries */
        if (x11Display != NULL) {
            XUngrabPointer(x11Display, CurrentTime);
            XUngrabKeyboard(x11Display, CurrentTime);
            if (x11Window != 0) {
                //XUndefineCursor(x11Display, x11Window);
                // TODO: Note that we leak this cursor; it should be
                // freed in the restore code.
                Cursor c = XCreateFontCursor(x11Display, 68);
                XDefineCursor(x11Display, x11Window, c);
            }
            XSync(x11Display, false);           
            XAllowEvents(x11Display, AsyncPointer, CurrentTime);
            XFlush(x11Display);
        }
#endif
    #elif defined(G3D_OSX)
        // TODO: OS X
    #endif
}


void _restoreInputGrab_() {
    #ifdef G3D_WINDOWS

        // Restore the old clipping region
        ClipCursor(&oldCursorRect);

        SetCursorPos(oldCursorPos.x, oldCursorPos.y);

        // Restore the old cursor
        SetCursor(oldCursor);

        // Restore old visibility count
        if (oldShowCursorCount < 0) {
            for (int c = 0; c > oldShowCursorCount; --c) {
                ShowCursor(false);
            }
        }
        
    #elif defined(G3D_LINUX)
        // TODO: Linux
    #elif defined(G3D_OSX)
        // TODO: OS X
    #endif
}


}; // internal namespace
 
void setAssertionHook(AssertionHook hook) {
    G3D::_internal::_debugHook = hook;
}

AssertionHook assertionHook() {
    return     G3D::_internal::_debugHook;
}

void setFailureHook(AssertionHook hook) {
    G3D::_internal::_failureHook = hook;
}

AssertionHook failureHook() {
    return G3D::_internal::_failureHook;
}


void setConsolePrintHook(ConsolePrintHook h) {
    G3D::_internal::_consolePrintHook = h;
}

ConsolePrintHook consolePrintHook() {
    return G3D::_internal::_consolePrintHook;
}


std::string __cdecl debugPrint(const std::string& s) {
#   ifdef G3D_WINDOWS
        const int MAX_STRING_LEN = 1024;
    
        // Windows can't handle really long strings sent to
        // the console, so we break the string.
        if (s.size() < MAX_STRING_LEN) {
            OutputDebugStringA(s.c_str());
        } else {
            for (unsigned int i = 0; i < s.size(); i += MAX_STRING_LEN) {
                std::string sub = s.substr(i, MAX_STRING_LEN);
                OutputDebugStringA(sub.c_str());
            }
        }
#    else
        fprintf(stderr, "%s", s.c_str());
        fflush(stderr);
#    endif

     return s;
}

std::string __cdecl debugPrintf(const char* fmt ...) {
    va_list argList;
    va_start(argList, fmt);
    std::string s = G3D::vformat(fmt, argList);
    va_end(argList);

    return debugPrint(s);
//    return debugPrint(consolePrint(s));
}

std::string consolePrint(const std::string& s) {
    FILE* L = Log::common()->getFile();
    fprintf(L, "%s", s.c_str());

    if (consolePrintHook()) {
        consolePrintHook()(s);
    }

    fflush(L);
    return s;
}


std::string __cdecl consolePrintf(const char* fmt ...) {
    va_list argList;
    va_start(argList, fmt);
    std::string s = G3D::vformat(fmt, argList);
    va_end(argList);

    return consolePrint(s);
}

} // namespace

#ifdef _MSC_VER
#   pragma warning (pop)
#endif