<commit_before>/*
 *  Copyright (c) 2014 Samsung Electronics Co.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 *
 *
 * @file        ocsp.cpp
 * @author      Dongsun Lee (ds73.lee@samsung.com)
 * @version     1.0
 * @brief       OCSP implementation.
 */

#include <string>
#include <ocsp.h>
#include <openssl/pem.h>
#include <openssl/ocsp.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <fts.h>
#include <unistd.h>
#include <key-manager-util.h>
#include <dpl/log/log.h>
#include <certificate-impl.h>

#include <ckm/ckm-error.h>

/* Maximum leeway in validity period: default 5 minutes */
#define MAX_VALIDITY_PERIOD     (5 * 60)

namespace CKM {

namespace {
typedef std::unique_ptr<BIO, std::function<void(BIO*)>> BioUniquePtr;

void BIO_write_and_free(BIO* bio) {
    if (!bio)
        return;

    std::vector<char> message(1024);
    int size = BIO_read(bio, message.data(), message.size());
    if (size > 0) {
        message.resize(size);
        LogError("OCSP error description:" << std::string(message.begin(), message.end()));
    }

    BIO_free_all(bio);
}

} // namespace anonymous

OCSPModule::OCSPModule() {
    // Do nothing.
}

OCSPModule::~OCSPModule(){
    // Do nothing.
}

int OCSPModule::verify(const CertificateImplVector &certificateChain) {
    bool unsupported = false; // ocsp is unsupported in certificate in chain (except root CA)

    if((systemCerts = loadSystemCerts(CKM_SYSTEM_CERTS_PATH)) == NULL) {
        LogError("Error in loadSystemCerts function");
        return CKM_API_OCSP_STATUS_INTERNAL_ERROR;
    }

    for(unsigned int i=0; i < certificateChain.size() -1; i++) {// except root certificate
        if (certificateChain[i].empty() || certificateChain[i+1].empty()) {
            LogError("Error. Broken certificate chain.");
            return CKM_API_OCSP_STATUS_INTERNAL_ERROR;
        }

        X509 *cert   = certificateChain[i].getX509();
        X509 *issuer = certificateChain[i+1].getX509();
        std::string url = certificateChain[i].getOCSPURL();

        if (url.empty()) {
            LogError("Certificate in certchain[" << i << "] does not provide OCSP extension.");
            unsupported = true;
            continue;
        }

        int result = ocsp_verify(cert, issuer, systemCerts, url);

        if(result != CKM_API_OCSP_STATUS_GOOD) {
            LogError("Fail to OCSP certification check. Errorcode=[" << result <<
                "], on certChain[" << i << "]");
            return result;
        }
    }

    if (unsupported)
        return CKM_API_OCSP_STATUS_UNSUPPORTED;

    return CKM_API_OCSP_STATUS_GOOD;
}

int OCSPModule::ocsp_verify(X509 *cert, X509 *issuer, STACK_OF(X509) *systemCerts, const std::string &constUrl) {
    OCSP_REQUEST *req = NULL;
    OCSP_RESPONSE *resp = NULL;
    OCSP_BASICRESP *bs = NULL;
    OCSP_CERTID *certid = NULL;
    BIO *cbio = NULL;
    SSL_CTX *use_ssl_ctx = NULL;
    char *host = NULL, *port = NULL, *path = NULL;
    ASN1_GENERALIZEDTIME *rev = NULL;
    ASN1_GENERALIZEDTIME *thisupd = NULL;
    ASN1_GENERALIZEDTIME *nextupd = NULL;
    int use_ssl = 0;
    int ocspStatus = -1;
    int i = 0 ,tmpIdx = 0;
    long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
    char subj_buf[256];
    int reason = 0;
    //    const char *reason_str = NULL;0
    X509_STORE *trustedStore=NULL;
    BioUniquePtr bioLogger(BIO_new(BIO_s_mem()), BIO_write_and_free);

    std::vector<char> url(constUrl.begin(), constUrl.end());

    if (!OCSP_parse_url(url.data(), &host, &port, &path, &use_ssl)) {
        /* report error */
        return CKM_API_OCSP_STATUS_INVALID_URL;
    }

    LogDebug("Host: " << host);
    LogDebug("Port: " << port);
    LogDebug("Path: " << path);
    LogDebug("Use_ssl: " << use_ssl);

    cbio = BIO_new_connect(host);
    if (cbio == NULL) {
        /*BIO_printf(bio_err, "Error creating connect BIO\n");*/
        /* report error */
        return CKM_API_OCSP_STATUS_INTERNAL_ERROR;
    }

	if (port != NULL) {
		BIO_set_conn_port(cbio, port);
    }

    if (use_ssl == 1) {
        BIO *sbio = NULL;
        use_ssl_ctx = SSL_CTX_new(SSLv23_client_method());
        if (use_ssl_ctx == NULL) {
            /* report error */
            return CKM_API_OCSP_STATUS_INTERNAL_ERROR;
        }

        SSL_CTX_set_mode(use_ssl_ctx, SSL_MODE_AUTO_RETRY);
        sbio = BIO_new_ssl(use_ssl_ctx, 1);
        if (sbio == NULL) {
            /* report error */
            return CKM_API_OCSP_STATUS_INTERNAL_ERROR;
        }

        cbio = BIO_push(sbio, cbio);
        if (cbio == NULL) {
            /* report error */
            return CKM_API_OCSP_STATUS_INTERNAL_ERROR;
        }
    }

    if (BIO_do_connect(cbio) <= 0) {
        LogDebug("Error in BIO_do_connect.");
        ERR_print_errors(bioLogger.get());
        /* report error */

        /* free stuff */
        if (host != NULL) {
            OPENSSL_free(host);
        }

        if (port != NULL) {
            OPENSSL_free(port);
        }

        if (path != NULL) {
            OPENSSL_free(path);
        }
        host = port = path = NULL;

        if (use_ssl && use_ssl_ctx) {
            SSL_CTX_free(use_ssl_ctx);
        }
        use_ssl_ctx = NULL;

        if (cbio != NULL) {
            BIO_free_all(cbio);
        }
        cbio = NULL;

        return CKM_API_OCSP_STATUS_NET_ERROR;
    }

    req = OCSP_REQUEST_new();

    if(req == NULL) {
        LogDebug("Error in OCPS_REQUEST_new");
        return CKM_API_OCSP_STATUS_INTERNAL_ERROR;
    }
    certid = OCSP_cert_to_id(NULL, cert, issuer);
    if(certid == NULL)  {
        LogDebug("Error in OCSP_cert_to_id");
        return CKM_API_OCSP_STATUS_INTERNAL_ERROR;
    }

    if(OCSP_request_add0_id(req, certid) == NULL) {
        LogDebug("Error in OCSP_request_add0_id");
        return CKM_API_OCSP_STATUS_INTERNAL_ERROR;
    }

    resp = OCSP_sendreq_bio(cbio, path, req);

    /* free some stuff we no longer need */
    if (host != NULL) {
        OPENSSL_free(host);
    }

    if (port != NULL) {
        OPENSSL_free(port);
    }

    if (path != NULL) {
        OPENSSL_free(path);
    }
    host = port = path = NULL;

    if (use_ssl && use_ssl_ctx) {
        SSL_CTX_free(use_ssl_ctx);
    }
    use_ssl_ctx = NULL;

    if (cbio != NULL) {
        BIO_free_all(cbio);
    }
    cbio = NULL;

    if (!resp) {
        /*BIO_printf(bio_err, "Error querying OCSP responsder\n");*/
        /* report error */
        /* free stuff */
        OCSP_REQUEST_free(req);
        return CKM_API_OCSP_STATUS_NET_ERROR;
    }

    i = OCSP_response_status(resp);

    if (i != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
        /* report error */
        ERR_print_errors(bioLogger.get());
        /* free stuff */
        OCSP_REQUEST_free(req);
        OCSP_RESPONSE_free(resp);
        return CKM_API_OCSP_STATUS_REMOTE_ERROR;
    }

    bs = OCSP_response_get1_basic(resp);
    if (!bs) {
        /* report error */
        ERR_print_errors(bioLogger.get());
        /* free stuff */
        OCSP_REQUEST_free(req);
        OCSP_RESPONSE_free(resp);

        LogDebug("Error in OCSP_response_get1_basic");
        return CKM_API_OCSP_STATUS_INVALID_RESPONSE;
    }

    if(systemCerts != NULL) {
        trustedStore = X509_STORE_new();
        for(tmpIdx=0; tmpIdx<sk_X509_num(systemCerts); tmpIdx++) {
            X509_STORE_add_cert(trustedStore, sk_X509_value(systemCerts, tmpIdx));
        }
        X509_STORE_add_cert(trustedStore, issuer);
    }

    int response = OCSP_basic_verify(bs, NULL, trustedStore, 0);
    if (response <= 0) {
        OCSP_REQUEST_free(req);
        OCSP_RESPONSE_free(resp);
        OCSP_BASICRESP_free(bs);
        X509_STORE_free(trustedStore);
        ERR_print_errors(bioLogger.get());
        return CKM_API_OCSP_STATUS_INVALID_RESPONSE;
    }

    if ((i = OCSP_check_nonce(req, bs)) <= 0) {
        if (i == -1) {
            ERR_print_errors(bioLogger.get());
        } else {
            /* report error */
            ERR_print_errors(bioLogger.get());
            /* free stuff */
            OCSP_REQUEST_free(req);
            OCSP_RESPONSE_free(resp);
            OCSP_BASICRESP_free(bs);
            X509_STORE_free(trustedStore);
            LogDebug("Error in OCSP_check_nonce");
            return CKM_API_OCSP_STATUS_INVALID_RESPONSE;
        }
    }

    (void)X509_NAME_oneline(X509_get_subject_name(cert), subj_buf, 255);
    if(!OCSP_resp_find_status(bs, certid, &ocspStatus, &reason,
          &rev, &thisupd, &nextupd)) {
        /* report error */
        ERR_print_errors(bioLogger.get());
        /* free stuff */
        OCSP_RESPONSE_free(resp);
        OCSP_REQUEST_free(req);
        OCSP_BASICRESP_free(bs);
        X509_STORE_free(trustedStore);

        LogDebug("Error in OCSP_resp_find_status");
        return CKM_API_OCSP_STATUS_INVALID_RESPONSE;
    }

    /* Check validity: if invalid write to output BIO so we
     * know which response this refers to.
     */
    if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
        /* report error */
        ERR_print_errors(bioLogger.get());
        /* free stuff */
        OCSP_REQUEST_free(req);
        OCSP_RESPONSE_free(resp);
        OCSP_BASICRESP_free(bs);
        X509_STORE_free(trustedStore);

        LogDebug("Error in OCSP_check_validity");
        return CKM_API_OCSP_STATUS_INVALID_RESPONSE;
    }

    if (req != NULL) {
        OCSP_REQUEST_free(req);
        req = NULL;
    }

    if (resp != NULL) {
        OCSP_RESPONSE_free(resp);
        resp = NULL;
    }

    if (bs != NULL) {
        OCSP_BASICRESP_free(bs);
        bs = NULL;
    }

    if(trustedStore != NULL) {
        X509_STORE_free(trustedStore);
        trustedStore = NULL;
    }

    switch(ocspStatus) {
    case V_OCSP_CERTSTATUS_GOOD:
        return CKM_API_OCSP_STATUS_GOOD;
    case V_OCSP_CERTSTATUS_REVOKED:
        return CKM_API_OCSP_STATUS_REVOKED;
    case V_OCSP_CERTSTATUS_UNKNOWN:
        return CKM_API_OCSP_STATUS_UNKNOWN;
    default:
        LogError("Internal openssl error: Certificate status have value is out of bound.");
        return CKM_API_OCSP_STATUS_INTERNAL_ERROR;
    }
}

} // namespace CKM

<commit_msg>Fix error connected with url parsing in ocsp module.<commit_after>/*
 *  Copyright (c) 2014 Samsung Electronics Co.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 *
 *
 * @file        ocsp.cpp
 * @author      Dongsun Lee (ds73.lee@samsung.com)
 * @version     1.0
 * @brief       OCSP implementation.
 */

#include <string>
#include <ocsp.h>
#include <openssl/pem.h>
#include <openssl/ocsp.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <fts.h>
#include <unistd.h>
#include <key-manager-util.h>
#include <dpl/log/log.h>
#include <certificate-impl.h>

#include <ckm/ckm-error.h>

/* Maximum leeway in validity period: default 5 minutes */
#define MAX_VALIDITY_PERIOD     (5 * 60)

namespace CKM {

namespace {
typedef std::unique_ptr<BIO, std::function<void(BIO*)>> BioUniquePtr;

void BIO_write_and_free(BIO* bio) {
    if (!bio)
        return;

    std::vector<char> message(1024);
    int size = BIO_read(bio, message.data(), message.size());
    if (size > 0) {
        message.resize(size);
        LogError("OCSP error description:" << std::string(message.begin(), message.end()));
    }

    BIO_free_all(bio);
}

} // namespace anonymous

OCSPModule::OCSPModule() {
    // Do nothing.
}

OCSPModule::~OCSPModule(){
    // Do nothing.
}

int OCSPModule::verify(const CertificateImplVector &certificateChain) {
    bool unsupported = false; // ocsp is unsupported in certificate in chain (except root CA)

    if((systemCerts = loadSystemCerts(CKM_SYSTEM_CERTS_PATH)) == NULL) {
        LogError("Error in loadSystemCerts function");
        return CKM_API_OCSP_STATUS_INTERNAL_ERROR;
    }

    for(unsigned int i=0; i < certificateChain.size() -1; i++) {// except root certificate
        if (certificateChain[i].empty() || certificateChain[i+1].empty()) {
            LogError("Error. Broken certificate chain.");
            return CKM_API_OCSP_STATUS_INTERNAL_ERROR;
        }

        X509 *cert   = certificateChain[i].getX509();
        X509 *issuer = certificateChain[i+1].getX509();
        std::string url = certificateChain[i].getOCSPURL();

        if (url.empty()) {
            LogError("Certificate in certchain[" << i << "] does not provide OCSP extension.");
            unsupported = true;
            continue;
        }

        int result = ocsp_verify(cert, issuer, systemCerts, url);

        if(result != CKM_API_OCSP_STATUS_GOOD) {
            LogError("Fail to OCSP certification check. Errorcode=[" << result <<
                "], on certChain[" << i << "]");
            return result;
        }
    }

    if (unsupported)
        return CKM_API_OCSP_STATUS_UNSUPPORTED;

    return CKM_API_OCSP_STATUS_GOOD;
}

int OCSPModule::ocsp_verify(X509 *cert, X509 *issuer, STACK_OF(X509) *systemCerts, const std::string &constUrl) {
    OCSP_REQUEST *req = NULL;
    OCSP_RESPONSE *resp = NULL;
    OCSP_BASICRESP *bs = NULL;
    OCSP_CERTID *certid = NULL;
    BIO *cbio = NULL;
    SSL_CTX *use_ssl_ctx = NULL;
    char *host = NULL, *port = NULL, *path = NULL;
    ASN1_GENERALIZEDTIME *rev = NULL;
    ASN1_GENERALIZEDTIME *thisupd = NULL;
    ASN1_GENERALIZEDTIME *nextupd = NULL;
    int use_ssl = 0;
    int ocspStatus = -1;
    int i = 0 ,tmpIdx = 0;
    long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
    char subj_buf[256];
    int reason = 0;
    //    const char *reason_str = NULL;0
    X509_STORE *trustedStore=NULL;
    BioUniquePtr bioLogger(BIO_new(BIO_s_mem()), BIO_write_and_free);

    std::vector<char> url(constUrl.begin(), constUrl.end());
    url.push_back(0);

    if (!OCSP_parse_url(url.data(), &host, &port, &path, &use_ssl)) {
        /* report error */
        return CKM_API_OCSP_STATUS_INVALID_URL;
    }

    LogDebug("Host: " << host);
    LogDebug("Port: " << port);
    LogDebug("Path: " << path);
    LogDebug("Use_ssl: " << use_ssl);

    cbio = BIO_new_connect(host);
    if (cbio == NULL) {
        /*BIO_printf(bio_err, "Error creating connect BIO\n");*/
        /* report error */
        return CKM_API_OCSP_STATUS_INTERNAL_ERROR;
    }

	if (port != NULL) {
		BIO_set_conn_port(cbio, port);
    }

    if (use_ssl == 1) {
        BIO *sbio = NULL;
        use_ssl_ctx = SSL_CTX_new(SSLv23_client_method());
        if (use_ssl_ctx == NULL) {
            /* report error */
            return CKM_API_OCSP_STATUS_INTERNAL_ERROR;
        }

        SSL_CTX_set_mode(use_ssl_ctx, SSL_MODE_AUTO_RETRY);
        sbio = BIO_new_ssl(use_ssl_ctx, 1);
        if (sbio == NULL) {
            /* report error */
            return CKM_API_OCSP_STATUS_INTERNAL_ERROR;
        }

        cbio = BIO_push(sbio, cbio);
        if (cbio == NULL) {
            /* report error */
            return CKM_API_OCSP_STATUS_INTERNAL_ERROR;
        }
    }

    if (BIO_do_connect(cbio) <= 0) {
        LogDebug("Error in BIO_do_connect.");
        ERR_print_errors(bioLogger.get());
        /* report error */

        /* free stuff */
        if (host != NULL) {
            OPENSSL_free(host);
        }

        if (port != NULL) {
            OPENSSL_free(port);
        }

        if (path != NULL) {
            OPENSSL_free(path);
        }
        host = port = path = NULL;

        if (use_ssl && use_ssl_ctx) {
            SSL_CTX_free(use_ssl_ctx);
        }
        use_ssl_ctx = NULL;

        if (cbio != NULL) {
            BIO_free_all(cbio);
        }
        cbio = NULL;

        return CKM_API_OCSP_STATUS_NET_ERROR;
    }

    req = OCSP_REQUEST_new();

    if(req == NULL) {
        LogDebug("Error in OCPS_REQUEST_new");
        return CKM_API_OCSP_STATUS_INTERNAL_ERROR;
    }
    certid = OCSP_cert_to_id(NULL, cert, issuer);
    if(certid == NULL)  {
        LogDebug("Error in OCSP_cert_to_id");
        return CKM_API_OCSP_STATUS_INTERNAL_ERROR;
    }

    if(OCSP_request_add0_id(req, certid) == NULL) {
        LogDebug("Error in OCSP_request_add0_id");
        return CKM_API_OCSP_STATUS_INTERNAL_ERROR;
    }

    resp = OCSP_sendreq_bio(cbio, path, req);

    /* free some stuff we no longer need */
    if (host != NULL) {
        OPENSSL_free(host);
    }

    if (port != NULL) {
        OPENSSL_free(port);
    }

    if (path != NULL) {
        OPENSSL_free(path);
    }
    host = port = path = NULL;

    if (use_ssl && use_ssl_ctx) {
        SSL_CTX_free(use_ssl_ctx);
    }
    use_ssl_ctx = NULL;

    if (cbio != NULL) {
        BIO_free_all(cbio);
    }
    cbio = NULL;

    if (!resp) {
        /*BIO_printf(bio_err, "Error querying OCSP responsder\n");*/
        /* report error */
        /* free stuff */
        OCSP_REQUEST_free(req);
        return CKM_API_OCSP_STATUS_NET_ERROR;
    }

    i = OCSP_response_status(resp);

    if (i != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
        /* report error */
        ERR_print_errors(bioLogger.get());
        /* free stuff */
        OCSP_REQUEST_free(req);
        OCSP_RESPONSE_free(resp);
        return CKM_API_OCSP_STATUS_REMOTE_ERROR;
    }

    bs = OCSP_response_get1_basic(resp);
    if (!bs) {
        /* report error */
        ERR_print_errors(bioLogger.get());
        /* free stuff */
        OCSP_REQUEST_free(req);
        OCSP_RESPONSE_free(resp);

        LogDebug("Error in OCSP_response_get1_basic");
        return CKM_API_OCSP_STATUS_INVALID_RESPONSE;
    }

    if(systemCerts != NULL) {
        trustedStore = X509_STORE_new();
        for(tmpIdx=0; tmpIdx<sk_X509_num(systemCerts); tmpIdx++) {
            X509_STORE_add_cert(trustedStore, sk_X509_value(systemCerts, tmpIdx));
        }
        X509_STORE_add_cert(trustedStore, issuer);
    }

    int response = OCSP_basic_verify(bs, NULL, trustedStore, 0);
    if (response <= 0) {
        OCSP_REQUEST_free(req);
        OCSP_RESPONSE_free(resp);
        OCSP_BASICRESP_free(bs);
        X509_STORE_free(trustedStore);
        ERR_print_errors(bioLogger.get());
        return CKM_API_OCSP_STATUS_INVALID_RESPONSE;
    }

    if ((i = OCSP_check_nonce(req, bs)) <= 0) {
        if (i == -1) {
            ERR_print_errors(bioLogger.get());
        } else {
            /* report error */
            ERR_print_errors(bioLogger.get());
            /* free stuff */
            OCSP_REQUEST_free(req);
            OCSP_RESPONSE_free(resp);
            OCSP_BASICRESP_free(bs);
            X509_STORE_free(trustedStore);
            LogDebug("Error in OCSP_check_nonce");
            return CKM_API_OCSP_STATUS_INVALID_RESPONSE;
        }
    }

    (void)X509_NAME_oneline(X509_get_subject_name(cert), subj_buf, 255);
    if(!OCSP_resp_find_status(bs, certid, &ocspStatus, &reason,
          &rev, &thisupd, &nextupd)) {
        /* report error */
        ERR_print_errors(bioLogger.get());
        /* free stuff */
        OCSP_RESPONSE_free(resp);
        OCSP_REQUEST_free(req);
        OCSP_BASICRESP_free(bs);
        X509_STORE_free(trustedStore);

        LogDebug("Error in OCSP_resp_find_status");
        return CKM_API_OCSP_STATUS_INVALID_RESPONSE;
    }

    /* Check validity: if invalid write to output BIO so we
     * know which response this refers to.
     */
    if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
        /* report error */
        ERR_print_errors(bioLogger.get());
        /* free stuff */
        OCSP_REQUEST_free(req);
        OCSP_RESPONSE_free(resp);
        OCSP_BASICRESP_free(bs);
        X509_STORE_free(trustedStore);

        LogDebug("Error in OCSP_check_validity");
        return CKM_API_OCSP_STATUS_INVALID_RESPONSE;
    }

    if (req != NULL) {
        OCSP_REQUEST_free(req);
        req = NULL;
    }

    if (resp != NULL) {
        OCSP_RESPONSE_free(resp);
        resp = NULL;
    }

    if (bs != NULL) {
        OCSP_BASICRESP_free(bs);
        bs = NULL;
    }

    if(trustedStore != NULL) {
        X509_STORE_free(trustedStore);
        trustedStore = NULL;
    }

    switch(ocspStatus) {
    case V_OCSP_CERTSTATUS_GOOD:
        return CKM_API_OCSP_STATUS_GOOD;
    case V_OCSP_CERTSTATUS_REVOKED:
        return CKM_API_OCSP_STATUS_REVOKED;
    case V_OCSP_CERTSTATUS_UNKNOWN:
        return CKM_API_OCSP_STATUS_UNKNOWN;
    default:
        LogError("Internal openssl error: Certificate status have value is out of bound.");
        return CKM_API_OCSP_STATUS_INTERNAL_ERROR;
    }
}

} // namespace CKM

<|endoftext|>


<commit_before>#include <bits/stdc++.h>
#include <stdio.h>

int main(){

  return 0;

}
<commit_msg>Update T.cpp<commit_after>#include <bits/stdc++.h>
using namespace std;
#define CONSTANT VALUE

int main(void){
    double R,A;
    scanf("%lf",&R);
    printf("A=%.4f\n",A);   //Rounding Values.
    return 0;
}
<|endoftext|>


<commit_before>/**************************************************************************/
/*!
    @file     Adafruit_FRAM_SPI.cpp
    @author   KTOWN (Adafruit Industries)
    @license  BSD (see license.txt)

    Driver for the Adafruit SPI FRAM breakout.

    Adafruit invests time and resources providing this open source code,
    please support Adafruit and open-source hardware by purchasing
    products from Adafruit!

    @section  HISTORY

    v1.0 - First release
*/
/**************************************************************************/
#include <avr/pgmspace.h>
#include <util/delay.h>
#include <stdlib.h>
#include <math.h>

#include "Adafruit_FRAM_SPI.h"

/*========================================================================*/
/*                            CONSTRUCTORS                                */
/*========================================================================*/

/**************************************************************************/
/*!
    Constructor
*/
/**************************************************************************/
Adafruit_FRAM_SPI::Adafruit_FRAM_SPI(int8_t cs)
{
  _cs = cs;
  _clk = _mosi = _miso = -1;
  _framInitialised = false;
}

Adafruit_FRAM_SPI::Adafruit_FRAM_SPI(int8_t clk, int8_t miso, int8_t mosi, int8_t cs)
{
  _cs = cs; _clk = clk; _mosi = mosi; _miso = miso;
  _framInitialised = false;
}

/*========================================================================*/
/*                           PUBLIC FUNCTIONS                             */
/*========================================================================*/

/**************************************************************************/
/*!
    Initializes SPI and configures the chip (call this function before
    doing anything else)
*/
/**************************************************************************/
boolean Adafruit_FRAM_SPI::begin(void)
{
  /* Configure SPI */
  pinMode(_cs, OUTPUT);
  digitalWrite(_cs, HIGH);

  if (_clk == -1) { // hardware SPI!
    SPI.begin();
    SPI.setClockDivider(SPI_CLOCK_DIV2); // highest speed!
    SPI.setDataMode(SPI_MODE0);
  } else {
    pinMode(_clk, OUTPUT);
    pinMode(_mosi, OUTPUT);
    pinMode(_miso, INPUT);
  }

  /* Make sure we're actually connected */
  uint8_t manufID;
  uint16_t prodID;
  getDeviceID(&manufID, &prodID);
  if (manufID != 0x04)
  {
    //Serial.print("Unexpected Manufacturer ID: 0x"); Serial.println(manufID, HEX);
    return false;
  }
  if (prodID != 0x0302)
  {
    //Serial.print("Unexpected Product ID: 0x"); Serial.println(prodID, HEX);
    return false;
  }

  /* Everything seems to be properly initialised and connected */
  _framInitialised = true;

  return true;
}

/**************************************************************************/
/*!
    @brief  Enables or disables writing to the SPI flash

    @params[in] enable
                True enables writes, false disables writes
*/
/**************************************************************************/
void Adafruit_FRAM_SPI::writeEnable (bool enable)
{
  digitalWrite(_cs, LOW);
  if (enable)
  {
    SPItransfer(OPCODE_WREN);
  }
  else
  {
    SPItransfer(OPCODE_WRDI);
  }
  digitalWrite(_cs, HIGH);
}

/**************************************************************************/
/*!
    @brief  Writes a byte at the specific FRAM address

    @params[in] addr
                The 16-bit address to write to in FRAM memory
    @params[in] i2cAddr
                The 8-bit value to write at framAddr
*/
/**************************************************************************/
void Adafruit_FRAM_SPI::write8 (uint16_t addr, uint8_t value)
{
  digitalWrite(_cs, LOW);
  SPItransfer(OPCODE_WRITE);
  SPItransfer((uint8_t)(addr >> 8));
  SPItransfer((uint8_t)(addr & 0xFF));
  SPItransfer(value);
  /* CS on the rising edge commits the WRITE */
  digitalWrite(_cs, HIGH);
}

/**************************************************************************/
/*!
    @brief  Reads an 8 bit value from the specified FRAM address

    @params[in] addr
                The 16-bit address to read from in FRAM memory

    @returns    The 8-bit value retrieved at framAddr
*/
/**************************************************************************/
uint8_t Adafruit_FRAM_SPI::read8 (uint16_t addr)
{
  digitalWrite(_cs, LOW);
  SPItransfer(OPCODE_READ);
  SPItransfer((uint8_t)(addr >> 8));
  SPItransfer((uint8_t)(addr & 0xFF));
  uint8_t x = SPItransfer(0);
  digitalWrite(_cs, HIGH);
  return x;
}

/**************************************************************************/
/*!
    @brief  Reads the Manufacturer ID and the Product ID from the IC

    @params[out]  manufacturerID
                  The 8-bit manufacturer ID (Fujitsu = 0x04)
    @params[out]  productID
                  The memory density (bytes 15..8) and proprietary
                  Product ID fields (bytes 7..0). Should be 0x0302 for
                  the MB85RS64VPNF-G-JNERE1.
*/
/**************************************************************************/
void Adafruit_FRAM_SPI::getDeviceID(uint8_t *manufacturerID, uint16_t *productID)
{
  uint8_t a[4] = { 0, 0, 0, 0 };
  uint8_t results;

  digitalWrite(_cs, LOW);
  SPItransfer(OPCODE_RDID);
  a[0] = SPItransfer(0);
  a[1] = SPItransfer(0);
  a[2] = SPItransfer(0);
  a[3] = SPItransfer(0);
  digitalWrite(_cs, HIGH);

  /* Shift values to separate manuf and prod IDs */
  /* See p.10 of http://www.fujitsu.com/downloads/MICRO/fsa/pdf/products/memory/fram/MB85RS64V-DS501-00015-4v0-E.pdf */
  *manufacturerID = (a[0]);
  *productID = (a[2] << 8) + a[3];
}

/**************************************************************************/
/*!
    @brief  Reads the status register
*/
/**************************************************************************/
uint8_t Adafruit_FRAM_SPI::getStatusRegister(void)
{
  uint8_t reg = 0;
  digitalWrite(_cs, LOW);
  SPItransfer(OPCODE_RDSR);
  reg = SPItransfer(0);
  digitalWrite(_cs, HIGH);
  return reg;
}

/**************************************************************************/
/*!
    @brief  Sets the status register
*/
/**************************************************************************/
void Adafruit_FRAM_SPI::setStatusRegister(uint8_t value)
{
  digitalWrite(_cs, LOW);
  SPItransfer(OPCODE_WRSR);
  SPItransfer(value);
  digitalWrite(_cs, HIGH);
}

uint8_t Adafruit_FRAM_SPI::SPItransfer(uint8_t x) {
  if (_clk == -1) {
    return SPI.transfer(x);
  } else {
    // Serial.println("Software SPI");
    uint8_t reply = 0;
    for (int i=7; i>=0; i--) {
      reply <<= 1;
      digitalWrite(_clk, LOW);
      digitalWrite(_mosi, x & (1<<i));
      digitalWrite(_clk, HIGH);
      if (digitalRead(_miso))
	reply |= 1;
    }
    return reply;
  }
}
<commit_msg>Support Arduino Due<commit_after>/**************************************************************************/
/*!
    @file     Adafruit_FRAM_SPI.cpp
    @author   KTOWN (Adafruit Industries)
    @license  BSD (see license.txt)

    Driver for the Adafruit SPI FRAM breakout.

    Adafruit invests time and resources providing this open source code,
    please support Adafruit and open-source hardware by purchasing
    products from Adafruit!

    @section  HISTORY

    v1.0 - First release
*/
/**************************************************************************/
//#include <avr/pgmspace.h>
//#include <util/delay.h>
#include <stdlib.h>
#include <math.h>

#include "Adafruit_FRAM_SPI.h"

/*========================================================================*/
/*                            CONSTRUCTORS                                */
/*========================================================================*/

/**************************************************************************/
/*!
    Constructor
*/
/**************************************************************************/
Adafruit_FRAM_SPI::Adafruit_FRAM_SPI(int8_t cs)
{
  _cs = cs;
  _clk = _mosi = _miso = -1;
  _framInitialised = false;
}

Adafruit_FRAM_SPI::Adafruit_FRAM_SPI(int8_t clk, int8_t miso, int8_t mosi, int8_t cs)
{
  _cs = cs; _clk = clk; _mosi = mosi; _miso = miso;
  _framInitialised = false;
}

/*========================================================================*/
/*                           PUBLIC FUNCTIONS                             */
/*========================================================================*/

/**************************************************************************/
/*!
    Initializes SPI and configures the chip (call this function before
    doing anything else)
*/
/**************************************************************************/
boolean Adafruit_FRAM_SPI::begin(void)
{
  /* Configure SPI */
  pinMode(_cs, OUTPUT);
  digitalWrite(_cs, HIGH);

  if (_clk == -1) { // hardware SPI!
    SPI.begin();

#ifdef __SAM3X8E__
    SPI.setClockDivider (9); // 9.3 MHz
#else
    SPI.setClockDivider (SPI_CLOCK_DIV2); // 8 MHz
#endif

    SPI.setDataMode(SPI_MODE0);
  } else {
    pinMode(_clk, OUTPUT);
    pinMode(_mosi, OUTPUT);
    pinMode(_miso, INPUT);
  }

  /* Make sure we're actually connected */
  uint8_t manufID;
  uint16_t prodID;
  getDeviceID(&manufID, &prodID);
  if (manufID != 0x04)
  {
    //Serial.print("Unexpected Manufacturer ID: 0x"); Serial.println(manufID, HEX);
    return false;
  }
  if (prodID != 0x0302)
  {
    //Serial.print("Unexpected Product ID: 0x"); Serial.println(prodID, HEX);
    return false;
  }

  /* Everything seems to be properly initialised and connected */
  _framInitialised = true;

  return true;
}

/**************************************************************************/
/*!
    @brief  Enables or disables writing to the SPI flash

    @params[in] enable
                True enables writes, false disables writes
*/
/**************************************************************************/
void Adafruit_FRAM_SPI::writeEnable (bool enable)
{
  digitalWrite(_cs, LOW);
  if (enable)
  {
    SPItransfer(OPCODE_WREN);
  }
  else
  {
    SPItransfer(OPCODE_WRDI);
  }
  digitalWrite(_cs, HIGH);
}

/**************************************************************************/
/*!
    @brief  Writes a byte at the specific FRAM address

    @params[in] addr
                The 16-bit address to write to in FRAM memory
    @params[in] i2cAddr
                The 8-bit value to write at framAddr
*/
/**************************************************************************/
void Adafruit_FRAM_SPI::write8 (uint16_t addr, uint8_t value)
{
  digitalWrite(_cs, LOW);
  SPItransfer(OPCODE_WRITE);
  SPItransfer((uint8_t)(addr >> 8));
  SPItransfer((uint8_t)(addr & 0xFF));
  SPItransfer(value);
  /* CS on the rising edge commits the WRITE */
  digitalWrite(_cs, HIGH);
}

/**************************************************************************/
/*!
    @brief  Reads an 8 bit value from the specified FRAM address

    @params[in] addr
                The 16-bit address to read from in FRAM memory

    @returns    The 8-bit value retrieved at framAddr
*/
/**************************************************************************/
uint8_t Adafruit_FRAM_SPI::read8 (uint16_t addr)
{
  digitalWrite(_cs, LOW);
  SPItransfer(OPCODE_READ);
  SPItransfer((uint8_t)(addr >> 8));
  SPItransfer((uint8_t)(addr & 0xFF));
  uint8_t x = SPItransfer(0);
  digitalWrite(_cs, HIGH);
  return x;
}

/**************************************************************************/
/*!
    @brief  Reads the Manufacturer ID and the Product ID from the IC

    @params[out]  manufacturerID
                  The 8-bit manufacturer ID (Fujitsu = 0x04)
    @params[out]  productID
                  The memory density (bytes 15..8) and proprietary
                  Product ID fields (bytes 7..0). Should be 0x0302 for
                  the MB85RS64VPNF-G-JNERE1.
*/
/**************************************************************************/
void Adafruit_FRAM_SPI::getDeviceID(uint8_t *manufacturerID, uint16_t *productID)
{
  uint8_t a[4] = { 0, 0, 0, 0 };
  uint8_t results;

  digitalWrite(_cs, LOW);
  SPItransfer(OPCODE_RDID);
  a[0] = SPItransfer(0);
  a[1] = SPItransfer(0);
  a[2] = SPItransfer(0);
  a[3] = SPItransfer(0);
  digitalWrite(_cs, HIGH);

  /* Shift values to separate manuf and prod IDs */
  /* See p.10 of http://www.fujitsu.com/downloads/MICRO/fsa/pdf/products/memory/fram/MB85RS64V-DS501-00015-4v0-E.pdf */
  *manufacturerID = (a[0]);
  *productID = (a[2] << 8) + a[3];
}

/**************************************************************************/
/*!
    @brief  Reads the status register
*/
/**************************************************************************/
uint8_t Adafruit_FRAM_SPI::getStatusRegister(void)
{
  uint8_t reg = 0;
  digitalWrite(_cs, LOW);
  SPItransfer(OPCODE_RDSR);
  reg = SPItransfer(0);
  digitalWrite(_cs, HIGH);
  return reg;
}

/**************************************************************************/
/*!
    @brief  Sets the status register
*/
/**************************************************************************/
void Adafruit_FRAM_SPI::setStatusRegister(uint8_t value)
{
  digitalWrite(_cs, LOW);
  SPItransfer(OPCODE_WRSR);
  SPItransfer(value);
  digitalWrite(_cs, HIGH);
}

uint8_t Adafruit_FRAM_SPI::SPItransfer(uint8_t x) {
  if (_clk == -1) {
    return SPI.transfer(x);
  } else {
    // Serial.println("Software SPI");
    uint8_t reply = 0;
    for (int i=7; i>=0; i--) {
      reply <<= 1;
      digitalWrite(_clk, LOW);
      digitalWrite(_mosi, x & (1<<i));
      digitalWrite(_clk, HIGH);
      if (digitalRead(_miso))
	reply |= 1;
    }
    return reply;
  }
}
<|endoftext|>


<commit_before>/***************************************************
  This is a library for the Adafruit Thermocouple Sensor w/MAX31855K

  Designed specifically to work with the Adafruit Thermocouple Sensor
  ----> https://www.adafruit.com/products/269

  These displays use SPI to communicate, 3 pins are required to
  interface
  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!

  Written by Limor Fried/Ladyada for Adafruit Industries.
  BSD license, all text above must be included in any redistribution
 ****************************************************/

#include "Adafruit_MAX31855.h"
#if defined(__AVR__)
#include <avr/pgmspace.h>
#endif
#include <stdlib.h>
#include <SPI.h>

Adafruit_MAX31855::Adafruit_MAX31855(int8_t SCLK, int8_t CS, int8_t MISO) {
  sclk = SCLK;
  cs = CS;
  miso = MISO;
  hSPI = 0;

  //define pin modes
  pinMode(cs, OUTPUT);
  pinMode(sclk, OUTPUT);
  pinMode(miso, INPUT);

  digitalWrite(cs, HIGH);
}

Adafruit_MAX31855::Adafruit_MAX31855(int8_t CS) {
  cs = CS;
  hSPI = 1;

  // Define CS pin mode
  pinMode(cs, OUTPUT);

  // Configure hardware SPI
  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE0);
  SPI.setClockDivider(SPI_CLOCK_DIV4);

  digitalWrite(cs, HIGH);
}

double Adafruit_MAX31855::internal(void) {
  uint16_t internal = (data >> 4) & 0x0fff;
  if (internal & 0x800)	// sign extension
    internal |= 0xf000;

  return internal * 0.0625;
}

double Adafruit_MAX31855::celsius(void) {
  if (data & 0x7)
    return NAN;		// uh oh, a serious problem!

  uint16_t tc = data >> 18;
  if (tc & 0x2000)	// sign extension
    tc |= 0xc000;

  return (int16_t)tc * 0.25;
}

void Adafruit_MAX31855::readData(void) {
  if (hSPI) {
    hspiread32();
    return;
  }

  digitalWrite(sclk, LOW);
  delayMicroseconds(1);
  digitalWrite(cs, LOW);
  delayMicroseconds(1);

  data = 0;
  for (int i = 32; i; i--) {
    digitalWrite(sclk, LOW);
    delayMicroseconds(1);
    data <<= 1;
    if (digitalRead(miso))
      data |= 1;

    digitalWrite(sclk, HIGH);
    delayMicroseconds(1);
  }

  digitalWrite(cs, HIGH);
}

void Adafruit_MAX31855::hspiread32(void) {
  digitalWrite(cs, LOW);
  delayMicroseconds(1);

  data = 0;
  for (uint8_t i = 4; i; i--) {
    data <<= 8;
    data |= SPI.transfer(0x00);
  }

  digitalWrite(cs, HIGH);
}
<commit_msg>Use SPI transactions<commit_after>/***************************************************
  This is a library for the Adafruit Thermocouple Sensor w/MAX31855K

  Designed specifically to work with the Adafruit Thermocouple Sensor
  ----> https://www.adafruit.com/products/269

  These displays use SPI to communicate, 3 pins are required to
  interface
  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!

  Written by Limor Fried/Ladyada for Adafruit Industries.
  BSD license, all text above must be included in any redistribution
 ****************************************************/

#include "Adafruit_MAX31855.h"
#if defined(__AVR__)
#include <avr/pgmspace.h>
#endif
#include <stdlib.h>
#include <SPI.h>

Adafruit_MAX31855::Adafruit_MAX31855(int8_t SCLK, int8_t CS, int8_t MISO) {
  sclk = SCLK;
  cs = CS;
  miso = MISO;
  hSPI = 0;

  //define pin modes
  pinMode(cs, OUTPUT);
  pinMode(sclk, OUTPUT);
  pinMode(miso, INPUT);

  digitalWrite(cs, HIGH);
}

Adafruit_MAX31855::Adafruit_MAX31855(int8_t CS) {
  cs = CS;
  hSPI = 1;

  // Define CS pin mode
  pinMode(cs, OUTPUT);

  digitalWrite(cs, HIGH);
}

double Adafruit_MAX31855::internal(void) {
  uint16_t internal = (data >> 4) & 0x0fff;
  if (internal & 0x800)	// sign extension
    internal |= 0xf000;

  return internal * 0.0625;
}

double Adafruit_MAX31855::celsius(void) {
  if (data & 0x7)
    return NAN;		// uh oh, a serious problem!

  uint16_t tc = data >> 18;
  if (tc & 0x2000)	// sign extension
    tc |= 0xc000;

  return (int16_t)tc * 0.25;
}

void Adafruit_MAX31855::readData(void) {
  if (hSPI) {
    hspiread32();
    return;
  }

  digitalWrite(sclk, LOW);
  delayMicroseconds(1);
  digitalWrite(cs, LOW);
  delayMicroseconds(1);

  data = 0;
  for (int i = 32; i; i--) {
    digitalWrite(sclk, LOW);
    delayMicroseconds(1);
    data <<= 1;
    if (digitalRead(miso))
      data |= 1;

    digitalWrite(sclk, HIGH);
    delayMicroseconds(1);
  }

  digitalWrite(cs, HIGH);
}

void Adafruit_MAX31855::hspiread32(void) {
  SPI.beginTransaction(SPISettings(4000000, MSBFIRST, SPI_MODE0));

  digitalWrite(cs, LOW);
  delayMicroseconds(1);

  data = 0;
  for (uint8_t i = 4; i; i--) {
    data <<= 8;
    data |= SPI.transfer(0x00);
  }

  digitalWrite(cs, HIGH);

  SPI.endTransaction();
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: SlsPageCacheManager.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 19:04:41 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"

#include "cache/SlsPageCacheManager.hxx"

#include "SlsBitmapCache.hxx"
#include "view/SlideSorterView.hxx"
#include "model/SlideSorterModel.hxx"

#include <deque>
#include <map>
#include <boost/weak_ptr.hpp>

namespace {

/** Collection of data that is stored for all active preview caches.
*/
class CacheDescriptor
{
public:
    SdDrawDocument* mpDocument;
    Size maPreviewSize;

    CacheDescriptor(SdDrawDocument* pDocument, const Size& rPreviewSize)
        :mpDocument(pDocument),maPreviewSize(rPreviewSize)
    {}
    /// Test for equality with respect to all members.
    class Equal {public: bool operator() (
        const CacheDescriptor& rDescriptor1, const CacheDescriptor& rDescriptor2) const {
        return rDescriptor1.mpDocument==rDescriptor2.mpDocument
            && rDescriptor1.maPreviewSize==rDescriptor2.maPreviewSize;
    } };
    /// Hash function that takes all members into account.
    class Hash {public: size_t operator() (const CacheDescriptor& rDescriptor) const {
        return (size_t)rDescriptor.mpDocument + rDescriptor.maPreviewSize.Width();
    } };
};

/** Collection of data that is stored for the inactive, recently used
    caches.
*/
class RecentlyUsedCacheDescriptor
{
public:
    SdDrawDocument* mpDocument;
    Size maPreviewSize;
    ::boost::shared_ptr< ::sd::slidesorter::cache::PageCacheManager::Cache> mpCache;

    RecentlyUsedCacheDescriptor(
        SdDrawDocument* pDocument,
        const Size& rPreviewSize,
        const ::boost::shared_ptr< ::sd::slidesorter::cache::PageCacheManager::Cache>& rpCache)
        :mpDocument(pDocument),maPreviewSize(rPreviewSize),mpCache(rpCache)
    {}
};

/** The list of recently used caches is organized as queue.  When elements
    are added the list is shortened to the maximally allowed number of
    elements by removing the least recently used elements.
*/
typedef ::std::deque<RecentlyUsedCacheDescriptor> RecentlyUsedQueue;

/** Compare the caches by preview size.  Those that match the given size
    come first, then, regardless of the given size, the largest ones before
    the smaller ones.
*/
class BestFittingCacheComparer
{
public:
    BestFittingCacheComparer (const Size& rPreferredSize)
        : maPreferredSize(rPreferredSize)
    {}
    bool operator()(const ::sd::slidesorter::cache::PageCacheManager::BestFittingPageCaches::value_type& rElement1,
        const ::sd::slidesorter::cache::PageCacheManager::BestFittingPageCaches::value_type& rElement2)
    {
        if (rElement1.first == maPreferredSize)
            return true;
        else if (rElement2.first == maPreferredSize)
            return false;
        else
            return (rElement1.first.Width()*rElement1.first.Height()
                > rElement2.first.Width()*rElement2.first.Height());
    }

private:
    Size maPreferredSize;
};

} // end of anonymous namespace

namespace sd { namespace slidesorter { namespace cache {

/** Container for the active caches.
*/
class PageCacheManager::PageCacheContainer
    : public ::std::hash_map<CacheDescriptor,
                             ::boost::shared_ptr<PageCacheManager::Cache>,
                             CacheDescriptor::Hash,
                             CacheDescriptor::Equal>
{
public:
    PageCacheContainer (void) {}

    /** Compare entries in the cache container with respect to the cache
        address only.
    */
    class CompareWithCache { public:
        CompareWithCache(const ::boost::shared_ptr<PageCacheManager::Cache>& rpCache)
            : mpCache(rpCache) {}
        bool operator () (const PageCacheContainer::value_type& rValue)
        { return rValue.second == mpCache; }
    private:
        ::boost::shared_ptr<PageCacheManager::Cache> mpCache;
    };
};

/** The recently used caches are stored in one queue for each document.
*/
class PageCacheManager::RecentlyUsedPageCaches
    : public ::std::map<SdDrawDocument*,RecentlyUsedQueue>
{
public:
    RecentlyUsedPageCaches (void) {};
};

class PageCacheManager::Deleter
{
public:
    void operator() (PageCacheManager* pObject) { delete pObject; }
};

//===== PageCacheManager ====================================================

::boost::weak_ptr<PageCacheManager> PageCacheManager::mpInstance;

::boost::shared_ptr<PageCacheManager> PageCacheManager::Instance (void)
{
    ::boost::shared_ptr<PageCacheManager> pInstance;

    ::osl::MutexGuard aGuard (::osl::Mutex::getGlobalMutex());

    pInstance = mpInstance.lock();
    if (pInstance.get() == NULL)
    {
        pInstance = ::boost::shared_ptr<PageCacheManager>(
            new PageCacheManager(),
            PageCacheManager::Deleter());
        mpInstance = pInstance;
    }

    return pInstance;
}

PageCacheManager::PageCacheManager (void)
    : mpPageCaches(new PageCacheContainer()),
      mpRecentlyUsedPageCaches(new RecentlyUsedPageCaches()),
      mnMaximalRecentlyCacheCount(2)
{
}

PageCacheManager::~PageCacheManager (void)
{
}

::boost::shared_ptr<PageCacheManager::Cache> PageCacheManager::GetCache (
    SdDrawDocument* pDocument,
    const Size& rPreviewSize)
{
    ::boost::shared_ptr<Cache> pResult;

    // Look for the cache in the list of active caches.
    CacheDescriptor aKey (pDocument, rPreviewSize);
    PageCacheContainer::iterator iCache (mpPageCaches->find(aKey));
    if (iCache != mpPageCaches->end())
        pResult = iCache->second;

    // Look for the cache in the list of recently used caches.
    if (pResult.get() == NULL)
        pResult = GetRecentlyUsedCache(pDocument, rPreviewSize);

    // Create the cache when no suitable one does exist.
    if (pResult.get() == NULL)
        pResult.reset(new Cache());

    // The cache may be newly created and thus empty or is old and may
    // contain previews that are not up-to-date.  Recycle previews from
    // other caches to fill in the holes.
    Recycle(pResult, pDocument,rPreviewSize);

    // Put the new (or old) cache into the container.
    if (pResult.get() != NULL)
        mpPageCaches->insert(PageCacheContainer::value_type(aKey, pResult));

    OSL_TRACE("returning cache %x for document %x and size %d %d",
        pResult.get(), pDocument, rPreviewSize.Width(),rPreviewSize.Height());

    return pResult;
}

void PageCacheManager::Recycle (
    const ::boost::shared_ptr<Cache>& rpCache,
    SdDrawDocument* pDocument,
    const Size& rPreviewSize)
{
    BestFittingPageCaches aCaches;

    // Add bitmap caches from active caches.
    PageCacheContainer::iterator iActiveCache;
    for (iActiveCache=mpPageCaches->begin(); iActiveCache!=mpPageCaches->end(); ++iActiveCache)
    {
        if (iActiveCache->first.mpDocument == pDocument)
            aCaches.push_back(BestFittingPageCaches::value_type(
                iActiveCache->first.maPreviewSize, iActiveCache->second));
    }

    // Add bitmap caches from recently used caches.
    RecentlyUsedPageCaches::iterator iQueue (mpRecentlyUsedPageCaches->find(pDocument));
    if (iQueue != mpRecentlyUsedPageCaches->end())
    {
        RecentlyUsedQueue::const_iterator iRecentCache;
        for (iRecentCache=iQueue->second.begin();iRecentCache!=iQueue->second.end();++iRecentCache)
            aCaches.push_back(BestFittingPageCaches::value_type(
                iRecentCache->maPreviewSize, iRecentCache->mpCache));
    }

    ::std::sort(aCaches.begin(), aCaches.end(), BestFittingCacheComparer(rPreviewSize));

    BestFittingPageCaches::const_iterator iBestCache;
    for (iBestCache=aCaches.begin(); iBestCache!=aCaches.end(); ++iBestCache)
    {
        rpCache->Recycle(*iBestCache->second);
    }
}

void PageCacheManager::ReleaseCache (const ::boost::shared_ptr<Cache>& rpCache)
{
    PageCacheContainer::iterator iCache (::std::find_if(
        mpPageCaches->begin(),
        mpPageCaches->end(),
        PageCacheContainer::CompareWithCache(rpCache)));

    if (iCache != mpPageCaches->end())
    {
        OSL_ASSERT(iCache->second == rpCache);

        PutRecentlyUsedCache(iCache->first.mpDocument,iCache->first.maPreviewSize,rpCache);

        mpPageCaches->erase(iCache);
    }
}

::boost::shared_ptr<PageCacheManager::Cache> PageCacheManager::ChangeSize (
    const ::boost::shared_ptr<Cache>& rpCache,
    const Size& rOldPreviewSize,
    const Size& rNewPreviewSize)
{
    OSL_TRACE("changing size of cache %x from %d %d to %d %d",
        rpCache.get(),
        rOldPreviewSize.Width(),rOldPreviewSize.Height(),
        rNewPreviewSize.Width(),rNewPreviewSize.Height());
    ::boost::shared_ptr<Cache> pResult;

    if (rpCache.get() != NULL)
    {
        // Look up the given cache in the list of active caches.
        PageCacheContainer::iterator iCacheToChange (::std::find_if(
            mpPageCaches->begin(),
            mpPageCaches->end(),
            PageCacheContainer::CompareWithCache(rpCache)));
        OSL_ASSERT(iCacheToChange != mpPageCaches->end());
        if (iCacheToChange != mpPageCaches->end())
        {
            OSL_ASSERT(iCacheToChange->second == rpCache);

            // Now, we can change the preview size of the existing one by
            // removing the cache from the list and re-insert it with the
            // updated size.
            mpPageCaches->erase(iCacheToChange);
            mpPageCaches->insert(PageCacheContainer::value_type(
                CacheDescriptor(iCacheToChange->first.mpDocument,rNewPreviewSize),
                rpCache));

            pResult = rpCache;
        }
    }

    return pResult;
}

void PageCacheManager::InvalidatePreviewBitmap (
    SdDrawDocument* pDocument,
    const SdrPage* pKey)
{
    if (pDocument!=NULL)
    {
        // Iterate over all caches that are currently in use and invalidate
        // the previews in those that belong to the document.
        PageCacheContainer::iterator iCache;
        for (iCache=mpPageCaches->begin(); iCache!=mpPageCaches->end();  ++iCache)
            if (iCache->first.mpDocument == pDocument)
                iCache->second->InvalidateBitmap(pKey);

        // Invalidate the previews in the recently used caches belonging to
        // the given document.
        RecentlyUsedPageCaches::iterator iQueue (mpRecentlyUsedPageCaches->find(pDocument));
        if (iQueue != mpRecentlyUsedPageCaches->end())
        {
            RecentlyUsedQueue::const_iterator iCache;
            for (iCache=iQueue->second.begin(); iCache!=iQueue->second.end(); ++iCache)
                iCache->mpCache->InvalidateBitmap(pKey);
        }
    }
}

void PageCacheManager::InvalidateAllCaches (void)
{
    // Iterate over all caches that are currently in use and invalidate
    // them.
    PageCacheContainer::iterator iCache;
    for (iCache=mpPageCaches->begin(); iCache!=mpPageCaches->end();  ++iCache)
        iCache->second->InvalidateCache();

    // Remove all recently used caches, there is not much sense in storing
    // invalidated and unused caches.
    mpRecentlyUsedPageCaches->clear();
}

::boost::shared_ptr<PageCacheManager::Cache> PageCacheManager::GetRecentlyUsedCache (
    SdDrawDocument* pDocument,
    const Size& rPreviewSize)
{
    ::boost::shared_ptr<Cache> pCache;

    // Look for the cache in the list of recently used caches.
    RecentlyUsedPageCaches::iterator iQueue (mpRecentlyUsedPageCaches->find(pDocument));
    if (iQueue != mpRecentlyUsedPageCaches->end())
    {
        RecentlyUsedQueue::iterator iCache;
        for (iCache=iQueue->second.begin(); iCache!= iQueue->second.end(); ++iCache)
            if (iCache->maPreviewSize == rPreviewSize)
            {
                pCache = iCache->mpCache;
                iQueue->second.erase(iCache);
                break;
            }
    }

    return pCache;
}

void PageCacheManager::PutRecentlyUsedCache(
    SdDrawDocument* pDocument,
    const Size& rPreviewSize,
    const ::boost::shared_ptr<Cache>& rpCache)
{
    // Look up the list of recently used caches for the given document.
    RecentlyUsedPageCaches::iterator iQueue (mpRecentlyUsedPageCaches->find(pDocument));
    if (iQueue == mpRecentlyUsedPageCaches->end())
        iQueue = mpRecentlyUsedPageCaches->insert(
            RecentlyUsedPageCaches::value_type(pDocument, RecentlyUsedQueue())
            ).first;

    if (iQueue != mpRecentlyUsedPageCaches->end())
    {
        iQueue->second.push_front(RecentlyUsedCacheDescriptor(pDocument,rPreviewSize,rpCache));
        // Shorten the list of recently used caches to the allowed maximal length.
        while (iQueue->second.size() > mnMaximalRecentlyCacheCount)
            iQueue->second.pop_back();
    }
}

} } } // end of namespace ::sd::slidesorter::cache
<commit_msg>INTEGRATION: CWS sdwarningsbegone (1.7.38); FILE MERGED 2006/11/22 12:42:10 cl 1.7.38.1: #i69285# warning free code changes for unxlngi6.pro<commit_after>/*************************************************************************
 *
 *  $RCSfile: SlsPageCacheManager.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: kz $ $Date: 2006-12-12 18:17:53 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"

#include "cache/SlsPageCacheManager.hxx"

#include "SlsBitmapCache.hxx"
#include "view/SlideSorterView.hxx"
#include "model/SlideSorterModel.hxx"

#include <deque>
#include <map>
#include <boost/weak_ptr.hpp>

namespace {

/** Collection of data that is stored for all active preview caches.
*/
class CacheDescriptor
{
public:
    SdDrawDocument* mpDocument;
    Size maPreviewSize;

    CacheDescriptor(SdDrawDocument* pDocument, const Size& rPreviewSize)
        :mpDocument(pDocument),maPreviewSize(rPreviewSize)
    {}
    /// Test for equality with respect to all members.
    class Equal {public: bool operator() (
        const CacheDescriptor& rDescriptor1, const CacheDescriptor& rDescriptor2) const {
        return rDescriptor1.mpDocument==rDescriptor2.mpDocument
            && rDescriptor1.maPreviewSize==rDescriptor2.maPreviewSize;
    } };
    /// Hash function that takes all members into account.
    class Hash {public: size_t operator() (const CacheDescriptor& rDescriptor) const {
        return (size_t)rDescriptor.mpDocument + rDescriptor.maPreviewSize.Width();
    } };
};

/** Collection of data that is stored for the inactive, recently used
    caches.
*/
class RecentlyUsedCacheDescriptor
{
public:
    SdDrawDocument* mpDocument;
    Size maPreviewSize;
    ::boost::shared_ptr< ::sd::slidesorter::cache::PageCacheManager::Cache> mpCache;

    RecentlyUsedCacheDescriptor(
        SdDrawDocument* pDocument,
        const Size& rPreviewSize,
        const ::boost::shared_ptr< ::sd::slidesorter::cache::PageCacheManager::Cache>& rpCache)
        :mpDocument(pDocument),maPreviewSize(rPreviewSize),mpCache(rpCache)
    {}
};

/** The list of recently used caches is organized as queue.  When elements
    are added the list is shortened to the maximally allowed number of
    elements by removing the least recently used elements.
*/
typedef ::std::deque<RecentlyUsedCacheDescriptor> RecentlyUsedQueue;

/** Compare the caches by preview size.  Those that match the given size
    come first, then, regardless of the given size, the largest ones before
    the smaller ones.
*/
class BestFittingCacheComparer
{
public:
    BestFittingCacheComparer (const Size& rPreferredSize)
        : maPreferredSize(rPreferredSize)
    {}
    bool operator()(const ::sd::slidesorter::cache::PageCacheManager::BestFittingPageCaches::value_type& rElement1,
        const ::sd::slidesorter::cache::PageCacheManager::BestFittingPageCaches::value_type& rElement2)
    {
        if (rElement1.first == maPreferredSize)
            return true;
        else if (rElement2.first == maPreferredSize)
            return false;
        else
            return (rElement1.first.Width()*rElement1.first.Height()
                > rElement2.first.Width()*rElement2.first.Height());
    }

private:
    Size maPreferredSize;
};

} // end of anonymous namespace

namespace sd { namespace slidesorter { namespace cache {

/** Container for the active caches.
*/
class PageCacheManager::PageCacheContainer
    : public ::std::hash_map<CacheDescriptor,
                             ::boost::shared_ptr<PageCacheManager::Cache>,
                             CacheDescriptor::Hash,
                             CacheDescriptor::Equal>
{
public:
    PageCacheContainer (void) {}

    /** Compare entries in the cache container with respect to the cache
        address only.
    */
    class CompareWithCache { public:
        CompareWithCache(const ::boost::shared_ptr<PageCacheManager::Cache>& rpCache)
            : mpCache(rpCache) {}
        bool operator () (const PageCacheContainer::value_type& rValue)
        { return rValue.second == mpCache; }
    private:
        ::boost::shared_ptr<PageCacheManager::Cache> mpCache;
    };
};

/** The recently used caches are stored in one queue for each document.
*/
class PageCacheManager::RecentlyUsedPageCaches
    : public ::std::map<SdDrawDocument*,RecentlyUsedQueue>
{
public:
    RecentlyUsedPageCaches (void) {};
};

class PageCacheManager::Deleter
{
public:
    void operator() (PageCacheManager* pObject) { delete pObject; }
};

//===== PageCacheManager ====================================================

::boost::weak_ptr<PageCacheManager> PageCacheManager::mpInstance;

::boost::shared_ptr<PageCacheManager> PageCacheManager::Instance (void)
{
    ::boost::shared_ptr<PageCacheManager> pInstance;

    ::osl::MutexGuard aGuard (::osl::Mutex::getGlobalMutex());

    pInstance = mpInstance.lock();
    if (pInstance.get() == NULL)
    {
        pInstance = ::boost::shared_ptr<PageCacheManager>(
            new PageCacheManager(),
            PageCacheManager::Deleter());
        mpInstance = pInstance;
    }

    return pInstance;
}

PageCacheManager::PageCacheManager (void)
    : mpPageCaches(new PageCacheContainer()),
      mpRecentlyUsedPageCaches(new RecentlyUsedPageCaches()),
      mnMaximalRecentlyCacheCount(2)
{
}

PageCacheManager::~PageCacheManager (void)
{
}

::boost::shared_ptr<PageCacheManager::Cache> PageCacheManager::GetCache (
    SdDrawDocument* pDocument,
    const Size& rPreviewSize)
{
    ::boost::shared_ptr<Cache> pResult;

    // Look for the cache in the list of active caches.
    CacheDescriptor aKey (pDocument, rPreviewSize);
    PageCacheContainer::iterator iCache (mpPageCaches->find(aKey));
    if (iCache != mpPageCaches->end())
        pResult = iCache->second;

    // Look for the cache in the list of recently used caches.
    if (pResult.get() == NULL)
        pResult = GetRecentlyUsedCache(pDocument, rPreviewSize);

    // Create the cache when no suitable one does exist.
    if (pResult.get() == NULL)
        pResult.reset(new Cache());

    // The cache may be newly created and thus empty or is old and may
    // contain previews that are not up-to-date.  Recycle previews from
    // other caches to fill in the holes.
    Recycle(pResult, pDocument,rPreviewSize);

    // Put the new (or old) cache into the container.
    if (pResult.get() != NULL)
        mpPageCaches->insert(PageCacheContainer::value_type(aKey, pResult));

    OSL_TRACE("returning cache %x for document %x and size %d %d",
        pResult.get(), pDocument, rPreviewSize.Width(),rPreviewSize.Height());

    return pResult;
}

void PageCacheManager::Recycle (
    const ::boost::shared_ptr<Cache>& rpCache,
    SdDrawDocument* pDocument,
    const Size& rPreviewSize)
{
    BestFittingPageCaches aCaches;

    // Add bitmap caches from active caches.
    PageCacheContainer::iterator iActiveCache;
    for (iActiveCache=mpPageCaches->begin(); iActiveCache!=mpPageCaches->end(); ++iActiveCache)
    {
        if (iActiveCache->first.mpDocument == pDocument)
            aCaches.push_back(BestFittingPageCaches::value_type(
                iActiveCache->first.maPreviewSize, iActiveCache->second));
    }

    // Add bitmap caches from recently used caches.
    RecentlyUsedPageCaches::iterator iQueue (mpRecentlyUsedPageCaches->find(pDocument));
    if (iQueue != mpRecentlyUsedPageCaches->end())
    {
        RecentlyUsedQueue::const_iterator iRecentCache;
        for (iRecentCache=iQueue->second.begin();iRecentCache!=iQueue->second.end();++iRecentCache)
            aCaches.push_back(BestFittingPageCaches::value_type(
                iRecentCache->maPreviewSize, iRecentCache->mpCache));
    }

    ::std::sort(aCaches.begin(), aCaches.end(), BestFittingCacheComparer(rPreviewSize));

    BestFittingPageCaches::const_iterator iBestCache;
    for (iBestCache=aCaches.begin(); iBestCache!=aCaches.end(); ++iBestCache)
    {
        rpCache->Recycle(*iBestCache->second);
    }
}

void PageCacheManager::ReleaseCache (const ::boost::shared_ptr<Cache>& rpCache)
{
    PageCacheContainer::iterator iCache (::std::find_if(
        mpPageCaches->begin(),
        mpPageCaches->end(),
        PageCacheContainer::CompareWithCache(rpCache)));

    if (iCache != mpPageCaches->end())
    {
        OSL_ASSERT(iCache->second == rpCache);

        PutRecentlyUsedCache(iCache->first.mpDocument,iCache->first.maPreviewSize,rpCache);

        mpPageCaches->erase(iCache);
    }
}

::boost::shared_ptr<PageCacheManager::Cache> PageCacheManager::ChangeSize (
    const ::boost::shared_ptr<Cache>& rpCache,
    const Size& rOldPreviewSize,
    const Size& rNewPreviewSize)
{
    OSL_TRACE("changing size of cache %x from %d %d to %d %d",
        rpCache.get(),
        rOldPreviewSize.Width(),rOldPreviewSize.Height(),
        rNewPreviewSize.Width(),rNewPreviewSize.Height());
    ::boost::shared_ptr<Cache> pResult;

    if (rpCache.get() != NULL)
    {
        // Look up the given cache in the list of active caches.
        PageCacheContainer::iterator iCacheToChange (::std::find_if(
            mpPageCaches->begin(),
            mpPageCaches->end(),
            PageCacheContainer::CompareWithCache(rpCache)));
        OSL_ASSERT(iCacheToChange != mpPageCaches->end());
        if (iCacheToChange != mpPageCaches->end())
        {
            OSL_ASSERT(iCacheToChange->second == rpCache);

            // Now, we can change the preview size of the existing one by
            // removing the cache from the list and re-insert it with the
            // updated size.
            mpPageCaches->erase(iCacheToChange);
            mpPageCaches->insert(PageCacheContainer::value_type(
                CacheDescriptor(iCacheToChange->first.mpDocument,rNewPreviewSize),
                rpCache));

            pResult = rpCache;
        }
    }

    return pResult;
}

void PageCacheManager::InvalidatePreviewBitmap (
    SdDrawDocument* pDocument,
    const SdrPage* pKey)
{
    if (pDocument!=NULL)
    {
        // Iterate over all caches that are currently in use and invalidate
        // the previews in those that belong to the document.
        PageCacheContainer::iterator iCache;
        for (iCache=mpPageCaches->begin(); iCache!=mpPageCaches->end();  ++iCache)
            if (iCache->first.mpDocument == pDocument)
                iCache->second->InvalidateBitmap(pKey);

        // Invalidate the previews in the recently used caches belonging to
        // the given document.
        RecentlyUsedPageCaches::iterator iQueue (mpRecentlyUsedPageCaches->find(pDocument));
        if (iQueue != mpRecentlyUsedPageCaches->end())
        {
            RecentlyUsedQueue::const_iterator iCache2;
            for (iCache2=iQueue->second.begin(); iCache2!=iQueue->second.end(); ++iCache2)
                iCache2->mpCache->InvalidateBitmap(pKey);
        }
    }
}

void PageCacheManager::InvalidateAllCaches (void)
{
    // Iterate over all caches that are currently in use and invalidate
    // them.
    PageCacheContainer::iterator iCache;
    for (iCache=mpPageCaches->begin(); iCache!=mpPageCaches->end();  ++iCache)
        iCache->second->InvalidateCache();

    // Remove all recently used caches, there is not much sense in storing
    // invalidated and unused caches.
    mpRecentlyUsedPageCaches->clear();
}

::boost::shared_ptr<PageCacheManager::Cache> PageCacheManager::GetRecentlyUsedCache (
    SdDrawDocument* pDocument,
    const Size& rPreviewSize)
{
    ::boost::shared_ptr<Cache> pCache;

    // Look for the cache in the list of recently used caches.
    RecentlyUsedPageCaches::iterator iQueue (mpRecentlyUsedPageCaches->find(pDocument));
    if (iQueue != mpRecentlyUsedPageCaches->end())
    {
        RecentlyUsedQueue::iterator iCache;
        for (iCache=iQueue->second.begin(); iCache!= iQueue->second.end(); ++iCache)
            if (iCache->maPreviewSize == rPreviewSize)
            {
                pCache = iCache->mpCache;
                iQueue->second.erase(iCache);
                break;
            }
    }

    return pCache;
}

void PageCacheManager::PutRecentlyUsedCache(
    SdDrawDocument* pDocument,
    const Size& rPreviewSize,
    const ::boost::shared_ptr<Cache>& rpCache)
{
    // Look up the list of recently used caches for the given document.
    RecentlyUsedPageCaches::iterator iQueue (mpRecentlyUsedPageCaches->find(pDocument));
    if (iQueue == mpRecentlyUsedPageCaches->end())
        iQueue = mpRecentlyUsedPageCaches->insert(
            RecentlyUsedPageCaches::value_type(pDocument, RecentlyUsedQueue())
            ).first;

    if (iQueue != mpRecentlyUsedPageCaches->end())
    {
        iQueue->second.push_front(RecentlyUsedCacheDescriptor(pDocument,rPreviewSize,rpCache));
        // Shorten the list of recently used caches to the allowed maximal length.
        while (iQueue->second.size() > mnMaximalRecentlyCacheCount)
            iQueue->second.pop_back();
    }
}

} } } // end of namespace ::sd::slidesorter::cache
<|endoftext|>


<commit_before><commit_msg>added affect editing, adding and deleting<commit_after><|endoftext|>


<commit_before><commit_msg>fix gcc build of vectnative after msvc round of fixes<commit_after><|endoftext|>


<commit_before>/*
 * Copyright 2019 The Project Oak Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <cstdlib>

#include "absl/flags/flag.h"
#include "absl/flags/parse.h"
#include "absl/memory/memory.h"
#include "asylo/util/logging.h"
#include "examples/hello_world/proto/hello_world.grpc.pb.h"
#include "examples/hello_world/proto/hello_world.pb.h"
#include "include/grpcpp/grpcpp.h"
#include "oak/client/application_client.h"
#include "oak/client/manager_client.h"
#include "oak/common/app_config.h"
#include "oak/common/utils.h"

ABSL_FLAG(std::string, manager_address, "127.0.0.1:8888",
          "Address of the Oak Manager to connect to");
ABSL_FLAG(std::string, storage_address, "127.0.0.1:7867",
          "Address of the storage provider to connect to");
ABSL_FLAG(std::string, module, "", "File containing the compiled WebAssembly module");

using ::oak::examples::hello_world::HelloRequest;
using ::oak::examples::hello_world::HelloResponse;
using ::oak::examples::hello_world::HelloWorld;

void say_hello(HelloWorld::Stub* stub, std::string name) {
  grpc::ClientContext context;
  HelloRequest request;
  request.set_greeting(name);
  LOG(INFO) << "Request: " << request.greeting();
  HelloResponse response;
  grpc::Status status = stub->SayHello(&context, request, &response);
  if (!status.ok()) {
    LOG(WARNING) << "Could not call SayHello('" << name << "'): " << status.error_code() << ": "
                 << status.error_message();
    return;
  }
  LOG(INFO) << "Response: " << response.reply();
}

void lots_of_replies(HelloWorld::Stub* stub, std::string name) {
  grpc::ClientContext context;
  HelloRequest request;
  request.set_greeting(name);
  LOG(INFO) << "Request: " << request.greeting();
  auto reader = stub->LotsOfReplies(&context, request);
  if (reader == nullptr) {
    LOG(QFATAL) << "Could not call LotsOfReplies";
  }
  HelloResponse response;
  while (reader->Read(&response)) {
    LOG(INFO) << "Response: " << response.reply();
  }
}

int main(int argc, char** argv) {
  absl::ParseCommandLine(argc, argv);

  // Connect to the Oak Manager.
  std::unique_ptr<oak::ManagerClient> manager_client =
      absl::make_unique<oak::ManagerClient>(grpc::CreateChannel(
          absl::GetFlag(FLAGS_manager_address), grpc::InsecureChannelCredentials()));

  // Load the Oak Module to execute. This needs to be compiled from Rust to WebAssembly separately.
  std::string module_bytes = oak::utils::read_file(absl::GetFlag(FLAGS_module));

  // Build an application configuration with a single WebAssembly node with the provided
  // WebAssembly module bytes.
  std::unique_ptr<oak::ApplicationConfiguration> app_config = oak::DefaultConfig(module_bytes);
  oak::AddLoggingToConfig(app_config.get());
  std::string storage_address = absl::GetFlag(FLAGS_storage_address);
  if (!storage_address.empty()) {
    oak::AddStorageToConfig(app_config.get(), storage_address);
  }

  std::unique_ptr<oak::CreateApplicationResponse> create_application_response =
      manager_client->CreateApplication(std::move(app_config));
  if (create_application_response == nullptr) {
    LOG(QFATAL) << "Failed to create application";
  }

  std::stringstream addr;
  addr << "127.0.0.1:" << create_application_response->grpc_port();
  std::string application_id(create_application_response->application_id());
  LOG(INFO) << "Connecting to Oak Application id=" << application_id << ": " << addr.str();

  oak::ApplicationClient::InitializeAssertionAuthorities();

  // Connect to the newly created Oak Application.
  auto stub = HelloWorld::NewStub(oak::ApplicationClient::CreateChannel(addr.str()));

  // Perform multiple invocations of the same Oak Application, with different parameters.
  say_hello(stub.get(), "WORLD");
  say_hello(stub.get(), "MONDO");
  say_hello(stub.get(), "世界");
  say_hello(stub.get(), "Query-of-Error");
  say_hello(stub.get(), "MONDE");

  lots_of_replies(stub.get(), "WORLDS");

  // Request termination of the Oak Application.
  LOG(INFO) << "Terminating application id=" << application_id;
  manager_client->TerminateApplication(application_id);

  return EXIT_SUCCESS;
}
<commit_msg>examples/hello_world: opt to configure translator<commit_after>/*
 * Copyright 2019 The Project Oak Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <cstdlib>

#include "absl/flags/flag.h"
#include "absl/flags/parse.h"
#include "absl/memory/memory.h"
#include "asylo/util/logging.h"
#include "examples/hello_world/proto/hello_world.grpc.pb.h"
#include "examples/hello_world/proto/hello_world.pb.h"
#include "include/grpcpp/grpcpp.h"
#include "oak/client/application_client.h"
#include "oak/client/manager_client.h"
#include "oak/common/app_config.h"
#include "oak/common/utils.h"

ABSL_FLAG(std::string, manager_address, "127.0.0.1:8888",
          "Address of the Oak Manager to connect to");
ABSL_FLAG(std::string, storage_address, "127.0.0.1:7867",
          "Address of the storage provider to connect to");
ABSL_FLAG(std::string, module, "", "File containing the compiled WebAssembly module");
ABSL_FLAG(std::string, translator_module, "",
          "File containing a compiled WebAssembly module with a Translator Node");

using ::oak::examples::hello_world::HelloRequest;
using ::oak::examples::hello_world::HelloResponse;
using ::oak::examples::hello_world::HelloWorld;

void say_hello(HelloWorld::Stub* stub, std::string name) {
  grpc::ClientContext context;
  HelloRequest request;
  request.set_greeting(name);
  LOG(INFO) << "Request: " << request.greeting();
  HelloResponse response;
  grpc::Status status = stub->SayHello(&context, request, &response);
  if (!status.ok()) {
    LOG(WARNING) << "Could not call SayHello('" << name << "'): " << status.error_code() << ": "
                 << status.error_message();
    return;
  }
  LOG(INFO) << "Response: " << response.reply();
}

void lots_of_replies(HelloWorld::Stub* stub, std::string name) {
  grpc::ClientContext context;
  HelloRequest request;
  request.set_greeting(name);
  LOG(INFO) << "Request: " << request.greeting();
  auto reader = stub->LotsOfReplies(&context, request);
  if (reader == nullptr) {
    LOG(QFATAL) << "Could not call LotsOfReplies";
  }
  HelloResponse response;
  while (reader->Read(&response)) {
    LOG(INFO) << "Response: " << response.reply();
  }
}

int main(int argc, char** argv) {
  absl::ParseCommandLine(argc, argv);

  // Connect to the Oak Manager.
  std::unique_ptr<oak::ManagerClient> manager_client =
      absl::make_unique<oak::ManagerClient>(grpc::CreateChannel(
          absl::GetFlag(FLAGS_manager_address), grpc::InsecureChannelCredentials()));

  // Load the Oak Module to execute. This needs to be compiled from Rust to WebAssembly separately.
  std::string module_bytes = oak::utils::read_file(absl::GetFlag(FLAGS_module));

  // Build an application configuration with a single WebAssembly Node config
  // using the provided WebAssembly module bytes.
  std::unique_ptr<oak::ApplicationConfiguration> app_config = oak::DefaultConfig(module_bytes);
  oak::AddLoggingToConfig(app_config.get());
  std::string storage_address = absl::GetFlag(FLAGS_storage_address);
  if (!storage_address.empty()) {
    oak::AddStorageToConfig(app_config.get(), storage_address);
  }

  // Optionally load another WebAssembly module holding code for a translator
  // Node.
  std::string translator_module = absl::GetFlag(FLAGS_translator_module);
  if (!translator_module.empty()) {
    LOG(INFO) << "Adding 'translator' module config with Wasm code from " << translator_module;
    std::string translator_module_bytes = oak::utils::read_file(translator_module);
    oak::NodeConfiguration* node_config = app_config->add_node_configs();
    node_config->set_name("translator");
    oak::WebAssemblyConfiguration* wasm_config = node_config->mutable_wasm_config();
    wasm_config->set_module_bytes(translator_module_bytes);
  }

  std::unique_ptr<oak::CreateApplicationResponse> create_application_response =
      manager_client->CreateApplication(std::move(app_config));
  if (create_application_response == nullptr) {
    LOG(QFATAL) << "Failed to create application";
  }

  std::stringstream addr;
  addr << "127.0.0.1:" << create_application_response->grpc_port();
  std::string application_id(create_application_response->application_id());
  LOG(INFO) << "Connecting to Oak Application id=" << application_id << ": " << addr.str();

  oak::ApplicationClient::InitializeAssertionAuthorities();

  // Connect to the newly created Oak Application.
  auto stub = HelloWorld::NewStub(oak::ApplicationClient::CreateChannel(addr.str()));

  // Perform multiple invocations of the same Oak Application, with different parameters.
  say_hello(stub.get(), "WORLD");
  say_hello(stub.get(), "MONDO");
  say_hello(stub.get(), "世界");
  say_hello(stub.get(), "Query-of-Error");
  say_hello(stub.get(), "MONDE");

  lots_of_replies(stub.get(), "WORLDS");

  // Request termination of the Oak Application.
  LOG(INFO) << "Terminating application id=" << application_id;
  manager_client->TerminateApplication(application_id);

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/* OpenSceneGraph example, osgsharedarray.
*
*  Permission is hereby granted, free of charge, to any person obtaining a copy
*  of this software and associated documentation files (the "Software"), to deal
*  in the Software without restriction, including without limitation the rights
*  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
*  copies of the Software, and to permit persons to whom the Software is
*  furnished to do so, subject to the following conditions:
*
*  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
*  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
*  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
*  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
*  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
*  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
*  THE SOFTWARE.
*/

#include <osg/Array>
#include <osg/Geode>
#include <osg/Geometry>
#include <osgViewer/Viewer>

/** This class is an example of how to create your own subclass of osg::Array. This
  * is useful if your application has data in its own form of storage and you don't
  * want to make another copy into one of the predefined osg::Array classes.
  *
  * @note This is not really intended to be a useful subclass of osg::Array. It
  * doesn't do anything smart about memory management. It is simply intended as
  * an example you can follow to create your own subclasses of osg::Array for
  * your application's storage requirements.
  */
class MyArray : public osg::Array {
public:
    /** Default ctor. Creates an empty array. */
    MyArray() :
        osg::Array(osg::Array::Vec3ArrayType,3,GL_FLOAT),
        _numElements(0),
        _ptr(NULL) {
    }

    /** "Normal" ctor.
      *
      * @param no The number of elements in the array.
      * @param ptr Pointer to the data. This class just keeps that
      * pointer. It doesn't manage the memory.
      */
    MyArray(unsigned int no, osg::Vec3* ptr) :
        osg::Array(osg::Array::Vec3ArrayType,3,GL_FLOAT),
        _numElements(no),
        _ptr(ptr) {
    }

    /** Copy ctor. */
    MyArray(const MyArray& other, const osg::CopyOp& copyop) :
        osg::Array(osg::Array::Vec3ArrayType,3,GL_FLOAT),
        _numElements(other._numElements),
        _ptr(other._ptr) {
    }

    /** What type of object would clone return? */
    virtual Object* cloneType() const {
        return new MyArray();
    }

    /** Create a copy of the object. */
    virtual osg::Object* clone(const osg::CopyOp& copyop) const {
        return new MyArray(*this,copyop);
    }

    /** Accept method for ArrayVisitors.
      *
      * @note This will end up in ArrayVisitor::apply(osg::Array&).
      */
    virtual void accept(osg::ArrayVisitor& av) {
        av.apply(*this);
    }

    /** Const accept method for ArrayVisitors.
      *
      * @note This will end up in ConstArrayVisitor::apply(const osg::Array&).
      */
    virtual void accept(osg::ConstArrayVisitor& cav) const {
        cav.apply(*this);
    }

    /** Accept method for ValueVisitors. */
    virtual void accept(unsigned int index, osg::ValueVisitor& vv) {
        vv.apply(_ptr[index]);
    }

    /** Const accept method for ValueVisitors. */
    virtual void accept(unsigned int index, osg::ConstValueVisitor& cvv) const {
        cvv.apply(_ptr[index]);
    }

    /** Compare method.
      * Return -1 if lhs element is less than rhs element, 0 if equal,
      * 1 if lhs element is greater than rhs element.
      */
    virtual int compare(unsigned int lhs,unsigned int rhs) const {
        const osg::Vec3& elem_lhs = _ptr[lhs];
        const osg::Vec3& elem_rhs = _ptr[rhs];
        if (elem_lhs<elem_rhs) return -1;
        if (elem_rhs<elem_lhs) return  1;
        return 0;
    }

    /** Returns a pointer to the first element of the array. */
    virtual const GLvoid* getDataPointer() const {
        return _ptr;
    }

    /** Returns the number of elements in the array. */
    virtual unsigned int getNumElements() const {
        return _numElements;
    }

    /** Returns the number of bytes of storage required to hold
      * all of the elements of the array.
      */
    virtual unsigned int getTotalDataSize() const {
        return _numElements * sizeof(osg::Vec3);
    }

private:
    unsigned int _numElements;
    osg::Vec3*   _ptr;
};

/** The data values for the example. Simply defines a cube with
  * per-face colors and normals.
  */
namespace {
}

/** Create a Geode that describes a cube using our own
  * subclass of osg::Array for the vertices. It uses
  * the "regular" array classes for all of the other
  * arrays.
  *
  * Creating your own Array class isn't really very
  * useful for a tiny amount of data like this. You
  * could just go ahead and copy the data into one of
  * the "regular" Array classes like this does for
  * normals and colors. The point of creating your
  * own subclass of Array is for use with datasets
  * that are much larger than anything you could
  * create a simple example from. In that case, you
  * might not want to create a copy of the data in
  * one of the Array classes that comes with OSG, but
  * instead reuse the copy your application already
  * has and wrap it up in a subclass of osg::Array
  * that presents the right interface for use with
  * OpenSceneGraph.
  *
  * Note that I'm only using the shared array for the
  * vertices. You could do something similar for any
  * of the Geometry node's data arrays.
  */
osg::Geode* createGeometry()
{
    const osg::Vec3 myVertices[] = { osg::Vec3(-1.,-1.,-1.),
                                     osg::Vec3( 1.,-1.,-1.),
                                     osg::Vec3(-1., 1.,-1.),
                                     osg::Vec3( 1., 1.,-1.),
                                     osg::Vec3(-1.,-1., 1.),
                                     osg::Vec3( 1.,-1., 1.),
                                     osg::Vec3(-1., 1., 1.),
                                     osg::Vec3( 1., 1., 1.)
                                   };

    const osg::Vec3 myNormals[] = { osg::Vec3( 0., 0., 1.),
                                    osg::Vec3( 1., 0., 0.),
                                    osg::Vec3( 0., 0.,-1.),
                                    osg::Vec3(-1., 0., 0.),
                                    osg::Vec3( 0., 1., 0.),
                                    osg::Vec3( 0.,-1., 0.)
                                  };

    const osg::Vec4 myColors[] = { osg::Vec4( 1., 0., 0., 1.),
                                   osg::Vec4( 0., 1., 0., 1.),
                                   osg::Vec4( 1., 1., 0., 1.),
                                   osg::Vec4( 0., 0., 1., 1.),
                                   osg::Vec4( 1., 0., 1., 1.),
                                   osg::Vec4( 0., 1., 1., 1.)
                                 };

    const unsigned short myIndices[] = { 4, 5, 7, 6,
                                        5, 1, 3, 7,
                                        1, 0, 2, 3,
                                        0, 4, 6, 2,
                                        6, 7, 3, 2,
                                        0, 1, 5, 4
                                       };

    osg::Geode* geode = new osg::Geode();

    // create Geometry
    osg::ref_ptr<osg::Geometry> geom(new osg::Geometry());

    // add vertices using MyArray class
    unsigned int numVertices = sizeof(myVertices)/sizeof(myVertices[0]);
    geom->setVertexArray(new MyArray(numVertices,const_cast<osg::Vec3*>(&myVertices[0])));

    // add normals
    unsigned int numNormals = sizeof(myNormals)/sizeof(myNormals[0]);
    geom->setNormalArray(new osg::Vec3Array(numNormals,const_cast<osg::Vec3*>(&myNormals[0])));
    geom->setNormalBinding(osg::Geometry::BIND_PER_PRIMITIVE);

    // add colors
    unsigned int numColors = sizeof(myColors)/sizeof(myColors[0]);
    osg::Vec4Array* normal_array = new osg::Vec4Array(numColors,const_cast<osg::Vec4*>(&myColors[0]));
    geom->setColorArray(normal_array);
    geom->setColorBinding(osg::Geometry::BIND_PER_PRIMITIVE);

    // add PrimitiveSet
    unsigned int numIndices = sizeof(myIndices)/sizeof(myIndices[0]);
    geom->addPrimitiveSet(new osg::DrawElementsUShort(osg::PrimitiveSet::QUADS,
                                                      numIndices,
                                                      const_cast<unsigned short *>(myIndices)));

    // Changing these flags will tickle different cases in
    // Geometry::drawImplementation. They should all work fine
    // with the shared array. Setting VertexIndices will hit
    // some other cases.
    geom->setUseVertexBufferObjects(false);
    geom->setUseDisplayList(false);
    geom->setFastPathHint(false);

    geode->addDrawable( geom.get() );

    return geode;
}

int main(int , char **)
{
    // construct the viewer.
    osgViewer::Viewer viewer;

    // add model to viewer.
    viewer.setSceneData( createGeometry() );

    // create the windows and run the threads.
    return viewer.run();
}
<commit_msg>From Mathias Froehlich, "attached is a change to osgsharedarray to move completely to the fast geometry path. Also the arrays are moved back to static storage since this is the data that is actually referenced in draw. So the change moving this onto the stack that happend somewhere before broke this."<commit_after>/* OpenSceneGraph example, osgsharedarray.
*
*  Permission is hereby granted, free of charge, to any person obtaining a copy
*  of this software and associated documentation files (the "Software"), to deal
*  in the Software without restriction, including without limitation the rights
*  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
*  copies of the Software, and to permit persons to whom the Software is
*  furnished to do so, subject to the following conditions:
*
*  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
*  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
*  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
*  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
*  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
*  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
*  THE SOFTWARE.
*/

#include <osg/Array>
#include <osg/Geode>
#include <osg/Geometry>
#include <osgViewer/Viewer>

/** This class is an example of how to create your own subclass of osg::Array. This
  * is useful if your application has data in its own form of storage and you don't
  * want to make another copy into one of the predefined osg::Array classes.
  *
  * @note This is not really intended to be a useful subclass of osg::Array. It
  * doesn't do anything smart about memory management. It is simply intended as
  * an example you can follow to create your own subclasses of osg::Array for
  * your application's storage requirements.
  */
class MyArray : public osg::Array {
public:
    /** Default ctor. Creates an empty array. */
    MyArray() :
        osg::Array(osg::Array::Vec3ArrayType,3,GL_FLOAT),
        _numElements(0),
        _ptr(NULL) {
    }

    /** "Normal" ctor.
      *
      * @param no The number of elements in the array.
      * @param ptr Pointer to the data. This class just keeps that
      * pointer. It doesn't manage the memory.
      */
    MyArray(unsigned int no, osg::Vec3* ptr) :
        osg::Array(osg::Array::Vec3ArrayType,3,GL_FLOAT),
        _numElements(no),
        _ptr(ptr) {
    }

    /** Copy ctor. */
    MyArray(const MyArray& other, const osg::CopyOp& copyop) :
        osg::Array(osg::Array::Vec3ArrayType,3,GL_FLOAT),
        _numElements(other._numElements),
        _ptr(other._ptr) {
    }

    /** What type of object would clone return? */
    virtual Object* cloneType() const {
        return new MyArray();
    }

    /** Create a copy of the object. */
    virtual osg::Object* clone(const osg::CopyOp& copyop) const {
        return new MyArray(*this,copyop);
    }

    /** Accept method for ArrayVisitors.
      *
      * @note This will end up in ArrayVisitor::apply(osg::Array&).
      */
    virtual void accept(osg::ArrayVisitor& av) {
        av.apply(*this);
    }

    /** Const accept method for ArrayVisitors.
      *
      * @note This will end up in ConstArrayVisitor::apply(const osg::Array&).
      */
    virtual void accept(osg::ConstArrayVisitor& cav) const {
        cav.apply(*this);
    }

    /** Accept method for ValueVisitors. */
    virtual void accept(unsigned int index, osg::ValueVisitor& vv) {
        vv.apply(_ptr[index]);
    }

    /** Const accept method for ValueVisitors. */
    virtual void accept(unsigned int index, osg::ConstValueVisitor& cvv) const {
        cvv.apply(_ptr[index]);
    }

    /** Compare method.
      * Return -1 if lhs element is less than rhs element, 0 if equal,
      * 1 if lhs element is greater than rhs element.
      */
    virtual int compare(unsigned int lhs,unsigned int rhs) const {
        const osg::Vec3& elem_lhs = _ptr[lhs];
        const osg::Vec3& elem_rhs = _ptr[rhs];
        if (elem_lhs<elem_rhs) return -1;
        if (elem_rhs<elem_lhs) return  1;
        return 0;
    }

    /** Returns a pointer to the first element of the array. */
    virtual const GLvoid* getDataPointer() const {
        return _ptr;
    }

    /** Returns the number of elements in the array. */
    virtual unsigned int getNumElements() const {
        return _numElements;
    }

    /** Returns the number of bytes of storage required to hold
      * all of the elements of the array.
      */
    virtual unsigned int getTotalDataSize() const {
        return _numElements * sizeof(osg::Vec3);
    }

private:
    unsigned int _numElements;
    osg::Vec3*   _ptr;
};

/** The data values for the example. Simply defines a cube with
  * per-face colors and normals.
  */

const osg::Vec3 myVertices[] = { osg::Vec3(-1.,-1., 1.),
                                 osg::Vec3( 1.,-1., 1.),
                                 osg::Vec3( 1., 1., 1.),
                                 osg::Vec3(-1., 1., 1.),

                                 osg::Vec3( 1.,-1., 1.),
                                 osg::Vec3( 1.,-1.,-1.),
                                 osg::Vec3( 1., 1.,-1.),
                                 osg::Vec3( 1., 1., 1.),

                                 osg::Vec3( 1.,-1.,-1.),
                                 osg::Vec3(-1.,-1.,-1.),
                                 osg::Vec3(-1., 1.,-1.),
                                 osg::Vec3( 1., 1.,-1.),

                                 osg::Vec3(-1.,-1.,-1.),
                                 osg::Vec3(-1.,-1., 1.),
                                 osg::Vec3(-1., 1., 1.),
                                 osg::Vec3(-1., 1.,-1.),

                                 osg::Vec3(-1., 1., 1.),
                                 osg::Vec3( 1., 1., 1.),
                                 osg::Vec3( 1., 1.,-1.),
                                 osg::Vec3(-1., 1.,-1.),

                                 osg::Vec3(-1.,-1.,-1.),
                                 osg::Vec3( 1.,-1.,-1.),
                                 osg::Vec3( 1.,-1., 1.),
                                 osg::Vec3(-1.,-1., 1.),
                               };

const osg::Vec3 myNormals[] = { osg::Vec3( 0., 0., 1.),
                                osg::Vec3( 0., 0., 1.),
                                osg::Vec3( 0., 0., 1.),
                                osg::Vec3( 0., 0., 1.),

                                osg::Vec3( 1., 0., 0.),
                                osg::Vec3( 1., 0., 0.),
                                osg::Vec3( 1., 0., 0.),
                                osg::Vec3( 1., 0., 0.),

                                osg::Vec3( 0., 0.,-1.),
                                osg::Vec3( 0., 0.,-1.),
                                osg::Vec3( 0., 0.,-1.),
                                osg::Vec3( 0., 0.,-1.),

                                osg::Vec3(-1., 0., 0.),
                                osg::Vec3(-1., 0., 0.),
                                osg::Vec3(-1., 0., 0.),
                                osg::Vec3(-1., 0., 0.),

                                osg::Vec3( 0., 1., 0.),
                                osg::Vec3( 0., 1., 0.),
                                osg::Vec3( 0., 1., 0.),
                                osg::Vec3( 0., 1., 0.),

                                osg::Vec3( 0.,-1., 0.),
                                osg::Vec3( 0.,-1., 0.),
                                osg::Vec3( 0.,-1., 0.),
                                osg::Vec3( 0.,-1., 0.)
                              };

const osg::Vec4 myColors[] = { osg::Vec4( 1., 0., 0., 1.),
                               osg::Vec4( 1., 0., 0., 1.),
                               osg::Vec4( 1., 0., 0., 1.),
                               osg::Vec4( 1., 0., 0., 1.),

                               osg::Vec4( 0., 1., 0., 1.),
                               osg::Vec4( 0., 1., 0., 1.),
                               osg::Vec4( 0., 1., 0., 1.),
                               osg::Vec4( 0., 1., 0., 1.),

                               osg::Vec4( 1., 1., 0., 1.),
                               osg::Vec4( 1., 1., 0., 1.),
                               osg::Vec4( 1., 1., 0., 1.),
                               osg::Vec4( 1., 1., 0., 1.),

                               osg::Vec4( 0., 0., 1., 1.),
                               osg::Vec4( 0., 0., 1., 1.),
                               osg::Vec4( 0., 0., 1., 1.),
                               osg::Vec4( 0., 0., 1., 1.),

                               osg::Vec4( 1., 0., 1., 1.),
                               osg::Vec4( 1., 0., 1., 1.),
                               osg::Vec4( 1., 0., 1., 1.),
                               osg::Vec4( 1., 0., 1., 1.),

                               osg::Vec4( 0., 1., 1., 1.),
                               osg::Vec4( 0., 1., 1., 1.),
                               osg::Vec4( 0., 1., 1., 1.),
                               osg::Vec4( 0., 1., 1., 1.)
                             };

/** Create a Geode that describes a cube using our own
  * subclass of osg::Array for the vertices. It uses
  * the "regular" array classes for all of the other
  * arrays.
  *
  * Creating your own Array class isn't really very
  * useful for a tiny amount of data like this. You
  * could just go ahead and copy the data into one of
  * the "regular" Array classes like this does for
  * normals and colors. The point of creating your
  * own subclass of Array is for use with datasets
  * that are much larger than anything you could
  * create a simple example from. In that case, you
  * might not want to create a copy of the data in
  * one of the Array classes that comes with OSG, but
  * instead reuse the copy your application already
  * has and wrap it up in a subclass of osg::Array
  * that presents the right interface for use with
  * OpenSceneGraph.
  *
  * Note that I'm only using the shared array for the
  * vertices. You could do something similar for any
  * of the Geometry node's data arrays.
  */
osg::Geode* createGeometry()
{
    osg::Geode* geode = new osg::Geode();

    // create Geometry
    osg::ref_ptr<osg::Geometry> geom(new osg::Geometry());

    // add vertices using MyArray class
    unsigned int numVertices = sizeof(myVertices)/sizeof(myVertices[0]);
    geom->setVertexArray(new MyArray(numVertices,const_cast<osg::Vec3*>(&myVertices[0])));

    // add normals
    unsigned int numNormals = sizeof(myNormals)/sizeof(myNormals[0]);
    geom->setNormalArray(new osg::Vec3Array(numNormals,const_cast<osg::Vec3*>(&myNormals[0])));
    geom->setNormalBinding(osg::Geometry::BIND_PER_VERTEX);

    // add colors
    unsigned int numColors = sizeof(myColors)/sizeof(myColors[0]);
    osg::Vec4Array* normal_array = new osg::Vec4Array(numColors,const_cast<osg::Vec4*>(&myColors[0]));
    geom->setColorArray(normal_array);
    geom->setColorBinding(osg::Geometry::BIND_PER_VERTEX);

    // add PrimitiveSet
    geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS, 0, numVertices));

    // Changing these flags will tickle different cases in
    // Geometry::drawImplementation. They should all work fine
    // with the shared array. Setting VertexIndices will hit
    // some other cases.
    geom->setUseVertexBufferObjects(false);
    geom->setUseDisplayList(false);
    geom->setFastPathHint(false);

    geode->addDrawable( geom.get() );

    return geode;
}

int main(int , char **)
{
    // construct the viewer.
    osgViewer::Viewer viewer;

    // add model to viewer.
    viewer.setSceneData( createGeometry() );

    // create the windows and run the threads.
    return viewer.run();
}
<|endoftext|>