Exemple #1
0
static void ShowMessage(const char *format, ...) {
  // CAUTION: vsprintf will produce undesirable results if the string
  // contains a % character that is not a format specification!
  // But CFString is OK!

    va_list                 args;
    char                    s[1024];
    CFOptionFlags           responseFlags;
    ProcessSerialNumber     ourProcess;
   
#if 1
    va_start(args, format);
    vsprintf(s, format, args);
    va_end(args);
#else
    strcpy(s, format);
#endif

    // If defaultButton is nil or an empty string, a default localized
    // button title (ÒOKÓ in English) is used.
    
    CFStringRef myString = CFStringCreateWithCString(NULL, s, kCFStringEncodingUTF8);

    ::GetCurrentProcess (&ourProcess);
    ::SetFrontProcess(&ourProcess);
    CFUserNotificationDisplayAlert(0.0, kCFUserNotificationPlainAlertLevel,
                NULL, NULL, NULL, CFSTR(" "), myString,
                NULL, NULL, NULL,
                &responseFlags);
    
    if (myString) CFRelease(myString);
}
static CFOptionFlags ShowAlert( CFOptionFlags flags, const RString& sMessage, CFStringRef OK,
				CFStringRef alt = NULL, CFStringRef other = NULL)
{
	CFOptionFlags result;
	CFStringRef text = CFStringCreateWithCString( NULL, sMessage, kCFStringEncodingUTF8 );

	if( text == NULL )
	{
		RString error = ssprintf( "CFString for dialog string \"%s\" could not be created.", sMessage.c_str() );
		WARN( error );
		DEBUG_ASSERT_M( false, error );
		return kCFUserNotificationDefaultResponse; // Is this better than displaying an "unknown error" message?
	}
	CFUserNotificationDisplayAlert( 0.0, flags, NULL, NULL, NULL, CFSTR(PRODUCT_FAMILY),
					text, OK, alt, other, &result );
	CFRelease( text );

	// Flush all input that's accumulated while the dialog box was up.
	if( INPUTFILTER )
	{
		vector<InputEvent> dummy;
		INPUTFILTER->Reset();
		INPUTFILTER->GetInputEvents( dummy );
	}

	return result;
}
Exemple #3
0
void error (lua_State *L, const char *fmt, ...) {
	char str[1024];
	const char *msg;
#ifdef USE_GTK
	GtkWidget *dialog;
#endif
	
	va_list argp;
	va_start(argp, fmt);
	vsnprintf(str, 1023, fmt, argp);
	va_end(argp);
	
	msg = luaL_gsub(L, str, "[\"", "'");
	msg = luaL_gsub(L, msg, "[string \"", "'");
	msg = luaL_gsub(L, msg, "\"]", "'");
	fputs(msg, stderr);

#ifdef USE_GTK
	gtk_init(NULL, NULL);
	dialog = gtk_message_dialog_new(
		NULL,
		GTK_DIALOG_MODAL,
		GTK_MESSAGE_ERROR,
		GTK_BUTTONS_CLOSE,
		"%s", msg
	);
	gtk_window_set_title(GTK_WINDOW (dialog), PROG_NAME);
	gtk_dialog_run(GTK_DIALOG (dialog));

#elif __WIN32__
	MessageBox(NULL, msg, PROG_NAME, MB_ICONERROR|MB_OK);

#elif __MACOSX__
	CFUserNotificationDisplayAlert (
		0, /* timeout */ 
		kCFUserNotificationStopAlertLevel, /* alert level */
		NULL, /* icon URL */ 
		NULL, /* sound URL */
		NULL, /* localization URL */
		CFSTR(PROG_NAME), /* header */
		CFStringCreateWithCString(
			NULL, /* choose default allocator */
			msg,
			kCFStringEncodingASCII /* encoding */			
		), 
		NULL, /* default button title (OK) */
		NULL, /* alternate button title */
		NULL, /* other button title */
		NULL /* response codes */
	);
#endif

	fputs("\n", stderr);
	lua_close(L);
	exit(1);
}
static void ShowErrorVa(const wchar_t *de, const wchar_t *en, va_list args)
{
	// Get current language
	const wchar_t *stringToUse = en;
#ifdef _WIN32
	if ((GetUserDefaultLangID() & 0xFF) == LANG_GERMAN) stringToUse = de;		
#elif defined(__APPLE_CC__)
	CFStringRef localisations[2] = { CFSTR("en"), CFSTR("de") };
	CFArrayRef allLocalisations = CFArrayCreate(kCFAllocatorDefault, (const void **) localisations, 2, &kCFTypeArrayCallBacks);
	CFArrayRef preferredLocalisations = CFBundleCopyPreferredLocalizationsFromArray(allLocalisations);
	CFStringRef oldStyleLang = (CFStringRef) CFArrayGetValueAtIndex(preferredLocalisations, 0);
	CFStringRef newStyleLang = CFLocaleCreateCanonicalLanguageIdentifierFromString(kCFAllocatorDefault, oldStyleLang);
	
	if (CFStringHasPrefix(newStyleLang, CFSTR("de"))) stringToUse = de;
	
	CFRelease(allLocalisations);
	CFRelease(preferredLocalisations);
	CFRelease(newStyleLang);
#else
	// TODO: Implement something here for android.
#endif
	// Create output string
	wchar_t text[1024];
	vswprintf(text, 1024, stringToUse, args);
	
	// Show message
#ifdef _WIN32
	MessageBoxW(NULL, text, L"Mindstorms Simulator", MB_TASKMODAL & MB_ICONWARNING);
#elif defined(IPHONE)
	// Ignore it
#elif defined(__APPLE_CC__)
	CFStringRef messageString = CFStringCreateWithBytes(kCFAllocatorDefault, (const UInt8 *) text, sizeof(wchar_t) * wcslen(text), (CFByteOrderGetCurrent() == CFByteOrderBigEndian) ? kCFStringEncodingUTF32BE : kCFStringEncodingUTF32LE, false);
	CFUserNotificationDisplayAlert(0.0, kCFUserNotificationStopAlertLevel, NULL, NULL, NULL, messageString, NULL, NULL, NULL, NULL, NULL);
	CFRelease(messageString);
#else
	// TODO: Implement something here for android.
	size_t length = wcslen(text)+1;
	char *englishMangledASCII = new char[length];
	for (unsigned i = 0; i < length; i++)
		englishMangledASCII[i] = (char) en[i];
	
	__android_log_print(ANDROID_LOG_FATAL, "librobosim.so", "Error: %s", englishMangledASCII);
	delete englishMangledASCII;
#endif	
}
Exemple #5
0
    void static ShowAlertNative(String title, String message, Array<String> buttons, AlertDelegate* delegate)
    {
        CFOptionFlags cfRes;

        CFStringRef b[3];

        for (int i = 0; i<3; ++i)
        {
            if (buttons.Length() > i)
            {
                b[i] = CFStringCreateWithCString(NULL, buttons.At(i).ToCString<char>(), kCFStringEncodingASCII);
            } else {
                b[i] = CFStringCreateWithCString(NULL, "", kCFStringEncodingASCII);
            }
        }

        CFUserNotificationDisplayAlert(0, kCFUserNotificationNoteAlertLevel,
                                       NULL, NULL, NULL,
                                       CFStringCreateWithCString(NULL, title.ToCString<char>(), kCFStringEncodingASCII),
                                       CFStringCreateWithCString(NULL, message.ToCString<char>(), kCFStringEncodingASCII),
                                       b[0],
                                       b[1],
                                       b[2],
                                       &cfRes);

        switch (cfRes)
        {
        case kCFUserNotificationDefaultResponse:
            delegate->Call(0, buttons.At(0));
            break;
        case kCFUserNotificationAlternateResponse:
            delegate->Call(1, buttons.At(1));
            break;
        case kCFUserNotificationOtherResponse:
            delegate->Call(2, buttons.At(2));
            break;
        default:
            break;
        }
    }
Exemple #6
0
void CrashHandler::InformUserOfCrash( const RString& sPath )
{
	CFBundleRef bundle = CFBundleGetMainBundle();
	CFStringRef sAlternate = LSTRING( bundle, "Quit " PRODUCT_FAMILY );
	/* XXX Translate these and remove the redefine of LSTRING. Another way to do this
	 * would be to pass bundle's URL to CFUserNotificationDisplayAlert's localizationURL
	 * parameter and let it do it. This wouldn't work for sBody though. */
#undef LSTRING
#define LSTRING(b,x) CFSTR(x)
	CFStringRef sDefault = LSTRING( bundle, "File Bug Report" );
	CFStringRef sOther = LSTRING( bundle, "Open crashinfo.txt" );
	CFStringRef sTitle = LSTRING( bundle, PRODUCT_FAMILY " has crashed" );
	CFStringRef sFormat = LSTRING( bundle, PRODUCT_FAMILY " has crashed. "
				       "Debugging information has been output to\n\n%s\n\n"
				       "Please file a bug report at\n\n%s" );
	CFStringRef sBody = CFStringCreateWithFormat( kCFAllocatorDefault, NULL, sFormat,
						      sPath.c_str(), REPORT_BUG_URL );
	CFOptionFlags response = kCFUserNotificationCancelResponse;
	CFTimeInterval timeout = 0.0; // Should we ever time out?
	
	CFUserNotificationDisplayAlert( timeout, kCFUserNotificationStopAlertLevel, NULL, NULL, NULL,
					sTitle, sBody, sDefault, sAlternate, sOther, &response );
	
	switch( response )
	{
	case kCFUserNotificationDefaultResponse:
		HOOKS->GoToURL( REPORT_BUG_URL );
		// Fall through.
	case kCFUserNotificationOtherResponse:
		// Open the file with the default application (probably TextEdit).
		HOOKS->GoToURL( "file://" + sPath );
		break;
	}
	CFRelease( sBody );
	CFRelease( sFormat );
	CFRelease( sTitle );
	CFRelease( sOther );
	CFRelease( sDefault );
	CFRelease( sAlternate );
}
Exemple #7
0
static void ShowMessage(const char *format, ...) {
  // CAUTION: vsprintf will produce undesirable results if the string
  // contains a % character that is not a format specification!
  // But CFString is OK!

    va_list                 args;
    char                    s[1024];
    CFOptionFlags           responseFlags;
    CFURLRef                myIconURLRef = NULL;
    CFBundleRef             myBundleRef;
   
    myBundleRef = CFBundleGetMainBundle();
    if (myBundleRef) {
        myIconURLRef = CFBundleCopyResourceURL(myBundleRef, CFSTR("MacInstaller.icns"), NULL, NULL);
    }
   
#if 1
    va_start(args, format);
    vsprintf(s, format, args);
    va_end(args);
#else
    strcpy(s, format);
#endif

    // If defaultButton is nil or an empty string, a default localized
    // button title ("OK" in English) is used.
    
    CFStringRef myString = CFStringCreateWithCString(NULL, s, kCFStringEncodingUTF8);

    BringAppToFront();
    CFUserNotificationDisplayAlert(0.0, kCFUserNotificationPlainAlertLevel,
                myIconURLRef, NULL, NULL, CFSTR(" "), myString,
                NULL, NULL, NULL,
                &responseFlags);
    
    if (myIconURLRef) CFRelease(myIconURLRef);
    if (myString) CFRelease(myString);
}
int wxMessageDialog::ShowModal()
{
    WX_HOOK_MODAL_DIALOG();

    int resultbutton = wxID_CANCEL;

    const long style = GetMessageDialogStyle();

    wxASSERT_MSG( (style & 0x3F) != wxYES,
        "this style is not supported on Mac" );

    AlertType alertType = kAlertPlainAlert;

    switch ( GetEffectiveIcon() )
    {
        case wxICON_ERROR:
            alertType = kAlertStopAlert;
            break;

        case wxICON_WARNING:
            alertType = kAlertCautionAlert;
            break;

        case wxICON_QUESTION:
        case wxICON_INFORMATION:
            alertType = kAlertNoteAlert;
            break;
    }

    // (the standard alert has two slots [title, text]
    //  for the three wxStrings [caption, message, extended message])
    //
    // if the extended text is empty we use the caption and
    // the message (for backwards compatibility)
    //
    // if the extended text is not empty we ignore the caption
    // and use the message and the extended message


    wxString msgtitle,msgtext;
    if(m_extendedMessage.IsEmpty())
    {
        if ( m_caption.IsEmpty() )
            msgtitle = m_message;
        else
        {
            msgtitle = m_caption;
            msgtext  = m_message;
        }
    }
    else
    {
        msgtitle = m_message;
        msgtext  = m_extendedMessage;
    }


    if ( !wxIsMainThread() )
    {
        CFStringRef defaultButtonTitle = NULL;
        CFStringRef alternateButtonTitle = NULL;
        CFStringRef otherButtonTitle = NULL;

        wxCFStringRef cfTitle( msgtitle, GetFont().GetEncoding() );
        wxCFStringRef cfText( msgtext, GetFont().GetEncoding() );

        wxCFStringRef cfNoString( GetNoLabel().c_str(), GetFont().GetEncoding() );
        wxCFStringRef cfYesString( GetYesLabel().c_str(), GetFont().GetEncoding() );
        wxCFStringRef cfOKString( GetOKLabel().c_str() , GetFont().GetEncoding()) ;
        wxCFStringRef cfCancelString( GetCancelLabel().c_str(), GetFont().GetEncoding() );

        int buttonId[4] = { 0, 0, 0, wxID_CANCEL /* time-out */ };

        if (style & wxYES_NO)
        {
            if ( style & wxNO_DEFAULT )
            {
                defaultButtonTitle = cfNoString;
                alternateButtonTitle = cfYesString;
                buttonId[0] = wxID_NO;
                buttonId[1] = wxID_YES;
            }
            else
            {
                defaultButtonTitle = cfYesString;
                alternateButtonTitle = cfNoString;
                buttonId[0] = wxID_YES;
                buttonId[1] = wxID_NO;
            }
            if (style & wxCANCEL)
            {
                otherButtonTitle = cfCancelString;
                buttonId[2] = wxID_CANCEL;
            }
        }
        else
        {
            // the MSW implementation even shows an OK button if it is not specified, we'll do the same
            buttonId[0] = wxID_OK;
            // using null as default title does not work on earlier systems
            defaultButtonTitle = cfOKString;
            if (style & wxCANCEL)
            {
                alternateButtonTitle = cfCancelString;
                buttonId[1] = wxID_CANCEL;
            }
        }

        CFOptionFlags exitButton;
        OSStatus err = CFUserNotificationDisplayAlert(
            0, alertType, NULL, NULL, NULL, cfTitle, cfText,
            defaultButtonTitle, alternateButtonTitle, otherButtonTitle, &exitButton );
        if (err == noErr)
            resultbutton = buttonId[exitButton];
    }
    else
    {
        short result;

        AlertStdCFStringAlertParamRec param;
        wxCFStringRef cfNoString( GetNoLabel().c_str(), GetFont().GetEncoding() );
        wxCFStringRef cfYesString( GetYesLabel().c_str(), GetFont().GetEncoding() );
        wxCFStringRef cfOKString( GetOKLabel().c_str(), GetFont().GetEncoding() );
        wxCFStringRef cfCancelString( GetCancelLabel().c_str(), GetFont().GetEncoding() );

        wxCFStringRef cfTitle( msgtitle, GetFont().GetEncoding() );
        wxCFStringRef cfText = msgtext.IsEmpty() ? wxCFStringRef() : wxCFStringRef( msgtext, GetFont().GetEncoding() );

        param.movable = true;
        param.flags = 0;
        param.version = kStdCFStringAlertVersionOne;

        bool skipDialog = false;

        if (style & wxYES_NO)
        {
            if (style & wxCANCEL)
            {
                param.defaultText = cfYesString;
                param.cancelText = cfCancelString;
                param.otherText = cfNoString;
                param.helpButton = false;
                param.defaultButton = style & wxNO_DEFAULT ? kAlertStdAlertOtherButton : kAlertStdAlertOKButton;
                param.cancelButton = kAlertStdAlertCancelButton;
            }
            else
            {
                param.defaultText = cfYesString;
                param.cancelText = NULL;
                param.otherText = cfNoString;
                param.helpButton = false;
                param.defaultButton = style & wxNO_DEFAULT ? kAlertStdAlertOtherButton : kAlertStdAlertOKButton;
                param.cancelButton = 0;
            }
        }
        // the MSW implementation even shows an OK button if it is not specified, we'll do the same
        else
        {
            if (style & wxCANCEL)
            {
                // that's a cancel missing
                param.defaultText = cfOKString;
                param.cancelText = cfCancelString;
                param.otherText = NULL;
                param.helpButton = false;
                param.defaultButton = kAlertStdAlertOKButton;
                param.cancelButton = 0;
            }
            else
            {
                param.defaultText = cfOKString;
                param.cancelText = NULL;
                param.otherText = NULL;
                param.helpButton = false;
                param.defaultButton = kAlertStdAlertOKButton;
                param.cancelButton = 0;
            }
        }

        param.position = kWindowDefaultPosition;
        if ( !skipDialog )
        {
            DialogRef alertRef;
            CreateStandardAlert( alertType, cfTitle, cfText, &param, &alertRef );
            wxDialog::OSXBeginModalDialog();
            RunStandardAlert( alertRef, NULL, &result );
            wxDialog::OSXEndModalDialog();
        }
        else
        {
            return wxID_CANCEL;
        }

        if (style & wxOK)
        {
            switch ( result )
            {
            case 1:
                resultbutton = wxID_OK;
                break;

            case 2:
                // TODO: add Cancel button
                // if (style & wxCANCEL)
                //     resultbutton = wxID_CANCEL;
                break;

            case 3:
            default:
                break;
            }
        }
        else if (style & wxYES_NO)
        {
            switch ( result )
            {
            case 1:
                resultbutton = wxID_YES;
                break;

            case 2:
                if (!(style & wxCANCEL))
                    resultbutton = wxID_CANCEL;
                break;

            case 3:
                resultbutton = wxID_NO;
                break;

            default:
                break;
            }
        }
    }

    SetReturnCode(resultbutton);

    return resultbutton;
}
Exemple #9
0
int showAlert(const char *title, const char *msg, const char *defaultButton,
              const char *cancelButton)
{
#if defined(IS_MACOSX)
	CFStringRef alertHeader = CFStringCreateWithUTF8String(title);
	CFStringRef alertMessage = CFStringCreateWithUTF8String(msg);
	CFStringRef defaultButtonTitle = CFStringCreateWithUTF8String(defaultButton);
	CFStringRef cancelButtonTitle = CFStringCreateWithUTF8String(cancelButton);
	CFOptionFlags responseFlags;
	SInt32 err = CFUserNotificationDisplayAlert(0.0,
	                                            kCFUserNotificationNoteAlertLevel,
	                                            NULL,
	                                            NULL,
	                                            NULL,
	                                            alertHeader,
	                                            alertMessage,
	                                            defaultButtonTitle,
	                                            cancelButtonTitle,
	                                            NULL,
	                                            &responseFlags);
	if (alertHeader != NULL) CFRelease(alertHeader);
	if (alertMessage != NULL) CFRelease(alertMessage);
	if (defaultButtonTitle != NULL) CFRelease(defaultButtonTitle);
	if (cancelButtonTitle != NULL) CFRelease(cancelButtonTitle);

	if (err != 0) return -1;
	return (responseFlags == kCFUserNotificationDefaultResponse) ? 0 : 1;
#elif defined(USE_X11)
	/* Note that args[0] is set by the xmessage() function. */
	const char *args[10] = {NULL, msg, "-title", title, "-center"};
	int response, ret;
	char *buttonList = NULL; /* To be free()'d. */

	if (defaultButton == NULL) defaultButton = "OK";

	if (cancelButton == NULL) {
		asprintf(&buttonList, "%s:2", defaultButton);
	} else {
		asprintf(&buttonList, "%s:2,%s:3", defaultButton, cancelButton);
	}

	if (buttonList == NULL) return -1; /* asprintf() failed. */
	args[5] = "-buttons";
	args[6] = buttonList;
	args[7] = "-default";
	args[8] = defaultButton;
	args[9] = NULL;

	ret = xmessage((char **)args, &response);
	if (buttonList != NULL) {
		free(buttonList);
		buttonList = NULL;
	}

	if (ret != TASK_SUCCESS) {
		if (ret == EXEC_FAILED) {
			fputs("xmessage or equivalent not found.\n", stderr);
		}
		return -1;
	}

	return (response == 2) ? 0 : 1;
#else
	/* TODO: Display custom buttons instead of the pre-defined "OK"
	 * and "Cancel". */
	int response = MessageBox(NULL, msg, title,
	                          (cancelButton == NULL) ? MB_OK : MB_OKCANCEL);
	return (response == IDOK) ? 0 : 1;
#endif
}
Exemple #10
0
/**
 * Ask for user consent.
 *
 * Check for user consent configuration,
 * Invoke proper gui app and check result
 *
 * @param card pointer to sc_card structure
 * @param title Text to appear in the window header
 * @param text Message to show to the user
 * @return SC_SUCCESS on user consent OK , else error code
 */
int sc_ask_user_consent(struct sc_card * card, const char *title, const char *message)
{
#ifdef __APPLE__
	CFOptionFlags result;  /* result code from the message box */
	/* convert the strings from char* to CFStringRef */
	CFStringRef header_ref; /* to store title */
	CFStringRef message_ref; /* to store message */
#endif
#ifdef linux
	pid_t pid;
	FILE *fin=NULL;
	FILE *fout=NULL;	/* to handle pipes as streams */
	struct stat st_file;	/* to verify that executable exists */
	int srv_send[2];	/* to send data from server to client */
	int srv_recv[2];	/* to receive data from client to server */
	char outbuf[1024];	/* to compose and send messages */	
	char buf[1024];		/* to store client responses */
	int n = 0;		/* to iterate on to-be-sent messages */
#endif
	int res = SC_ERROR_INTERNAL;	/* by default error :-( */
	char *msg = NULL;	/* to makr errors */

	if ((card == NULL) || (card->ctx == NULL))
		return SC_ERROR_INVALID_ARGUMENTS;
	LOG_FUNC_CALLED(card->ctx);

	if ((title==NULL) || (message==NULL)) 
		LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);

	if (GET_DNIE_UI_CTX(card).user_consent_enabled == 0) {
		sc_log(card->ctx,
		       "User Consent is disabled in configuration file");
		LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
	}
#ifdef _WIN32
	/* in Windows, do not use pinentry, but MessageBox system call */
	res = MessageBox (
		NULL,
		TEXT(message),
		TEXT(title),
		MB_ICONWARNING | MB_OKCANCEL | MB_DEFBUTTON2 | MB_APPLMODAL
		);
	if ( res == IDOK ) 
		LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
	LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_ALLOWED);
#elif __APPLE__
	/* Also in Mac OSX use native functions */

	/* convert the strings from char* to CFStringRef */
	header_ref = CFStringCreateWithCString( NULL, title, strlen(title) );
	message_ref = CFStringCreateWithCString( NULL,message, strlen(message) );

	/* Displlay user notification alert */
	CFUserNotificationDisplayAlert(
		0, /* no timeout */
		kCFUserNotificationNoteAlertLevel,  /* Alert level */
		NULL,	/* IconURL, use default, you can change */
			/* it depending message_type flags */
		NULL,	/* SoundURL (not used) */ 
		NULL,	/* localization of strings */
		header_ref,	/* header. Cannot be null */
		message_ref,	/* message text */
		CFSTR("Cancel"), /* default ( "OK" if null) button text */ 
		CFSTR("OK"), /* second button title */
                NULL, /* third button title, null--> no other button */
		&result /* response flags */
	);

	/* Clean up the strings */
	CFRelease( header_ref );
        CFRelease( message_ref );
	/* Return 0 only if "OK" is selected */
	if( result == kCFUserNotificationAlternateResponse )
		LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
	LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_ALLOWED);
#elif linux
	/* check that user_consent_app exists. TODO: check if executable */
	res = stat(GET_DNIE_UI_CTX(card).user_consent_app, &st_file);
	if (res != 0) {
		sc_log(card->ctx, "Invalid pinentry application: %s\n",
		       GET_DNIE_UI_CTX(card).user_consent_app);
		LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
	}

	/* just a simple bidirectional pipe+fork+exec implementation */
	/* In a pipe, xx[0] is for reading, xx[1] is for writing */
	if (pipe(srv_send) < 0) {
		msg = "pipe(srv_send)";
		goto do_error;
	}
	if (pipe(srv_recv) < 0) {
		msg = "pipe(srv_recv)";
		goto do_error;
	}
	pid = fork();
	switch (pid) {
	case -1:		/* error  */
		msg = "fork()";
		goto do_error;
	case 0:		/* child  */
		/* make our pipes, our new stdin & stderr, closing older ones */
		dup2(srv_send[0], STDIN_FILENO);	/* map srv send for input */
		dup2(srv_recv[1], STDOUT_FILENO);	/* map srv_recv for output */
		/* once dup2'd pipes are no longer needed on client; so close */
		close(srv_send[0]);
		close(srv_send[1]);
		close(srv_recv[0]);
		close(srv_recv[1]);
		/* call exec() with proper user_consent_app from configuration */
		/* if ok should never return */
		execlp(GET_DNIE_UI_CTX(card).user_consent_app, GET_DNIE_UI_CTX(card).user_consent_app, (char *)NULL);
		res = SC_ERROR_INTERNAL;
		msg = "execlp() error";	/* exec() failed */
		goto do_error;
	default:		/* parent */
		/* Close the pipe ends that the child uses to read from / write to 
		 * so when we close the others, an EOF will be transmitted properly.
		 */
		close(srv_send[0]);
		close(srv_recv[1]);
		/* use iostreams to take care on newlines and text based data */
		fin = fdopen(srv_recv[0], "r");
		if (fin == NULL) {
			msg = "fdopen(in)";
			goto do_error;
		}
		fout = fdopen(srv_send[1], "w");
		if (fout == NULL) {
			msg = "fdopen(out)";
			goto do_error;
		}
		/* read and ignore first line */
		fflush(stdin);
		for (n = 0; n<4; n++) {
			char *pt;
			memset(outbuf, 0, sizeof(outbuf));
			if (n==0) snprintf(outbuf,1023,"%s %s\n",user_consent_msgs[0],title);
			else if (n==1) snprintf(outbuf,1023,"%s %s\n",user_consent_msgs[1],message);
			else snprintf(outbuf,1023,"%s\n",user_consent_msgs[n]);
			/* send message */
			fputs(outbuf, fout);
			fflush(fout);
			/* get response */
			memset(buf, 0, sizeof(buf));
			pt=fgets(buf, sizeof(buf) - 1, fin);
			if (pt==NULL) {
				res = SC_ERROR_INTERNAL;
				msg = "fgets() Unexpected IOError/EOF";
				goto do_error;
			}
			if (strstr(buf, "OK") == NULL) {
				res = SC_ERROR_NOT_ALLOWED;
				msg = "fail/cancel";
				goto do_error;
			}
		}
	}			/* switch */
	/* arriving here means signature has been accepted by user */
	res = SC_SUCCESS;
	msg = NULL;
do_error:
	/* close out channel to force client receive EOF and also die */
	if (fout != NULL) fclose(fout);
	if (fin != NULL) fclose(fin);
#else
#error "Don't know how to handle user consent in this (rare) Operating System"
#endif
	if (msg != NULL)
		sc_log(card->ctx, "%s", msg);
	LOG_FUNC_RETURN(card->ctx, res);
}
Exemple #11
0
bool wxGUIAppTraitsBase::ShowAssertDialog(const wxString& msg)
{
#if defined(__WXMSW__) || !wxUSE_MSGDLG
    // under MSW we prefer to use the base class version using ::MessageBox()
    // even if wxMessageBox() is available because it has less chances to
    // double fault our app than our wxMessageBox()
    return wxAppTraitsBase::ShowAssertDialog(msg);
#else // wxUSE_MSGDLG
    wxString msgDlg = msg;

#if wxUSE_STACKWALKER
    // on Unix stack frame generation may take some time, depending on the
    // size of the executable mainly... warn the user that we are working
    wxFprintf(stderr, wxT("[Debug] Generating a stack trace... please wait"));
    fflush(stderr);

    const wxString stackTrace = GetAssertStackTrace();
    if ( !stackTrace.empty() )
        msgDlg << _T("\n\nCall stack:\n") << stackTrace;
#endif // wxUSE_STACKWALKER

    // this message is intentionally not translated -- it is for
    // developpers only
    msgDlg += wxT("\nDo you want to stop the program?\n")
              wxT("You can also choose [Cancel] to suppress ")
              wxT("further warnings.");

#ifdef __WXMAC__
    // in order to avoid reentrancy problems, use the lowest alert API available
    CFOptionFlags exitButton;
    wxMacCFStringHolder cfText(msgDlg);
    OSStatus err = CFUserNotificationDisplayAlert(
            0, kAlertStopAlert, NULL, NULL, NULL, CFSTR("wxWidgets Debug Alert"), cfText,
            CFSTR("Yes"), CFSTR("No"), CFSTR("Cancel"), &exitButton );
    if ( err == noErr )
    {
        switch( exitButton )
        {
            case 0 : // yes
                wxTrap();
                break;
            case 2 : // cancel
                // no more asserts
                return true;
            case 1 : // no -> nothing to do
                break ;
        }
    }
#else
    switch ( wxMessageBox(msgDlg, wxT("wxWidgets Debug Alert"),
                          wxYES_NO | wxCANCEL | wxICON_STOP ) )
    {
        case wxYES:
            wxTrap();
            break;

        case wxCANCEL:
            // no more asserts
            return true;

        //case wxNO: nothing to do
    }
#endif
    return false;
#endif // !wxUSE_MSGDLG/wxUSE_MSGDLG
}
Exemple #12
0
/*++
Function:
  MessageBoxA

This is a small subset of MessageBox that simply logs a message to the
system logging facility and returns. A typical log entry will look
like:

May 23 15:48:10 rice example1: MessageBox: Caption: Error Text

Note:
  hWnd should always be NULL.

See MSDN doc.
--*/
int
PALAPI
MessageBoxA(
	    IN LPVOID hWnd,
	    IN LPCSTR lpText,
	    IN LPCSTR lpCaption,
	    IN UINT uType)
{
    INT rc = 0;

    PERF_ENTRY(MessageBoxA);
    ENTRY( "MessageBoxA (hWnd=%p, lpText=%p (%s), lpCaption=%p (%s), uType=%#x)\n",
           hWnd, lpText?lpText:"NULL", lpText?lpText:"NULL",
           lpCaption?lpCaption:"NULL",
           lpCaption?lpCaption:"NULL", uType );

    if (hWnd != NULL)
    {
        ASSERT("hWnd != NULL");
    }

    if (lpText == NULL)
    {
        WARN("No message text\n");

        lpText = "(no message text)";
    }

    if (lpCaption == NULL)
    {
        lpCaption = "Error";
    }
    
    if (uType & MB_DEFMASK)
    {
        WARN("No support for alternate default buttons.\n");
    }

    /* set default status based on the type of button */
    switch(uType & MB_TYPEMASK)
    {
    case MB_OK:
        rc = IDOK;
        break;

    case MB_ABORTRETRYIGNORE:
        rc = IDABORT;
        break;

    case MB_YESNO:
        rc = IDNO;
        break;

    case MB_OKCANCEL :
        rc = IDCANCEL;
        break;

    case MB_RETRYCANCEL :
        rc = IDCANCEL;
        break;

    default:
        ASSERT("Bad uType");
        rc = IDOK;
        break;
    }

    PALCEnterCriticalSection( &msgbox_critsec);

#ifdef __APPLE__
    OSStatus osstatus;

    SecuritySessionId secSession;
    SessionAttributeBits secSessionInfo;

    osstatus = SessionGetInfo(callerSecuritySession, &secSession, &secSessionInfo);
    if (noErr == osstatus && (secSessionInfo & sessionHasGraphicAccess) != 0)
    {
        CFStringRef cfsTitle = CFStringCreateWithCString(kCFAllocatorDefault, lpCaption, kCFStringEncodingUTF8);
        CFStringRef cfsText = CFStringCreateWithCString(kCFAllocatorDefault, lpText, kCFStringEncodingUTF8);
        CFStringRef cfsButton1 = NULL;
        CFStringRef cfsButton2 = NULL;
        CFStringRef cfsButton3 = NULL;
        CFOptionFlags alertFlags = 0;
        CFOptionFlags response;
                
        switch (uType & MB_TYPEMASK)
        {
        case MB_OK:
            // Nothing needed; since if all the buttons are null, a stock "OK" is used.
            break;
        
        case MB_ABORTRETRYIGNORE:
            // Localization? Would be needed if this were used outside of debugging.
            cfsButton1 = CFSTR("Abort");
            cfsButton2 = CFSTR("Retry");
            cfsButton3 = CFSTR("Ignore");
            alertFlags = kCFUserNotificationCautionAlertLevel;
            break;
            
        case MB_YESNO:
            cfsButton1 = CFSTR("Yes");
            cfsButton2 = CFSTR("No");
            break;
            
        case MB_OKCANCEL:
            cfsButton1 = CFSTR("OK");
            cfsButton2 = CFSTR("Cancel");
            break;
        
        case MB_RETRYCANCEL:
            cfsButton1 = CFSTR("Retry");
            cfsButton2 = CFSTR("Cancel");
            break;
        }
        
        CFUserNotificationDisplayAlert(0 /* no time out */, alertFlags, NULL /* iconURL */,
            NULL /* soundURL */, NULL /* localizationURL */, cfsTitle, cfsText, cfsButton1,
            cfsButton2, cfsButton3, &response);
            
        switch (uType & MB_TYPEMASK)
        {
        case MB_OK:
            break;
        
        case MB_ABORTRETRYIGNORE:
            switch (response)
            {
            case kCFUserNotificationDefaultResponse:
                rc = IDABORT;
                break;
            case kCFUserNotificationAlternateResponse:
                rc = IDRETRY;
                break;
            case kCFUserNotificationOtherResponse:
                rc = IDIGNORE;
                break;
            }
            break;
        
        case MB_YESNO:
            switch (response)
            {
            case kCFUserNotificationDefaultResponse:
                rc = IDYES;
                break;
            case kCFUserNotificationAlternateResponse:
                rc = IDNO;
                break;
            }
            break;
        
        case MB_OKCANCEL:
            switch (response)
            {
            case kCFUserNotificationDefaultResponse:
                rc = IDOK;
                break;
            case kCFUserNotificationAlternateResponse:
                rc = IDCANCEL;
                break;
            }
            break;
        
        case MB_RETRYCANCEL:
            switch (response)
            {
            case kCFUserNotificationDefaultResponse:
                rc = IDRETRY;
                break;
            case kCFUserNotificationAlternateResponse:
                rc = IDCANCEL;
                break;
            }
            break;
        }
    }
    else
    {
        // We're not in a login session, e.g., running via ssh, and so bringing
        // up a message box would be bad form.
        fprintf ( stderr, "MessageBox: %s: %s", lpCaption, lpText );
        syslog(LOG_USER|LOG_ERR, "MessageBox: %s: %s", lpCaption, lpText);
    }
#else // __APPLE__
    fprintf ( stderr, "MessageBox: %s: %s", lpCaption, lpText );
    syslog(LOG_USER|LOG_ERR, "MessageBox: %s: %s", lpCaption, lpText);

    // Some systems support displaying a GUI dialog. (This will suspend the current thread until they hit the
    // 'OK' button and allow a debugger to be attached).
    PAL_DisplayDialog(lpCaption, lpText);
#endif // __APPLE__ else

    PALCLeaveCriticalSection( &msgbox_critsec);

    LOGEXIT("MessageBoxA returns %d\n", rc);
    PERF_EXIT(MessageBoxA);
    return rc;
}
Exemple #13
0
int wxMessageDialog::ShowModal()
{
    int resultbutton = wxID_CANCEL;

    const long style = GetMessageDialogStyle();

    wxASSERT_MSG( (style & 0x3F) != wxYES, wxT("this style is not supported on Mac") );

    AlertType alertType = kAlertPlainAlert;
    if (style & wxICON_EXCLAMATION)
        alertType = kAlertCautionAlert;
    else if (style & wxICON_HAND)
        alertType = kAlertStopAlert;
    else if (style & wxICON_INFORMATION)
        alertType = kAlertNoteAlert;
    else if (style & wxICON_QUESTION)
        alertType = kAlertNoteAlert;

#if TARGET_API_MAC_OSX
    if ( !wxIsMainThread() )
    {
        CFStringRef defaultButtonTitle = NULL;
        CFStringRef alternateButtonTitle = NULL;
        CFStringRef otherButtonTitle = NULL;

        wxMacCFStringHolder cfTitle( m_caption, m_font.GetEncoding() );
        wxMacCFStringHolder cfText( m_message, m_font.GetEncoding() );

        wxMacCFStringHolder cfNoString( _("No"), m_font.GetEncoding() );
        wxMacCFStringHolder cfYesString( _("Yes"), m_font.GetEncoding() );
        wxMacCFStringHolder cfOKString( _("OK") , m_font.GetEncoding()) ;
        wxMacCFStringHolder cfCancelString( _("Cancel"), m_font.GetEncoding() );

        int buttonId[4] = { 0, 0, 0, wxID_CANCEL /* time-out */ };

        if (style & wxYES_NO)
        {
            if ( style & wxNO_DEFAULT )
            {
                defaultButtonTitle = cfNoString;
                alternateButtonTitle = cfYesString;
                buttonId[0] = wxID_NO;
                buttonId[1] = wxID_YES;
            }
            else
            {
                defaultButtonTitle = cfYesString;
                alternateButtonTitle = cfNoString;
                buttonId[0] = wxID_YES;
                buttonId[1] = wxID_NO;
            }
            if (style & wxCANCEL)
            {
                otherButtonTitle = cfCancelString;
                buttonId[2] = wxID_CANCEL;
            }
        }
        else
        {
            // the MSW implementation even shows an OK button if it is not specified, we'll do the same
            buttonId[0] = wxID_OK;
            // using null as default title does not work on earlier systems
            defaultButtonTitle = cfOKString;
            if (style & wxCANCEL)
            {
                alternateButtonTitle = cfCancelString;
                buttonId[1] = wxID_CANCEL;
            }
        }

        CFOptionFlags exitButton;
        OSStatus err = CFUserNotificationDisplayAlert(
            0, alertType, NULL, NULL, NULL, cfTitle, cfText,
            defaultButtonTitle, alternateButtonTitle, otherButtonTitle, &exitButton );
        if (err == noErr)
            resultbutton = buttonId[exitButton];
    }
    else
#endif
    {
        short result;

        AlertStdCFStringAlertParamRec param;
        wxMacCFStringHolder cfNoString( _("No"), m_font.GetEncoding() );
        wxMacCFStringHolder cfYesString( _("Yes"), m_font.GetEncoding() );

        wxMacCFStringHolder cfTitle( m_caption, m_font.GetEncoding() );
        wxMacCFStringHolder cfText( m_message, m_font.GetEncoding() );

        param.movable = true;
        param.flags = 0;
        param.version = kStdCFStringAlertVersionOne;

        bool skipDialog = false;

        if (style & wxYES_NO)
        {
            if (style & wxCANCEL)
            {
                param.defaultText = cfYesString;
                param.cancelText = (CFStringRef) kAlertDefaultCancelText;
                param.otherText = cfNoString;
                param.helpButton = false;
                param.defaultButton = style & wxNO_DEFAULT ? kAlertStdAlertOtherButton : kAlertStdAlertOKButton;
                param.cancelButton = kAlertStdAlertCancelButton;
            }
            else
            {
                param.defaultText = cfYesString;
                param.cancelText = NULL;
                param.otherText = cfNoString;
                param.helpButton = false;
                param.defaultButton = style & wxNO_DEFAULT ? kAlertStdAlertOtherButton : kAlertStdAlertOKButton;
                param.cancelButton = 0;
            }
        }
        // the MSW implementation even shows an OK button if it is not specified, we'll do the same
        else
        {
            if (style & wxCANCEL)
            {
                // that's a cancel missing
                param.defaultText = (CFStringRef) kAlertDefaultOKText;
                param.cancelText = (CFStringRef) kAlertDefaultCancelText;
                param.otherText = NULL;
                param.helpButton = false;
                param.defaultButton = kAlertStdAlertOKButton;
                param.cancelButton = 0;
            }
            else
            {
                param.defaultText = (CFStringRef) kAlertDefaultOKText;
                param.cancelText = NULL;
                param.otherText = NULL;
                param.helpButton = false;
                param.defaultButton = kAlertStdAlertOKButton;
                param.cancelButton = 0;
            }
        }

        param.position = kWindowDefaultPosition;
        if ( !skipDialog )
        {
            DialogRef alertRef;
            CreateStandardAlert( alertType, cfTitle, cfText, &param, &alertRef );
            RunStandardAlert( alertRef, NULL, &result );
        }
        else
        {
            return wxID_CANCEL;
        }

        if (style & wxOK)
        {
            switch ( result )
            {
            case 1:
                resultbutton = wxID_OK;
                break;

            case 2:
                // TODO: add Cancel button
                // if (style & wxCANCEL)
                //     resultbutton = wxID_CANCEL;
                break;

            case 3:
            default:
                break;
            }
        }
        else if (style & wxYES_NO)
        {
            switch ( result )
            {
            case 1:
                resultbutton = wxID_YES;
                break;

            case 2:
                if (!(style & wxCANCEL))
                    resultbutton = wxID_CANCEL;
                break;

            case 3:
                resultbutton = wxID_NO;
                break;

            default:
                break;
            }
        }
    }

    return resultbutton;
}
Exemple #14
0
int main(int argc, char *argv[]) {
	int dwErr;
	BOOL bDetect = FALSE;
	int i;
	lgLcdConnectContextEx conn;
	lgLcdOpenByTypeContext ctx;
	lgLcdBitmap160x43x1 bitmap;

	if (argc > 1 && (strcmp(argv[1], "/detect") == 0)) {
		warn("Detect mode!");
		bDetect = TRUE;
	} else if (!(argc > 1) || (strcmp(argv[1], "/mumble") != 0)) {
		CFUserNotificationDisplayAlert(0, 0, NULL,  NULL, NULL, CFSTR("Nothing to see here"), CFSTR("This program is run by Mumble, and should not be started separately."), CFSTR("OK"), NULL, NULL, NULL);
		return 0;
	}

	/*
	 * Clear and set up initial structures.
	 */
	memset(&conn, 0, sizeof(conn));
	memset(&ctx, 0, sizeof(ctx));
	memset(&bitmap, 0, sizeof(bitmap));

	conn.appFriendlyName = G15_WIDGET_NAME;
	conn.isAutostartable = FALSE;
	conn.isPersistent = FALSE;
	conn.dwAppletCapabilitiesSupported =LGLCD_APPLET_CAP_BASIC | LGLCD_APPLET_CAP_BW;
	conn.connection = LGLCD_INVALID_CONNECTION;

	/*
	 * Initialize and connect.
	 */
	dwErr = lgLcdInit();
	if (dwErr != ERROR_SUCCESS)
		die(G15_ERR_INIT, "Unable to initialize Logitech LCD library. (Error: %i)", dwErr);

	dwErr = lgLcdConnectEx(&conn);
	if (dwErr != ERROR_SUCCESS)
		die(G15_ERR_CONNECT, "Unable to connect to Logitech LCD manager. (Error: %i)", dwErr);

	ctx.connection = conn.connection;
	ctx.device = LGLCD_INVALID_DEVICE;
	ctx.deviceType =LGLCD_DEVICE_BW;

	dwErr = lgLcdOpenByType(&ctx);

	warn("That returned %d %d", dwErr, ERROR_SUCCESS);

	if (bDetect)
		return (dwErr != ERROR_SUCCESS);
	else if (dwErr != ERROR_SUCCESS)
		die(G15_ERR_OPEN, "Unable to open device. (Error: %i)", dwErr);

	/*
	 * Diplay buffer format.
	 */
	bitmap.hdr.Format = LGLCD_BMP_FORMAT_160x43x1;

	/*
	 * Main drawing loop.
	 */
	while (1) {
		int ret;
		int remain = 0;
		BYTE bPriority;

		ret = read(0, &bPriority, 1);
		if (ret == -1 || ret != 1)
			die(G15_ERR_READFILE, "Error while reading priority.");

		do {
			ret = read(0, bitmap.pixels + remain, G15_MAX_FBMEM - remain);
			if (ret < 1)
				die(G15_ERR_READFILE, "Error while reading framebuffer. %d (%s)", ret, strerror(errno));
			remain += ret;
		} while (remain < G15_MAX_FBMEM);

		dwErr = lgLcdUpdateBitmap(ctx.device, (const lgLcdBitmapHeader *) &bitmap, bPriority ? LGLCD_SYNC_UPDATE(LGLCD_PRIORITY_ALERT) : LGLCD_SYNC_UPDATE(LGLCD_PRIORITY_NORMAL));
		if (dwErr != ERROR_SUCCESS)
			warn("Unable to update bitmap for device #%i successfully. (Error: %i)", i, dwErr);
	}

	/*
	 * Close device connections.
	 */
	dwErr = lgLcdClose(ctx.device);
	if (dwErr != ERROR_SUCCESS)
		die(G15_ERR_CLOSE, "Unable to close LCD device. (Error: %i)", dwErr);

	/*
	 * Disconnect from LCD monitor.
	 */
	dwErr = lgLcdDisconnect(conn.connection);
	if (dwErr != ERROR_SUCCESS)
		die(G15_ERR_DISCONNECT, "Unable to disconnect from LCD manager. (Error: %i)", dwErr);

	/*
	 * Deinitialize G15 library.
	 */
	dwErr = lgLcdDeInit();
	if (dwErr != ERROR_SUCCESS)
		die(G15_ERR_DEINIT, "Unable to deinitialize LCD library. (Error: %i)", dwErr);

	warn("Terminated successfully.");

	return 0;
}