<commit_before>#pragma ident "$Id$"

//============================================================================
//
//  This file is part of GPSTk, the GPS Toolkit.
//
//  The GPSTk is free software; you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as published
//  by the Free Software Foundation; either version 2.1 of the License, or
//  any later version.
//
//  The GPSTk 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 GPSTk; if not, write to the Free Software Foundation,
//  Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Copyright 2004, The University of Texas at Austin
//
//============================================================================

//============================================================================
//
//This software developed by Applied Research Laboratories at the University of
//Texas at Austin, under contract to an agency or agencies within the U.S.
//Department of Defense. The U.S. Government retains all rights to use,
//duplicate, distribute, disclose, or release this software.
//
//Pursuant to DoD Directive 523024
//
// DISTRIBUTION STATEMENT A: This software has been approved for public
//                           release, distribution is unlimited.
//
//=============================================================================

/**
 * @file SP3EphemerisStore.cpp
 * Read & store SP3 formated ephemeris data
 */

#include "SP3EphemerisStore.hpp"
#include "MiscMath.hpp"
#include "ECEF.hpp"
#include "icd_200_constants.hpp"

using namespace gpstk::StringUtils;

namespace gpstk
{
   //-----------------------------------------------------------------------------
   //-----------------------------------------------------------------------------
   void SP3EphemerisStore::loadFile(const std::string& filename)
      throw(FileMissingException)
   {
      try
      {
         SP3Stream strm(filename.c_str());
         if (!strm)
         {
            FileMissingException e("File " + filename + " could not be opened.");
            GPSTK_THROW(e);
         }

         SP3Header header;
         strm >> header;

         addFile(filename, header);

         /// If any file doesn't have the velocity data, clear the
         /// the flag indicating that there is any velocity data
         if (tolower(header.pvFlag) != 'v')
            setHaveVelocity(false);

         SP3Data rec;
         while(strm >> rec)
            addEphemeris(rec);
      }
      catch (gpstk::Exception& e)
      {
         GPSTK_RETHROW(e);
      }
   }  // end SP3EphemerisStore::load

   //--------------------------------------------------------------------------
   //--------------------------------------------------------------------------
   void SP3EphemerisStore::dump(short detail, std::ostream& s) const
   {
      s << "Dump of SP3EphemerisStore:" << std::endl;
      std::vector<std::string> fileNames = getFileNames();
      std::vector<std::string>::const_iterator f=fileNames.begin();
      for (f=fileNames.begin(); f!=fileNames.end(); f++)
         s << *f << std::endl;
/*
  Add this back in when/if we add header info to the file store.
      while(fmi != fm.end()) {
         s << " File " << fmi->first << ", Times: " << fmi->second.time
            << " to " << (fmi->second.time+fmi->second.epochInterval*fmi->second.numberOfEpochs)
            << ", (" << fmi->second.numberOfEpochs
            << "  " << fmi->second.epochInterval << "sec intervals)." << std::endl;
         if(detail > 0) {
            s << "  Data used as input : " << fmi->second.dataUsed
               << "  Coordinate system : " << fmi->second.coordSystem << std::endl;
            s << "  Orbit estimate type : " << fmi->second.orbitType
               << "  Agency : " << fmi->second.agency << std::endl;
            s << "  List of satellite PRN/acc (" << fmi->second.svList.size()
               << " total) :\n";
            int i=0;
            std::map<short,short>::const_iterator it=fmi->second.svList.begin();
            while(it != fmi->second.svList.end()) {
               s << "  " << std::setw(2) << it->first << "/" << it->second;
               if(!(++i % 8)) s << std::endl;
               it++;
            }
            if(++i % 8) s << std::endl;
            s << "  Comments:\n";
            for(i=0; i<fmi->second.comments.size(); i++)
               s << "    " << fmi->second.comments[i] << std::endl;
            s << std::endl;
         }
         fmi++;
      }
*/
      TabularEphemerisStore::dump(detail, s);

   } // end of SP3EphemerisStore::dump

}  // namespace gpstk
<commit_msg>set data version to header version while loading SP3 file<commit_after>#pragma ident "$Id$"

//============================================================================
//
//  This file is part of GPSTk, the GPS Toolkit.
//
//  The GPSTk is free software; you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as published
//  by the Free Software Foundation; either version 2.1 of the License, or
//  any later version.
//
//  The GPSTk 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 GPSTk; if not, write to the Free Software Foundation,
//  Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Copyright 2004, The University of Texas at Austin
//
//============================================================================

//============================================================================
//
//This software developed by Applied Research Laboratories at the University of
//Texas at Austin, under contract to an agency or agencies within the U.S.
//Department of Defense. The U.S. Government retains all rights to use,
//duplicate, distribute, disclose, or release this software.
//
//Pursuant to DoD Directive 523024
//
// DISTRIBUTION STATEMENT A: This software has been approved for public
//                           release, distribution is unlimited.
//
//=============================================================================

/**
 * @file SP3EphemerisStore.cpp
 * Read & store SP3 formated ephemeris data
 */

#include "SP3EphemerisStore.hpp"
#include "MiscMath.hpp"
#include "ECEF.hpp"
#include "icd_200_constants.hpp"

using namespace gpstk::StringUtils;

namespace gpstk
{
   //-----------------------------------------------------------------------------
   //-----------------------------------------------------------------------------
   void SP3EphemerisStore::loadFile(const std::string& filename)
      throw(FileMissingException)
   {
      try
      {
         SP3Stream strm(filename.c_str());
         if (!strm)
         {
            FileMissingException e("File " + filename + " could not be opened.");
            GPSTK_THROW(e);
         }

         SP3Header header;
         strm >> header;

         addFile(filename, header);

         /// If any file doesn't have the velocity data, clear the
         /// the flag indicating that there is any velocity data
         if (tolower(header.pvFlag) != 'v')
            setHaveVelocity(false);

         SP3Data rec;
         while(strm >> rec) {
            rec.version = header.version;
            addEphemeris(rec);
         }
      }
      catch (gpstk::Exception& e)
      {
         GPSTK_RETHROW(e);
      }
   }  // end SP3EphemerisStore::load

   //--------------------------------------------------------------------------
   //--------------------------------------------------------------------------
   void SP3EphemerisStore::dump(short detail, std::ostream& s) const
   {
      s << "Dump of SP3EphemerisStore:" << std::endl;
      std::vector<std::string> fileNames = getFileNames();
      std::vector<std::string>::const_iterator f=fileNames.begin();
      for (f=fileNames.begin(); f!=fileNames.end(); f++)
         s << *f << std::endl;
/*
  Add this back in when/if we add header info to the file store.
      while(fmi != fm.end()) {
         s << " File " << fmi->first << ", Times: " << fmi->second.time
            << " to " << (fmi->second.time+fmi->second.epochInterval*fmi->second.numberOfEpochs)
            << ", (" << fmi->second.numberOfEpochs
            << "  " << fmi->second.epochInterval << "sec intervals)." << std::endl;
         if(detail > 0) {
            s << "  Data used as input : " << fmi->second.dataUsed
               << "  Coordinate system : " << fmi->second.coordSystem << std::endl;
            s << "  Orbit estimate type : " << fmi->second.orbitType
               << "  Agency : " << fmi->second.agency << std::endl;
            s << "  List of satellite PRN/acc (" << fmi->second.svList.size()
               << " total) :\n";
            int i=0;
            std::map<short,short>::const_iterator it=fmi->second.svList.begin();
            while(it != fmi->second.svList.end()) {
               s << "  " << std::setw(2) << it->first << "/" << it->second;
               if(!(++i % 8)) s << std::endl;
               it++;
            }
            if(++i % 8) s << std::endl;
            s << "  Comments:\n";
            for(i=0; i<fmi->second.comments.size(); i++)
               s << "    " << fmi->second.comments[i] << std::endl;
            s << std::endl;
         }
         fmi++;
      }
*/
      TabularEphemerisStore::dump(detail, s);

   } // end of SP3EphemerisStore::dump

}  // namespace gpstk
<|endoftext|>


<commit_before>/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SampleCode.h"
#include "SkView.h"
#include "SkCanvas.h"
#include "SkPath.h"
#include "SkRegion.h"
#include "SkShader.h"
#include "SkUtils.h"
#include "SkImage.h"
#include "SkSurface.h"

#define FAT_PIXEL_COLOR     SK_ColorBLACK
#define PIXEL_CENTER_SIZE   3
#define WIRE_FRAME_COLOR    0xFFFF0000  /*0xFF00FFFF*/
#define WIRE_FRAME_SIZE     1.5f

static void erase(SkSurface* surface) {
    surface->getCanvas()->clear(0);
}

static SkShader* createChecker() {
    SkBitmap bm;
    bm.setConfig(SkBitmap::kARGB_8888_Config, 2, 2);
    bm.allocPixels();
    bm.lockPixels();
    *bm.getAddr32(0, 0) = *bm.getAddr32(1, 1) = SkPreMultiplyColor(0xFFFDFDFD);
    *bm.getAddr32(0, 1) = *bm.getAddr32(1, 0) = SkPreMultiplyColor(0xFFF4F4F4);
    SkShader* s = SkShader::CreateBitmapShader(bm, SkShader::kRepeat_TileMode,
                                               SkShader::kRepeat_TileMode);

    SkMatrix m;
    m.setScale(12, 12);
    s->setLocalMatrix(m);
    return s;
}

class FatBits {
public:
    FatBits() : fShader(createChecker()) {
        fAA = false;
        fStyle = kHair_Style;
        fGrid = true;
        fShowSkeleton = true;
        fUseGPU = false;
    }

    int getZoom() const { return fZ; }

    bool getAA() const { return fAA; }
    void setAA(bool aa) { fAA = aa; }

    bool getGrid() const { return fGrid; }
    void setGrid(bool g) { fGrid = g; }

    bool getShowSkeleton() const { return fShowSkeleton; }
    void setShowSkeleton(bool ss) { fShowSkeleton = ss; }

    bool getUseGPU() const { return fUseGPU; }
    void setUseGPU(bool ug) { fUseGPU = ug; }

    enum Style {
        kHair_Style,
        kStroke_Style,
    };
    Style getStyle() const { return fStyle; }
    void setStyle(Style s) { fStyle = s; }

    void setWHZ(int width, int height, int zoom) {
        fW = width;
        fH = height;
        fZ = zoom;
        fBounds.set(0, 0, SkIntToScalar(width * zoom), SkIntToScalar(height * zoom));
        fMatrix.setScale(SkIntToScalar(zoom), SkIntToScalar(zoom));
        fInverse.setScale(SK_Scalar1 / zoom, SK_Scalar1 / zoom);
        fShader->setLocalMatrix(fMatrix);

        SkImage::Info info = {
            width, height, SkImage::kPMColor_ColorType, SkImage::kPremul_AlphaType
        };
        fMinSurface.reset(SkSurface::NewRaster(info, NULL));
        info.fWidth *= zoom;
        info.fHeight *= zoom;
        fMaxSurface.reset(SkSurface::NewRaster(info, NULL));
    }

    void drawBG(SkCanvas*);
    void drawFG(SkCanvas*);
    void drawLine(SkCanvas*, SkPoint pts[2]);
    void drawRect(SkCanvas* canvas, SkPoint pts[2]);

private:
    bool fAA, fGrid, fShowSkeleton, fUseGPU;
    Style fStyle;
    int fW, fH, fZ;
    SkMatrix fMatrix, fInverse;
    SkRect   fBounds;
    SkAutoTUnref<SkShader> fShader;
    SkAutoTUnref<SkSurface> fMinSurface;
    SkAutoTUnref<SkSurface> fMaxSurface;

    void setupPaint(SkPaint* paint) {
        bool aa = this->getAA();
        switch (fStyle) {
            case kHair_Style:
                paint->setStrokeWidth(0);
                break;
            case kStroke_Style:
                paint->setStrokeWidth(SK_Scalar1);
//                paint->setStrokeWidth(SK_Scalar1 + SK_Scalar1/500);
                break;
        }
        paint->setAntiAlias(aa);
    }

    void setupSkeletonPaint(SkPaint* paint) {
        paint->setStyle(SkPaint::kStroke_Style);
        paint->setStrokeWidth(WIRE_FRAME_SIZE);
        paint->setColor(fShowSkeleton ? WIRE_FRAME_COLOR : 0);
        paint->setAntiAlias(true);
    }

    void drawLineSkeleton(SkCanvas* max, const SkPoint pts[]);
    void drawRectSkeleton(SkCanvas* max, const SkRect& r) {
        SkPaint paint;
        this->setupSkeletonPaint(&paint);
        SkPath path;

        if (fUseGPU && fAA) {
            SkRect rr = r;
            rr.inset(fZ/2, fZ/2);
            path.addRect(rr);
            path.moveTo(rr.fLeft, rr.fTop);
            path.lineTo(rr.fRight, rr.fBottom);
            rr = r;
            rr.inset(-fZ/2, -fZ/2);
            path.addRect(rr);
        } else {
            path.addRect(r);
            if (fUseGPU) {
                path.moveTo(r.fLeft, r.fTop);
                path.lineTo(r.fRight, r.fBottom);
            }
        }
        max->drawPath(path, paint);
    }

    void copyMinToMax() {
        erase(fMaxSurface);
        SkCanvas* canvas = fMaxSurface->getCanvas();
        canvas->save();
        canvas->concat(fMatrix);
        fMinSurface->draw(canvas, 0, 0, NULL);
        canvas->restore();

        SkPaint paint;
        paint.setXfermodeMode(SkXfermode::kClear_Mode);
        for (int iy = 1; iy < fH; ++iy) {
            SkScalar y = SkIntToScalar(iy * fZ);
            canvas->drawLine(0, y - SK_ScalarHalf, 999, y - SK_ScalarHalf, paint);
        }
        for (int ix = 1; ix < fW; ++ix) {
            SkScalar x = SkIntToScalar(ix * fZ);
            canvas->drawLine(x - SK_ScalarHalf, 0, x - SK_ScalarHalf, 999, paint);
        }
    }
};

void FatBits::drawBG(SkCanvas* canvas) {
    SkPaint paint;

    paint.setShader(fShader);
    canvas->drawRect(fBounds, paint);
    paint.setShader(NULL);
}

void FatBits::drawFG(SkCanvas* canvas) {
    SkPaint inner, outer;

    inner.setAntiAlias(true);
    inner.setColor(SK_ColorBLACK);
    inner.setStrokeWidth(PIXEL_CENTER_SIZE);

    outer.setAntiAlias(true);
    outer.setColor(SK_ColorWHITE);
    outer.setStrokeWidth(PIXEL_CENTER_SIZE + 2);

    SkScalar half = SkIntToScalar(fZ) / 2;
    for (int iy = 0; iy < fH; ++iy) {
        SkScalar y = SkIntToScalar(iy * fZ) + half;
        for (int ix = 0; ix < fW; ++ix) {
            SkScalar x = SkIntToScalar(ix * fZ) + half;

            canvas->drawPoint(x, y, outer);
            canvas->drawPoint(x, y, inner);
        }
    }
}

void FatBits::drawLineSkeleton(SkCanvas* max, const SkPoint pts[]) {
    SkPaint paint;
    this->setupSkeletonPaint(&paint);

    SkPath path;
    path.moveTo(pts[0]);
    path.lineTo(pts[1]);

    switch (fStyle) {
        case kHair_Style:
            if (fUseGPU) {
                SkPaint p;
                p.setStyle(SkPaint::kStroke_Style);
                p.setStrokeWidth(SK_Scalar1 * fZ);
                SkPath dst;
                p.getFillPath(path, &dst);
                path.addPath(dst);
            }
            break;
        case kStroke_Style: {
            SkPaint p;
            p.setStyle(SkPaint::kStroke_Style);
            p.setStrokeWidth(SK_Scalar1 * fZ);
            SkPath dst;
            p.getFillPath(path, &dst);
            path = dst;

            if (fUseGPU) {
                path.moveTo(dst.getPoint(0));
                path.lineTo(dst.getPoint(2));
            }
        } break;
    }
    max->drawPath(path, paint);
}

void FatBits::drawLine(SkCanvas* canvas, SkPoint pts[]) {
    SkPaint paint;

    fInverse.mapPoints(pts, 2);

    if (fGrid) {
        SkScalar dd = 0;//SK_Scalar1 / 50;
        pts[0].set(SkScalarRoundToScalar(pts[0].fX) + dd,
                   SkScalarRoundToScalar(pts[0].fY) + dd);
        pts[1].set(SkScalarRoundToScalar(pts[1].fX) + dd,
                   SkScalarRoundToScalar(pts[1].fY) + dd);
    }

    erase(fMinSurface);
    this->setupPaint(&paint);
    paint.setColor(FAT_PIXEL_COLOR);
    fMinSurface->getCanvas()->drawLine(pts[0].fX, pts[0].fY, pts[1].fX, pts[1].fY, paint);
    this->copyMinToMax();

    SkCanvas* max = fMaxSurface->getCanvas();

    fMatrix.mapPoints(pts, 2);
    this->drawLineSkeleton(max, pts);

    fMaxSurface->draw(canvas, 0, 0, NULL);
}

void FatBits::drawRect(SkCanvas* canvas, SkPoint pts[2]) {
    SkPaint paint;

    fInverse.mapPoints(pts, 2);

    if (fGrid) {
        pts[0].set(SkScalarRoundToScalar(pts[0].fX), SkScalarRoundToScalar(pts[0].fY));
        pts[1].set(SkScalarRoundToScalar(pts[1].fX), SkScalarRoundToScalar(pts[1].fY));
    }

    SkRect r;
    r.set(pts, 2);

    erase(fMinSurface);
    this->setupPaint(&paint);
    paint.setColor(FAT_PIXEL_COLOR);
    fMinSurface->getCanvas()->drawRect(r, paint);
    this->copyMinToMax();

    SkCanvas* max = fMaxSurface->getCanvas();

    fMatrix.mapPoints(pts, 2);
    r.set(pts, 2);
    this->drawRectSkeleton(max, r);

    fMaxSurface->draw(canvas, 0, 0, NULL);
}

///////////////////////////////////////////////////////////////////////////////////////////////////

class IndexClick : public SkView::Click {
    int fIndex;
public:
    IndexClick(SkView* v, int index) : SkView::Click(v), fIndex(index) {}

    static int GetIndex(SkView::Click* click) {
        return ((IndexClick*)click)->fIndex;
    }
};

class DrawLineView : public SampleView {
    FatBits fFB;
    SkPoint fPts[2];
    bool    fIsRect;
public:
    DrawLineView() {
        fFB.setWHZ(24, 16, 48);
        fPts[0].set(48, 48);
        fPts[1].set(48 * 5, 48 * 4);
        fIsRect = false;
    }

    void setStyle(FatBits::Style s) {
        fFB.setStyle(s);
        this->inval(NULL);
    }

protected:
    virtual bool onQuery(SkEvent* evt) SK_OVERRIDE {
        if (SampleCode::TitleQ(*evt)) {
            SampleCode::TitleR(evt, "FatBits");
            return true;
        }
        SkUnichar uni;
        if (SampleCode::CharQ(*evt, &uni)) {
            switch (uni) {
                case 'r':
                    fIsRect = !fIsRect;
                    this->inval(NULL);
                    return true;
                case 'x':
                    fFB.setGrid(!fFB.getGrid());
                    this->inval(NULL);
                    return true;
                case 's':
                    if (FatBits::kStroke_Style == fFB.getStyle()) {
                        this->setStyle(FatBits::kHair_Style);
                    } else {
                        this->setStyle(FatBits::kStroke_Style);
                    }
                    return true;
                case 'a':
                    fFB.setAA(!fFB.getAA());
                    this->inval(NULL);
                    return true;
                case 'w':
                    fFB.setShowSkeleton(!fFB.getShowSkeleton());
                    this->inval(NULL);
                    return true;
                case 'g':
                    fFB.setUseGPU(!fFB.getUseGPU());
                    this->inval(NULL);
                    return true;
            }
        }
        return this->INHERITED::onQuery(evt);
    }

    virtual void onDrawContent(SkCanvas* canvas) {
        fFB.drawBG(canvas);
        if (fIsRect) {
            fFB.drawRect(canvas, fPts);
        } else {
            fFB.drawLine(canvas, fPts);
        }
        fFB.drawFG(canvas);

        {
            SkString str;
            str.printf("%s %s %s",
                       fFB.getAA() ? "AA" : "BW",
                       FatBits::kHair_Style == fFB.getStyle() ? "Hair" : "Stroke",
                       fFB.getUseGPU() ? "GPU" : "CPU");
            SkPaint paint;
            paint.setAntiAlias(true);
            paint.setTextSize(16);
            paint.setColor(SK_ColorBLUE);
            canvas->drawText(str.c_str(), str.size(), 10, 16, paint);
        }
    }

    virtual SkView::Click* onFindClickHandler(SkScalar x, SkScalar y) {
        SkPoint pt = { x, y };
        int index = -1;
        SkScalar tol = 12;
        if (fPts[0].equalsWithinTolerance(pt, tol)) {
            index = 0;
        } else if (fPts[1].equalsWithinTolerance(pt, tol)) {
            index = 1;
        }
        return new IndexClick(this, index);
    }

    virtual bool onClick(Click* click) {
        int index = IndexClick::GetIndex(click);
        if (index >= 0 && index <= 1) {
            fPts[index] = click->fCurr;
        } else {
            SkScalar dx = click->fCurr.fX - click->fPrev.fX;
            SkScalar dy = click->fCurr.fY - click->fPrev.fY;
            fPts[0].offset(dx, dy);
            fPts[1].offset(dx, dy);
        }
        this->inval(NULL);
        return true;
    }

private:

    typedef SampleView INHERITED;
};

//////////////////////////////////////////////////////////////////////////////

static SkView* MyFactory() { return new DrawLineView; }
static SkViewRegister reg(MyFactory);

<commit_msg>add 'c' toggle to test clipping<commit_after>/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SampleCode.h"
#include "SkView.h"
#include "SkCanvas.h"
#include "SkPath.h"
#include "SkRegion.h"
#include "SkShader.h"
#include "SkUtils.h"
#include "SkImage.h"
#include "SkSurface.h"

#define FAT_PIXEL_COLOR     SK_ColorBLACK
#define PIXEL_CENTER_SIZE   3
#define WIRE_FRAME_COLOR    0xFFFF0000  /*0xFF00FFFF*/
#define WIRE_FRAME_SIZE     1.5f

static void erase(SkSurface* surface) {
    surface->getCanvas()->clear(0);
}

static SkShader* createChecker() {
//    SkColor colors[] = { 0xFFFDFDFD, 0xFFF4F4F4 };
    SkColor colors[] = { 0xFFFFFFFF, 0xFFFFFFFF };
    SkBitmap bm;
    bm.setConfig(SkBitmap::kARGB_8888_Config, 2, 2);
    bm.allocPixels();
    bm.lockPixels();
    *bm.getAddr32(0, 0) = *bm.getAddr32(1, 1) = SkPreMultiplyColor(colors[0]);
    *bm.getAddr32(0, 1) = *bm.getAddr32(1, 0) = SkPreMultiplyColor(colors[1]);
    SkShader* s = SkShader::CreateBitmapShader(bm, SkShader::kRepeat_TileMode,
                                               SkShader::kRepeat_TileMode);

    SkMatrix m;
    m.setScale(12, 12);
    s->setLocalMatrix(m);
    return s;
}

class FatBits {
public:
    FatBits() : fShader(createChecker()) {
        fAA = false;
        fStyle = kHair_Style;
        fGrid = true;
        fShowSkeleton = true;
        fUseGPU = false;
        fUseClip = false;

        fClipRect.set(2, 2, 11, 8 );
    }

    int getZoom() const { return fZ; }

    bool getAA() const { return fAA; }
    void setAA(bool aa) { fAA = aa; }

    bool getGrid() const { return fGrid; }
    void setGrid(bool g) { fGrid = g; }

    bool getShowSkeleton() const { return fShowSkeleton; }
    void setShowSkeleton(bool ss) { fShowSkeleton = ss; }

    bool getUseGPU() const { return fUseGPU; }
    void setUseGPU(bool ug) { fUseGPU = ug; }

    bool getUseClip() const { return fUseClip; }
    void setUseClip(bool uc) { fUseClip = uc; }

    enum Style {
        kHair_Style,
        kStroke_Style,
    };
    Style getStyle() const { return fStyle; }
    void setStyle(Style s) { fStyle = s; }

    void setWHZ(int width, int height, int zoom) {
        fW = width;
        fH = height;
        fZ = zoom;
        fBounds.set(0, 0, SkIntToScalar(width * zoom), SkIntToScalar(height * zoom));
        fMatrix.setScale(SkIntToScalar(zoom), SkIntToScalar(zoom));
        fInverse.setScale(SK_Scalar1 / zoom, SK_Scalar1 / zoom);
        fShader->setLocalMatrix(fMatrix);

        SkImage::Info info = {
            width, height, SkImage::kPMColor_ColorType, SkImage::kPremul_AlphaType
        };
        fMinSurface.reset(SkSurface::NewRaster(info, NULL));
        info.fWidth *= zoom;
        info.fHeight *= zoom;
        fMaxSurface.reset(SkSurface::NewRaster(info, NULL));
    }

    void drawBG(SkCanvas*);
    void drawFG(SkCanvas*);
    void drawLine(SkCanvas*, SkPoint pts[2]);
    void drawRect(SkCanvas* canvas, SkPoint pts[2]);

private:
    bool fAA, fGrid, fShowSkeleton, fUseGPU, fUseClip;
    Style fStyle;
    int fW, fH, fZ;
    SkMatrix fMatrix, fInverse;
    SkRect   fBounds, fClipRect;
    SkAutoTUnref<SkShader> fShader;
    SkAutoTUnref<SkSurface> fMinSurface;
    SkAutoTUnref<SkSurface> fMaxSurface;

    void setupPaint(SkPaint* paint) {
        bool aa = this->getAA();
        switch (fStyle) {
            case kHair_Style:
                paint->setStrokeWidth(0);
                break;
            case kStroke_Style:
                paint->setStrokeWidth(SK_Scalar1);
//                paint->setStrokeWidth(SK_Scalar1 + SK_Scalar1/500);
                break;
        }
        paint->setAntiAlias(aa);
    }

    void setupSkeletonPaint(SkPaint* paint) {
        paint->setStyle(SkPaint::kStroke_Style);
        paint->setStrokeWidth(WIRE_FRAME_SIZE);
        paint->setColor(fShowSkeleton ? WIRE_FRAME_COLOR : 0);
        paint->setAntiAlias(true);
    }

    void drawLineSkeleton(SkCanvas* max, const SkPoint pts[]);
    void drawRectSkeleton(SkCanvas* max, const SkRect& r) {
        SkPaint paint;
        this->setupSkeletonPaint(&paint);
        SkPath path;

        if (fUseGPU && fAA) {
            SkRect rr = r;
            rr.inset(fZ/2, fZ/2);
            path.addRect(rr);
            path.moveTo(rr.fLeft, rr.fTop);
            path.lineTo(rr.fRight, rr.fBottom);
            rr = r;
            rr.inset(-fZ/2, -fZ/2);
            path.addRect(rr);
        } else {
            path.addRect(r);
            if (fUseGPU) {
                path.moveTo(r.fLeft, r.fTop);
                path.lineTo(r.fRight, r.fBottom);
            }
        }
        max->drawPath(path, paint);
    }

    void copyMinToMax() {
        erase(fMaxSurface);
        SkCanvas* canvas = fMaxSurface->getCanvas();
        canvas->save();
        canvas->concat(fMatrix);
        fMinSurface->draw(canvas, 0, 0, NULL);
        canvas->restore();

        SkPaint paint;
        paint.setXfermodeMode(SkXfermode::kClear_Mode);
        for (int iy = 1; iy < fH; ++iy) {
            SkScalar y = SkIntToScalar(iy * fZ);
            canvas->drawLine(0, y - SK_ScalarHalf, 999, y - SK_ScalarHalf, paint);
        }
        for (int ix = 1; ix < fW; ++ix) {
            SkScalar x = SkIntToScalar(ix * fZ);
            canvas->drawLine(x - SK_ScalarHalf, 0, x - SK_ScalarHalf, 999, paint);
        }
    }
};

void FatBits::drawBG(SkCanvas* canvas) {
    SkPaint paint;

    paint.setShader(fShader);
    canvas->drawRect(fBounds, paint);
    paint.setShader(NULL);
}

void FatBits::drawFG(SkCanvas* canvas) {
    SkPaint inner, outer;

    inner.setAntiAlias(true);
    inner.setColor(SK_ColorBLACK);
    inner.setStrokeWidth(PIXEL_CENTER_SIZE);

    outer.setAntiAlias(true);
    outer.setColor(SK_ColorWHITE);
    outer.setStrokeWidth(PIXEL_CENTER_SIZE + 2);

    SkScalar half = SkIntToScalar(fZ) / 2;
    for (int iy = 0; iy < fH; ++iy) {
        SkScalar y = SkIntToScalar(iy * fZ) + half;
        for (int ix = 0; ix < fW; ++ix) {
            SkScalar x = SkIntToScalar(ix * fZ) + half;

            canvas->drawPoint(x, y, outer);
            canvas->drawPoint(x, y, inner);
        }
    }

    if (fUseClip) {
        SkPaint p;
        p.setStyle(SkPaint::kStroke_Style);
        p.setColor(SK_ColorLTGRAY);
        SkRect r = {
            fClipRect.fLeft * fZ,
            fClipRect.fTop * fZ,
            fClipRect.fRight * fZ,
            fClipRect.fBottom * fZ
        };
        canvas->drawRect(r, p);
    }
}

void FatBits::drawLineSkeleton(SkCanvas* max, const SkPoint pts[]) {
    SkPaint paint;
    this->setupSkeletonPaint(&paint);

    SkPath path;
    path.moveTo(pts[0]);
    path.lineTo(pts[1]);

    switch (fStyle) {
        case kHair_Style:
            if (fUseGPU) {
                SkPaint p;
                p.setStyle(SkPaint::kStroke_Style);
                p.setStrokeWidth(SK_Scalar1 * fZ);
                SkPath dst;
                p.getFillPath(path, &dst);
                path.addPath(dst);
            }
            break;
        case kStroke_Style: {
            SkPaint p;
            p.setStyle(SkPaint::kStroke_Style);
            p.setStrokeWidth(SK_Scalar1 * fZ);
            SkPath dst;
            p.getFillPath(path, &dst);
            path = dst;

            if (fUseGPU) {
                path.moveTo(dst.getPoint(0));
                path.lineTo(dst.getPoint(2));
            }
        } break;
    }
    max->drawPath(path, paint);
}

void FatBits::drawLine(SkCanvas* canvas, SkPoint pts[]) {
    SkPaint paint;

    fInverse.mapPoints(pts, 2);

    if (fGrid) {
        SkScalar dd = 0;//SK_Scalar1 / 50;
        pts[0].set(SkScalarRoundToScalar(pts[0].fX) + dd,
                   SkScalarRoundToScalar(pts[0].fY) + dd);
        pts[1].set(SkScalarRoundToScalar(pts[1].fX) + dd,
                   SkScalarRoundToScalar(pts[1].fY) + dd);
    }

    erase(fMinSurface);
    this->setupPaint(&paint);
    paint.setColor(FAT_PIXEL_COLOR);
    if (fUseClip) {
        fMinSurface->getCanvas()->save();
        SkRect r = fClipRect;
        r.inset(SK_Scalar1/3, SK_Scalar1/3);
        fMinSurface->getCanvas()->clipRect(r, SkRegion::kIntersect_Op, true);
    }
    fMinSurface->getCanvas()->drawLine(pts[0].fX, pts[0].fY, pts[1].fX, pts[1].fY, paint);
    if (fUseClip) {
        fMinSurface->getCanvas()->restore();
    }
    this->copyMinToMax();

    SkCanvas* max = fMaxSurface->getCanvas();

    fMatrix.mapPoints(pts, 2);
    this->drawLineSkeleton(max, pts);

    fMaxSurface->draw(canvas, 0, 0, NULL);
}

void FatBits::drawRect(SkCanvas* canvas, SkPoint pts[2]) {
    SkPaint paint;

    fInverse.mapPoints(pts, 2);

    if (fGrid) {
        pts[0].set(SkScalarRoundToScalar(pts[0].fX), SkScalarRoundToScalar(pts[0].fY));
        pts[1].set(SkScalarRoundToScalar(pts[1].fX), SkScalarRoundToScalar(pts[1].fY));
    }

    SkRect r;
    r.set(pts, 2);

    erase(fMinSurface);
    this->setupPaint(&paint);
    paint.setColor(FAT_PIXEL_COLOR);
    fMinSurface->getCanvas()->drawRect(r, paint);
    this->copyMinToMax();

    SkCanvas* max = fMaxSurface->getCanvas();

    fMatrix.mapPoints(pts, 2);
    r.set(pts, 2);
    this->drawRectSkeleton(max, r);

    fMaxSurface->draw(canvas, 0, 0, NULL);
}

///////////////////////////////////////////////////////////////////////////////////////////////////

class IndexClick : public SkView::Click {
    int fIndex;
public:
    IndexClick(SkView* v, int index) : SkView::Click(v), fIndex(index) {}

    static int GetIndex(SkView::Click* click) {
        return ((IndexClick*)click)->fIndex;
    }
};

class DrawLineView : public SampleView {
    FatBits fFB;
    SkPoint fPts[2];
    bool    fIsRect;
public:
    DrawLineView() {
        fFB.setWHZ(24, 16, 48);
        fPts[0].set(48, 48);
        fPts[1].set(48 * 5, 48 * 4);
        fIsRect = false;
    }

    void setStyle(FatBits::Style s) {
        fFB.setStyle(s);
        this->inval(NULL);
    }

protected:
    virtual bool onQuery(SkEvent* evt) SK_OVERRIDE {
        if (SampleCode::TitleQ(*evt)) {
            SampleCode::TitleR(evt, "FatBits");
            return true;
        }
        SkUnichar uni;
        if (SampleCode::CharQ(*evt, &uni)) {
            switch (uni) {
                case 'c':
                    fFB.setUseClip(!fFB.getUseClip());
                    this->inval(NULL);
                    return true;
                case 'r':
                    fIsRect = !fIsRect;
                    this->inval(NULL);
                    return true;
                case 'x':
                    fFB.setGrid(!fFB.getGrid());
                    this->inval(NULL);
                    return true;
                case 's':
                    if (FatBits::kStroke_Style == fFB.getStyle()) {
                        this->setStyle(FatBits::kHair_Style);
                    } else {
                        this->setStyle(FatBits::kStroke_Style);
                    }
                    return true;
                case 'a':
                    fFB.setAA(!fFB.getAA());
                    this->inval(NULL);
                    return true;
                case 'w':
                    fFB.setShowSkeleton(!fFB.getShowSkeleton());
                    this->inval(NULL);
                    return true;
                case 'g':
                    fFB.setUseGPU(!fFB.getUseGPU());
                    this->inval(NULL);
                    return true;
            }
        }
        return this->INHERITED::onQuery(evt);
    }

    virtual void onDrawContent(SkCanvas* canvas) {
        fFB.drawBG(canvas);
        if (fIsRect) {
            fFB.drawRect(canvas, fPts);
        } else {
            fFB.drawLine(canvas, fPts);
        }
        fFB.drawFG(canvas);

        {
            SkString str;
            str.printf("%s %s %s %s",
                       fFB.getAA() ? "AA" : "BW",
                       FatBits::kHair_Style == fFB.getStyle() ? "Hair" : "Stroke",
                       fFB.getUseGPU() ? "GPU" : "CPU",
                       fFB.getUseClip() ? "clip" : "noclip");
            SkPaint paint;
            paint.setAntiAlias(true);
            paint.setTextSize(16);
            paint.setColor(SK_ColorBLUE);
            canvas->drawText(str.c_str(), str.size(), 10, 16, paint);
        }
    }

    virtual SkView::Click* onFindClickHandler(SkScalar x, SkScalar y) {
        SkPoint pt = { x, y };
        int index = -1;
        SkScalar tol = 12;
        if (fPts[0].equalsWithinTolerance(pt, tol)) {
            index = 0;
        } else if (fPts[1].equalsWithinTolerance(pt, tol)) {
            index = 1;
        }
        return new IndexClick(this, index);
    }

    virtual bool onClick(Click* click) {
        int index = IndexClick::GetIndex(click);
        if (index >= 0 && index <= 1) {
            fPts[index] = click->fCurr;
        } else {
            SkScalar dx = click->fCurr.fX - click->fPrev.fX;
            SkScalar dy = click->fCurr.fY - click->fPrev.fY;
            fPts[0].offset(dx, dy);
            fPts[1].offset(dx, dy);
        }
        this->inval(NULL);
        return true;
    }

private:

    typedef SampleView INHERITED;
};

//////////////////////////////////////////////////////////////////////////////

static SkView* MyFactory() { return new DrawLineView; }
static SkViewRegister reg(MyFactory);

<|endoftext|>


<commit_before>#ifndef STAN_LANG_AST_DOUBLE_BLOCK_TYPE_HPP
#define STAN_LANG_AST_DOUBLE_BLOCK_TYPE_HPP

#include <stan/lang/ast/node/offset_multiplier.hpp>
#include <stan/lang/ast/node/range.hpp>

namespace stan {
namespace lang {

/**
 * Double block var type.
 */
struct double_block_type {
  // TODO(VMatthijs): We should only allow to have either a range or a
  // offset_multiplier.

  /**
   * Bounds constraints
   */
  range bounds_;

  /**
   * Offset and multiplier
   */
  offset_multiplier ls_;

  /**
   * Construct a block var type with default values.
   */
  double_block_type();

  /**
   * Construct a block var type with specified values.
   *
   * @param bounds variable upper and/or lower bounds
   * @param ls variable offset and multiplier
   */
  explicit double_block_type(const range &bounds, const offset_multiplier &ls);

  /**
   * Construct a block var type with specified values.
   *
   * @param bounds variable upper and/or lower bounds
   */
  explicit double_block_type(const range &bounds);

  /**
   * Construct a block var type with specified values.
   *
   * @param ls variable offset and multiplier
   */
  explicit double_block_type(const offset_multiplier &ls);

  /**
   * Get bounds constraints.
   */
  range bounds() const;

  /**
   * Get offset and multiplier.
   */
  offset_multiplier ls() const;
};

}  // namespace lang
}  // namespace stan
#endif
<commit_msg>Update double_block_type.hpp<commit_after>#ifndef STAN_LANG_AST_DOUBLE_BLOCK_TYPE_HPP
#define STAN_LANG_AST_DOUBLE_BLOCK_TYPE_HPP

#include <stan/lang/ast/node/offset_multiplier.hpp>
#include <stan/lang/ast/node/range.hpp>

namespace stan {
namespace lang {

/**
 * Double block var type.
 */
struct double_block_type {

  /**
   * Bounds constraints
   */
  range bounds_;

  /**
   * Offset and multiplier
   */
  offset_multiplier ls_;

  /**
   * Construct a block var type with default values.
   */
  double_block_type();

  /**
   * Construct a block var type with specified values.
   *
   * @param bounds variable upper and/or lower bounds
   * @param ls variable offset and multiplier
   */
  explicit double_block_type(const range &bounds, const offset_multiplier &ls);

  /**
   * Construct a block var type with specified values.
   *
   * @param bounds variable upper and/or lower bounds
   */
  explicit double_block_type(const range &bounds);

  /**
   * Construct a block var type with specified values.
   *
   * @param ls variable offset and multiplier
   */
  explicit double_block_type(const offset_multiplier &ls);

  /**
   * Get bounds constraints.
   */
  range bounds() const;

  /**
   * Get offset and multiplier.
   */
  offset_multiplier ls() const;
};

}  // namespace lang
}  // namespace stan
#endif
<|endoftext|>


<commit_before>/**
 *  Copyright (c) 2014-present, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed in accordance with the terms specified in
 *  the LICENSE file found in the root directory of this source tree.
 */

// clang-format off
// Keep it on top of all other includes to fix double include WinSock.h header file
// which is windows specific boost build problem
#include "osquery/remote/transports/tls.h"
// clang-format on

#include <gtest/gtest.h>

#include <vector>

#include <osquery/config/config.h>
#include <osquery/database.h>
#include <osquery/flags.h>
#include <osquery/sql.h>
#include <osquery/system.h>
#include <osquery/registry_factory.h>

#include "osquery/remote/requests.h"
#include "osquery/remote/serializers/json.h"
#include <osquery/remote/tests/test_utils.h>
#include "osquery/tests/test_util.h"

#include <osquery/remote/enroll/tls_enroll.h>

namespace osquery {

DECLARE_string(tls_hostname);
DECLARE_bool(disable_database);

class TLSEnrollTests : public testing::Test {
 protected:
  void SetUp() override;
  void TearDown() override;

  Status testReadRequests(JSON& response_tree);

 private:
  std::string test_read_uri_;
};

void TLSEnrollTests::SetUp() {
  Initializer::platformSetup();
  registryAndPluginInit();
  FLAGS_disable_database = true;
  DatabasePlugin::setAllowOpen(true);
  DatabasePlugin::initPlugin();

  // Start a server.
  TLSServerRunner::start();
  TLSServerRunner::setClientConfig();
  clearNodeKey();

  test_read_uri_ =
      "https://" + Flag::getValue("tls_hostname") + "/test_read_requests";
}

void TLSEnrollTests::TearDown() {
  // Stop the server.
  TLSServerRunner::unsetClientConfig();
  TLSServerRunner::stop();
}

Status TLSEnrollTests::testReadRequests(JSON& response_tree) {
  Request<TLSTransport, JSONSerializer> request_(test_read_uri_);
  request_.setOption("hostname", Flag::getValue("tls_hostname"));
  auto status = request_.call(JSON());
  if (status.ok()) {
    status = request_.getResponse(response_tree);
  }
  return status;
}

TEST_F(TLSEnrollTests, test_tls_enroll) {
  auto node_key = getNodeKey("tls");

  JSON response;
  std::string value;

  auto status = testReadRequests(response);
  EXPECT_TRUE(status.ok());
  EXPECT_EQ(response.doc().Size(), 1U);

  auto const& obj = response.doc()[0];
  EXPECT_TRUE(obj.IsObject());
  EXPECT_TRUE(obj.HasMember("command"));
  EXPECT_TRUE(obj["command"].IsString());
  value = obj["command"].GetString();
  EXPECT_EQ(value, "enroll");

  EXPECT_TRUE(obj.HasMember("host_identifier"));
  EXPECT_TRUE(obj["host_identifier"].IsString());
  value = obj["host_identifier"].GetString();
  EXPECT_EQ(value, getHostIdentifier());

  // Check that osquery_info exists in the host_details.
  ASSERT_EQ(kEnrollHostDetails.count("osquery_info"), 1U);
  auto osquery_info = SQL::selectAllFrom("osquery_info");
  ASSERT_EQ(osquery_info.size(), 1U);
  ASSERT_EQ(osquery_info[0].count("uuid"), 1U);

  EXPECT_TRUE(obj.HasMember("host_details"));
  EXPECT_TRUE(obj["host_details"].HasMember("osquery_info"));
  EXPECT_TRUE(obj["host_details"]["osquery_info"].HasMember("uuid"));

  EXPECT_TRUE(obj["host_details"]["osquery_info"]["uuid"].IsString());
  value = obj["host_details"]["osquery_info"]["uuid"].GetString();
  EXPECT_EQ(osquery_info[0]["uuid"], value);
}
}
<commit_msg>Improve tls_enroll_tests (#5458)<commit_after>/**
 *  Copyright (c) 2014-present, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed in accordance with the terms specified in
 *  the LICENSE file found in the root directory of this source tree.
 */

// clang-format off
// Keep it on top of all other includes to fix double include WinSock.h header file
// which is windows specific boost build problem
#include "osquery/remote/transports/tls.h"
// clang-format on

#include <gtest/gtest.h>

#include <vector>

#include <osquery/config/config.h>
#include <osquery/database.h>
#include <osquery/flags.h>
#include <osquery/sql.h>
#include <osquery/system.h>
#include <osquery/registry_factory.h>

#include "osquery/remote/requests.h"
#include "osquery/remote/serializers/json.h"
#include <osquery/remote/tests/test_utils.h>
#include "osquery/tests/test_util.h"

#include <osquery/remote/enroll/tls_enroll.h>

namespace osquery {

DECLARE_string(tls_hostname);
DECLARE_bool(disable_database);

class TLSEnrollTests : public testing::Test {
 protected:
  void SetUp() override;
  void TearDown() override;

  Status testReadRequests(JSON& response_tree);

 private:
  std::string test_read_uri_;
};

void TLSEnrollTests::SetUp() {
  Initializer::platformSetup();
  registryAndPluginInit();
  FLAGS_disable_database = true;
  DatabasePlugin::setAllowOpen(true);
  DatabasePlugin::initPlugin();

  // Start a server.
  TLSServerRunner::start();
  TLSServerRunner::setClientConfig();
  clearNodeKey();

  test_read_uri_ =
      "https://" + Flag::getValue("tls_hostname") + "/test_read_requests";
}

void TLSEnrollTests::TearDown() {
  // Stop the server.
  TLSServerRunner::unsetClientConfig();
  TLSServerRunner::stop();
}

Status TLSEnrollTests::testReadRequests(JSON& response_tree) {
  Request<TLSTransport, JSONSerializer> request_(test_read_uri_);
  request_.setOption("hostname", Flag::getValue("tls_hostname"));
  auto status = request_.call(JSON());
  if (status.ok()) {
    status = request_.getResponse(response_tree);
  }
  return status;
}

TEST_F(TLSEnrollTests, test_tls_enroll) {
  auto node_key = getNodeKey("tls");

  JSON response;
  std::string value;

  auto status = testReadRequests(response);
  ASSERT_TRUE(status.ok());
  ASSERT_TRUE(response.doc().IsArray());
  ASSERT_EQ(response.doc().Size(), 1U);

  auto const& obj = response.doc()[0];
  ASSERT_TRUE(obj.IsObject());

  ASSERT_TRUE(obj.HasMember("command"));
  ASSERT_TRUE(obj["command"].IsString());
  value = obj["command"].GetString();
  EXPECT_EQ(value, "enroll");

  ASSERT_TRUE(obj.HasMember("host_identifier"));
  ASSERT_TRUE(obj["host_identifier"].IsString());
  value = obj["host_identifier"].GetString();
  EXPECT_EQ(value, getHostIdentifier());

  ASSERT_EQ(kEnrollHostDetails.count("osquery_info"), 1U);
  auto osquery_info = SQL::selectAllFrom("osquery_info");
  ASSERT_EQ(osquery_info.size(), 1U);
  ASSERT_EQ(osquery_info[0].count("uuid"), 1U);
  ASSERT_TRUE(obj.HasMember("host_details"));
  ASSERT_TRUE(obj["host_details"].HasMember("osquery_info"));
  ASSERT_TRUE(obj["host_details"]["osquery_info"].HasMember("uuid"));
  ASSERT_TRUE(obj["host_details"]["osquery_info"]["uuid"].IsString());
  value = obj["host_details"]["osquery_info"]["uuid"].GetString();
  EXPECT_EQ(osquery_info[0]["uuid"], value);
}
}
<|endoftext|>


<commit_before>#include "config.hpp"

#include "cpptoml/cpptoml.h"
#include "file_exist.hpp"
#include "file_name.hpp"
#include "osal.hpp"

Config::Config(int argc, char **argv)
  : target(fileName(getCurrentWorkingDir())),
    remoteRepository("https://github.com/antonte/coddle-repository.git"),
    remoteVersion("master"),
    cflags("-Wall -Wextra -march=native -gdwarf-3 -D_GLIBCXX_DEBUG -std=c++17"),
    debug(false)
{
  for (int i = 1; i < argc; ++i)
    if (argv[i] == std::string("debug"))
    {
      debug = true;
      break;
    }

  loadConfig("/etc/coddle.toml");
  loadConfig("~/.coddle.toml");
  loadConfig("coddle.toml");
}

void Config::loadConfig(const std::string &configFileName)
{
  if (isFileExist(configFileName))
  {
    auto &&toml = cpptoml::parse_file(configFileName);
    target = toml->get_as<std::string>("target").value_or(target);
    remoteRepository = toml->get_as<std::string>("remoteRepository").value_or(remoteRepository);
    remoteVersion = toml->get_as<std::string>("remoteVersion").value_or(remoteVersion);
    localRepository = toml->get_as<std::string>("localRepository").value_or(localRepository);
    cflags = toml->get_as<std::string>("cflags").value_or(cflags);
    debug = toml->get_as<bool>("debug").value_or(debug);
    multithreaded = toml->get_as<bool>("multithreaded").value_or(false);
  }
}
<commit_msg>Point to win branch of repository on Windows machines<commit_after>#include "config.hpp"

#include "cpptoml/cpptoml.h"
#include "file_exist.hpp"
#include "file_name.hpp"
#include "osal.hpp"

Config::Config(int argc, char **argv)
  : target(fileName(getCurrentWorkingDir())),
    remoteRepository("https://github.com/antonte/coddle-repository.git"),
#ifndef _WIN32
    remoteVersion("master"),
#else
    remoteVersion("win"),
#endif
    cflags("-Wall -Wextra -march=native -gdwarf-3 -D_GLIBCXX_DEBUG -std=c++17"),
    debug(false)
{
  for (int i = 1; i < argc; ++i)
    if (argv[i] == std::string("debug"))
    {
      debug = true;
      break;
    }

  loadConfig("/etc/coddle.toml");
  loadConfig("~/.coddle.toml");
  loadConfig("coddle.toml");
}

void Config::loadConfig(const std::string &configFileName)
{
  if (isFileExist(configFileName))
  {
    auto &&toml = cpptoml::parse_file(configFileName);
    target = toml->get_as<std::string>("target").value_or(target);
    remoteRepository = toml->get_as<std::string>("remoteRepository").value_or(remoteRepository);
    remoteVersion = toml->get_as<std::string>("remoteVersion").value_or(remoteVersion);
    localRepository = toml->get_as<std::string>("localRepository").value_or(localRepository);
    cflags = toml->get_as<std::string>("cflags").value_or(cflags);
    debug = toml->get_as<bool>("debug").value_or(debug);
    multithreaded = toml->get_as<bool>("multithreaded").value_or(false);
  }
}
<|endoftext|>


<commit_before>//  File: tpm_seal.cc
//  Author: Tom Roeder <tmroeder@google.com>
//
//  Description: A test of the TrouSerS API
//
//  Copyright (c) 2013, Google Inc.  All rights reserved.
//
// 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 <gflags/gflags.h>
#include <glog/logging.h>

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>

#include <tss/tss_error.h>
#include <tss/platform.h>
#include <tss/tss_defines.h>
#include <tss/tss_typedef.h>
#include <tss/tss_structs.h>
#include <tss/tspi.h>
#include <trousers/trousers.h>

#include <list>

using std::list;

int main(int argc, char **argv) {
  google::ParseCommandLineFlags(&argc, &argv, true);
  FLAGS_alsologtostderr = true;
  google::InitGoogleLogging(argv[0]);

  TSS_HCONTEXT tss_ctx;
  TSS_HTPM tpm;
  TSS_RESULT result;
  TSS_HKEY srk = 0;
  TSS_HPOLICY srk_policy = 0;
  TSS_UUID srk_uuid = {0x00000000, 0x0000, 0x0000, 0x00, 0x00, {0x00, 0x00, 0x00, 0x00, 0x00, 0x01}};
  BYTE secret[20];

  // Use the well-known secret of 20 zeroes.
  memset(secret, 0, 20);

  // Set up the TSS context and the SRK + policy (with the right secret).
  result = Tspi_Context_Create(&tss_ctx);
  CHECK_EQ(result, TSS_SUCCESS) << "Could not create a TSS context.";

  result = Tspi_Context_Connect(tss_ctx,
                                NULL /* Default TPM */);
  CHECK_EQ(result, TSS_SUCCESS) << "Could not connect to the default TPM";

  result = Tspi_Context_GetTpmObject(tss_ctx, &tpm);
  CHECK_EQ(result, TSS_SUCCESS) << "Could not get a handle to the TPM";

  result = Tspi_Context_LoadKeyByUUID(tss_ctx,
                                      TSS_PS_TYPE_SYSTEM,
                                      srk_uuid,
                                      &srk);
  CHECK_EQ(result, TSS_SUCCESS) << "Could not load the SRK handle";

  result = Tspi_GetPolicyObject(srk,
                                        TSS_POLICY_USAGE,
                                        &srk_policy);
  CHECK_EQ(result, TSS_SUCCESS) << "Could not get the SRK policy handle";

  result = Tspi_Policy_SetSecret(srk_policy,
                                 TSS_SECRET_MODE_SHA1,
                                 20,
                                 secret);
  CHECK_EQ(result, TSS_SUCCESS) << "Could not set the well-known secret";

  // Create and fill the PCR information.
  TSS_HPCRS pcrs;
  result = Tspi_Context_CreateObject(tss_ctx,
                                     TSS_OBJECT_TYPE_PCRS,
                                     0,
                                     &pcrs);
  CHECK_EQ(result, TSS_SUCCESS) << "Could not create a PCRs object";

  // This seal operation is meant to be used with DRTM, so the only PCRs that it
  // reads are 17 and 18. This is where you can set other PCRs to use.
  list<UINT32> pcrs_to_seal{17, 18};
  BYTE *pcr_value = NULL;
  UINT32 pcr_value_len = 0;
  for(UINT32 ui : pcrs_to_seal) {
    result = Tspi_TPM_PcrRead(tpm, ui, &pcr_value_len, &pcr_value);
    CHECK_EQ(result, TSS_SUCCESS) << "Could not read the value of PCR " << ui;

    result = Tspi_PcrComposite_SetPcrValue(pcrs, ui, pcr_value_len, pcr_value);
    CHECK_EQ(result, TSS_SUCCESS) << "Could not set the PCR value"
                                  << ui << " for sealing";
  }

  TSS_HENCDATA enc_data;
  result = Tspi_Context_CreateObject(tss_ctx,
                                     TSS_OBJECT_TYPE_ENCDATA,
                                     TSS_ENCDATA_SEAL,
                                     &enc_data);
  CHECK_EQ(result, TSS_SUCCESS) << "Could not create the data for sealing";

  BYTE data[16] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
  result = Tspi_Data_Seal(enc_data, srk, 16, data, pcrs);
  CHECK_EQ(result, TSS_SUCCESS) << "Could not seal the test data";

  // Extract the sealed data, then try to unseal it.
  BYTE *sealed_data;
  UINT32 sealed_data_len;
  result = Tspi_GetAttribData(enc_data,
                              TSS_TSPATTRIB_ENCDATA_BLOB,
                              TSS_TSPATTRIB_ENCDATABLOB_BLOB,
                              &sealed_data_len,
                              &sealed_data);
  CHECK_EQ(result, TSS_SUCCESS) << "Could not get the sealed bits";

  BYTE *unsealed_data;
  UINT32 unsealed_data_len;
  result = Tspi_Data_Unseal(enc_data, srk, &unsealed_data_len, &unsealed_data);
  CHECK_EQ(result, TSS_SUCCESS) << "Could not unseal the data";

  // Check that the data was unsealed correctly.
  CHECK_EQ(unsealed_data_len, 16U) << "The unsealed data was the wrong length";
  CHECK_EQ(memcmp(unsealed_data, data, 16), 0)
      << "The unsealed data did not match the original data";

  // Clean-up code.
  result = Tspi_Context_FreeMemory(tss_ctx, NULL);
  CHECK_EQ(result, TSS_SUCCESS) << "Could not free the context";

  result = Tspi_Context_Close(tss_ctx);
  CHECK_EQ(result, TSS_SUCCESS) << "Could not clean up the context";

  return 0;
}
<commit_msg>Load the AIK by blob. This method assumes for the moment that there is a file called aikblob in the current working directory and that this AIK blob is associated with a key in the TPM.<commit_after>//  File: tpm_seal.cc
//  Author: Tom Roeder <tmroeder@google.com>
//
//  Description: A test of the TrouSerS API
//
//  Copyright (c) 2013, Google Inc.  All rights reserved.
//
// 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 <gflags/gflags.h>
#include <glog/logging.h>

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>

#include <tss/tss_error.h>
#include <tss/platform.h>
#include <tss/tss_defines.h>
#include <tss/tss_typedef.h>
#include <tss/tss_structs.h>
#include <tss/tspi.h>
#include <trousers/trousers.h>

#include <fstream>
#include <list>
#include <sstream>
#include <string>

using std::ifstream;
using std::list;
using std::string;
using std::stringstream;

int main(int argc, char **argv) {
  google::ParseCommandLineFlags(&argc, &argv, true);
  FLAGS_alsologtostderr = true;
  google::InitGoogleLogging(argv[0]);

  TSS_HCONTEXT tss_ctx;
  TSS_HTPM tpm;
  TSS_RESULT result;
  TSS_HKEY srk = 0;
  TSS_HPOLICY srk_policy = 0;
  TSS_UUID srk_uuid = {0x00000000, 0x0000, 0x0000, 0x00, 0x00, {0x00, 0x00, 0x00, 0x00, 0x00, 0x01}};
  BYTE secret[20];

  // Use the well-known secret of 20 zeroes.
  memset(secret, 0, 20);

  // Set up the TSS context and the SRK + policy (with the right secret).
  result = Tspi_Context_Create(&tss_ctx);
  CHECK_EQ(result, TSS_SUCCESS) << "Could not create a TSS context.";

  result = Tspi_Context_Connect(tss_ctx,
                                NULL /* Default TPM */);
  CHECK_EQ(result, TSS_SUCCESS) << "Could not connect to the default TPM";

  result = Tspi_Context_GetTpmObject(tss_ctx, &tpm);
  CHECK_EQ(result, TSS_SUCCESS) << "Could not get a handle to the TPM";

  result = Tspi_Context_LoadKeyByUUID(tss_ctx,
                                      TSS_PS_TYPE_SYSTEM,
                                      srk_uuid,
                                      &srk);
  CHECK_EQ(result, TSS_SUCCESS) << "Could not load the SRK handle";

  result = Tspi_GetPolicyObject(srk,
                                        TSS_POLICY_USAGE,
                                        &srk_policy);
  CHECK_EQ(result, TSS_SUCCESS) << "Could not get the SRK policy handle";

  result = Tspi_Policy_SetSecret(srk_policy,
                                 TSS_SECRET_MODE_SHA1,
                                 20,
                                 secret);
  CHECK_EQ(result, TSS_SUCCESS) << "Could not set the well-known secret";

  // Create and fill the PCR information.
  TSS_HPCRS pcrs;
  result = Tspi_Context_CreateObject(tss_ctx,
                                     TSS_OBJECT_TYPE_PCRS,
                                     0,
                                     &pcrs);
  CHECK_EQ(result, TSS_SUCCESS) << "Could not create a PCRs object";

  // This seal operation is meant to be used with DRTM, so the only PCRs that it
  // reads are 17 and 18. This is where you can set other PCRs to use.
  list<UINT32> pcrs_to_seal{17, 18};
  BYTE *pcr_value = NULL;
  UINT32 pcr_value_len = 0;
  for(UINT32 ui : pcrs_to_seal) {
    result = Tspi_TPM_PcrRead(tpm, ui, &pcr_value_len, &pcr_value);
    CHECK_EQ(result, TSS_SUCCESS) << "Could not read the value of PCR " << ui;

    result = Tspi_PcrComposite_SetPcrValue(pcrs, ui, pcr_value_len, pcr_value);
    CHECK_EQ(result, TSS_SUCCESS) << "Could not set the PCR value"
                                  << ui << " for sealing";
  }

  TSS_HENCDATA enc_data;
  result = Tspi_Context_CreateObject(tss_ctx,
                                     TSS_OBJECT_TYPE_ENCDATA,
                                     TSS_ENCDATA_SEAL,
                                     &enc_data);
  CHECK_EQ(result, TSS_SUCCESS) << "Could not create the data for sealing";

  BYTE data[16] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
  result = Tspi_Data_Seal(enc_data, srk, 16, data, pcrs);
  CHECK_EQ(result, TSS_SUCCESS) << "Could not seal the test data";

  // Extract the sealed data, then try to unseal it.
  BYTE *sealed_data;
  UINT32 sealed_data_len;
  result = Tspi_GetAttribData(enc_data,
                              TSS_TSPATTRIB_ENCDATA_BLOB,
                              TSS_TSPATTRIB_ENCDATABLOB_BLOB,
                              &sealed_data_len,
                              &sealed_data);
  CHECK_EQ(result, TSS_SUCCESS) << "Could not get the sealed bits";

  BYTE *unsealed_data;
  UINT32 unsealed_data_len;
  result = Tspi_Data_Unseal(enc_data, srk, &unsealed_data_len, &unsealed_data);
  CHECK_EQ(result, TSS_SUCCESS) << "Could not unseal the data";

  // Check that the data was unsealed correctly.
  CHECK_EQ(unsealed_data_len, 16U) << "The unsealed data was the wrong length";
  CHECK_EQ(memcmp(unsealed_data, data, 16), 0)
      << "The unsealed data did not match the original data";

  // Get the public key blob from the AIK.
  // Load the blob and try to load the AIK
  ifstream blob_stream("aikblob", ifstream::in);
  stringstream blob_buf;
  blob_buf << blob_stream.rdbuf();
  string blob = blob_buf.str();
  UINT32 blob_len = (UINT32)blob.size();
  TSS_HKEY aik;
  result = Tspi_Context_LoadKeyByBlob(tss_ctx, srk, blob_len,
reinterpret_cast<BYTE *>(const_cast<char
*>(blob.data())), &aik);
  CHECK_EQ(result, TSS_SUCCESS) << "Could not load the AIK";

  // Clean-up code.
  result = Tspi_Context_FreeMemory(tss_ctx, NULL);
  CHECK_EQ(result, TSS_SUCCESS) << "Could not free the context";

  result = Tspi_Context_Close(tss_ctx);
  CHECK_EQ(result, TSS_SUCCESS) << "Could not clean up the context";

  return 0;
}
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "Setup.h"

#define ERRMSG_ERROR        _T("DeviceHive")
#define ERRMSG_GETTEMPNAME  _T("Failed to get temporary file name.")
#define ERRMSG_WRITETEMP    _T("Failed to write to temporary file.")
#define ERRMSG_RUNPARAMS    _T("Failed to define installation folder.")
#define MSG_NEWLINE         _T("\r\n")
#define COMMAND_LINE        _T("msiexec /i %s")

void ShowMessage(LPCTSTR lpText, LPCTSTR lpCaption, DWORD error_code);

int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
    _In_opt_ HINSTANCE hPrevInstance,
    _In_ LPTSTR    lpCmdLine,
    _In_ int       nCmdShow)
{
    UNREFERENCED_PARAMETER(hPrevInstance);
    UNREFERENCED_PARAMETER(lpCmdLine);

    HRSRC msi = FindResource(hInstance, MAKEINTRESOURCE(IDR_MSI), _T("MSI"));
    HGLOBAL global = LoadResource(hInstance, msi);
    LPVOID msiAddress = LockResource(global);
    DWORD msiSize = SizeofResource(hInstance, msi);

    TCHAR lpPathBuffer[MAX_PATH] = { 0 };
    GetTempPath(MAX_PATH, lpPathBuffer);

    TCHAR szDeviceHiveSetupMsi[MAX_PATH] = { 0 };
    if (GetTempFileName(lpPathBuffer, _T("NEW"), 0, szDeviceHiveSetupMsi) == 0)
    {
        ShowMessage(ERRMSG_GETTEMPNAME, ERRMSG_ERROR, GetLastError());
        return 1;
    }

    HANDLE hTempFile = CreateFile((LPTSTR)szDeviceHiveSetupMsi, GENERIC_READ | GENERIC_WRITE, 0, NULL,
                                  CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

    DWORD bytesWritten;
    TCHAR szTempName[MAX_PATH] = { 0 };

    WriteFile(hTempFile, msiAddress, msiSize, &bytesWritten, NULL);
    if (msiSize != bytesWritten)
    {
        CloseHandle(hTempFile);
        DeleteFile(szTempName);
        ShowMessage(ERRMSG_WRITETEMP, ERRMSG_ERROR, GetLastError());
        return 1;
    }

    CloseHandle(hTempFile);

    STARTUPINFO startInfo;
    memset(&startInfo, 0, sizeof(startInfo));
    startInfo.cb = sizeof(STARTUPINFO);
    PROCESS_INFORMATION procInfo;

    TCHAR cmdLine[MAX_PATH] = { 0 };
    swprintf_s(cmdLine, MAX_PATH, COMMAND_LINE, szDeviceHiveSetupMsi);

    if (CreateProcess(NULL, cmdLine, NULL, NULL, FALSE, 0, NULL, NULL, &startInfo, &procInfo) == FALSE)
    {
        DeleteFile(szTempName);
        ShowMessage(ERRMSG_RUNPARAMS, ERRMSG_ERROR, GetLastError());
        return 1;
    }

    return 0;
}

void ShowMessage(LPCTSTR lpText, LPCTSTR lpCaption, DWORD error_code)
{
    TCHAR message[MAX_PATH];
    _stprintf_s(message, MAX_PATH, _T("Error code: %d"), error_code);

    SIZE_T message_size = _tcslen(lpText) + _tcslen(MSG_NEWLINE) + _tcslen(message) + 1;
    TCHAR *lpMessage = new TCHAR[message_size];
    _tcscpy_s(lpMessage, message_size, lpText);
    _tcscat_s(lpMessage, message_size, MSG_NEWLINE);
    _tcscat_s(lpMessage, message_size, message);

    MessageBox(NULL, lpMessage, lpCaption, MB_OK | MB_ICONERROR);

    delete[] lpMessage;
}<commit_msg>Pass command args to setup.exe<commit_after>#include "stdafx.h"
#include "Setup.h"

#define ERRMSG_ERROR        _T("DeviceHive")
#define ERRMSG_GETTEMPNAME  _T("Failed to get temporary file name.")
#define ERRMSG_WRITETEMP    _T("Failed to write to temporary file.")
#define ERRMSG_RUNPARAMS    _T("Failed to define installation folder.")
#define MSG_NEWLINE         _T("\r\n")
#define COMMAND_LINE        _T("msiexec /i %s %s")

void ShowMessage(LPCTSTR lpText, LPCTSTR lpCaption, DWORD error_code);

int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
    _In_opt_ HINSTANCE hPrevInstance,
    _In_ LPTSTR    lpCmdLine,
    _In_ int       nCmdShow)
{
    UNREFERENCED_PARAMETER(hPrevInstance);
    UNREFERENCED_PARAMETER(lpCmdLine);

    HRSRC msi = FindResource(hInstance, MAKEINTRESOURCE(IDR_MSI), _T("MSI"));
    HGLOBAL global = LoadResource(hInstance, msi);
    LPVOID msiAddress = LockResource(global);
    DWORD msiSize = SizeofResource(hInstance, msi);

    TCHAR lpPathBuffer[MAX_PATH] = { 0 };
    GetTempPath(MAX_PATH, lpPathBuffer);

    TCHAR szDeviceHiveSetupMsi[MAX_PATH] = { 0 };
    if (GetTempFileName(lpPathBuffer, _T("NEW"), 0, szDeviceHiveSetupMsi) == 0)
    {
        ShowMessage(ERRMSG_GETTEMPNAME, ERRMSG_ERROR, GetLastError());
        return 1;
    }

    HANDLE hTempFile = CreateFile((LPTSTR)szDeviceHiveSetupMsi, GENERIC_READ | GENERIC_WRITE, 0, NULL,
                                  CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

    DWORD bytesWritten;
    TCHAR szTempName[MAX_PATH] = { 0 };

    WriteFile(hTempFile, msiAddress, msiSize, &bytesWritten, NULL);
    if (msiSize != bytesWritten)
    {
        CloseHandle(hTempFile);
        DeleteFile(szTempName);
        ShowMessage(ERRMSG_WRITETEMP, ERRMSG_ERROR, GetLastError());
        return 1;
    }

    CloseHandle(hTempFile);

    STARTUPINFO startInfo;
    memset(&startInfo, 0, sizeof(startInfo));
    startInfo.cb = sizeof(STARTUPINFO);
    PROCESS_INFORMATION procInfo;

    TCHAR cmdLine[MAX_PATH] = { 0 };
    swprintf_s(cmdLine, MAX_PATH, COMMAND_LINE, szDeviceHiveSetupMsi, lpCmdLine);

    if (CreateProcess(NULL, cmdLine, NULL, NULL, FALSE, 0, NULL, NULL, &startInfo, &procInfo) == FALSE)
    {
        DeleteFile(szTempName);
        ShowMessage(ERRMSG_RUNPARAMS, ERRMSG_ERROR, GetLastError());
        return 1;
    }

    return 0;
}

void ShowMessage(LPCTSTR lpText, LPCTSTR lpCaption, DWORD error_code)
{
    TCHAR message[MAX_PATH];
    _stprintf_s(message, MAX_PATH, _T("Error code: %d"), error_code);

    SIZE_T message_size = _tcslen(lpText) + _tcslen(MSG_NEWLINE) + _tcslen(message) + 1;
    TCHAR *lpMessage = new TCHAR[message_size];
    _tcscpy_s(lpMessage, message_size, lpText);
    _tcscat_s(lpMessage, message_size, MSG_NEWLINE);
    _tcscat_s(lpMessage, message_size, message);

    MessageBox(NULL, lpMessage, lpCaption, MB_OK | MB_ICONERROR);

    delete[] lpMessage;
}<|endoftext|>


<commit_before>/******************************************************************************
 *       SOFA, Simulation Open-Framework Architecture, version 1.0 beta 3      *
 *                (c) 2006-2008 MGH, INRIA, USTL, UJF, CNRS                    *
 *                                                                             *
 * This program is free software; you can redistribute it and/or modify it     *
 * under the terms of the GNU General Public License as published by the Free  *
 * Software Foundation; either version 2 of the License, or (at your option)   *
 * any later version.                                                          *
 *                                                                             *
 * This program 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 General Public License for    *
 * more details.                                                               *
 *                                                                             *
 * You should have received a copy of the GNU General Public License along     *
 * with this program; if not, write to the Free Software Foundation, Inc., 51  *
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.                   *
 *******************************************************************************
 *                            SOFA :: Applications                             *
 *                                                                             *
 * Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*
 * H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza,  *
 * M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy          *
 *                                                                             *
 * Contact information: contact@sofa-framework.org                             *
 ******************************************************************************/
#include "SofaPluginManager.h"
#include "FileManagement.h"

#ifdef SOFA_QT4
//#include <Q3Header>
//#include <Q3PopupMenu>
#include <QMessageBox>
#include <QLibrary>
#include <QSettings>
#else
//#include <qheader.h>
//#include <qpopupmenu.h>
#include <qmessagebox.h>
#include <qlibrary.h>
#include <qsettings.h>
#endif

#include <iostream>

#ifndef SOFA_QT4
typedef QListViewItem Q3ListViewItem;
#endif

namespace sofa
{
namespace gui
{
namespace qt
{

SofaPluginManager::SofaPluginManager()
{
    // SIGNAL / SLOTS CONNECTIONS
    this->connect(buttonAdd, SIGNAL(clicked() ),  this, SLOT( addLibrary() ));
    this->connect(buttonRemove, SIGNAL(clicked() ),  this, SLOT( removeLibrary() ));
    this->connect(listPlugins, SIGNAL(selectionChanged(Q3ListViewItem*) ), this, SLOT(updateComponentList(Q3ListViewItem*) ));
    this->connect(listPlugins, SIGNAL(selectionChanged(Q3ListViewItem*) ), this, SLOT(updateDescription(Q3ListViewItem*) ));

    //read the plugin list in the settings
    QSettings settings("SOFA-FRAMEWORK", "SOFA");
    int size = settings.beginReadArray("plugins");
    listPlugins->clear();
    typedef void (*componentLoader)();
    typedef char* (*componentStr)();

    for (int i=0 ; i<size; ++i)
    {
        settings.setArrayIndex(i);
        QString sfile = settings.value("location").toString();

        //load the plugin libs
        QLibrary lib(sfile);
        componentLoader componentLoaderFunc = (componentLoader) lib.resolve("initExternalModule");
        componentStr componentNameFunc = (componentStr) lib.resolve("getModuleName");
        //componentStr componentDescFunc = (componentStr) lib.resolve("getModuleDescription");
        //fill the list view
        if (componentLoaderFunc && componentNameFunc/* && componentDescFunc*/)
        {
            componentLoaderFunc();
            QString sname(componentNameFunc());
            //QString sdesc(componentDescFunc());
            Q3ListViewItem * item = new Q3ListViewItem(listPlugins, sname, sfile/*, sdesc*/);
            item->setSelectable(true);
        }
    }
    settings.endArray();
}

void SofaPluginManager::addLibrary()
{
    //get the lib to load
    QString sfile = getOpenFileName ( this, NULL, "dynamic library (*.dll *.so *.dylib)", "load library dialog",  "Choose the component library to load" );

    //try to load the lib
    QLibrary lib(sfile);
    if (!lib.load())
        std::cout<<lib.errorString().latin1()<<std::endl;

    //get the functions
    typedef void (*componentLoader)();
    typedef char* (*componentStr)();
    componentLoader componentLoaderFunc = (componentLoader) lib.resolve("initExternalModule");
    componentStr componentNameFunc = (componentStr) lib.resolve("getModuleName");
    //componentStr componentDescFunc = (componentStr) lib.resolve("getModuleDescription");

    if (componentLoaderFunc && componentNameFunc/* && componentDescFunc*/)
    {
        //fill the list view
        componentLoaderFunc();
        QString sname(componentNameFunc());
        //QString sdesc(componentDescFunc());
        Q3ListViewItem * item = new Q3ListViewItem(listPlugins, sname, sfile/*, sdesc*/);
        item->setSelectable(true);

        //add to the settings (to record it)
        QSettings settings("SOFA-FRAMEWORK", "SOFA");
        int size = settings.beginReadArray("plugins");
        settings.endArray();
        settings.beginWriteArray("plugins");
        settings.setArrayIndex(size);
        settings.setValue("location", sfile);
        settings.endArray();
    }
    else
    {
        QMessageBox * mbox = new QMessageBox(this,"library loading error");
        mbox->setText("Unable to load this library");
        mbox->show();
    }
}

void SofaPluginManager::removeLibrary()
{
    //get the selected item
    Q3ListViewItem * curItem = listPlugins->selectedItem();
    QString location = curItem->text(1); //get the location value
    //remove it from the list view
    listPlugins->removeItem(curItem);

    //remove it from the settings
    QSettings settings("SOFA-FRAMEWORK", "SOFA");
    int size = settings.beginReadArray("plugins");

    for (int i=0 ; i<size; ++i)
    {
        settings.setArrayIndex(i);
        QString sfile = settings.value("location").toString();
        if (sfile == location)
        {
            settings.endArray();
            settings.beginWriteArray("plugins");
            settings.setArrayIndex(i);
            settings.remove("location");
        }
    }

    settings.endArray();
}

void SofaPluginManager::updateComponentList(Q3ListViewItem* curItem)
{
    //update the component list when an item is selected
    listComponents->clear();
    QString location = curItem->text(1); //get the location value
    QLibrary lib(location);
    typedef char* (*componentStr)();
    componentStr componentListFunc = (componentStr) lib.resolve("getModuleComponentList");
    if(componentListFunc)
    {
        QString cpts( componentListFunc() );
        cpts.replace(", ","\n");
        cpts.replace(",","\n");
        listComponents->setText(cpts);
    }
}

void SofaPluginManager::updateDescription(Q3ListViewItem* curItem)
{
    //update the component list when an item is selected
    description->clear();
    QString location = curItem->text(1); //get the location value
    QLibrary lib(location);
    typedef char* (*componentStr)();
    componentStr componentDescFunc = (componentStr) lib.resolve("getModuleDescription");
    if(componentDescFunc)
    {
        description->setText(QString(componentDescFunc()));
    }
}

}
}
}

<commit_msg>r3789/sofa-dev : FIX : compilation with QT3<commit_after>/******************************************************************************
 *       SOFA, Simulation Open-Framework Architecture, version 1.0 beta 3      *
 *                (c) 2006-2008 MGH, INRIA, USTL, UJF, CNRS                    *
 *                                                                             *
 * This program is free software; you can redistribute it and/or modify it     *
 * under the terms of the GNU General Public License as published by the Free  *
 * Software Foundation; either version 2 of the License, or (at your option)   *
 * any later version.                                                          *
 *                                                                             *
 * This program 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 General Public License for    *
 * more details.                                                               *
 *                                                                             *
 * You should have received a copy of the GNU General Public License along     *
 * with this program; if not, write to the Free Software Foundation, Inc., 51  *
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.                   *
 *******************************************************************************
 *                            SOFA :: Applications                             *
 *                                                                             *
 * Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*
 * H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza,  *
 * M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy          *
 *                                                                             *
 * Contact information: contact@sofa-framework.org                             *
 ******************************************************************************/
#include "SofaPluginManager.h"
#include "FileManagement.h"

#ifdef SOFA_QT4
//#include <Q3Header>
//#include <Q3PopupMenu>
#include <QMessageBox>
#include <QLibrary>
#include <QSettings>
#else
//#include <qheader.h>
//#include <qpopupmenu.h>
#include <qmessagebox.h>
#include <qlibrary.h>
#include <qsettings.h>
#endif

#include <iostream>

#ifndef SOFA_QT4
typedef QListViewItem Q3ListViewItem;
#endif

namespace sofa
{
namespace gui
{
namespace qt
{

SofaPluginManager::SofaPluginManager()
{
#ifdef SOFA_QT4
    // SIGNAL / SLOTS CONNECTIONS
    this->connect(buttonAdd, SIGNAL(clicked() ),  this, SLOT( addLibrary() ));
    this->connect(buttonRemove, SIGNAL(clicked() ),  this, SLOT( removeLibrary() ));
    this->connect(listPlugins, SIGNAL(selectionChanged(Q3ListViewItem*) ), this, SLOT(updateComponentList(Q3ListViewItem*) ));
    this->connect(listPlugins, SIGNAL(selectionChanged(Q3ListViewItem*) ), this, SLOT(updateDescription(Q3ListViewItem*) ));

    //read the plugin list in the settings
    QSettings settings("SOFA-FRAMEWORK", "SOFA");
    int size = settings.beginReadArray("plugins");
    listPlugins->clear();
    typedef void (*componentLoader)();
    typedef char* (*componentStr)();

    for (int i=0 ; i<size; ++i)
    {
        settings.setArrayIndex(i);
        QString sfile = settings.value("location").toString();

        //load the plugin libs
        QLibrary lib(sfile);
        componentLoader componentLoaderFunc = (componentLoader) lib.resolve("initExternalModule");
        componentStr componentNameFunc = (componentStr) lib.resolve("getModuleName");
        //componentStr componentDescFunc = (componentStr) lib.resolve("getModuleDescription");
        //fill the list view
        if (componentLoaderFunc && componentNameFunc/* && componentDescFunc*/)
        {
            componentLoaderFunc();
            QString sname(componentNameFunc());
            //QString sdesc(componentDescFunc());
            Q3ListViewItem * item = new Q3ListViewItem(listPlugins, sname, sfile/*, sdesc*/);
            item->setSelectable(true);
        }
    }
    settings.endArray();
#endif
}

void SofaPluginManager::addLibrary()
{
#ifdef SOFA_QT4
    //get the lib to load
    QString sfile = getOpenFileName ( this, NULL, "dynamic library (*.dll *.so *.dylib)", "load library dialog",  "Choose the component library to load" );

    //try to load the lib
    QLibrary lib(sfile);
    if (!lib.load())
        std::cout<<lib.errorString().latin1()<<std::endl;

    //get the functions
    typedef void (*componentLoader)();
    typedef char* (*componentStr)();
    componentLoader componentLoaderFunc = (componentLoader) lib.resolve("initExternalModule");
    componentStr componentNameFunc = (componentStr) lib.resolve("getModuleName");
    //componentStr componentDescFunc = (componentStr) lib.resolve("getModuleDescription");

    if (componentLoaderFunc && componentNameFunc/* && componentDescFunc*/)
    {
        //fill the list view
        componentLoaderFunc();
        QString sname(componentNameFunc());
        //QString sdesc(componentDescFunc());
        Q3ListViewItem * item = new Q3ListViewItem(listPlugins, sname, sfile/*, sdesc*/);
        item->setSelectable(true);

        //add to the settings (to record it)
        QSettings settings("SOFA-FRAMEWORK", "SOFA");
        int size = settings.beginReadArray("plugins");
        settings.endArray();
        settings.beginWriteArray("plugins");
        settings.setArrayIndex(size);
        settings.setValue("location", sfile);
        settings.endArray();
    }
    else
    {
        QMessageBox * mbox = new QMessageBox(this,"library loading error");
        mbox->setText("Unable to load this library");
        mbox->show();
    }
#endif
}

void SofaPluginManager::removeLibrary()
{
#ifdef SOFA_QT4
    //get the selected item
    Q3ListViewItem * curItem = listPlugins->selectedItem();
    QString location = curItem->text(1); //get the location value
    //remove it from the list view
    listPlugins->removeItem(curItem);

    //remove it from the settings
    QSettings settings("SOFA-FRAMEWORK", "SOFA");
    int size = settings.beginReadArray("plugins");

    for (int i=0 ; i<size; ++i)
    {
        settings.setArrayIndex(i);
        QString sfile = settings.value("location").toString();
        if (sfile == location)
        {
            settings.endArray();
            settings.beginWriteArray("plugins");
            settings.setArrayIndex(i);
            settings.remove("location");
        }
    }

    settings.endArray();
#endif
}

void SofaPluginManager::updateComponentList(Q3ListViewItem* curItem)
{
#ifdef SOFA_QT4
    //update the component list when an item is selected
    listComponents->clear();
    QString location = curItem->text(1); //get the location value
    QLibrary lib(location);
    typedef char* (*componentStr)();
    componentStr componentListFunc = (componentStr) lib.resolve("getModuleComponentList");
    if(componentListFunc)
    {
        QString cpts( componentListFunc() );
        cpts.replace(", ","\n");
        cpts.replace(",","\n");
        listComponents->setText(cpts);
    }
#endif
}

void SofaPluginManager::updateDescription(Q3ListViewItem* curItem)
{
#ifdef SOFA_QT4
    //update the component list when an item is selected
    description->clear();
    QString location = curItem->text(1); //get the location value
    QLibrary lib(location);
    typedef char* (*componentStr)();
    componentStr componentDescFunc = (componentStr) lib.resolve("getModuleDescription");
    if(componentDescFunc)
    {
        description->setText(QString(componentDescFunc()));
    }
}
#endif
}
}
}

<|endoftext|>


<commit_before>
/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include "SampleCode.h"
#include "SkView.h"
#include "SkBlurMaskFilter.h"
#include "SkCanvas.h"
#include "SkGradientShader.h"
#include "SkGraphics.h"
#include "SkImageDecoder.h"
#include "SkPath.h"
#include "SkRandom.h"
#include "SkRegion.h"
#include "SkShader.h"
#include "SkUtils.h"
#include "SkXfermode.h"
#include "SkColorPriv.h"
#include "SkColorFilter.h"
#include "SkTime.h"
#include "SkTypeface.h"
#include "SkTextBox.h"
#include "SkOSFile.h"
#include "SkStream.h"
#include "SkKey.h"

#ifdef SK_BUILD_FOR_WIN
extern SkTypeface* SkCreateTypefaceFromLOGFONT(const LOGFONT&);
#endif

static const char gText[] =
	"When in the Course of human events it becomes necessary for one people "
	"to dissolve the political bands which have connected them with another "
	"and to assume among the powers of the earth, the separate and equal "
	"station to which the Laws of Nature and of Nature's God entitle them, "
	"a decent respect to the opinions of mankind requires that they should "
	"declare the causes which impel them to the separation.";

class TextBoxView : public SampleView {
public:
	TextBoxView() {
#ifdef SK_BUILD_FOR_WIN
		LOGFONT lf;
		sk_bzero(&lf, sizeof(lf));
		lf.lfHeight = 9;
		SkTypeface* tf0 = SkCreateTypefaceFromLOGFONT(lf);
		lf.lfHeight = 12;
		SkTypeface* tf1 = SkCreateTypefaceFromLOGFONT(lf);
		// we assert that different sizes should not affect which face we get
		SkASSERT(tf0 == tf1);
		tf0->unref();
		tf1->unref();
#endif
	}

protected:
    // overrides from SkEventSink
    virtual bool onQuery(SkEvent* evt)  {
        if (SampleCode::TitleQ(*evt)) {
            SkString str("TextBox");
            SampleCode::TitleR(evt, str.c_str());
            return true;
        }
        return this->INHERITED::onQuery(evt);
    }

    virtual void onDrawContent(SkCanvas* canvas) {
		SkScalar margin = 20;
        SkTextBox tbox;
		tbox.setMode(SkTextBox::kLineBreak_Mode);
		tbox.setBox(margin, margin,
					this->width() - margin, this->height() - margin);
		tbox.setSpacing(SkIntToScalar(3)/3, 0);

		SkPaint paint;
		paint.setAntiAlias(true);
        paint.setLCDRenderText(true);
		tbox.setText(gText, strlen(gText), paint);

		for (int i = 9; i < 24; i += 2) {
			paint.setTextSize(SkIntToScalar(i));
			tbox.draw(canvas);
			canvas->translate(0, tbox.getTextHeight() + paint.getFontSpacing());
		}
    }

private:
    typedef SampleView INHERITED;
};

//////////////////////////////////////////////////////////////////////////////

static SkView* MyFactory() { return new TextBoxView; }
static SkViewRegister reg(MyFactory);

<commit_msg>splitscreen for black and white versions<commit_after>
/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include "SampleCode.h"
#include "SkView.h"
#include "SkBlurMaskFilter.h"
#include "SkCanvas.h"
#include "SkColorShader.h"
#include "SkGradientShader.h"
#include "SkGraphics.h"
#include "SkImageDecoder.h"
#include "SkPath.h"
#include "SkRandom.h"
#include "SkRegion.h"
#include "SkShader.h"
#include "SkUtils.h"
#include "SkXfermode.h"
#include "SkColorPriv.h"
#include "SkColorFilter.h"
#include "SkTime.h"
#include "SkTypeface.h"
#include "SkTextBox.h"
#include "SkOSFile.h"
#include "SkStream.h"
#include "SkKey.h"

extern void skia_set_text_gamma(float blackGamma, float whiteGamma);

#ifdef SK_BUILD_FOR_WIN
extern SkTypeface* SkCreateTypefaceFromLOGFONT(const LOGFONT&);
#endif

static const char gText[] =
	"When in the Course of human events it becomes necessary for one people "
	"to dissolve the political bands which have connected them with another "
	"and to assume among the powers of the earth, the separate and equal "
	"station to which the Laws of Nature and of Nature's God entitle them, "
	"a decent respect to the opinions of mankind requires that they should "
	"declare the causes which impel them to the separation.";

class TextBoxView : public SampleView {
public:
	TextBoxView() {
#ifdef SK_BUILD_FOR_WIN
		LOGFONT lf;
		sk_bzero(&lf, sizeof(lf));
		lf.lfHeight = 9;
		SkTypeface* tf0 = SkCreateTypefaceFromLOGFONT(lf);
		lf.lfHeight = 12;
		SkTypeface* tf1 = SkCreateTypefaceFromLOGFONT(lf);
		// we assert that different sizes should not affect which face we get
		SkASSERT(tf0 == tf1);
		tf0->unref();
		tf1->unref();
#endif
    }

protected:
    // overrides from SkEventSink
    virtual bool onQuery(SkEvent* evt)  {
        if (SampleCode::TitleQ(*evt)) {
            SkString str("TextBox");
            SampleCode::TitleR(evt, str.c_str());
            return true;
        }
        return this->INHERITED::onQuery(evt);
    }

    void drawTest(SkCanvas* canvas, SkScalar w, SkScalar h, SkColor fg, SkColor bg) {
        SkAutoCanvasRestore acr(canvas, true);

        canvas->clipRect(SkRect::MakeWH(w, h));
        canvas->drawColor(bg);
		SkScalar margin = 20;
        SkTextBox tbox;
		tbox.setMode(SkTextBox::kLineBreak_Mode);
		tbox.setBox(margin, margin,
					w - margin, h - margin);
		tbox.setSpacing(SkIntToScalar(3)/3, 0);

		SkPaint paint;
		paint.setAntiAlias(true);
        paint.setLCDRenderText(true);
        paint.setColor(fg);
		tbox.setText(gText, strlen(gText), paint);

		for (int i = 9; i < 24; i += 2) {
			paint.setTextSize(SkIntToScalar(i));
			tbox.draw(canvas);
			canvas->translate(0, tbox.getTextHeight() + paint.getFontSpacing());
		}
    }

    virtual void onDrawContent(SkCanvas* canvas) {
        SkScalar width = this->width() / 3;
        drawTest(canvas, width, this->height(), SK_ColorBLACK, SK_ColorWHITE);
        canvas->translate(width, 0);
        drawTest(canvas, width, this->height(), SK_ColorWHITE, SK_ColorBLACK);
        canvas->translate(width, 0);
        drawTest(canvas, width, this->height()/2, SK_ColorGRAY, SK_ColorWHITE);
        canvas->translate(0, this->height()/2);
        drawTest(canvas, width, this->height()/2, SK_ColorGRAY, SK_ColorBLACK);
    }

private:
    typedef SampleView INHERITED;
};

//////////////////////////////////////////////////////////////////////////////

static SkView* MyFactory() { return new TextBoxView; }
static SkViewRegister reg(MyFactory);

<|endoftext|>