bool TlsSocket::Start() { #ifdef HAVE_LIBGNUTLS gnutls_certificate_credentials_t cred; m_retCode = gnutls_certificate_allocate_credentials(&cred); if (m_retCode != 0) { ReportError("Could not create TLS context"); return false; } m_context = cred; if (m_certFile && m_keyFile) { m_retCode = gnutls_certificate_set_x509_key_file((gnutls_certificate_credentials_t)m_context, m_certFile, m_keyFile, GNUTLS_X509_FMT_PEM); if (m_retCode != 0) { ReportError("Could not load certificate or key file"); Close(); return false; } } gnutls_session_t sess; m_retCode = gnutls_init(&sess, m_isClient ? GNUTLS_CLIENT : GNUTLS_SERVER); if (m_retCode != 0) { ReportError("Could not create TLS session"); Close(); return false; } m_session = sess; m_initialized = true; const char* priority = !m_cipher.Empty() ? m_cipher.Str() : "NORMAL"; m_retCode = gnutls_priority_set_direct((gnutls_session_t)m_session, priority, nullptr); if (m_retCode != 0) { ReportError("Could not select cipher for TLS"); Close(); return false; } if (m_host) { m_retCode = gnutls_server_name_set((gnutls_session_t)m_session, GNUTLS_NAME_DNS, m_host, m_host.Length()); if (m_retCode != 0) { ReportError("Could not set host name for TLS"); Close(); return false; } } m_retCode = gnutls_credentials_set((gnutls_session_t)m_session, GNUTLS_CRD_CERTIFICATE, (gnutls_certificate_credentials_t*)m_context); if (m_retCode != 0) { ReportError("Could not initialize TLS session"); Close(); return false; } gnutls_transport_set_ptr((gnutls_session_t)m_session, (gnutls_transport_ptr_t)(size_t)m_socket); m_retCode = gnutls_handshake((gnutls_session_t)m_session); if (m_retCode != 0) { ReportError("TLS handshake failed"); Close(); return false; } m_connected = true; return true; #endif /* HAVE_LIBGNUTLS */ #ifdef HAVE_OPENSSL m_context = SSL_CTX_new(SSLv23_method()); if (!m_context) { ReportError("Could not create TLS context"); return false; } if (m_certFile && m_keyFile) { if (SSL_CTX_use_certificate_chain_file((SSL_CTX*)m_context, m_certFile) != 1) { ReportError("Could not load certificate file"); Close(); return false; } if (SSL_CTX_use_PrivateKey_file((SSL_CTX*)m_context, m_keyFile, SSL_FILETYPE_PEM) != 1) { ReportError("Could not load key file"); Close(); return false; } } m_session = SSL_new((SSL_CTX*)m_context); if (!m_session) { ReportError("Could not create TLS session"); Close(); return false; } if (!m_cipher.Empty() && !SSL_set_cipher_list((SSL*)m_session, m_cipher)) { ReportError("Could not select cipher for TLS"); Close(); return false; } if (m_host && !SSL_set_tlsext_host_name((SSL*)m_session, m_host)) { ReportError("Could not set host name for TLS"); Close(); return false; } if (!SSL_set_fd((SSL*)m_session, m_socket)) { ReportError("Could not set the file descriptor for TLS"); Close(); return false; } int error_code = m_isClient ? SSL_connect((SSL*)m_session) : SSL_accept((SSL*)m_session); if (error_code < 1) { ReportError("TLS handshake failed"); Close(); return false; } m_connected = true; return true; #endif /* HAVE_OPENSSL */ }
HRESULT PrintItemName( IWiaItem *pWiaItem ) { // // Validate arguments // if (NULL == pWiaItem) { return E_INVALIDARG; } // // Get the IWiaPropertyStorage interface // IWiaPropertyStorage *pWiaPropertyStorage = NULL; HRESULT hr = pWiaItem->QueryInterface( IID_IWiaPropertyStorage, (void**)&pWiaPropertyStorage ); if (SUCCEEDED(hr)) { // // Declare PROPSPECs and PROPVARIANTs, and initialize them to zero. // PROPSPEC PropSpec[1] = {0}; PROPVARIANT PropVar[1] = {0}; // // How many properties are we querying for? // const ULONG c_nPropertyCount = sizeof(PropSpec)/sizeof(PropSpec[0]); // // Define which properties we want to read: // Device ID. This is what we'd use to create // the device. // PropSpec[0].ulKind = PRSPEC_PROPID; PropSpec[0].propid = WIA_IPA_FULL_ITEM_NAME; // // Ask for the property values // hr = pWiaPropertyStorage->ReadMultiple( c_nPropertyCount, PropSpec, PropVar ); if (SUCCEEDED(hr)) { // // IWiaPropertyStorage::ReadMultiple will return S_FALSE if some // properties could not be read, so we have to check the return // types for each requested item. // // // Check the return type for the device ID // if (VT_BSTR == PropVar[0].vt) { // // Do something with the device ID // _tprintf( TEXT("Item Name: %ws\n"), PropVar[0].bstrVal ); } // // Free the returned PROPVARIANTs // FreePropVariantArray( c_nPropertyCount, PropVar ); } else { ReportError( TEXT("Error calling IWiaPropertyStorage::ReadMultiple"), hr ); } // // Release the IWiaPropertyStorage interface // pWiaPropertyStorage->Release(); pWiaPropertyStorage = NULL; } // // Return the result of reading the properties // return hr; }
HRESULT EnumerateItems( IWiaItem *pWiaItem ) { // // Validate arguments // if (NULL == pWiaItem) { return E_INVALIDARG; } // // Get the item type for this item // LONG lItemType = 0; HRESULT hr = pWiaItem->GetItemType( &lItemType ); // // Do something with this item. Print the item name. // PrintItemName( pWiaItem ); // // If this is an image, transfer it // if (lItemType & WiaItemTypeImage) { hr = TransferWiaItem( pWiaItem ); } // // If it is a folder, or it has attachments, enumerate its children // if (lItemType & WiaItemTypeFolder || lItemType & WiaItemTypeHasAttachments) { // // Get the child item enumerator for this item // IEnumWiaItem *pEnumWiaItem = NULL; hr = pWiaItem->EnumChildItems( &pEnumWiaItem ); if (SUCCEEDED(hr)) { // // We will loop until we get an error or pEnumWiaItem->Next returns // S_FALSE to signal the end of the list. // while (S_OK == hr) { // // Get the next child item // IWiaItem *pChildWiaItem = NULL; hr = pEnumWiaItem->Next( 1, &pChildWiaItem, NULL ); // // pEnumWiaItem->Next will return S_FALSE when the list is // exhausted, so check for S_OK before using the returned // value. // if (S_OK == hr) { // // Recurse into this item // hr = EnumerateItems( pChildWiaItem ); // // Release this item // pChildWiaItem->Release(); pChildWiaItem = NULL; } else if (FAILED(hr)) { // // Report that an error occurred during enumeration // ReportError( TEXT("Error calling pEnumWiaItem->Next"), hr ); } } // // If the result of the enumeration is S_FALSE, since this // is normal, we will change it to S_OK // if (S_FALSE == hr) { hr = S_OK; } // // Release the enumerator // pEnumWiaItem->Release(); pEnumWiaItem = NULL; } } return hr; }
BOOL SetupWizard::OnInitDialog () { BOOL ret = CPropertySheet::OnInitDialog(); try { SetIcon (AfxGetApp()->LoadIcon(IDR_MAINFRAME), TRUE); CStringW title; if (theApp.isMiKTeXDirect) { title.Format (T_(_T("MiKTeX %s Setup (%d-bit)")), static_cast<LPCTSTR>(UW_(MIKTEX_FULL_VERSION_STR)), static_cast<int>(sizeof(void*)) * 8); } else if (theApp.pSetupService->GetOptions().IsPrefabricated) { PathName configFile (theApp.GetLocalPackageRepository()); configFile += "pr.ini"; SmartPointer<Cfg> pConfig (Cfg::Create()); pConfig->Read (configFile); CString prefix; CString version (MIKTEXTEXT(MIKTEX_SERIES_STR)); version += MIKTEXTEXT('.'); version += UT_(pConfig->GetValue("repository", "version").c_str()); switch (theApp.GetPackageLevel().Get()) { case PackageLevel::Essential: prefix = T_("Essential "); break; case PackageLevel::Basic: prefix = T_("Basic "); break; case PackageLevel::Complete: prefix = ""; break; default: MIKTEX_ASSERT (false); __assume (false); break; } title.Format (T_(_T("%sMiKTeX %s Installer (%d-bit)")), static_cast<LPCTSTR>(prefix), static_cast<LPCTSTR>(version), static_cast<int>(sizeof(void*)) * 8); } else { title.Format (T_(_T("MiKTeX %s Net Installer (%d-bit)")), static_cast<LPCTSTR>(UW_(MIKTEX_VERSION_STR)), static_cast<int>(sizeof(void*)) * 8); } SetTitle (title); SetActivePage (&m_License); } catch (const MiKTeXException & e) { ReportError (e); } catch (const exception & e) { ReportError (e); } return (ret); }
NS_IMETHODIMP ImportEudoraMailImpl::ImportMailbox(nsIImportMailboxDescriptor *pSource, nsIFile *pDestination, PRUnichar **pErrorLog, PRUnichar **pSuccessLog, bool *fatalError) { NS_PRECONDITION(pSource != nsnull, "null ptr"); NS_PRECONDITION(pDestination != nsnull, "null ptr"); NS_PRECONDITION(fatalError != nsnull, "null ptr"); nsString success; nsString error; if (!pSource || !pDestination || !fatalError) { IMPORT_LOG0("*** Bad param passed to eudora mailbox import\n"); nsEudoraStringBundle::GetStringByID(EUDORAIMPORT_MAILBOX_BADPARAM, error); if (fatalError) *fatalError = true; SetLogs(success, error, pErrorLog, pSuccessLog); return NS_ERROR_NULL_POINTER; } bool abort = false; nsString name; PRUnichar * pName; if (NS_SUCCEEDED(pSource->GetDisplayName(&pName))) { name = pName; NS_Free(pName); } PRUint32 mailSize = 0; pSource->GetSize(&mailSize); if (mailSize == 0) { IMPORT_LOG0("Mailbox size is 0, skipping mailbox.\n"); ReportSuccess(name, 0, &success); SetLogs(success, error, pErrorLog, pSuccessLog); return NS_OK; } nsCOMPtr <nsILocalFile> inFile; if (NS_FAILED(pSource->GetFile(getter_AddRefs(inFile)))) { ReportError(EUDORAIMPORT_MAILBOX_BADSOURCEFILE, name, &error); SetLogs(success, error, pErrorLog, pSuccessLog); return NS_ERROR_FAILURE; } #ifdef IMPORT_DEBUG nsCString pPath; inFile->GetNativePath(pPath); IMPORT_LOG1("Import mailbox: %s\n", pPath.get()); #endif PRInt32 msgCount = 0; nsresult rv = NS_OK; m_bytes = 0; rv = m_eudora.ImportMailbox(&m_bytes, &abort, name.get(), inFile, pDestination, &msgCount); if (NS_SUCCEEDED(rv)) ReportSuccess(name, msgCount, &success); else ReportError(EUDORAIMPORT_MAILBOX_CONVERTERROR, name, &error); SetLogs(success, error, pErrorLog, pSuccessLog); IMPORT_LOG0("*** Returning from eudora mailbox import\n"); return rv; }
long *GetSurfList( long surfnum, long numsurfs, long *numlistsurfs ) { /*** Get a sequence of surface numbers. ***/ long i, numerror=0; long *lsurflist = NULL; int *surflist, nlistsurfs; char instring[80], surfstring[100]=""; NumSeq surfseq; /**********************************************************************/ /*** If we only have one surface, no need to ask. ***/ if ( numsurfs <= 1 ) { nlistsurfs = 1; lsurflist = (long *) calloc( (size_t) nlistsurfs, sizeof( long )); lsurflist[0] = 0; *numlistsurfs = nlistsurfs; return( lsurflist ); } /*** Now form the list the regular way, using Ted's routines. ***/ surfseq = NumSeqCreate(); if ( strlen( surfstring ) < 1 ) sprintf(surfstring,"%d", surfnum+1); printf(" Enter the sequence of surfaces you want (e.g., 1,2,4-5,7)\n" " ranging from (from 1-%d)\n" " [def=%s] ? ", numsurfs, surfstring ); fgets(instring, 70, stdin ); if ( strlen( instring ) > 0 ) strcpy( surfstring,instring ); while (NumSeqParse(surfseq, surfstring) && numerror < 10) { printf("*** ? Illegal sequence\n"); printf(" Enter the desired range again [def= %s] > ", surfstring); scanf("%s",instring); if (Trulen((const char*) instring) >= 0) strcpy( surfstring,instring ); numerror++; } if (numerror >= 10) { ReportError("GetSurflist", "Blow out trying to get legal string", 0, ""); return ( NULL ); } /*** Now convert the string into an array of surface numbers. ***/ NumSeqArray( surfseq, &surflist, &nlistsurfs ); if ( surflist == NULL ) { ReportError("GeturfList", "error converting sequence to list", 0, ""); return( NULL ); } /*** Now scan the list and make sure it makes sense, and shift values to start at 0. ***/ lsurflist = (long *) calloc( (size_t) nlistsurfs, sizeof( long )); for (i=0; i<nlistsurfs; i++ ) { if ( surflist[i] < 0 ) surflist[i] = 1; if ( surflist[i] > numsurfs ) surflist[i] = numsurfs; lsurflist[i] = surflist[i] - 1; } *numlistsurfs = nlistsurfs; free( surflist ); NumSeqDestroy( surfseq ); return( lsurflist ); }
void dng_info::PostParse (dng_host &host) { uint32 index; fExif->PostParse (host, *fShared.Get ()); fShared->PostParse (host, *fExif.Get ()); for (index = 0; index < fIFDCount; index++) { fIFD [index]->PostParse (); } for (index = 0; index < fChainedIFDCount; index++) { fChainedIFD [index]->PostParse (); } if (fShared->fDNGVersion != 0) { // Find main IFD. fMainIndex = -1; for (index = 0; index < fIFDCount; index++) { if (fIFD [index]->fUsesNewSubFileType && fIFD [index]->fNewSubFileType == sfMainImage) { if (fMainIndex == -1) { fMainIndex = index; } #if qDNGValidate else { ReportError ("Multiple IFDs marked as main image"); } #endif } else if (fIFD [index]->fNewSubFileType == sfPreviewImage || fIFD [index]->fNewSubFileType == sfAltPreviewImage) { // Fill in default color space for DNG previews if not included. if (fIFD [index]->fPreviewInfo.fColorSpace == previewColorSpace_MaxEnum) { if (fIFD [index]->fSamplesPerPixel == 1) { fIFD [index]->fPreviewInfo.fColorSpace = previewColorSpace_GrayGamma22; } else { fIFD [index]->fPreviewInfo.fColorSpace = previewColorSpace_sRGB; } } } } // Deal with lossless JPEG bug in early DNG versions. if (fShared->fDNGVersion < dngVersion_1_1_0_0) { if (fMainIndex != -1) { fIFD [fMainIndex]->fLosslessJPEGBug16 = true; } } // Find mask index. for (index = 0; index < fIFDCount; index++) { if (fIFD [index]->fNewSubFileType == sfTransparencyMask) { if (fMaskIndex == -1) { fMaskIndex = index; } #if qDNGValidate else { ReportError ("Multiple IFDs marked as transparency mask image"); } #endif } } // Warn about Chained IFDs. #if qDNGValidate if (fChainedIFDCount > 0) { ReportWarning ("This file has Chained IFDs, which will be ignored by DNG readers"); } #endif } }
void HandleSocketMessage(gpointer data, gpointer user_data) { int instance, type; char mMsgBuf[1024]; char *msg = (char *)data; int i = sscanf(msg, "%d,%d,%s", &instance, &type, mMsgBuf); NS_ASSERTION(i >= 2, "Wrong message format\n"); // In case that the last message string argument contains spaces, sscanf // returns before the first space. Below line returns the complete message // string. char* mMsgString = (char*)strchr(msg, ','); mMsgString++; mMsgString = (char*)strchr(mMsgString, ','); mMsgString++; GtkBrowser *pBrowser; switch (type) { case JEVENT_INIT: break; case JEVENT_CREATEWINDOW: { // only create new browser window when the instance does not exist if (instance < gBrowserArray.GetSize() && gBrowserArray[instance] != NULL) break; if (i != 3) break; int javaXId = atoi(mMsgString); NS_ASSERTION(javaXId, "Invalid X window handle\n"); pBrowser = g_new0(GtkBrowser, 1); pBrowser->topLevelWindow = gtk_plug_new(javaXId); pBrowser->mozEmbed = gtk_moz_embed_new(); if (pBrowser->mozEmbed) { gtk_container_add(GTK_CONTAINER(pBrowser->topLevelWindow), pBrowser->mozEmbed); install_mozembed_cb(pBrowser); gtk_moz_embed_set_chrome_mask(GTK_MOZ_EMBED(pBrowser->mozEmbed), GTK_MOZ_EMBED_FLAG_DEFAULTCHROME); gtk_widget_realize(pBrowser->topLevelWindow); gtk_widget_show_all(pBrowser->topLevelWindow); pBrowser->id = instance; gBrowserArray.SetAtGrow(instance, pBrowser); SendSocketMessage(instance, CEVENT_INIT_WINDOW_SUCC); } gtk_signal_connect(GTK_OBJECT(pBrowser->topLevelWindow), "set-focus", GTK_SIGNAL_FUNC(set_focus_cb), pBrowser); } break; case JEVENT_DESTROYWINDOW: pBrowser = (GtkBrowser *)gBrowserArray[instance]; if(pBrowser != NULL){ gtk_widget_destroy(pBrowser->mozEmbed); gtk_object_destroy((GtkObject *)pBrowser->topLevelWindow); gBrowserArray.SetAt(instance, NULL); } SendSocketMessage(instance, CEVENT_DISTORYWINDOW_SUCC); break; case JEVENT_SHUTDOWN: gtk_main_quit(); break; case JEVENT_SET_BOUNDS: { NS_ASSERTION(i == 3, "Wrong message format\n"); int x, y, w, h; i = sscanf(mMsgString, "%d,%d,%d,%d", &x, &y, &w, &h); if (i == 4) { pBrowser = (GtkBrowser *)gBrowserArray[instance]; NS_ASSERTION(pBrowser, "Can't get native browser instance\n"); gtk_widget_set_usize(pBrowser->topLevelWindow, w, h); } } break; case JEVENT_NAVIGATE: NS_ASSERTION(i == 3, "Wrong message format\n"); pBrowser = (GtkBrowser *)gBrowserArray[instance]; NS_ASSERTION(pBrowser, "Can't get native browser instance\n"); gtk_moz_embed_load_url(GTK_MOZ_EMBED(pBrowser->mozEmbed), mMsgString); break; case JEVENT_NAVIGATE_POST: NS_ASSERTION(i == 3, "Wrong message format\n"); strncpy(gCachedURL, mMsgString, sizeof(gCachedURL)); break; case JEVENT_NAVIGATE_POSTDATA: NS_ASSERTION(i == 3, "Wrong message format\n"); pBrowser = (GtkBrowser *)gBrowserArray[instance]; OpenURL(pBrowser, gCachedURL, mMsgString, POST_HEADER); break; case JEVENT_GOBACK: pBrowser = (GtkBrowser *)gBrowserArray[instance]; NS_ASSERTION(pBrowser, "Can't get native browser instance\n"); gtk_moz_embed_go_back(GTK_MOZ_EMBED(pBrowser->mozEmbed)); break; case JEVENT_GOFORWARD: pBrowser = (GtkBrowser *)gBrowserArray[instance]; NS_ASSERTION(pBrowser, "Can't get native browser instance\n"); gtk_moz_embed_go_forward(GTK_MOZ_EMBED(pBrowser->mozEmbed)); break; case JEVENT_REFRESH: pBrowser = (GtkBrowser *)gBrowserArray[instance]; NS_ASSERTION(pBrowser, "Can't get native browser instance\n"); gtk_moz_embed_reload(GTK_MOZ_EMBED(pBrowser->mozEmbed), GTK_MOZ_EMBED_FLAG_RELOADNORMAL); break; case JEVENT_STOP: pBrowser = (GtkBrowser *)gBrowserArray[instance]; NS_ASSERTION(pBrowser, "Can't get native browser instance\n"); gtk_moz_embed_stop_load(GTK_MOZ_EMBED(pBrowser->mozEmbed)); break; case JEVENT_GETURL: { pBrowser = (GtkBrowser *)gBrowserArray[instance]; NS_ASSERTION(pBrowser, "Can't get native browser instance\n"); nsCOMPtr<nsIWebBrowser> webBrowser; gtk_moz_embed_get_nsIWebBrowser(GTK_MOZ_EMBED(pBrowser->mozEmbed), getter_AddRefs(webBrowser)); nsCOMPtr<nsIWebNavigation> webNavigation(do_QueryInterface(webBrowser)); nsCOMPtr<nsIURI> currentURI; webNavigation->GetCurrentURI(getter_AddRefs(currentURI)); if (currentURI == NULL) SendSocketMessage(instance, CEVENT_RETURN_URL, ""); else { nsEmbedCString uriString; currentURI->GetAsciiSpec(uriString); SendSocketMessage(instance, CEVENT_RETURN_URL, uriString.get()); } } break; case JEVENT_FOCUSGAINED: case JEVENT_FOCUSLOST: { pBrowser = (GtkBrowser *)gBrowserArray[instance]; NS_ASSERTION(pBrowser, "Can't get native browser instance\n"); if (!pBrowser->topLevelWindow) { ReportError("Top level Window is Null!\n"); break; } GtkWidget *widget = GTK_WIDGET (pBrowser->topLevelWindow); GdkEvent event; GtkWindowClass *parent_class = (GtkWindowClass*) gtk_type_class (GTK_TYPE_WINDOW); if (!widget) { ReportError("Failed to get browser's toplevel window !\n"); break; } if (!parent_class) { ReportError("Failed to get gtk window class !\n"); break; } event.focus_change.type = GDK_FOCUS_CHANGE; event.focus_change.window = widget->window; event.focus_change.send_event = TRUE; if (type == JEVENT_FOCUSGAINED) { event.focus_change.in = TRUE; GTK_WIDGET_CLASS (parent_class)->focus_in_event (widget, (GdkEventFocus *)&event); } else { event.focus_change.in = FALSE; GTK_WIDGET_CLASS (parent_class)->focus_out_event (widget, (GdkEventFocus *)&event); } } break; case JEVENT_GETCONTENT: { pBrowser = (GtkBrowser *)gBrowserArray[instance]; NS_ASSERTION(pBrowser, "Can't get native browser instance\n"); nsCOMPtr<nsIWebBrowser> webBrowser; gtk_moz_embed_get_nsIWebBrowser(GTK_MOZ_EMBED(pBrowser->mozEmbed), getter_AddRefs(webBrowser)); nsCOMPtr<nsIWebNavigation> webNavigation(do_QueryInterface(webBrowser)); char *retStr = GetContent(webNavigation); if (retStr == NULL) SendSocketMessage(instance, CEVENT_GETCONTENT, ""); else SendSocketMessage(instance, CEVENT_GETCONTENT, retStr); } break; case JEVENT_SETCONTENT: { NS_ASSERTION(i == 3, "Wrong message format\n"); pBrowser = (GtkBrowser *)gBrowserArray[instance]; NS_ASSERTION(pBrowser, "Can't get native browser instance\n"); nsCOMPtr<nsIWebBrowser> webBrowser; gtk_moz_embed_get_nsIWebBrowser(GTK_MOZ_EMBED(pBrowser->mozEmbed), getter_AddRefs(webBrowser)); nsCOMPtr<nsIWebNavigation> webNavigation(do_QueryInterface(webBrowser)); SetContent(webNavigation, mMsgString); } break; case JEVENT_EXECUTESCRIPT: { NS_ASSERTION(i == 3, "Wrong message format\n"); pBrowser = (GtkBrowser *)gBrowserArray[instance]; NS_ASSERTION(pBrowser, "Can't get native browser instance\n"); nsCOMPtr<nsIWebBrowser> webBrowser; gtk_moz_embed_get_nsIWebBrowser(GTK_MOZ_EMBED(pBrowser->mozEmbed), getter_AddRefs(webBrowser)); nsCOMPtr<nsIWebNavigation> webNavigation(do_QueryInterface(webBrowser)); char *retStr = ExecuteScript(webNavigation, mMsgString); if (retStr == NULL) SendSocketMessage(instance, CEVENT_EXECUTESCRIPT, ""); else SendSocketMessage(instance, CEVENT_EXECUTESCRIPT, retStr); } break; } }
int mozembed_main(int argc, char **argv) { if (argc > 1) { if (strstr(argv[1], "-port=")) { int port = atoi(&(argv[1][6])); gMessenger.SetPort(port); gMessenger.CreateServerSocket(); } else if (strcmp(argv[1], "-test") == 0) { gTestMode = 1; } } if (!gTestMode && gMessenger.IsFailed()) { ReportError("Failed to create server socket!"); exit(1); } gtk_set_locale(); gtk_init(&argc, &argv); // force the startup code to be executed because we need to start // the profile in a different way gtk_moz_embed_push_startup(); if (NS_FAILED(InitializeProfile())) { ReportError("Failed to initialize profile!"); exit(1); } gMsgLock = PR_NewLock(); if (!gTestMode) { PRThread *socketListenThread = PR_CreateThread(PR_USER_THREAD, PortListening, (void*)SocketMsgHandler, PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_UNJOINABLE_THREAD, 0); if (!socketListenThread) { ReportError("Failed to create socket listening thread!"); exit(1); } // add event source to process socket messages #ifdef MOZ_WIDGET_GTK g_source_add (GDK_PRIORITY_EVENTS, TRUE, &event_funcs, NULL, NULL, NULL); #endif #ifdef MOZ_WIDGET_GTK2 GSource *newsource = g_source_new(&event_funcs, sizeof(GSource)); g_source_attach(newsource, NULL); #endif } else { GtkBrowser *browser = new_gtk_browser(GTK_MOZ_EMBED_FLAG_DEFAULTCHROME); // set our minimum size gtk_widget_set_usize(browser->mozEmbed, 400, 400); set_browser_visibility(browser, TRUE); } // get the singleton object and hook up to its new window callback // so we can create orphaned windows. GtkMozEmbedSingle *single; single = gtk_moz_embed_single_get(); if (!single) { ReportError("Failed to get singleton embed object!"); exit(1); } gtk_signal_connect(GTK_OBJECT(single), "new_window_orphan", GTK_SIGNAL_FUNC(new_window_orphan_cb), NULL); gtk_main(); gtk_moz_embed_pop_startup(); PR_DestroyLock(gMsgLock); return 0; }
//---------------------------------------------------------------------------- bool FxCompiler::UpdateShader (Shader* shader, const Program& program, InputArray& inputs, OutputArray& outputs, ConstantArray& constants, SamplerArray& samplers) { int numInputs = (int)inputs.size(); if (numInputs != shader->GetNumInputs()) { ReportError("Mismatch in number of inputs.\n"); return false; } int numOutputs = (int)outputs.size(); if (numOutputs != shader->GetNumOutputs()) { ReportError("Mismatch in number of outputs.\n"); return false; } int numConstants = (int)constants.size(); if (numConstants != shader->GetNumConstants()) { ReportError("Mismatch in number of constants.\n"); return false; } int numSamplers = (int)samplers.size(); if (numSamplers != shader->GetNumSamplers()) { ReportError("Mismatch in number of samplers.\n"); return false; } std::string message; int i; for (i = 0; i < numInputs; ++i) { Input& input = inputs[i]; if (input.Name != shader->GetInputName(i)) { message = "Mismatch in input names '" + input.Name + "' and '" + shader->GetInputName(i); ReportError(message); return false; } if (input.Type != shader->GetInputType(i)) { message = "Mismatch in input types '" + msVTName[input.Type] + "' and '" + msVTName[shader->GetInputType(i)]; ReportError(message); return false; } if (input.Semantic != shader->GetInputSemantic(i)) { message = "Mismatch in input semantics '" + msVSName[input.Semantic] + "' and '" + msVSName[shader->GetInputSemantic(i)]; ReportError(message); return false; } } for (i = 0; i < numOutputs; ++i) { Output& output = outputs[i]; if (output.Name != shader->GetOutputName(i)) { message = "Mismatch in output names '" + output.Name + "' and '" + shader->GetOutputName(i); ReportError(message); return false; } if (output.Type != shader->GetOutputType(i)) { message = "Mismatch in output types '" + msVTName[output.Type] + "' and '" + msVTName[shader->GetOutputType(i)]; ReportError(message); return false; } if (output.Semantic != shader->GetOutputSemantic(i)) { message = "Mismatch in output semantics '" + msVSName[output.Semantic] + "' and '" + msVSName[shader->GetOutputSemantic(i)]; ReportError(message); return false; } } for (i = 0; i < numConstants; ++i) { Constant& constant = constants[i]; if (constant.Name != shader->GetConstantName(i)) { message = "Mismatch in constant names '" + constant.Name + "' and '" + shader->GetConstantName(i); ReportError(message); return false; } if (constant.NumRegistersUsed != shader->GetNumRegistersUsed(i)) { char number0[8], number1[8]; sprintf(number0, "%d", constant.NumRegistersUsed); sprintf(number1, "%d", shader->GetNumRegistersUsed(i)); message = "Mismatch in constant registers used '" + std::string(number0) + "' and '" + std::string(number1); ReportError(message); return false; } shader->SetBaseRegister(mActiveProfile, i, constant.BaseRegister); } for (i = 0; i < numSamplers; ++i) { Sampler& sampler = samplers[i]; if (sampler.Name != shader->GetSamplerName(i)) { message = "Mismatch in sampler names '" + sampler.Name + "' and '" + shader->GetSamplerName(i); ReportError(message); return false; } if (sampler.Type != shader->GetSamplerType(i)) { message = "Mismatch in sampler types '" + msSTName[sampler.Type] + "' and '" + msSTName[shader->GetSamplerType(i)]; ReportError(message); return false; } shader->SetTextureUnit(mActiveProfile, i, sampler.Unit); } shader->SetProgram(mActiveProfile, program.Text); return true; }
BOOL TPrinter::Print(PTWindowsObject ParentWin, PTPrintout Printout) { typedef BOOL (FAR PASCAL *PTAbortProc)( HDC Prn, short Code ); BOOL Banding; PTAbortProc AbortProcInst; WORD PageNumber; BOOL result = FALSE; // Assume error occurred Error = 0; if ( Printout == NULL ) return result; if ( ParentWin == NULL ) return result; if ( Status != PS_OK ) { Error = SP_ERROR; ReportError(Printout); return result; } PrnDC = GetDC(); if ( PrnDC == 0 ) return result; PTWindowsObject Dlg = GetApplicationObject()->MakeWindow( new TPrinterAbortDlg(ParentWin, "AbortDialog", Printout->Title, Device, Port) ); if ( Dlg == NULL ) { DeleteDC(PrnDC); return result; } EnableWindow(ParentWin->HWindow, FALSE); AbortProcInst = (PTAbortProc) MakeProcInstance( (FARPROC) AbortProc, GetApplicationObject()->hInstance); Escape(PrnDC, SETABORTPROC, 0, LPSTR(AbortProcInst), NULL); // Get the page size PageSize.x = GetDeviceCaps(PrnDC, HORZRES); PageSize.y = GetDeviceCaps(PrnDC, VERTRES); // Only band if the user requests banding and the printer // supports banding Banding = ( Printout->Banding ) && (GetDeviceCaps(PrnDC, RASTERCAPS) & RC_BANDING); if ( !Banding ) { // Set the banding rectangle to full page BandRect.left = 0; BandRect.top = 0; BandRect.right = PageSize.x; BandRect.bottom = PageSize.y; } else { // Only use BANDINFO if supported (note: using Flags as a temporary) Flags = BANDINFO; // Escape(QUERYESCSUPPORT) returns nonzero for implemented // escape function, and zero otherwise. UseBandInfo = Escape(PrnDC, QUERYESCSUPPORT, sizeof(Flags), (LPSTR) &Flags, NULL); } Flags = PF_BOTH; Error = Escape(PrnDC, STARTDOC, strlen(Printout->Title), Printout->Title, NULL); PageNumber = 1; if ( Error > 0 ) { do { if ( Banding ) { FirstBand = TRUE; Error = Escape(PrnDC, NEXTBAND, 0, NULL, (LPSTR) &BandRect); } do { // Call the abort proc between bands or pages (*AbortProcInst)(PrnDC, 0); if ( Banding ) { CalcBandingFlags(); if ( (Printout->ForceAllBands) && ( ( Flags & PF_BOTH ) == PF_TEXT ) ) SetPixel(PrnDC, 0, 0, 0); } if ( Error > 0 ) { Printout->PrintPage(PrnDC, PageNumber, PageSize, &BandRect, Flags); if ( Banding ) Error = Escape(PrnDC, NEXTBAND, 0, NULL, (LPSTR) &BandRect); } } while ( (Error > 0) && (Banding) && (!IsRectEmpty(&BandRect)) ); // NewFrame should only be called if not banding if ( (Error > 0) && (!Banding) ) Error = Escape(PrnDC, NEWFRAME, 0, NULL, NULL); PageNumber++; } while ( (Error > 0) && (Printout->IsNextPage()) ); // Tell GDI the document is finished if ( Error > 0 ) { if ( Banding && UserAbort ) Escape(PrnDC, ABORTDOC, 0, NULL, NULL); else Escape(PrnDC, ENDDOC, 0, NULL, NULL); } } // Free allocated resources FreeProcInstance((FARPROC) AbortProcInst); EnableWindow(ParentWin->HWindow, TRUE); delete Dlg; DeleteDC(PrnDC); if ( Error & SP_NOTREPORTED ) ReportError(Printout); result = (Error > 0) && (!UserAbort); UserAbort = FALSE; return result; }
//---------------------------------------------------------------------------- bool FxCompiler::Process (const Program& program, InputArray& inputs, OutputArray& outputs, ConstantArray& constants, SamplerArray& samplers) { // Variable lines are one of the following: // var TYPE NAME : $vin.SEMANTIC : inputType : index : 1 // var TYPE NAME : $vout.SEMANTIC : outputType : index : 1 // var TYPE NAME : : c[REGISTER] : index : 1 // var TYPE NAME : : c[REGISTER], NUMREG : index : 1 // var TYPE NAME : : texunit UNITNUMBER : -1 : 1 // The last field is "used", a value of "0" or "1". However, the parser // stored in 'program' only those variables with a used value "1". The // all-capitals identifiers are needed by the Wild Magic FX system. TokenArrays::const_iterator iter = program.Variables.begin(); TokenArrays::const_iterator end = program.Variables.end(); for (/**/; iter != end; ++iter) { const TokenArray& tokens = *iter; // The token array has 10 or 11 tokens. if (tokens.size() < 10 || tokens.size() > 11) { ReportError("Invalid number of tokens", &tokens); return false; } // Get the variable type. Shader::VariableType vartype = Shader::VT_NONE; Shader::SamplerType samtype = Shader::ST_NONE; std::string::size_type begin = tokens[1].find("sampler", 0); if (begin != std::string::npos) { SamplerTypeMap::iterator iter = mSamplerTypes.find(tokens[1]); if (iter == mSamplerTypes.end()) { ReportError("Invalid sampler type", &tokens); return false; } samtype = iter->second; } else { VariableTypeMap::iterator iter = mVariableTypes.find(tokens[1]); if (iter == mVariableTypes.end()) { ReportError("Invalid variable type", &tokens); return false; } vartype = iter->second; } // Get the variable name. std::string name = tokens[2]; // Test whether the variable is a singleton or was declared as an // array. If it is an array, we need to determine how many registers // it uses. This requires processing variable lines with the same // variable index. bool varArray; begin = name.find("[", 0); if (begin != std::string::npos) { varArray = true; name = name.substr(0, begin); // strip off "[register]" } else { varArray = false; } // Get the separator before the classifier. if (tokens[3] != ":") { ReportError("Expecting separator character at index 3", &tokens); return false; } // Get the classifier. begin = tokens[4].find("$vin.", 0); if (begin != std::string::npos) { // The variable is a shader input. if (!GetInput(tokens, name, vartype, inputs)) { return false; } continue; } begin = tokens[4].find("$vout.", 0); if (begin != std::string::npos) { // The variable is a shader output. if (!GetOutput(tokens, name, vartype, outputs)) { return false; } continue; } if (tokens[4] == ":") { begin = tokens[1].find("sampler", 0); if (begin != std::string::npos) { // The variable is a shader sampler. if (!GetSampler(tokens, name, samtype, samplers)) { return false; } } else { // The variable is a shader constant. if (varArray) { if (constants.size() > 0 && name == constants.back().Name) { // This is another occurrence of the array variable. // Just increment the register count. ++constants.back().NumRegistersUsed; } else { // Create the constant with the first occurrence of // the array variable. if (!GetConstant(tokens, name, vartype, constants)) { return false; } } } else { if (!GetConstant(tokens, name, vartype, constants)) { return false; } } } continue; } ReportError("Failed to find classifier", &tokens); return false; } return true; }
//---------------------------------------------------------------------------- bool FxCompiler::Parse (const std::string& fileName, const std::string& profileName, Program& program) { std::ifstream inFile(fileName.c_str()); if (!inFile) { // If the file does not exist, the assumption is that the profile does // not support the shader (in which case, the Cg compiler failed). Messages.push_back("Profile " + profileName + " not supported.\n"); return false; } program.Text = ""; while (!inFile.eof()) { std::string line; getline(inFile, line); if (line.empty()) { continue; } // Any uncommented lines are part of the program text. if (line[0] != '/' && line[0] != '#') { program.Text += line + "\n"; continue; } std::vector<std::string> tokens; std::string::size_type begin; // Get a variable line from the Cg output file. begin = line.find("var", 0); if (begin != std::string::npos) { GetTokens(line, begin, tokens); if (tokens.size() >= 2 && tokens[0] == "var") { std::string used = tokens.back(); if (used == "0" || used == "1") { if (used == "1") { program.Variables.push_back(tokens); } continue; } } inFile.close(); ReportError("Invalid variable line", &tokens); return false; } // Get the profile name. begin = line.find("profile", 0); if (begin != std::string::npos) { GetTokens(line, begin, tokens); if (tokens.size() >= 2 && tokens[0] == "profile") { // When the user has already compiled the programs, it is // because a profile is a special one. The "!!ARBfp1.0" // string and the last token of "#profile specialProfile" // most likely do not match, so do not compare them. if (mAlreadyCompiled || tokens[1] == profileName) { continue; } } inFile.close(); ReportError("Invalid profile line", &tokens); return false; } // Get the program name. begin = line.find("program", 0); if (begin != std::string::npos) { GetTokens(line, begin, tokens); if (tokens.size() >= 2 && tokens[0] == "program") { program.Name = tokens[1]; continue; } inFile.close(); ReportError("Invalid program line", &tokens); return false; } } inFile.close(); return true; }
//========================================================================= void Epetra_MapColoring::Print(std::ostream& os) const { int MyPID = Map().Comm().MyPID(); int NumProc = Map().Comm().NumProc(); if (MyPID==0) os << std::endl << " *****************************************" << std::endl << " Coloring information arranged map element" << std::endl << " *****************************************" << std::endl << std::endl; for (int iproc=0; iproc < NumProc; iproc++) { if (MyPID==iproc) { int NumMyElements1 =Map(). NumMyElements(); if (MyPID==0) { os.width(8); os << " MyPID"; os << " "; os.width(12); os << "GID "; os.width(20); os << "Color "; os << std::endl; } for (int i=0; i < NumMyElements1; i++) { os.width(10); os << MyPID; os << " "; os.width(10); if(Map().GlobalIndicesInt()) { #ifndef EPETRA_NO_32BIT_GLOBAL_INDICES int * MyGlobalElements1 = Map().MyGlobalElements(); os << MyGlobalElements1[i] << " "; #else throw ReportError("Epetra_MapColoring::Print: ERROR, GlobalIndicesInt but no API for it.",-1); #endif } else if(Map().GlobalIndicesLongLong()) { #ifndef EPETRA_NO_64BIT_GLOBAL_INDICES long long * MyGlobalElements1 = Map().MyGlobalElements64(); os << MyGlobalElements1[i] << " "; #else throw ReportError("Epetra_MapColoring::Print: ERROR, GlobalIndicesLongLong but no API for it.",-1); #endif } else throw ReportError("Epetra_MapColoring::Print: ERROR, Don't know map global index type.",-1); os.width(20); os << ElementColors_[i]; os << std::endl; } os << std::flush; } // Do a few global ops to give I/O a chance to complete Map().Comm().Barrier(); Map().Comm().Barrier(); Map().Comm().Barrier(); } if (MyPID==0) os << std::endl << " **************************************" << std::endl << " Coloring information arranged by color" << std::endl << " **************************************" << std::endl << std::endl; {for (int iproc=0; iproc < NumProc; iproc++) { if (MyPID==iproc) { if (NumColors()==0) os << " No colored elements on processor " << MyPID << std::endl; else { os << "Number of colors in map = " << NumColors() << std::endl << "Default color = " << DefaultColor() << std::endl << std::endl; if (MyPID==0) { os.width(8); os << " MyPID"; os << " "; os.width(12); os << "LID "; os.width(20); os << "Color "; os << std::endl; } int * ColorValues = ListOfColors(); for (int ii=0; ii<NumColors(); ii++) { int CV = ColorValues[ii]; int ColorCount = NumElementsWithColor(CV); int * LIDList = ColorLIDList(CV); for (int i=0; i < ColorCount; i++) { os.width(10); os << MyPID; os << " "; os.width(10); os << LIDList[i] << " "; os.width(20); os << CV; os << std::endl; } os << std::flush; } } } // Do a few global ops to give I/O a chance to complete Map().Comm().Barrier(); Map().Comm().Barrier(); Map().Comm().Barrier(); }} return; }
/***************************************************************************** InitTopoMap() *****************************************************************************/ void InitTopoMap(LISTPTR Input, OPTIONSTRUCT * Options, MAPSIZE * Map, TOPOPIX *** TopoMap) { const char *Routine = "InitTopoMap"; char VarName[BUFSIZE + 1]; /* Variable name */ int i; /* Counter */ int x; /* Counter */ int y; /* Counter */ int flag; /* either or not reverse the matrix */ int NumberType; /* Number type of data set */ unsigned char *Mask = NULL; /* Basin mask */ float *Elev; /* Surface elevation */ STRINIENTRY StrEnv[] = { {"TERRAIN", "DEM FILE", "", ""}, {"TERRAIN", "BASIN MASK FILE", "", ""}, {NULL, NULL, "", NULL} }; /* Process the [TERRAIN] section in the input file */ if (!(*TopoMap = (TOPOPIX **) calloc(Map->NY, sizeof(TOPOPIX *)))) ReportError((char *) Routine, 1); for (y = 0; y < Map->NY; y++) { if (!((*TopoMap)[y] = (TOPOPIX *) calloc(Map->NX, sizeof(TOPOPIX)))) ReportError((char *) Routine, 1); } /* Read the key-entry pairs from the input file */ for (i = 0; StrEnv[i].SectionName; i++) { GetInitString(StrEnv[i].SectionName, StrEnv[i].KeyName, StrEnv[i].Default, StrEnv[i].VarStr, (unsigned long) BUFSIZE, Input); if (IsEmptyStr(StrEnv[i].VarStr)) ReportError(StrEnv[i].KeyName, 51); } /* Read the elevation data from the DEM dataset */ GetVarName(001, 0, VarName); GetVarNumberType(001, &NumberType); if (!(Elev = (float *) calloc(Map->NX * Map->NY, SizeOfNumberType(NumberType)))) ReportError((char *) Routine, 1); flag = Read2DMatrix(StrEnv[demfile].VarStr, Elev, NumberType, Map->NY, Map->NX, 0, VarName, 0); /* Assign the attributes to the map pixel */ /* Reverse the matrix is flag = 1 & netcdf option is selected */ if ((Options->FileFormat == NETCDF && flag == 0) || (Options->FileFormat == BIN)){ for (y = 0, i = 0; y < Map->NY; y++) { for (x = 0; x < Map->NX; x++, i++) { (*TopoMap)[y][x].Dem = Elev[i]; } } } else if (Options->FileFormat == NETCDF && flag == 1){ for (y = Map->NY - 1, i = 0; y >= 0; y--) { for (x = 0; x < Map->NX; x++, i++) { (*TopoMap)[y][x].Dem = Elev[i]; } } } else ReportError((char *) Routine, 57); free(Elev); /* find out the minimum grid elevation of the basin */ MINELEV = 9999; for (y = 0, i = 0; y < Map->NY; y++) { for (x = 0; x < Map->NX; x++, i++) { if ((*TopoMap)[y][x].Dem < MINELEV) { MINELEV = (*TopoMap)[y][x].Dem; } } } /* Read the mask */ GetVarName(002, 0, VarName); GetVarNumberType(002, &NumberType); if (!(Mask = (unsigned char *) calloc(Map->NX * Map->NY, SizeOfNumberType(NumberType)))) ReportError((char *) Routine, 1); flag = Read2DMatrix(StrEnv[maskfile].VarStr, Mask, NumberType, Map->NY, Map->NX, 0, VarName, 0); if ((Options->FileFormat == NETCDF && flag == 0) || (Options->FileFormat == BIN)) { for (y = 0, i = 0; y < Map->NY; y++) { for (x = 0; x < Map->NX; x++, i++) { (*TopoMap)[y][x].Mask = Mask[i]; } } } else if (Options->FileFormat == NETCDF && flag == 1){ for (y = Map->NY - 1, i = 0; y >= 0; y--) { for (x = 0; x < Map->NX; x++, i++) { (*TopoMap)[y][x].Mask = Mask[i]; } } } else ReportError((char *) Routine, 57); free(Mask); /* Calculate slope, aspect, magnitude of subsurface flow gradient, and fraction of flow flowing in each direction based on the land surface slope. */ ElevationSlopeAspect(Map, *TopoMap); /* After calculating the slopes and aspects for all the points, reset the mask if the model is to be run in point mode */ if (Options->Extent == POINT) { for (y = 0; y < Map->NY; y++) for (x = 0; x < Map->NX; x++) (*TopoMap)[y][x].Mask = OUTSIDEBASIN; (*TopoMap)[Options->PointY][Options->PointX].Mask = (1 != OUTSIDEBASIN); } }
void Epetra_IntVector::Print(std::ostream& os) const { int MyPID = Map().Comm().MyPID(); int NumProc = Map().Comm().NumProc(); for (int iproc=0; iproc < NumProc; iproc++) { if (MyPID==iproc) { int NumMyElements1 =Map(). NumMyElements(); int MaxElementSize1 = Map().MaxElementSize(); int * MyGlobalElements1_int = 0; long long * MyGlobalElements1_LL = 0; if(Map().GlobalIndicesInt()) { #ifndef EPETRA_NO_32BIT_GLOBAL_INDICES MyGlobalElements1_int = Map().MyGlobalElements(); #else throw ReportError("Epetra_IntVector::Print: Global indices int but no API for it.",-1); #endif } else if(Map().GlobalIndicesLongLong()) { #ifndef EPETRA_NO_64BIT_GLOBAL_INDICES MyGlobalElements1_LL = Map().MyGlobalElements64(); #else throw ReportError("Epetra_IntVector::Print: Global indices long long but no API for it.",-1); #endif } int * FirstPointInElementList1=0; if (MaxElementSize1!=1) FirstPointInElementList1 = Map().FirstPointInElementList(); if (MyPID==0) { os.width(8); os << " MyPID"; os << " "; os.width(12); if (MaxElementSize1==1) os << "GID "; else os << " GID/Point"; os.width(20); os << "Value "; os << std::endl; } for (int i=0; i < NumMyElements1; i++) { for (int ii=0; ii< Map().ElementSize(i); ii++) { int iii; os.width(10); os << MyPID; os << " "; os.width(10); if (MaxElementSize1==1) { if(MyGlobalElements1_int) os << MyGlobalElements1_int[i] << " "; if(MyGlobalElements1_LL) os << MyGlobalElements1_LL[i] << " "; iii = i; } else { if(MyGlobalElements1_int) os << MyGlobalElements1_int[i]<< "/" << ii << " "; if(MyGlobalElements1_LL) os << MyGlobalElements1_LL[i]<< "/" << ii << " "; iii = FirstPointInElementList1[i]+ii; } os.width(20); os << Values_[iii]; os << std::endl; } } os << std::flush; } // Do a few global ops to give I/O a chance to complete Map().Comm().Barrier(); Map().Comm().Barrier(); Map().Comm().Barrier(); } return; }
void CSlotConnect::Process(eConnSrcDst eSrc, long SrcI, eConnSrcDst eDst, long SrcDstI, CFullValue & SrcValue, int Direction) { // Always Executed as a SET - Hence the use of the ReflectedGets if (!m_bValid) return; if (eDst==eCSD_Default) eDst = m_eDst; switch (eDst) { case eCSD_Slot: { CFullValue V=SrcValue; ProcessOps(V); if (m_eSrc==eCSD_Link) ApplyRangeLink2Slot(*Slots[m_lDstIndex], V); gs_SlotMngr.AppendChange(eSrc, SrcI, eCSD_Slot, m_lDstIndex, -1, V, &m_Delay, false, !m_bConnect1Done); break; } case eCSD_CdBlk: { if (m_Delay.Configured()) { CFullValue V=SrcValue; gs_SlotMngr.AppendChange(eSrc, SrcI, eCSD_SlotConn, SrcDstI, -1, V, &m_Delay, false, !m_bConnect1Done); break; } // FALL THROUGH } case eCSD_SlotConn: { CFullValue V=SrcValue; ProcessOps(V); if (m_bCdBlkVarFlt) { V.ChangeType(VT_R8); m_pCdBlkVar->set(V.m_vValue.dblVal); } else { V.ChangeType(VT_I4); m_pCdBlkVar->set(V.m_vValue.lVal); } // Execute pgm CGExecContext ECtx(NULL); m_pCdBlk->m_Code.Execute(ECtx); // Update Destination Tags for (int i=0; i<m_pCdBlk->m_ReflectedGets.GetSize(); i++) { CSlotConnect &C=(*m_pCdBlk->m_ReflectedGets[i]); if (C.m_bCdBlkVarFlt) { CFullValue D=V; D.m_vValue=C.m_pCdBlkVar->getD(); C.ProcessOps(D); gs_SlotMngr.AppendChange(eCSD_CdBlk, C.m_lSrcIndex, C.m_eDst, C.m_lDstIndex, -1, D, &C.m_Delay, false, !m_bConnect1Done); } else { CFullValue L=V; L.m_vValue=C.m_pCdBlkVar->getL(); C.ProcessOps(L); gs_SlotMngr.AppendChange(eCSD_CdBlk, C.m_lSrcIndex, C.m_eDst, C.m_lDstIndex, -1, L, &C.m_Delay, false, !m_bConnect1Done); } } break; } case eCSD_Link: { CFullValue V=SrcValue; if (m_eSrc==eCSD_Slot) ApplyRangeSlot2Link(*Slots[m_lSrcIndex], V); ProcessOps(V); gs_SlotMngr.AppendChange(eSrc, m_lSrcIndex, eDst, m_lDstIndex, -1, V, &m_Delay, false, !m_bConnect1Done); break; } default: ReportError("CSlotConnect::Process", 0, "Invalid Destination %s ", SrcDstString(eDst)); } m_bConnect1Done=true; }
wxObject* wxSizerXmlHandler::Handle_sizer() { wxXmlNode *parentNode = m_node->GetParent(); if ( !m_parentSizer && (!parentNode || parentNode->GetType() != wxXML_ELEMENT_NODE || !m_parentAsWindow) ) { ReportError("sizer must have a window parent"); return NULL; } // Create the sizer of the appropriate class. wxSizer * const sizer = DoCreateSizer(m_class); // creation of sizer failed for some (already reported) reason, so exit: if ( !sizer ) return NULL; wxSize minsize = GetSize(wxT("minsize")); if (!(minsize == wxDefaultSize)) sizer->SetMinSize(minsize); // save state wxSizer *old_par = m_parentSizer; bool old_ins = m_isInside; // set new state m_parentSizer = sizer; m_isInside = true; m_isGBS = (m_class == wxT("wxGridBagSizer")); wxObject* parent = m_parent; #if wxUSE_STATBOX // wxStaticBoxSizer's child controls should be parented by the box itself, // not its parent. wxStaticBoxSizer* const stsizer = wxDynamicCast(sizer, wxStaticBoxSizer); if ( stsizer ) parent = stsizer->GetStaticBox(); #endif // wxUSE_STATBOX CreateChildren(parent, true/*only this handler*/); // set growable rows and cols for sizers which support this if ( wxFlexGridSizer *flexsizer = wxDynamicCast(sizer, wxFlexGridSizer) ) { SetFlexibleMode(flexsizer); SetGrowables(flexsizer, wxT("growablerows"), true); SetGrowables(flexsizer, wxT("growablecols"), false); } // restore state m_isInside = old_ins; m_parentSizer = old_par; if (m_parentSizer == NULL) // setup window: { m_parentAsWindow->SetSizer(sizer); wxXmlNode *nd = m_node; m_node = parentNode; if (GetSize() == wxDefaultSize) { if ( wxDynamicCast(m_parentAsWindow, wxScrolledWindow) != NULL ) { sizer->FitInside(m_parentAsWindow); } else { sizer->Fit(m_parentAsWindow); } } m_node = nd; if (m_parentAsWindow->IsTopLevel()) { sizer->SetSizeHints(m_parentAsWindow); } } return sizer; }
void dng_info::Parse (dng_host &host, dng_stream &stream) { fTIFFBlockOffset = stream.Position (); fTIFFBlockOriginalOffset = stream.PositionInOriginalFile (); // Check byte order indicator. uint16 byteOrder = stream.Get_uint16 (); if (byteOrder == byteOrderII) { fBigEndian = false; #if qDNGValidate if (gVerbose) { printf ("\nUses little-endian byte order\n"); } #endif stream.SetLittleEndian (); } else if (byteOrder == byteOrderMM) { fBigEndian = true; #if qDNGValidate if (gVerbose) { printf ("\nUses big-endian byte order\n"); } #endif stream.SetBigEndian (); } else { #if qDNGValidate ReportError ("Unknown byte order"); #endif ThrowBadFormat (); } // Check "magic number" indicator. fMagic = stream.Get_uint16 (); #if qDNGValidate if (gVerbose) { printf ("Magic number = %u\n\n", (unsigned) fMagic); } #endif ValidateMagic (); // Parse IFD 0. uint64 next_offset = stream.Get_uint32 (); fExif.Reset (host.Make_dng_exif ()); fShared.Reset (host.Make_dng_shared ()); fIFD [0].Reset (host.Make_dng_ifd ()); ParseIFD (host, stream, fExif.Get (), fShared.Get (), fIFD [0].Get (), fTIFFBlockOffset + next_offset, fTIFFBlockOffset, 0); next_offset = fIFD [0]->fNextIFD; fIFDCount = 1; // Parse chained IFDs. while (next_offset) { if (next_offset >= stream.Length ()) { #if qDNGValidate { ReportWarning ("Chained IFD offset past end of stream"); } #endif break; } // Some TIFF file writers forget about the next IFD offset, so // validate the IFD at that offset before parsing it. if (!ValidateIFD (stream, fTIFFBlockOffset + next_offset, fTIFFBlockOffset)) { #if qDNGValidate { ReportWarning ("Chained IFD is not valid"); } #endif break; } if (fChainedIFDCount == kMaxChainedIFDs) { #if qDNGValidate { ReportWarning ("Chained IFD count exceeds DNG SDK parsing limit"); } #endif break; } fChainedIFD [fChainedIFDCount].Reset (host.Make_dng_ifd ()); ParseIFD (host, stream, NULL, NULL, fChainedIFD [fChainedIFDCount].Get (), fTIFFBlockOffset + next_offset, fTIFFBlockOffset, tcFirstChainedIFD + fChainedIFDCount); next_offset = fChainedIFD [fChainedIFDCount]->fNextIFD; fChainedIFDCount++; } // Parse SubIFDs. uint32 searchedIFDs = 0; bool tooManySubIFDs = false; while (searchedIFDs < fIFDCount && !tooManySubIFDs) { uint32 searchLimit = fIFDCount; for (uint32 searchIndex = searchedIFDs; searchIndex < searchLimit && !tooManySubIFDs; searchIndex++) { for (uint32 subIndex = 0; subIndex < fIFD [searchIndex]->fSubIFDsCount; subIndex++) { if (fIFDCount == kMaxSubIFDs + 1) { tooManySubIFDs = true; break; } stream.SetReadPosition (fIFD [searchIndex]->fSubIFDsOffset + subIndex * 4); uint32 sub_ifd_offset = stream.Get_uint32 (); fIFD [fIFDCount].Reset (host.Make_dng_ifd ()); ParseIFD (host, stream, fExif.Get (), fShared.Get (), fIFD [fIFDCount].Get (), fTIFFBlockOffset + sub_ifd_offset, fTIFFBlockOffset, tcFirstSubIFD + fIFDCount - 1); fIFDCount++; } searchedIFDs = searchLimit; } } #if qDNGValidate { if (tooManySubIFDs) { ReportWarning ("SubIFD count exceeds DNG SDK parsing limit"); } } #endif // Parse EXIF IFD. if (fShared->fExifIFD) { ParseIFD (host, stream, fExif.Get (), fShared.Get (), NULL, fTIFFBlockOffset + fShared->fExifIFD, fTIFFBlockOffset, tcExifIFD); } // Parse GPS IFD. if (fShared->fGPSInfo) { ParseIFD (host, stream, fExif.Get (), fShared.Get (), NULL, fTIFFBlockOffset + fShared->fGPSInfo, fTIFFBlockOffset, tcGPSInfo); } // Parse Interoperability IFD. if (fShared->fInteroperabilityIFD) { // Some Kodak KDC files have bogus Interoperability IFDs, so // validate the IFD before trying to parse it. if (ValidateIFD (stream, fTIFFBlockOffset + fShared->fInteroperabilityIFD, fTIFFBlockOffset)) { ParseIFD (host, stream, fExif.Get (), fShared.Get (), NULL, fTIFFBlockOffset + fShared->fInteroperabilityIFD, fTIFFBlockOffset, tcInteroperabilityIFD); } #if qDNGValidate else { ReportWarning ("The Interoperability IFD is not a valid IFD"); } #endif } // Parse Kodak DCR Private IFD. if (fShared->fKodakDCRPrivateIFD) { ParseIFD (host, stream, fExif.Get (), fShared.Get (), NULL, fTIFFBlockOffset + fShared->fKodakDCRPrivateIFD, fTIFFBlockOffset, tcKodakDCRPrivateIFD); } // Parse Kodak KDC Private IFD. if (fShared->fKodakKDCPrivateIFD) { ParseIFD (host, stream, fExif.Get (), fShared.Get (), NULL, fTIFFBlockOffset + fShared->fKodakKDCPrivateIFD, fTIFFBlockOffset, tcKodakKDCPrivateIFD); } // Parse MakerNote tag. if (fShared->fMakerNoteCount) { ParseMakerNote (host, stream, (uint32) (fTIFFBlockOffset + fShared->fMakerNoteCount), fShared->fMakerNoteOffset, fTIFFBlockOffset, 0, stream.Length ()); } // Parse DNGPrivateData tag. if (fShared->fDNGPrivateDataCount && fShared->fDNGVersion) { ParseDNGPrivateData (host, stream); } #if qDNGValidate // If we are running dng_validate on stand-alone camera profile file, // complete the validation of the profile. if (fMagic == magicExtendedProfile) { dng_camera_profile_info &profileInfo = fShared->fCameraProfile; dng_camera_profile profile; profile.Parse (stream, profileInfo); if (profileInfo.fColorPlanes < 3 || !profile.IsValid (profileInfo.fColorPlanes)) { ReportError ("Invalid camera profile file"); } } #endif }
int main(int argc, char **argv) { #ifndef _WIN32 struct sigaction handler; #endif HANDLE codi; int nError; int nDebugMode = 1; int nPermit=-1, nPowerMode=-1; int nListSerial = 0; signed char nRfPower=254; int opt; char *pDevicePath = NULL; #ifndef _WIN32 // 보편적인 시그널 핸들러를 설치한다. handler.sa_handler = signal_handler; sigfillset(&handler.sa_mask); sigaction(SIGINT, &handler, 0); sigaction(SIGTERM, &handler, 0); sigaction(SIGCHLD, &handler, 0); #endif #ifndef _WIN32 while((opt=getopt(argc, argv, "dp:q:G:")) != -1) { #else while((opt=getopt(argc, argv, "d")) != -1) { #endif switch(opt) { case 'd': nDebugMode = 0; break; case 'l': nListSerial = 1; break; case 'q': nPermit = (int)strtol(optarg,(char **)NULL,10) == 0 ? 0 : 255; break; case 'G': nPowerMode = (int)strtol(optarg,(char **)NULL,10); break; case 'p': nRfPower = (signed char)strtol(optarg,(char **)NULL,10); break; case 'h': default : Usage(argv[0]); return (1); } } if((argc - optind) < 1) { Usage(argv[0]); return (2); } // 디버깅 화면 출력(0), 해제(1) SET_DEBUG_FILE(stderr); SET_DEBUG_MODE(nDebugMode); pDevicePath = strdup(argv[optind]); memset(g_szCodiId, 0, sizeof(g_szCodiId)); memset(codiDevice.szDevice, 0, sizeof(codiDevice.szDevice)); strncpy(codiDevice.szDevice, pDevicePath, MIN(strlen(pDevicePath), sizeof(codiDevice.szDevice)-1)); // CODIAPI를 초기화 한다. nError = codiInit(); if (nError != CODIERR_NOERROR) { ReportError(NULL, nError); return (3); } // 새로운 Coordinator 장치를 등록한다. nError = codiRegister(&codi, &codiDevice); if (nError != CODIERR_NOERROR) { ReportError(NULL, nError); codiExit(); return (3); } // Coordinator 서비스를 시작 시킨다. nError = codiStartup(codi); if (nError != CODIERR_NOERROR) { ReportError(NULL, nError); codiUnregister(codi); codiExit(); return (3); } // 사용자 프로그램을 여기에 코딩한다. MainProcedure(codi, nPermit, nRfPower, nPowerMode); // Coordinator 서비스를 종료한다. nError = codiShutdown(codi); if (nError != CODIERR_NOERROR) ReportError(NULL, nError); // 등록된 디바이스를 해제한다. nError = codiUnregister(codi); if (nError != CODIERR_NOERROR) ReportError(NULL, nError); // API를 종료한다. codiExit(); return (0); } const char *GetStateMessage(int nState) { switch(nState) { case CODISTATE_NORMAL : return "Normal"; case CODISTATE_NOT_STARTED : return "Coordinator not started"; case CODISTATE_NOT_CONNECTED : return "Coordinator not connected"; case CODISTATE_STACK_NOT_READY : return "Coordinator Stack not ready"; case CODISTATE_STACK_DOWN : return "Coordinator Stack down"; case CODISTATE_JOIN_FAIL : return "Coordinator Join Fail"; case CODISTATE_NO_RESPONSE : return "Coordinator No Response"; case CODISTATE_ERROR : return "Coordinator Error"; } return "Unknown State"; } #define STATE_INIT 0 #define STATE_READY 1 #define STATE_PERMIT 17 #define STATE_SET_PERMIT 40 #define STATE_RF_POWER 41 #define STATE_POWER_MODE 42 #define STATE_RESET 55 #define STATE_WAIT 100 void MainProcedure(HANDLE codi, int nPermit, signed char nRfPower, int nPowerMode) { TIMETICK start, prev, cur; //BYTE szBuffer[1024]; int nError = CODIERR_NOERROR, nLength; int nState, nElapse; BOOL bSet; CODI_PERMIT_PAYLOAD permit; CODI_NETWORK_PAYLOAD network; GetTimeTick(&start); for(nState=STATE_INIT; !m_bCodiExitPending;) { GetTimeTick(&prev); //nError = codiGetState(codi); //XDEBUG("CODINATOR STATE(%d) = %s\r\n", nError, GetStateMessage(nError)); //XDEBUG("m_bCodiExitPending %d\r\n", m_bCodiExitPending); switch(nState) { case STATE_INIT : nState = STATE_READY; break; case STATE_READY : nError = codiGetState(codi); XDEBUG("CODINATOR STATE(%d) = %s\r\n", nError, GetStateMessage(nError)); if (nError != CODISTATE_NORMAL) { nState = STATE_RESET; break; } nState = STATE_SET_PERMIT; break; case STATE_RESET : nError = codiReset(codi); if (nError != CODIERR_NOERROR) ReportError(NULL, nError); USLEEP(10000000); nState = STATE_READY; break; case STATE_SET_PERMIT: #ifdef __FN_RFSET__ if(nPermit >=0 && nPermit <= 255) { memset(&permit, 0, sizeof(CODI_CMD_PERMIT)); permit.permit_time = (BYTE)(nPermit & 0xFF); nError = codiSetProperty(codi, CODI_CMD_PERMIT, (BYTE *)&permit, sizeof(CODI_PERMIT_PAYLOAD), 3000); if (nError != CODIERR_NOERROR) ReportError(NULL, nError); } #endif nState = STATE_PERMIT; break; case STATE_PERMIT : memset(&permit, 0, sizeof(CODI_PERMIT_PAYLOAD)); nError = codiGetProperty(codi, CODI_CMD_PERMIT, (BYTE *)&permit, &nLength, 5000); if (nError != CODIERR_NOERROR) { ReportError(NULL, nError); } #ifdef __FN_RFSET__ else { PRINT("OUT:PERMIT:%d\n", permit.permit_time); } #endif nState = STATE_RF_POWER; break; case STATE_RF_POWER : bSet = FALSE; memset(&network, 0, sizeof(CODI_NETWORK_PAYLOAD)); nError = codiGetProperty(codi, CODI_CMD_NETWORK_PARAM, (BYTE *)&network, &nLength, 5000); if (nError != CODIERR_NOERROR) { ReportError(NULL, nError); } #ifdef __FN_RFSET__ else { if(nRfPower != 254) { network.power = nRfPower; bSet = TRUE; } if(nPowerMode >= 0) { network.txpowermode = (BYTE)nPowerMode; bSet = TRUE; } if(bSet) { nError = codiSetProperty(codi, CODI_CMD_NETWORK_PARAM, (BYTE *)&network, nLength, 3000); } PRINT("OUT:CINFO:%d,%d,%d\n", network.channel, network.panid, network.power); } #endif nState = STATE_WAIT; break; case STATE_WAIT : GetTimeTick(&cur); nElapse = GetTimeInterval(&start, &cur); USLEEP(30000000); nState = STATE_WAIT; break; } GetTimeTick(&cur); nElapse = GetTimeInterval(&prev, &cur); //XDEBUG("Elapse=%d ms\r\n", nElapse); } }
bool dng_info::IsValidDNG () { // Check shared info. if (!fShared->IsValidDNG ()) { return false; } // Check TIFF magic number. if (fMagic != 42) { #if qDNGValidate ReportError ("Invalid TIFF magic number"); #endif return false; } // Make sure we have a main image IFD. if (fMainIndex == -1) { #if qDNGValidate ReportError ("Unable to find main image IFD"); #endif return false; } // Make sure is each IFD is valid. for (uint32 index = 0; index < fIFDCount; index++) { uint32 parentCode = (index == 0 ? 0 : tcFirstSubIFD + index - 1); if (!fIFD [index]->IsValidDNG (*fShared.Get (), parentCode)) { // Only errors in the main and transparency mask IFDs are fatal to parsing. if (index == (uint32) fMainIndex || index == (uint32) fMaskIndex) { return false; } } } return true; }
/***************************************************************************** Function name: InitNetwork() Purpose : Initialize road/channel work. Memory is allocated, and the necessary adjustments for the soil profile are calculated Comments : *****************************************************************************/ void InitNetwork(int NY, int NX, float DX, float DY, TOPOPIX **TopoMap, SOILPIX **SoilMap, VEGPIX **VegMap, VEGTABLE *VType, ROADSTRUCT ***Network, CHANNEL *ChannelData, LAYER Veg, OPTIONSTRUCT *Options) { const char *Routine = "InitNetwork"; int i; /* counter */ int x; /* column counter */ int y; /* row counter */ int sx, sy; int minx, miny; int doimpervious; int numroads; /* Counter of number of pixels with a road and channel */ int numroadschan; /* Counter of number of pixels with a road */ FILE *inputfile; /* Allocate memory for network structure */ if (!(*Network = (ROADSTRUCT **) calloc(NY, sizeof(ROADSTRUCT *)))) ReportError((char *) Routine, 1); for (y = 0; y < NY; y++) { if (!((*Network)[y] = (ROADSTRUCT *) calloc(NX, sizeof(ROADSTRUCT)))) ReportError((char *) Routine, 1); } for (y = 0; y < NY; y++) { for (x = 0; x < NX; x++) { if (INBASIN(TopoMap[y][x].Mask)) { if (!((*Network)[y][x].Adjust = (float *) calloc((VType[VegMap[y][x].Veg - 1].NSoilLayers + 1), sizeof(float)))) ReportError((char *) Routine, 1); if (!((*Network)[y][x].PercArea = (float *) calloc((VType[VegMap[y][x].Veg - 1].NSoilLayers + 1), sizeof(float)))) ReportError((char *) Routine, 1); } } } numroadschan = 0; numroads = 0; /* If a road/channel Network is imposed on the area, read the Network information, and calculate the storage adjustment factors */ if (Options->HasNetwork) { for (y = 0; y < NY; y++) { for (x = 0; x < NX; x++) { if (INBASIN(TopoMap[y][x].Mask)) { ChannelCut(y, x, ChannelData, &((*Network)[y][x])); AdjustStorage(VType[VegMap[y][x].Veg - 1].NSoilLayers, SoilMap[y][x].Depth, VType[VegMap[y][x].Veg - 1].RootDepth, (*Network)[y][x].Area, DX, DY, (*Network)[y][x].BankHeight, (*Network)[y][x].PercArea, (*Network)[y][x].Adjust, &((*Network)[y][x].CutBankZone)); (*Network)[y][x].IExcess = 0.; if (channel_grid_has_channel(ChannelData->road_map, x, y)) { numroads++; if (channel_grid_has_channel(ChannelData->stream_map, x, y)) { numroadschan++; } (*Network)[y][x].fraction = ChannelFraction(&(TopoMap[y][x]), ChannelData->road_map[x][y]); (*Network)[y][x].MaxInfiltrationRate = MaxRoadInfiltration(ChannelData->road_map, x, y); (*Network)[y][x].RoadClass = channel_grid_class(ChannelData->road_map, x, y); (*Network)[y][x].FlowSlope = channel_grid_flowslope(ChannelData->road_map, x, y); (*Network)[y][x].FlowLength = channel_grid_flowlength(ChannelData->road_map, x, y,(*Network)[y][x].FlowSlope); (*Network)[y][x].RoadArea = channel_grid_cell_width(ChannelData->road_map, x, y) * channel_grid_cell_length(ChannelData->road_map, x, y); } else { (*Network)[y][x].MaxInfiltrationRate = DHSVM_HUGE; (*Network)[y][x].FlowSlope = 0.; (*Network)[y][x].FlowLength = 0.; (*Network)[y][x].RoadArea = 0.; (*Network)[y][x].RoadClass = NULL; (*Network)[y][x].IExcess = 0.; } } } } } /* if no road/channel Network is imposed, set the adjustment factors to the values they have in the absence of an imposed network */ else { for (y = 0; y < NY; y++) { for (x = 0; x < NX; x++) { if (INBASIN(TopoMap[y][x].Mask)) { for (i = 0; i <= VType[VegMap[y][x].Veg - 1].NSoilLayers; i++) { (*Network)[y][x].Adjust[i] = 1.0; (*Network)[y][x].PercArea[i] = 1.0; (*Network)[y][x].CutBankZone = NO_CUT; (*Network)[y][x].MaxInfiltrationRate = 0.; } (*Network)[y][x].FlowSlope = 0.; (*Network)[y][x].FlowLength = 0.; (*Network)[y][x].RoadArea = 0.; (*Network)[y][x].RoadClass = NULL; (*Network)[y][x].IExcess = 0.; } } } } if (numroads > 0){ printf("There are %d pixels with a road and %d with a road and a channel.\n", numroads, numroadschan); } /* this all pertains to the impervious surface */ doimpervious = 0; for (i = 0; i < Veg.NTypes; i++) if (VType[i].ImpervFrac > 0.0) doimpervious = 1; if (doimpervious) { if (!(inputfile = fopen(Options->ImperviousFilePath, "rt"))) { fprintf(stderr, "User has specified a percentage impervious area \n"); fprintf(stderr, "To incorporate impervious area, DHSVM needs a file\n"); fprintf(stderr, "identified by the key: \"IMPERVIOUS SURFACE ROUTING FILE\",\n"); fprintf(stderr, "in the \"VEGETATION\" section. This file is used to \n"); fprintf(stderr, "determine the fate of surface runoff, i.e. where does it go \n"); fprintf(stderr, "This file was not found: see InitNetwork.c \n"); fprintf(stderr, "The code find_nearest_channel.c will make the file\n"); ReportError(Options->ImperviousFilePath, 3); } for (y = 0; y < NY; y++) { for (x = 0; x < NX; x++) { if (INBASIN(TopoMap[y][x].Mask)) { if (fscanf(inputfile, "%d %d %d %d \n", &sy, &sx, &miny, &minx) != EOF) { TopoMap[y][x].drains_x = minx; TopoMap[y][x].drains_y = miny; } else { ReportError(Options->ImperviousFilePath, 63); } if (sx != x || sy != y) { ReportError(Options->ImperviousFilePath, 64); } if (!channel_grid_has_channel(ChannelData->stream_map, minx, miny)) { printf("Routing file is wrong. The desitination cell is no channel cell!\n"); exit(0); } } } } } }
nsresult nsExpatDriver::HandleError() { PRInt32 code = XML_GetErrorCode(mExpatParser); NS_ASSERTION(code > XML_ERROR_NONE, "unexpected XML error code"); // Map Expat error code to an error string // XXX Deal with error returns. nsAutoString description; nsParserMsgUtils::GetLocalizedStringByID(XMLPARSER_PROPERTIES, code, description); if (code == XML_ERROR_TAG_MISMATCH) { /** * Expat can send the following: * localName * namespaceURI<separator>localName * namespaceURI<separator>localName<separator>prefix * * and we use 0xFFFF for the <separator>. * */ const PRUnichar *mismatch = MOZ_XML_GetMismatchedTag(mExpatParser); const PRUnichar *uriEnd = nsnull; const PRUnichar *nameEnd = nsnull; const PRUnichar *pos; for (pos = mismatch; *pos; ++pos) { if (*pos == kExpatSeparatorChar) { if (uriEnd) { nameEnd = pos; } else { uriEnd = pos; } } } nsAutoString tagName; if (uriEnd && nameEnd) { // We have a prefix. tagName.Append(nameEnd + 1, pos - nameEnd - 1); tagName.Append(PRUnichar(':')); } const PRUnichar *nameStart = uriEnd ? uriEnd + 1 : mismatch; tagName.Append(nameStart, (nameEnd ? nameEnd : pos) - nameStart); nsAutoString msg; nsParserMsgUtils::GetLocalizedStringByName(XMLPARSER_PROPERTIES, "Expected", msg); // . Expected: </%S>. PRUnichar *message = nsTextFormatter::smprintf(msg.get(), tagName.get()); if (!message) { return NS_ERROR_OUT_OF_MEMORY; } description.Append(message); nsTextFormatter::smprintf_free(message); } // Adjust the column number so that it is one based rather than zero based. PRUint32 colNumber = XML_GetCurrentColumnNumber(mExpatParser) + 1; PRUint32 lineNumber = XML_GetCurrentLineNumber(mExpatParser); nsAutoString errorText; CreateErrorText(description.get(), XML_GetBase(mExpatParser), lineNumber, colNumber, errorText); NS_ASSERTION(mSink, "no sink?"); nsAutoString sourceText(mLastLine); AppendErrorPointer(colNumber, mLastLine.get(), sourceText); // Try to create and initialize the script error. nsCOMPtr<nsIScriptError> serr(do_CreateInstance(NS_SCRIPTERROR_CONTRACTID)); nsresult rv = NS_ERROR_FAILURE; if (serr) { nsCOMPtr<nsIScriptError2> serr2(do_QueryInterface(serr)); rv = serr2->InitWithWindowID(description.get(), mURISpec.get(), mLastLine.get(), lineNumber, colNumber, nsIScriptError::errorFlag, "malformed-xml", mInnerWindowID); } // If it didn't initialize, we can't do any logging. bool shouldReportError = NS_SUCCEEDED(rv); if (mSink && shouldReportError) { rv = mSink->ReportError(errorText.get(), sourceText.get(), serr, &shouldReportError); if (NS_FAILED(rv)) { shouldReportError = PR_TRUE; } } if (shouldReportError) { nsCOMPtr<nsIConsoleService> cs (do_GetService(NS_CONSOLESERVICE_CONTRACTID)); if (cs) { cs->LogMessage(serr); } } return NS_ERROR_HTMLPARSER_STOPPARSING; }
void VideoProducer::NodeRegistered() { if (fInitStatus != B_OK) { ReportError(B_NODE_IN_DISTRESS); return; } /* Set up the parameter web */ //TODO: remove and put sensible stuff there BParameterWeb *web = new BParameterWeb(); BParameterGroup *main = web->MakeGroup(Name()); BParameterGroup *g; /* g = main->MakeGroup("Color"); BDiscreteParameter *state = g->MakeDiscreteParameter( P_COLOR, B_MEDIA_RAW_VIDEO, "Color", "Color"); state->AddItem(B_HOST_TO_LENDIAN_INT32(0x00ff0000), "Red"); state->AddItem(B_HOST_TO_LENDIAN_INT32(0x0000ff00), "Green"); state->AddItem(B_HOST_TO_LENDIAN_INT32(0x000000ff), "Blue"); */ BParameter *p; g = main->MakeGroup("Info"); p = g->MakeTextParameter( P_INFO, B_MEDIA_RAW_VIDEO, "", "Info", 256); int32 id = P_LAST; if (fCamDevice) { #ifndef SINGLE_PARAMETER_GROUP main = web->MakeGroup("Device"); #endif fCamDevice->AddParameters(main, id); if (fCamDevice->Sensor()) { #ifndef SINGLE_PARAMETER_GROUP main = web->MakeGroup("Sensor"); #endif fCamDevice->Sensor()->AddParameters(main, id); } } fColor = B_HOST_TO_LENDIAN_INT32(0x00ff0000); fLastColorChange = system_time(); /* After this call, the BControllable owns the BParameterWeb object and * will delete it for you */ SetParameterWeb(web); fOutput.node = Node(); fOutput.source.port = ControlPort(); fOutput.source.id = 0; fOutput.destination = media_destination::null; strcpy(fOutput.name, Name()); /* Tailor these for the output of your device */ fOutput.format.type = B_MEDIA_RAW_VIDEO; fOutput.format.u.raw_video = media_raw_video_format::wildcard; fOutput.format.u.raw_video.interlace = 1; fOutput.format.u.raw_video.display.format = B_RGB32; fOutput.format.u.raw_video.field_rate = FIELD_RATE; // XXX: mmu /* Start the BMediaEventLooper control loop running */ Run(); }
HRESULT TransferWiaItem( IWiaItem *pWiaItem ) { // // Validate arguments // if (NULL == pWiaItem) { return E_INVALIDARG; } // // Get the IWiaPropertyStorage interface so we can set required properties // IWiaPropertyStorage *pWiaPropertyStorage = NULL; HRESULT hr = pWiaItem->QueryInterface( IID_IWiaPropertyStorage, (void**)&pWiaPropertyStorage ); if (SUCCEEDED(hr)) { // // Prepare PROPSPECs and PROPVARIANTs for setting the // media type and format // PROPSPEC PropSpec[2] = {0}; PROPVARIANT PropVariant[2] = {0}; const ULONG c_nPropCount = sizeof(PropVariant)/sizeof(PropVariant[0]); // // Use BMP as the output format // GUID guidOutputFormat = WiaImgFmt_BMP; // // Initialize the PROPSPECs // PropSpec[0].ulKind = PRSPEC_PROPID; PropSpec[0].propid = WIA_IPA_FORMAT; PropSpec[1].ulKind = PRSPEC_PROPID; PropSpec[1].propid = WIA_IPA_TYMED; // // Initialize the PROPVARIANTs // PropVariant[0].vt = VT_CLSID; PropVariant[0].puuid = &guidOutputFormat; PropVariant[1].vt = VT_I4; PropVariant[1].lVal = TYMED_FILE; // // Set the properties // hr = pWiaPropertyStorage->WriteMultiple( c_nPropCount, PropSpec, PropVariant, WIA_IPA_FIRST ); if (SUCCEEDED(hr)) { // // Get the IWiaDataTransfer interface // IWiaDataTransfer *pWiaDataTransfer = NULL; hr = pWiaItem->QueryInterface( IID_IWiaDataTransfer, (void**)&pWiaDataTransfer ); if (SUCCEEDED(hr)) { // // Create our callback class // CWiaDataCallback *pCallback = new CWiaDataCallback; if (pCallback) { // // Get the IWiaDataCallback interface from our callback class. // IWiaDataCallback *pWiaDataCallback = NULL; hr = pCallback->QueryInterface( IID_IWiaDataCallback, (void**)&pWiaDataCallback ); if (SUCCEEDED(hr)) { // // Perform the transfer using default settings // STGMEDIUM stgMedium = {0}; hr = pWiaDataTransfer->idtGetData( &stgMedium, pWiaDataCallback ); if (S_OK == hr) { // // Print the filename (note that this filename is always // a WCHAR string, not TCHAR. // _tprintf( TEXT("Transferred filename: %ws\n"), stgMedium.lpszFileName ); // // Release any memory associated with the stgmedium // ReleaseStgMedium( &stgMedium ); } else { ReportError( TEXT("pWiaDataTransfer->idtGetData failed"), hr ); } // // Release the callback interface // pWiaDataCallback->Release(); pWiaDataCallback = NULL; } else { ReportError( TEXT("pCallback->QueryInterface failed on IID_IWiaDataCallback"), hr ); } // // Release our callback. It should now delete itself. // pCallback->Release(); pCallback = NULL; } else { ReportError( TEXT("Unable to create CWiaDataCallback class instance") ); } // // Release the IWiaDataTransfer // pWiaDataTransfer->Release(); pWiaDataTransfer = NULL; } else { ReportError( TEXT("pWiaItem->QueryInterface failed on IID_IWiaDataTransfer"), hr ); } } // // Release the IWiaPropertyStorage // pWiaPropertyStorage->Release(); pWiaPropertyStorage = NULL; } else { ReportError( TEXT("pWiaItem->QueryInterface failed on IID_IWiaPropertyStorage"), hr ); } return hr; }
// return: 0: okay; 1: needs more sample; 2: needs reconfiguring; 3: more data available int receive_sample(IMFTransform *transform, DWORD out_stream_id, IMFSample** out_sample) { HRESULT hr; MFT_OUTPUT_DATA_BUFFER out_buffers; IMFSample *sample = NULL; MFT_OUTPUT_STREAM_INFO out_info; DWORD status = 0; bool mft_create_sample = false; if (!out_sample) { ReportError(L"NULL pointer passed to receive_sample()", MF_E_SAMPLE_NOT_WRITABLE); return -1; } SafeRelease(out_sample); hr = transform->GetOutputStreamInfo(out_stream_id, &out_info); if (FAILED(hr)) { ReportError(L"MFT: Failed to get stream info", hr); return -1; } mft_create_sample = (out_info.dwFlags & MFT_OUTPUT_STREAM_PROVIDES_SAMPLES) || (out_info.dwFlags & MFT_OUTPUT_STREAM_CAN_PROVIDE_SAMPLES); while (true) { sample = NULL; *out_sample = NULL; status = 0; if (!mft_create_sample) { sample = create_sample(NULL, out_info.cbSize, out_info.cbAlignment); if (!sample) { ReportError(L"MFT: Unable to allocate memory for samples", hr); return -1; } } out_buffers.dwStreamID = out_stream_id; out_buffers.pSample = sample; hr = transform->ProcessOutput(0, 1, &out_buffers, &status); if (!FAILED(hr)) { *out_sample = out_buffers.pSample; break; } if (hr == MF_E_TRANSFORM_NEED_MORE_INPUT) { // TODO: better handling try again and EOF cases using drain value return 1; } if (hr == MF_E_TRANSFORM_STREAM_CHANGE) { ReportError(L"MFT: stream format changed, re-configuration required", hr); return 2; } break; } if (out_buffers.dwStatus & MFT_OUTPUT_DATA_BUFFER_INCOMPLETE) { return 3; } // TODO: better handling try again and EOF cases using drain value if (*out_sample == NULL) { ReportError(L"MFT: decoding failure", hr); return -1; } return 0; }
HRESULT ReadSomeWiaProperties( IWiaPropertyStorage *pWiaPropertyStorage ) { // // Validate arguments // if (NULL == pWiaPropertyStorage) { return E_INVALIDARG; } // // Declare PROPSPECs and PROPVARIANTs, and initialize them to zero. // PROPSPEC PropSpec[3] = {0}; PROPVARIANT PropVar[3] = {0}; // // How many properties are we querying for? // const ULONG c_nPropertyCount = sizeof(PropSpec)/sizeof(PropSpec[0]); // // Define which properties we want to read: // Device ID. This is what we'd use to create // the device. // PropSpec[0].ulKind = PRSPEC_PROPID; PropSpec[0].propid = WIA_DIP_DEV_ID; // // Device Name // PropSpec[1].ulKind = PRSPEC_PROPID; PropSpec[1].propid = WIA_DIP_DEV_NAME; // // Device description // PropSpec[2].ulKind = PRSPEC_PROPID; PropSpec[2].propid = WIA_DIP_DEV_DESC; // // Ask for the property values // HRESULT hr = pWiaPropertyStorage->ReadMultiple( c_nPropertyCount, PropSpec, PropVar ); if (SUCCEEDED(hr)) { // // IWiaPropertyStorage::ReadMultiple will return S_FALSE if some // properties could not be read, so we have to check the return // types for each requested item. // // // Check the return type for the device ID // if (VT_BSTR == PropVar[0].vt) { // // Do something with the device ID // _tprintf( TEXT("WIA_DIP_DEV_ID: %ws\n"), PropVar[0].bstrVal ); } // // Check the return type for the device name // if (VT_BSTR == PropVar[1].vt) { // // Do something with the device name // _tprintf( TEXT("WIA_DIP_DEV_NAME: %ws\n"), PropVar[1].bstrVal ); } // // Check the return type for the device description // if (VT_BSTR == PropVar[2].vt) { // // Do something with the device description // _tprintf( TEXT("WIA_DIP_DEV_DESC: %ws\n"), PropVar[2].bstrVal ); } // // Free the returned PROPVARIANTs // FreePropVariantArray( c_nPropertyCount, PropVar ); } else { ReportError( TEXT("Error calling IWiaPropertyStorage::ReadMultiple"), hr ); } // // Return the result of reading the properties // return hr; }
/***************************************************************************** InitSoilMap() *****************************************************************************/ void InitSoilMap(LISTPTR Input, OPTIONSTRUCT * Options, MAPSIZE * Map, LAYER * Soil, TOPOPIX ** TopoMap, SOILPIX *** SoilMap) { const char *Routine = "InitSoilMap"; char VarName[BUFSIZE + 1]; /* Variable name */ int i; /* counter */ int x; /* counter */ int y; /* counter */ int NumberType; /* number type */ unsigned char *Type; /* Soil type */ float *Depth; /* Soil depth */ int flag; STRINIENTRY StrEnv[] = { {"SOILS", "SOIL MAP FILE", "", ""}, {"SOILS", "SOIL DEPTH FILE", "", ""}, {NULL, NULL, "", NULL} }; /* Process the filenames in the [SOILS] section in the input file */ /* Assign the attributes to the correct map pixel */ if (!(*SoilMap = (SOILPIX **) calloc(Map->NY, sizeof(SOILPIX *)))) ReportError((char *) Routine, 1); for (y = 0; y < Map->NY; y++) { if (!((*SoilMap)[y] = (SOILPIX *) calloc(Map->NX, sizeof(SOILPIX)))) ReportError((char *) Routine, 1); } /* Read the key-entry pairs from the input file */ for (i = 0; StrEnv[i].SectionName; i++) { GetInitString(StrEnv[i].SectionName, StrEnv[i].KeyName, StrEnv[i].Default, StrEnv[i].VarStr, (unsigned long) BUFSIZE, Input); if (IsEmptyStr(StrEnv[i].VarStr)) ReportError(StrEnv[i].KeyName, 51); } /* Read the soil type */ GetVarName(003, 0, VarName); GetVarNumberType(003, &NumberType); if (!(Type = (unsigned char *) calloc(Map->NX * Map->NY, SizeOfNumberType(NumberType)))) ReportError((char *) Routine, 1); flag = Read2DMatrix(StrEnv[soiltype_file].VarStr, Type, NumberType, Map->NY, Map->NX, 0, VarName, 0); if ((Options->FileFormat == NETCDF && flag == 0) || (Options->FileFormat == BIN)) { for (y = 0, i = 0; y < Map->NY; y++) { for (x = 0; x < Map->NX; x++, i++) { if (((int) Type[i]) > Soil->NTypes) ReportError(StrEnv[soiltype_file].VarStr, 32); (*SoilMap)[y][x].Soil = Type[i]; } } } else if (Options->FileFormat == NETCDF && flag == 1){ for (y = Map->NY - 1, i = 0; y >= 0; y--) { for (x = 0; x < Map->NX; x++, i++) { if (((int) Type[i]) > Soil->NTypes) ReportError(StrEnv[soiltype_file].VarStr, 32); (*SoilMap)[y][x].Soil = Type[i]; } } } else ReportError((char *) Routine, 57); /* Read the total soil depth */ GetVarName(004, 0, VarName); GetVarNumberType(004, &NumberType); if (!(Depth = (float *) calloc(Map->NX * Map->NY, SizeOfNumberType(NumberType)))) ReportError((char *) Routine, 1); flag = Read2DMatrix(StrEnv[soildepth_file].VarStr, Depth, NumberType, Map->NY, Map->NX, 0, VarName, 0); /* Assign the attributes to the correct map pixel */ if ((Options->FileFormat == NETCDF && flag == 0) || (Options->FileFormat == BIN)) { for (y = 0, i = 0; y < Map->NY; y++) { for (x = 0; x < Map->NX; x++, i++) { (*SoilMap)[y][x].Depth = Depth[i]; } } } else if (Options->FileFormat == NETCDF && flag == 1){ for (y = Map->NY - 1, i = 0; y >= 0; y--) { for (x = 0; x < Map->NX; x++, i++) { (*SoilMap)[y][x].Depth = Depth[i]; } } } else ReportError((char *) Routine, 57); for (y = 0, i = 0; y < Map->NY; y++) { for (x = 0; x < Map->NX; x++, i++) { if (Options->Infiltration == DYNAMIC) (*SoilMap)[y][x].InfiltAcc = 0.; (*SoilMap)[y][x].MoistInit = 0.; /* allocate memory for the number of root layers, plus an additional layer below the deepest root layer */ if (INBASIN(TopoMap[y][x].Mask)) { if (!((*SoilMap)[y][x].Moist = (float *) calloc((Soil->NLayers[Type[i] - 1] + 1), sizeof(float)))) ReportError((char *) Routine, 1); if (!((*SoilMap)[y][x].Perc = (float *) calloc(Soil->NLayers[Type[i] - 1], sizeof(float)))) ReportError((char *) Routine, 1); if (!((*SoilMap)[y][x].Temp = (float *) calloc(Soil->NLayers[Type[i] - 1], sizeof(float)))) ReportError((char *) Routine, 1); } else { (*SoilMap)[y][x].Moist = NULL; (*SoilMap)[y][x].Perc = NULL; (*SoilMap)[y][x].Temp = NULL; } } } free(Type); free(Depth); }
HRESULT CreateWiaDeviceAndDoSomeStuff( IWiaDevMgr *pWiaDevMgr, IWiaPropertyStorage *pWiaPropertyStorage ) { // // Validate arguments // if (NULL == pWiaPropertyStorage) { return E_INVALIDARG; } // // Declare PROPSPECs and PROPVARIANTs, and initialize them to zero. // PROPSPEC PropSpec[1] = {0}; PROPVARIANT PropVar[1] = {0}; // // How many properties are we querying for? // const ULONG c_nPropertyCount = sizeof(PropSpec)/sizeof(PropSpec[0]); // // Define which properties we want to read. We want the // device ID, so we can create the device. // PropSpec[0].ulKind = PRSPEC_PROPID; PropSpec[0].propid = WIA_DIP_DEV_ID; // // Ask for the property values // HRESULT hr = pWiaPropertyStorage->ReadMultiple( c_nPropertyCount, PropSpec, PropVar ); if (SUCCEEDED(hr)) { // // Check the return type for the device ID to make // sure this property was actually read. // if (VT_BSTR == PropVar[0].vt) { // // Create the WIA device, which results in obtaining // the root IWiaItem // IWiaItem *pWiaRootItem = NULL; hr = CreateWiaDevice( pWiaDevMgr, PropVar[0].bstrVal, &pWiaRootItem ); if (SUCCEEDED(hr)) { // // Recursively enumerate the items // (This function will also do some stuff with each item) // hr = EnumerateItems( pWiaRootItem ); // // Free the root item // pWiaRootItem->Release(); pWiaRootItem = NULL; } else { ReportError( TEXT("Error calling CreateWiaDevice"), hr ); } } // // Free the returned PROPVARIANTs // FreePropVariantArray( c_nPropertyCount, PropVar ); } else { ReportError( TEXT("Error calling IWiaPropertyStorage::ReadMultiple"), hr ); } // // Return the result of all of this // return hr; }
/***************************************************** * \brief Read a natural block of raster band data *****************************************************/ CPLErr PostGISRasterTileRasterBand::IReadBlock(CPL_UNUSED int nBlockXOff, CPL_UNUSED int nBlockYOff, void * pImage) { CPLString osCommand; PGresult * poResult = NULL; int nWKBLength = 0; int nPixelSize = GDALGetDataTypeSize(eDataType)/8; PostGISRasterTileDataset * poRTDS = (PostGISRasterTileDataset *)poDS; // Get by PKID if (poRTDS->poRDS->pszPrimaryKeyName) { //osCommand.Printf("select ST_AsBinary(st_band(%s, %d),TRUE) from %s.%s where " osCommand.Printf("select st_band(%s, %d) from %s.%s where " "%s = '%s'", poRTDS->poRDS->pszColumn, nBand, poRTDS->poRDS->pszSchema, poRTDS->poRDS->pszTable, poRTDS->poRDS->pszPrimaryKeyName, poRTDS->pszPKID); } // Get by upperleft else { osCommand.Printf("select st_band(%s, %d) from %s.%s where " "abs(ST_UpperLeftX(%s) - %.8f) < 1e-8 and abs(ST_UpperLeftY(%s) - %.8f) < 1e-8", poRTDS->poRDS->pszColumn, nBand, poRTDS->poRDS->pszSchema, poRTDS->poRDS->pszTable, poRTDS->poRDS->pszColumn, poRTDS->adfGeoTransform[GEOTRSFRM_TOPLEFT_X], poRTDS->poRDS->pszColumn, poRTDS->adfGeoTransform[GEOTRSFRM_TOPLEFT_Y]); } poResult = PQexec(poRTDS->poRDS->poConn, osCommand.c_str()); #ifdef DEBUG_QUERY CPLDebug("PostGIS_Raster", "PostGISRasterTileRasterBand::IReadBlock(): " "Query = \"%s\" --> number of rows = %d", osCommand.c_str(), poResult ? PQntuples(poResult) : 0 ); #endif if (poResult == NULL || PQresultStatus(poResult) != PGRES_TUPLES_OK || PQntuples(poResult) <= 0) { if (poResult) PQclear(poResult); ReportError(CE_Failure, CPLE_AppDefined, "Error getting block of data (upperpixel = %f, %f)", poRTDS->adfGeoTransform[GEOTRSFRM_TOPLEFT_X], poRTDS->adfGeoTransform[GEOTRSFRM_TOPLEFT_Y]); return CE_Failure; } // TODO: Check this if (bIsOffline) { CPLError(CE_Failure, CPLE_AppDefined, "This raster has outdb " "storage. This feature isn't still available"); PQclear(poResult); return CE_Failure; } /* Copy only data size, without payload */ int nExpectedDataSize = nBlockXSize * nBlockYSize * nPixelSize; GByte * pbyData = CPLHexToBinary(PQgetvalue(poResult, 0, 0), &nWKBLength); int nExpectedWKBLength = RASTER_HEADER_SIZE + BAND_SIZE(nPixelSize, nExpectedDataSize); CPLErr eRet = CE_None; if( nWKBLength != nExpectedWKBLength ) { CPLDebug("PostGIS_Raster", "nWKBLength=%d, nExpectedWKBLength=%d", nWKBLength, nExpectedWKBLength ); eRet = CE_Failure; } else { GByte * pbyDataToRead = (GByte*)GET_BAND_DATA(pbyData,1, nPixelSize, nExpectedDataSize); // Do byte-swapping if necessary */ int bIsLittleEndian = (pbyData[0] == 1); #ifdef CPL_LSB int bSwap = !bIsLittleEndian; #else int bSwap = bIsLittleEndian; #endif if( bSwap && nPixelSize > 1 ) { GDALSwapWords( pbyDataToRead, nPixelSize, nBlockXSize * nBlockYSize, nPixelSize ); } memcpy(pImage, pbyDataToRead, nExpectedDataSize); } CPLFree(pbyData); PQclear(poResult); return eRet; }