<commit_before>// @(#)root/gui:$Name:  $:$Id: TGProgressBar.cxx,v 1.8 2003/11/05 13:08:26 rdm Exp $
// Author: Fons Rademakers   10/10/2000

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TGProgressBar, TGHProgressBar and TGVProgressBar                     //
//                                                                      //
// The classes in this file implement progress bars. Progress bars can  //
// be used to show progress of tasks taking more then a few seconds.    //
// TGProgressBar is an abstract base class, use either TGHProgressBar   //
// or TGVProgressBar. TGHProgressBar can in addition show the position  //
// as text in the bar.                                                  //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TGProgressBar.h"
#include "TGResourcePool.h"
#include "Riostream.h"
#include "TColor.h"

const TGFont *TGProgressBar::fgDefaultFont = 0;
TGGC         *TGProgressBar::fgDefaultGC = 0;

ClassImp(TGProgressBar)
ClassImp(TGHProgressBar)
ClassImp(TGVProgressBar)

//______________________________________________________________________________
TGProgressBar::TGProgressBar(const TGWindow *p, UInt_t w, UInt_t h,
                             ULong_t back, ULong_t barcolor, GContext_t norm,
                             FontStruct_t font, UInt_t options) :
   TGFrame(p, w, h, options | kOwnBackground, back)
{
   // Create progress bar.

   fMin        = 0;
   fMax        = 100;
   fPos        = 0;
   fPosPix     = 0;
   fType       = kSolidFill;
   fBarType    = kStandard;
   fShowPos    = kFALSE;
   fPercent    = kTRUE;
   fNormGC     = norm;
   fFontStruct = font;
   fBarColorGC.SetForeground(barcolor);
}

//______________________________________________________________________________
void TGProgressBar::SetRange(Float_t min, Float_t max)
{
   // Set min and max of progress bar.

   if (min >= max) {
      Error("SetRange", "max must be > min");
      return;
   }

   Bool_t draw = kFALSE;
   if (fPos > fMin) {
      // already in progress... rescale
      if (fPos < min) fPos = min;
      if (fPos > max) fPos = max;
      draw = kTRUE;
   } else
      fPos = min;

   fMin = min;
   fMax = max;

   if (draw)
      DoRedraw();
}

//______________________________________________________________________________
void TGProgressBar::SetPosition(Float_t pos)
{
   // Set progress position between [min,max].

   if (pos < fMin) pos = fMin;
   if (pos > fMax) pos = fMax;

   if (fPos == pos)
      return;

   fPos = pos;

   //fClient->NeedRedraw(this);
   fDrawBar = kTRUE;
   DoRedraw();
}

//______________________________________________________________________________
void TGProgressBar::Increment(Float_t inc)
{
   // Increment progress position.

   if (fPos == fMax)
      return;

   fPos += inc;
   if (fPos > fMax) fPos = fMax;

   //fClient->NeedRedraw(this);
   fDrawBar = kTRUE;
   DoRedraw();
}

//______________________________________________________________________________
void TGProgressBar::Reset()
{
   // Reset progress bar (i.e. set pos to 0).

   fPos = 0;

   fClient->NeedRedraw(this);
}

//______________________________________________________________________________
void TGProgressBar::SetFillType(EFillType type)
{
   // Set fill type.

   fType = type;

   fClient->NeedRedraw(this);
}

//______________________________________________________________________________
void TGProgressBar::SetBarColor(ULong_t color)
{
   // Set progress bar color.

   fBarColorGC.SetForeground(color);

   fClient->NeedRedraw(this);
}

//______________________________________________________________________________
void TGProgressBar::SetBarColor(const char *color)
{
   // Set progress bar color.

   ULong_t ic;
   fClient->GetColorByName(color, ic);

   fBarColorGC.SetForeground(ic);

   fClient->NeedRedraw(this);
}

//______________________________________________________________________________
FontStruct_t TGProgressBar::GetDefaultFontStruct()
{
   if (!fgDefaultFont)
      fgDefaultFont = gClient->GetResourcePool()->GetDefaultFont();
   return fgDefaultFont->GetFontStruct();
}

//______________________________________________________________________________
const TGGC &TGProgressBar::GetDefaultGC()
{
   if (!fgDefaultGC)
      fgDefaultGC = new TGGC(*gClient->GetResourcePool()->GetFrameGC());
   return *fgDefaultGC;
}

//______________________________________________________________________________
TGHProgressBar::TGHProgressBar(const TGWindow *p, EBarType type, UInt_t w)
   : TGProgressBar(p, w, type == kStandard ? kProgressBarStandardWidth :
                   kProgressBarTextWidth, type == kStandard ? GetDefaultFrameBackground() :
                   fgWhitePixel, fgDefaultSelectedBackground, GetDefaultGC()(),
                   GetDefaultFontStruct(),
                   type == kStandard ? kSunkenFrame : kDoubleBorder | kSunkenFrame)
{
   // Simple constructor allow you to create either a standard progress
   // bar, or a more fancy progress bar (fancy means: double sized border,
   // white background and a bit wider to allow for text to be printed
   // in the bar.

   fBarType  = type;
   fBarWidth = (type == kStandard) ? kProgressBarStandardWidth : kProgressBarTextWidth;
}

//______________________________________________________________________________
void TGHProgressBar::ShowPosition(Bool_t set, Bool_t percent, const char *format)
{
   // Show postion text, either in percent or formatted according format.

   fShowPos = set;
   fPercent = percent;
   fFormat  = format;

   fClient->NeedRedraw(this);
}

//______________________________________________________________________________
void TGHProgressBar::DoRedraw()
{
   // Draw horizontal progress bar.

   if (!fDrawBar) {
      // calls TGProgressBar::DrawBorder()
      TGFrame::DoRedraw();
   }

   fPosPix = Int_t(((Float_t)fWidth - (fBorderWidth << 1)) *
             (fPos - fMin) / (fMax - fMin) +
             fBorderWidth);

   Int_t pospix = fPosPix;

   if (fType == kSolidFill)
      gVirtualX->FillRectangle(fId, fBarColorGC(), fBorderWidth,
                               fBorderWidth, fPosPix - fBorderWidth, fBarWidth -
                               (fBorderWidth << 1));
   else {
      Int_t blocksize = kBlockSize;
      Int_t delta     = kBlockSpace;
      Int_t pos       = fBorderWidth;
      while (pos < fPosPix) {
         if (pos + blocksize > Int_t(fWidth)-fBorderWidth)
            blocksize = fWidth-fBorderWidth-pos;
         gVirtualX->FillRectangle(fId, fBarColorGC(), pos,
                                  fBorderWidth, blocksize, fBarWidth -
                                  (fBorderWidth << 1));
         if (fDrawBar && fShowPos)
            gVirtualX->ClearArea(fId, pos+blocksize, fBorderWidth,
                                 delta, fBarWidth - (fBorderWidth << 1));

         pos += blocksize + delta;
      }
      pospix = pos - delta;
   }

   if (fShowPos) {
      char buf[256];
      if (fPercent)
         sprintf(buf, "%d%%", Int_t((fPos-fMin)/(fMax-fMin)*100.));
      else
         sprintf(buf, fFormat.Data(), fPos);

      Int_t x, y, max_ascent, max_descent;
      UInt_t twidth  = gVirtualX->TextWidth(fFontStruct, buf, strlen(buf));
      gVirtualX->GetFontProperties(fFontStruct, max_ascent, max_descent);
      UInt_t theight = max_ascent + max_descent;

      x = (fWidth - twidth) >> 1;
      y = (fHeight - theight) >> 1;

      if (fDrawBar && fPosPix < Int_t(x+twidth))
         gVirtualX->ClearArea(fId, pospix, fBorderWidth,
                              fWidth - pospix - fBorderWidth,
                              fBarWidth - (fBorderWidth << 1));

      gVirtualX->DrawString(fId, fNormGC, x, y + max_ascent, buf, strlen(buf));
   }

   fDrawBar = kFALSE;
}

//______________________________________________________________________________
TGVProgressBar::TGVProgressBar(const TGWindow *p, EBarType type, UInt_t h)
   : TGProgressBar(p, type == kStandard ? kProgressBarStandardWidth :
                   kProgressBarTextWidth, h, type == kStandard ? GetDefaultFrameBackground() :
                   fgWhitePixel, fgDefaultSelectedBackground, GetDefaultGC()(),
                   GetDefaultFontStruct(),
                   type == kStandard ? kSunkenFrame : kDoubleBorder | kSunkenFrame)
{
   // Simple constructor allow you to create either a standard progress
   // bar, or a more fancy progress bar (fancy means: double sized border,
   // white background and a bit wider to allow for text to be printed
   // in the bar.

   fBarType  = type;
   fBarWidth = (type == kStandard) ? kProgressBarStandardWidth : kProgressBarTextWidth;
}

//______________________________________________________________________________
void TGVProgressBar::DoRedraw()
{
   // Draw vertical progress bar.

   if (!fDrawBar) {
      // calls TGProgressBar::DrawBorder()
      TGFrame::DoRedraw();
   }

   fPosPix = Int_t(((Float_t)fHeight - (fBorderWidth << 1)) *
             (fPos - fMin) / (fMax - fMin) +
             fBorderWidth);

   if (fType == kSolidFill)
      gVirtualX->FillRectangle(fId, fBarColorGC(), fBorderWidth,
                               fHeight - fPosPix, fBarWidth - (fBorderWidth << 1),
                               fPosPix - fBorderWidth);
   else {
      Int_t blocksize = kBlockSize;
      Int_t delta     = kBlockSpace;
      Int_t pos       = fBorderWidth;
      while (pos < fPosPix) {
         if (pos + blocksize > Int_t(fHeight)-fBorderWidth)
            blocksize = fHeight-fBorderWidth-pos;
         gVirtualX->FillRectangle(fId, fBarColorGC(), fBorderWidth,
                                  fHeight - pos - blocksize, fBarWidth - (fBorderWidth << 1),
                                  blocksize);
         pos += blocksize + delta;
      }
   }

   if (fShowPos) {
      // not text shown for vertical progress bars
   }

   fDrawBar = kFALSE;
}

//______________________________________________________________________________
void TGProgressBar::SavePrimitive(ofstream &out, Option_t *option)
{
   // Save progress bar parameters as a C++ statement(s) on output stream out.

   const char *barcolor;
   char quote = '"';
   switch (fBarType) {
      case kFancy:
         if (GetOptions() != (kSunkenFrame | kDoubleBorder | kOwnBackground))
            out << "   " << GetName() << "->ChangeOptions(" << GetOptionString()
                << ");" << endl;
         if (GetBackground() != GetWhitePixel()) {
            SaveUserColor(out, option);
            out << "   " << GetName() << "->SetBackgroundColor(ucolor);" << endl;
         }
         break;

      case kStandard:
         if (GetOptions() != (kSunkenFrame | kOwnBackground))
            out << "   " << GetName() << "->ChangeOptions(" << GetOptionString()
                << ");" << endl;
         if (GetBackground() != GetDefaultFrameBackground()) {
            SaveUserColor(out, option);
            out << "   " << GetName() << "->SetBackgroundColor(ucolor);" << endl;
         }
         break;
   }

   if (fBarColorGC.GetForeground() != GetDefaultSelectedBackground()) {
      barcolor = TColor::PixelAsHexString(fBarColorGC.GetForeground());
      out << "   " << GetName() <<"->SetBarColor(" << quote << barcolor << quote
          << ");"  << endl;
   }

   if (fMin != 0 && fMax != 100)
      out << "   " << GetName() << "->SetRange(" << fMin << "," << fMax << ");" << endl;

   out <<"   "<< GetName() <<"->SetPosition("<< fPos <<");"<< endl;

}

//______________________________________________________________________________
void TGVProgressBar::SavePrimitive(ofstream &out, Option_t *option)
{
   // Save a vertical progress bar as a C++ statement(s) on output stream out.

   out << "   TGVProgressBar *";
   out << GetName() << " = new TGVProgressBar(" << fParent->GetName();

   if ((fBarType == kFancy) && (fBarWidth == kProgressBarTextWidth)) {
      out << ",TGProgressBar::kFancy";
   } else if ((fBarType == kStandard) && (fBarWidth == kProgressBarStandardWidth)){
      out << ",TGProgressBar::kStandard";
   }

   out << "," << GetHeight() <<");" << endl;

   if (GetFillType() == kBlockFill)
      out << "   " << GetName() <<"->SetFillType(TGProgressBar::kBlockFill);"<< endl;

   TGProgressBar::SavePrimitive(out, option);
}

//______________________________________________________________________________
void TGHProgressBar::SavePrimitive(ofstream &out, Option_t *option)
{
    // Save a horizontal progress bar as a C++ statement(s) on output stream out

   char quote = '"';

   out <<"   TGHProgressBar *";
   out << GetName() <<" = new TGHProgressBar("<< fParent->GetName();

   if ((fBarType == kFancy) && (fBarWidth == kProgressBarTextWidth)) {
      out << ",TGProgressBar::kFancy";
   } else if ((fBarType == kStandard) && (fBarWidth == kProgressBarStandardWidth)){
      out << ",TGProgressBar::kStandard";
   }

   out << "," << GetWidth() << ");" << endl;

   if (GetFillType() == kBlockFill)
      out << "   " << GetName() <<"->SetFillType(TGProgressBar::kBlockFill);"<< endl;

   if (GetShowPos()) {
       out << "   " << GetName() <<"->ShowPosition(kTRUE,";
       if (UsePercent()) {
           out << "kTRUE,";
       } else {
         out << "kFALSE,";
       }
       out << quote << GetFormat() << quote << ");"<< endl;

   } else if (UsePercent() && !GetFillType()) {
      out << "   " << GetName() <<"->ShowPosition();" << endl;
   }
   TGProgressBar::SavePrimitive(out, option);
}
<commit_msg>Initialize members fDrawBar and fBarWidth in the constructors. fDrawBar is not initialized when DoRedraw is called.<commit_after>// @(#)root/gui:$Name:  $:$Id: TGProgressBar.cxx,v 1.9 2003/11/12 19:34:59 rdm Exp $
// Author: Fons Rademakers   10/10/2000

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TGProgressBar, TGHProgressBar and TGVProgressBar                     //
//                                                                      //
// The classes in this file implement progress bars. Progress bars can  //
// be used to show progress of tasks taking more then a few seconds.    //
// TGProgressBar is an abstract base class, use either TGHProgressBar   //
// or TGVProgressBar. TGHProgressBar can in addition show the position  //
// as text in the bar.                                                  //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TGProgressBar.h"
#include "TGResourcePool.h"
#include "Riostream.h"
#include "TColor.h"

const TGFont *TGProgressBar::fgDefaultFont = 0;
TGGC         *TGProgressBar::fgDefaultGC = 0;

ClassImp(TGProgressBar)
ClassImp(TGHProgressBar)
ClassImp(TGVProgressBar)

//______________________________________________________________________________
TGProgressBar::TGProgressBar(const TGWindow *p, UInt_t w, UInt_t h,
                             ULong_t back, ULong_t barcolor, GContext_t norm,
                             FontStruct_t font, UInt_t options) :
   TGFrame(p, w, h, options | kOwnBackground, back)
{
   // Create progress bar.

   fMin        = 0;
   fMax        = 100;
   fPos        = 0;
   fPosPix     = 0;
   fType       = kSolidFill;
   fBarType    = kStandard;
   fShowPos    = kFALSE;
   fPercent    = kTRUE;
   fNormGC     = norm;
   fFontStruct = font;
   fBarColorGC.SetForeground(barcolor);
   fBarWidth   = kProgressBarStandardWidth;
   fDrawBar    = kFALSE;
}

//______________________________________________________________________________
void TGProgressBar::SetRange(Float_t min, Float_t max)
{
   // Set min and max of progress bar.

   if (min >= max) {
      Error("SetRange", "max must be > min");
      return;
   }

   Bool_t draw = kFALSE;
   if (fPos > fMin) {
      // already in progress... rescale
      if (fPos < min) fPos = min;
      if (fPos > max) fPos = max;
      draw = kTRUE;
   } else
      fPos = min;

   fMin = min;
   fMax = max;

   if (draw)
      DoRedraw();
}

//______________________________________________________________________________
void TGProgressBar::SetPosition(Float_t pos)
{
   // Set progress position between [min,max].

   if (pos < fMin) pos = fMin;
   if (pos > fMax) pos = fMax;

   if (fPos == pos)
      return;

   fPos = pos;

   //fClient->NeedRedraw(this);
   fDrawBar = kTRUE;
   DoRedraw();
}

//______________________________________________________________________________
void TGProgressBar::Increment(Float_t inc)
{
   // Increment progress position.

   if (fPos == fMax)
      return;

   fPos += inc;
   if (fPos > fMax) fPos = fMax;

   //fClient->NeedRedraw(this);
   fDrawBar = kTRUE;
   DoRedraw();
}

//______________________________________________________________________________
void TGProgressBar::Reset()
{
   // Reset progress bar (i.e. set pos to 0).

   fPos = 0;

   fClient->NeedRedraw(this);
}

//______________________________________________________________________________
void TGProgressBar::SetFillType(EFillType type)
{
   // Set fill type.

   fType = type;

   fClient->NeedRedraw(this);
}

//______________________________________________________________________________
void TGProgressBar::SetBarColor(ULong_t color)
{
   // Set progress bar color.

   fBarColorGC.SetForeground(color);

   fClient->NeedRedraw(this);
}

//______________________________________________________________________________
void TGProgressBar::SetBarColor(const char *color)
{
   // Set progress bar color.

   ULong_t ic;
   fClient->GetColorByName(color, ic);

   fBarColorGC.SetForeground(ic);

   fClient->NeedRedraw(this);
}

//______________________________________________________________________________
FontStruct_t TGProgressBar::GetDefaultFontStruct()
{
   if (!fgDefaultFont)
      fgDefaultFont = gClient->GetResourcePool()->GetDefaultFont();
   return fgDefaultFont->GetFontStruct();
}

//______________________________________________________________________________
const TGGC &TGProgressBar::GetDefaultGC()
{
   if (!fgDefaultGC)
      fgDefaultGC = new TGGC(*gClient->GetResourcePool()->GetFrameGC());
   return *fgDefaultGC;
}

//______________________________________________________________________________
TGHProgressBar::TGHProgressBar(const TGWindow *p, EBarType type, UInt_t w)
   : TGProgressBar(p, w, type == kStandard ? kProgressBarStandardWidth :
                   kProgressBarTextWidth, type == kStandard ? GetDefaultFrameBackground() :
                   fgWhitePixel, fgDefaultSelectedBackground, GetDefaultGC()(),
                   GetDefaultFontStruct(),
                   type == kStandard ? kSunkenFrame : kDoubleBorder | kSunkenFrame)
{
   // Simple constructor allow you to create either a standard progress
   // bar, or a more fancy progress bar (fancy means: double sized border,
   // white background and a bit wider to allow for text to be printed
   // in the bar.

   fBarType  = type;
   fBarWidth = (type == kStandard) ? kProgressBarStandardWidth : kProgressBarTextWidth;
}

//______________________________________________________________________________
void TGHProgressBar::ShowPosition(Bool_t set, Bool_t percent, const char *format)
{
   // Show postion text, either in percent or formatted according format.

   fShowPos = set;
   fPercent = percent;
   fFormat  = format;

   fClient->NeedRedraw(this);
}

//______________________________________________________________________________
void TGHProgressBar::DoRedraw()
{
   // Draw horizontal progress bar.

   if (!fDrawBar) {
      // calls TGProgressBar::DrawBorder()
      TGFrame::DoRedraw();
   }

   fPosPix = Int_t(((Float_t)fWidth - (fBorderWidth << 1)) *
             (fPos - fMin) / (fMax - fMin) +
             fBorderWidth);

   Int_t pospix = fPosPix;

   if (fType == kSolidFill)
      gVirtualX->FillRectangle(fId, fBarColorGC(), fBorderWidth,
                               fBorderWidth, fPosPix - fBorderWidth, fBarWidth -
                               (fBorderWidth << 1));
   else {
      Int_t blocksize = kBlockSize;
      Int_t delta     = kBlockSpace;
      Int_t pos       = fBorderWidth;
      while (pos < fPosPix) {
         if (pos + blocksize > Int_t(fWidth)-fBorderWidth)
            blocksize = fWidth-fBorderWidth-pos;
         gVirtualX->FillRectangle(fId, fBarColorGC(), pos,
                                  fBorderWidth, blocksize, fBarWidth -
                                  (fBorderWidth << 1));
         if (fDrawBar && fShowPos)
            gVirtualX->ClearArea(fId, pos+blocksize, fBorderWidth,
                                 delta, fBarWidth - (fBorderWidth << 1));

         pos += blocksize + delta;
      }
      pospix = pos - delta;
   }

   if (fShowPos) {
      char buf[256];
      if (fPercent)
         sprintf(buf, "%d%%", Int_t((fPos-fMin)/(fMax-fMin)*100.));
      else
         sprintf(buf, fFormat.Data(), fPos);

      Int_t x, y, max_ascent, max_descent;
      UInt_t twidth  = gVirtualX->TextWidth(fFontStruct, buf, strlen(buf));
      gVirtualX->GetFontProperties(fFontStruct, max_ascent, max_descent);
      UInt_t theight = max_ascent + max_descent;

      x = (fWidth - twidth) >> 1;
      y = (fHeight - theight) >> 1;

      if (fDrawBar && fPosPix < Int_t(x+twidth))
         gVirtualX->ClearArea(fId, pospix, fBorderWidth,
                              fWidth - pospix - fBorderWidth,
                              fBarWidth - (fBorderWidth << 1));

      gVirtualX->DrawString(fId, fNormGC, x, y + max_ascent, buf, strlen(buf));
   }

   fDrawBar = kFALSE;
}

//______________________________________________________________________________
TGVProgressBar::TGVProgressBar(const TGWindow *p, EBarType type, UInt_t h)
   : TGProgressBar(p, type == kStandard ? kProgressBarStandardWidth :
                   kProgressBarTextWidth, h, type == kStandard ? GetDefaultFrameBackground() :
                   fgWhitePixel, fgDefaultSelectedBackground, GetDefaultGC()(),
                   GetDefaultFontStruct(),
                   type == kStandard ? kSunkenFrame : kDoubleBorder | kSunkenFrame)
{
   // Simple constructor allow you to create either a standard progress
   // bar, or a more fancy progress bar (fancy means: double sized border,
   // white background and a bit wider to allow for text to be printed
   // in the bar.

   fBarType  = type;
   fBarWidth = (type == kStandard) ? kProgressBarStandardWidth : kProgressBarTextWidth;
   fDrawBar  = kFALSE;
}

//______________________________________________________________________________
void TGVProgressBar::DoRedraw()
{
   // Draw vertical progress bar.

   if (!fDrawBar) {
      // calls TGProgressBar::DrawBorder()
      TGFrame::DoRedraw();
   }

   fPosPix = Int_t(((Float_t)fHeight - (fBorderWidth << 1)) *
             (fPos - fMin) / (fMax - fMin) +
             fBorderWidth);

   if (fType == kSolidFill)
      gVirtualX->FillRectangle(fId, fBarColorGC(), fBorderWidth,
                               fHeight - fPosPix, fBarWidth - (fBorderWidth << 1),
                               fPosPix - fBorderWidth);
   else {
      Int_t blocksize = kBlockSize;
      Int_t delta     = kBlockSpace;
      Int_t pos       = fBorderWidth;
      while (pos < fPosPix) {
         if (pos + blocksize > Int_t(fHeight)-fBorderWidth)
            blocksize = fHeight-fBorderWidth-pos;
         gVirtualX->FillRectangle(fId, fBarColorGC(), fBorderWidth,
                                  fHeight - pos - blocksize, fBarWidth - (fBorderWidth << 1),
                                  blocksize);
         pos += blocksize + delta;
      }
   }

   if (fShowPos) {
      // not text shown for vertical progress bars
   }

   fDrawBar = kFALSE;
}

//______________________________________________________________________________
void TGProgressBar::SavePrimitive(ofstream &out, Option_t *option)
{
   // Save progress bar parameters as a C++ statement(s) on output stream out.

   const char *barcolor;
   char quote = '"';
   switch (fBarType) {
      case kFancy:
         if (GetOptions() != (kSunkenFrame | kDoubleBorder | kOwnBackground))
            out << "   " << GetName() << "->ChangeOptions(" << GetOptionString()
                << ");" << endl;
         if (GetBackground() != GetWhitePixel()) {
            SaveUserColor(out, option);
            out << "   " << GetName() << "->SetBackgroundColor(ucolor);" << endl;
         }
         break;

      case kStandard:
         if (GetOptions() != (kSunkenFrame | kOwnBackground))
            out << "   " << GetName() << "->ChangeOptions(" << GetOptionString()
                << ");" << endl;
         if (GetBackground() != GetDefaultFrameBackground()) {
            SaveUserColor(out, option);
            out << "   " << GetName() << "->SetBackgroundColor(ucolor);" << endl;
         }
         break;
   }

   if (fBarColorGC.GetForeground() != GetDefaultSelectedBackground()) {
      barcolor = TColor::PixelAsHexString(fBarColorGC.GetForeground());
      out << "   " << GetName() <<"->SetBarColor(" << quote << barcolor << quote
          << ");"  << endl;
   }

   if (fMin != 0 && fMax != 100)
      out << "   " << GetName() << "->SetRange(" << fMin << "," << fMax << ");" << endl;

   out <<"   "<< GetName() <<"->SetPosition("<< fPos <<");"<< endl;

}

//______________________________________________________________________________
void TGVProgressBar::SavePrimitive(ofstream &out, Option_t *option)
{
   // Save a vertical progress bar as a C++ statement(s) on output stream out.

   out << "   TGVProgressBar *";
   out << GetName() << " = new TGVProgressBar(" << fParent->GetName();

   if ((fBarType == kFancy) && (fBarWidth == kProgressBarTextWidth)) {
      out << ",TGProgressBar::kFancy";
   } else if ((fBarType == kStandard) && (fBarWidth == kProgressBarStandardWidth)){
      out << ",TGProgressBar::kStandard";
   }

   out << "," << GetHeight() <<");" << endl;

   if (GetFillType() == kBlockFill)
      out << "   " << GetName() <<"->SetFillType(TGProgressBar::kBlockFill);"<< endl;

   TGProgressBar::SavePrimitive(out, option);
}

//______________________________________________________________________________
void TGHProgressBar::SavePrimitive(ofstream &out, Option_t *option)
{
    // Save a horizontal progress bar as a C++ statement(s) on output stream out

   char quote = '"';

   out <<"   TGHProgressBar *";
   out << GetName() <<" = new TGHProgressBar("<< fParent->GetName();

   if ((fBarType == kFancy) && (fBarWidth == kProgressBarTextWidth)) {
      out << ",TGProgressBar::kFancy";
   } else if ((fBarType == kStandard) && (fBarWidth == kProgressBarStandardWidth)){
      out << ",TGProgressBar::kStandard";
   }

   out << "," << GetWidth() << ");" << endl;

   if (GetFillType() == kBlockFill)
      out << "   " << GetName() <<"->SetFillType(TGProgressBar::kBlockFill);"<< endl;

   if (GetShowPos()) {
       out << "   " << GetName() <<"->ShowPosition(kTRUE,";
       if (UsePercent()) {
           out << "kTRUE,";
       } else {
         out << "kFALSE,";
       }
       out << quote << GetFormat() << quote << ");"<< endl;

   } else if (UsePercent() && !GetFillType()) {
      out << "   " << GetName() <<"->ShowPosition();" << endl;
   }
   TGProgressBar::SavePrimitive(out, option);
}
<|endoftext|>


<commit_before>#include "ui/click-menu.h"
#include <QMouseEvent>

ClickMenu::ClickMenu(QWidget *parent)
	: QMenu(parent)
{}

void ClickMenu::mouseReleaseEvent(QMouseEvent *event)
{
	QAction *action = actionAt(event->pos());
	if (action == nullptr) {
		QMenu::mouseReleaseEvent(event);
		return;
	}

	if (event->button() == Qt::MiddleButton) {
		emit triggeredMiddle(action);
	} else {
		action->trigger();
	}

	close();
	event->accept();
}
<commit_msg>Fix quick tab navigation closing directly when opened with many tabs (fix #1504)<commit_after>#include "ui/click-menu.h"
#include <QMouseEvent>

ClickMenu::ClickMenu(QWidget *parent)
	: QMenu(parent)
{}

void ClickMenu::mouseReleaseEvent(QMouseEvent *event)
{
	QAction *action = activeAction();
	if (action == nullptr) {
		QMenu::mouseReleaseEvent(event);
		return;
	}

	if (event->button() == Qt::MiddleButton) {
		emit triggeredMiddle(action);
	} else {
		action->trigger();
	}

	close();
	event->accept();
}
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_SPACE_CONTINUOUS_LAGRANGE_FEM_HH
#define DUNE_GDT_SPACE_CONTINUOUS_LAGRANGE_FEM_HH

#include <memory>
#include <type_traits>

#include <dune/common/typetraits.hh>

#if HAVE_DUNE_FEM
# include <dune/fem/space/common/functionspace.hh>
# include <dune/fem/space/lagrangespace.hh>
#endif // HAVE_DUNE_FEM

#include "../../mapper/fem.hh"
#include "../../basefunctionset/fem.hh"

#include "../continuouslagrange.hh"
#include "../constraints.hh"

namespace Dune {
namespace GDT {
namespace ContinuousLagrangeSpace {

#if HAVE_DUNE_FEM

// forward, to be used in the traits and to allow for specialization
template< class GridPartImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >
class FemWrapper
{
  static_assert(Dune::AlwaysFalse< GridPartImp >::value, "Untested for these dimensions!");
};

/**
 *  \brief Traits class for ContinuousLagrangeSpace::FemWrapper.
 */
template< class GridPartImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >
class FemWrapperTraits
{
public:
  typedef FemWrapper< GridPartImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols > derived_type;
  typedef GridPartImp GridPartType;
  typedef typename GridPartType::GridViewType GridViewType;
  static const int                            polOrder = polynomialOrder;
  static_assert(polOrder >= 1, "Wrong polOrder given!");
  static const unsigned int             dimDomain = GridPartType::dimension;
private:
  typedef typename GridPartType::ctype  DomainFieldType;
public:
  typedef RangeFieldImp                 RangeFieldType;
  static const unsigned int             dimRange = rangeDim;
  static const unsigned int             dimRangeCols = rangeDimCols;
private:
  typedef Dune::Fem::FunctionSpace< DomainFieldType, RangeFieldType, dimDomain, dimRange > FunctionSpaceType;
public:
  typedef Dune::Fem::LagrangeDiscreteFunctionSpace< FunctionSpaceType, GridPartType, polOrder > BackendType;
  typedef Mapper::FemDofWrapper< typename BackendType::MapperType > MapperType;
  typedef typename GridPartType::template Codim< 0 >::EntityType EntityType;
  typedef BaseFunctionSet::FemWrapper
      < typename BackendType::BaseFunctionSetType, EntityType, DomainFieldType, dimDomain,
        RangeFieldType, dimRange, dimRangeCols > BaseFunctionSetType;
  static const bool needs_grid_view = false;
}; // class SpaceWrappedFemContinuousLagrangeTraits

// untested for the vector-valued case, especially ContinuousLagrangeSpaceBase
template< class GridPartImp, int polynomialOrder, class RangeFieldImp >
class FemWrapper< GridPartImp, polynomialOrder, RangeFieldImp, 1, 1 >
  : public ContinuousLagrangeSpaceBase< FemWrapperTraits< GridPartImp, polynomialOrder, RangeFieldImp, 1, 1 >
                                      , GridPartImp::dimension, RangeFieldImp, 1, 1 >
{
  typedef ContinuousLagrangeSpaceBase< FemWrapperTraits< GridPartImp, polynomialOrder, RangeFieldImp, 1, 1 >
                                     , GridPartImp::dimension, RangeFieldImp, 1, 1 > BaseType;
  typedef FemWrapper< GridPartImp, polynomialOrder, RangeFieldImp, 1, 1 >                             ThisType;
public:
  typedef FemWrapperTraits< GridPartImp, polynomialOrder, RangeFieldImp, 1, 1 > Traits;

  typedef typename Traits::GridPartType GridPartType;
  typedef typename Traits::GridViewType GridViewType;
  static const int                      polOrder = Traits::polOrder;
  typedef typename GridPartType::ctype  DomainFieldType;
  static const unsigned int             dimDomain = GridPartType::dimension;
  typedef typename Traits::RangeFieldType RangeFieldType;
  static const unsigned int               dimRange = Traits::dimRange;
  static const unsigned int               dimRangeCols = Traits::dimRangeCols;

  typedef typename Traits::BackendType          BackendType;
  typedef typename Traits::MapperType           MapperType;
  typedef typename Traits::BaseFunctionSetType  BaseFunctionSetType;
  typedef typename Traits::EntityType           EntityType;

  typedef Dune::Stuff::LA::SparsityPatternDefault PatternType;

  FemWrapper(const std::shared_ptr< const GridPartType >& gridP)
    : gridPart_(gridP)
    , gridView_(std::make_shared< GridViewType >(gridPart_->gridView()))
    , backend_(std::make_shared< BackendType >(const_cast< GridPartType& >(*(gridPart_))))
    , mapper_(std::make_shared< MapperType >(backend_->mapper()))
    , tmpMappedRows_(mapper_->maxNumDofs())
    , tmpMappedCols_(mapper_->maxNumDofs())
  {}

  FemWrapper(const ThisType& other)
    : gridPart_(other.gridPart_)
    , gridView_(other.gridView_)
    , backend_(other.backend_)
    , mapper_(other.mapper_)
    , tmpMappedRows_(mapper_->maxNumDofs())
    , tmpMappedCols_(mapper_->maxNumDofs())
  {}

  ThisType& operator=(const ThisType& other)
  {
    if (this != &other) {
      gridPart_ = other.gridPart_;
      gridView_ = other.gridView_;
      backend_ = other.backend_;
      mapper_ = other.mapper_;
      tmpMappedRows_.resize(mapper_->maxNumDofs());
      tmpMappedCols_.resize(mapper_->maxNumDofs());
    }
    return *this;
  }

  ~FemWrapper() {}

  const std::shared_ptr< const GridPartType >& grid_part() const
  {
    return gridPart_;
  }

  const std::shared_ptr< const GridViewType >& grid_view() const
  {
    return gridView_;
  }

  const BackendType& backend() const
  {
    return *backend_;
  }

  bool continuous() const
  {
    return true;
  }

  const MapperType& mapper() const
  {
    return *mapper_;
  }

  BaseFunctionSetType base_function_set(const EntityType& entity) const
  {
    return BaseFunctionSetType(*backend_, entity);
  }

private:
  std::shared_ptr< const GridPartType > gridPart_;
  std::shared_ptr< const GridViewType > gridView_;
  std::shared_ptr< const BackendType > backend_;
  std::shared_ptr< const MapperType > mapper_;
  mutable Dune::DynamicVector< size_t > tmpMappedRows_;
  mutable Dune::DynamicVector< size_t > tmpMappedCols_;
}; // class FemWrapper< ..., 1 >

#else // HAVE_DUNE_FEM

template< class GridPartImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >
class FemWrapper
{
  static_assert(Dune::AlwaysFalse< GridPartImp >::value, "You are missing dune-fem!");
};

#endif // HAVE_DUNE_FEM

} // namespace ContinuousLagrangeSpace
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_SPACE_CONTINUOUS_LAGRANGE_FEM_HH
<commit_msg>[space.cg.fem] removed obsolete continuous()<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_SPACE_CONTINUOUS_LAGRANGE_FEM_HH
#define DUNE_GDT_SPACE_CONTINUOUS_LAGRANGE_FEM_HH

#include <memory>
#include <type_traits>

#include <dune/common/typetraits.hh>

#if HAVE_DUNE_FEM
# include <dune/fem/space/common/functionspace.hh>
# include <dune/fem/space/lagrangespace.hh>
#endif // HAVE_DUNE_FEM

#include "../../mapper/fem.hh"
#include "../../basefunctionset/fem.hh"

#include "../continuouslagrange.hh"
#include "../constraints.hh"

namespace Dune {
namespace GDT {
namespace ContinuousLagrangeSpace {

#if HAVE_DUNE_FEM

// forward, to be used in the traits and to allow for specialization
template< class GridPartImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >
class FemWrapper
{
  static_assert(Dune::AlwaysFalse< GridPartImp >::value, "Untested for these dimensions!");
};

/**
 *  \brief Traits class for ContinuousLagrangeSpace::FemWrapper.
 */
template< class GridPartImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >
class FemWrapperTraits
{
public:
  typedef FemWrapper< GridPartImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols > derived_type;
  typedef GridPartImp GridPartType;
  typedef typename GridPartType::GridViewType GridViewType;
  static const int                            polOrder = polynomialOrder;
  static_assert(polOrder >= 1, "Wrong polOrder given!");
  static const unsigned int             dimDomain = GridPartType::dimension;
private:
  typedef typename GridPartType::ctype  DomainFieldType;
public:
  typedef RangeFieldImp                 RangeFieldType;
  static const unsigned int             dimRange = rangeDim;
  static const unsigned int             dimRangeCols = rangeDimCols;
private:
  typedef Dune::Fem::FunctionSpace< DomainFieldType, RangeFieldType, dimDomain, dimRange > FunctionSpaceType;
public:
  typedef Dune::Fem::LagrangeDiscreteFunctionSpace< FunctionSpaceType, GridPartType, polOrder > BackendType;
  typedef Mapper::FemDofWrapper< typename BackendType::MapperType > MapperType;
  typedef typename GridPartType::template Codim< 0 >::EntityType EntityType;
  typedef BaseFunctionSet::FemWrapper
      < typename BackendType::BaseFunctionSetType, EntityType, DomainFieldType, dimDomain,
        RangeFieldType, dimRange, dimRangeCols > BaseFunctionSetType;
  static const bool needs_grid_view = false;
}; // class SpaceWrappedFemContinuousLagrangeTraits

// untested for the vector-valued case, especially ContinuousLagrangeSpaceBase
template< class GridPartImp, int polynomialOrder, class RangeFieldImp >
class FemWrapper< GridPartImp, polynomialOrder, RangeFieldImp, 1, 1 >
  : public ContinuousLagrangeSpaceBase< FemWrapperTraits< GridPartImp, polynomialOrder, RangeFieldImp, 1, 1 >
                                      , GridPartImp::dimension, RangeFieldImp, 1, 1 >
{
  typedef ContinuousLagrangeSpaceBase< FemWrapperTraits< GridPartImp, polynomialOrder, RangeFieldImp, 1, 1 >
                                     , GridPartImp::dimension, RangeFieldImp, 1, 1 > BaseType;
  typedef FemWrapper< GridPartImp, polynomialOrder, RangeFieldImp, 1, 1 >                             ThisType;
public:
  typedef FemWrapperTraits< GridPartImp, polynomialOrder, RangeFieldImp, 1, 1 > Traits;

  typedef typename Traits::GridPartType GridPartType;
  typedef typename Traits::GridViewType GridViewType;
  static const int                      polOrder = Traits::polOrder;
  typedef typename GridPartType::ctype  DomainFieldType;
  static const unsigned int             dimDomain = GridPartType::dimension;
  typedef typename Traits::RangeFieldType RangeFieldType;
  static const unsigned int               dimRange = Traits::dimRange;
  static const unsigned int               dimRangeCols = Traits::dimRangeCols;

  typedef typename Traits::BackendType          BackendType;
  typedef typename Traits::MapperType           MapperType;
  typedef typename Traits::BaseFunctionSetType  BaseFunctionSetType;
  typedef typename Traits::EntityType           EntityType;

  typedef Dune::Stuff::LA::SparsityPatternDefault PatternType;

  FemWrapper(const std::shared_ptr< const GridPartType >& gridP)
    : gridPart_(gridP)
    , gridView_(std::make_shared< GridViewType >(gridPart_->gridView()))
    , backend_(std::make_shared< BackendType >(const_cast< GridPartType& >(*(gridPart_))))
    , mapper_(std::make_shared< MapperType >(backend_->mapper()))
    , tmpMappedRows_(mapper_->maxNumDofs())
    , tmpMappedCols_(mapper_->maxNumDofs())
  {}

  FemWrapper(const ThisType& other)
    : gridPart_(other.gridPart_)
    , gridView_(other.gridView_)
    , backend_(other.backend_)
    , mapper_(other.mapper_)
    , tmpMappedRows_(mapper_->maxNumDofs())
    , tmpMappedCols_(mapper_->maxNumDofs())
  {}

  ThisType& operator=(const ThisType& other)
  {
    if (this != &other) {
      gridPart_ = other.gridPart_;
      gridView_ = other.gridView_;
      backend_ = other.backend_;
      mapper_ = other.mapper_;
      tmpMappedRows_.resize(mapper_->maxNumDofs());
      tmpMappedCols_.resize(mapper_->maxNumDofs());
    }
    return *this;
  }

  ~FemWrapper() {}

  const std::shared_ptr< const GridPartType >& grid_part() const
  {
    return gridPart_;
  }

  const std::shared_ptr< const GridViewType >& grid_view() const
  {
    return gridView_;
  }

  const BackendType& backend() const
  {
    return *backend_;
  }

  const MapperType& mapper() const
  {
    return *mapper_;
  }

  BaseFunctionSetType base_function_set(const EntityType& entity) const
  {
    return BaseFunctionSetType(*backend_, entity);
  }

private:
  std::shared_ptr< const GridPartType > gridPart_;
  std::shared_ptr< const GridViewType > gridView_;
  std::shared_ptr< const BackendType > backend_;
  std::shared_ptr< const MapperType > mapper_;
  mutable Dune::DynamicVector< size_t > tmpMappedRows_;
  mutable Dune::DynamicVector< size_t > tmpMappedCols_;
}; // class FemWrapper< ..., 1 >

#else // HAVE_DUNE_FEM

template< class GridPartImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >
class FemWrapper
{
  static_assert(Dune::AlwaysFalse< GridPartImp >::value, "You are missing dune-fem!");
};

#endif // HAVE_DUNE_FEM

} // namespace ContinuousLagrangeSpace
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_SPACE_CONTINUOUS_LAGRANGE_FEM_HH
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2015 Cloudius Systems, Ltd.
 */

#pragma once

#include "core/reactor.hh"
#include "core/iostream.hh"
#include "core/distributed.hh"
#include "core/print.hh"
#include "core/sstring.hh"
#include "net/api.hh"
#include "util/serialization.hh"
#include "gms/inet_address.hh"
#include "rpc/rpc.hh"
#include <unordered_map>
#include "db/config.hh"
#include "frozen_mutation.hh"
#include "db/serializer.hh"

namespace net {

/* All verb handler identifiers */
enum class messaging_verb : int32_t {
    MUTATION,
    MUTATION_DONE,
    BINARY, // Deprecated
    READ_REPAIR,
    READ,
    READ_DATA,
    READ_DIGEST,
    REQUEST_RESPONSE, // client-initiated reads and writes
    STREAM_INITIATE, // Deprecated
    STREAM_INITIATE_DONE, // Deprecated
    STREAM_REPLY, // Deprecated
    STREAM_REQUEST, // Deprecated
    RANGE_SLICE,
    BOOTSTRAP_TOKEN, // Deprecated
    TREE_REQUEST, // Deprecated
    TREE_RESPONSE, // Deprecated
    JOIN, // Deprecated
    GOSSIP_DIGEST_SYN,
    GOSSIP_DIGEST_ACK,
    GOSSIP_DIGEST_ACK2,
    DEFINITIONS_ANNOUNCE, // Deprecated
    DEFINITIONS_UPDATE,
    TRUNCATE,
    SCHEMA_CHECK,
    INDEX_SCAN, // Deprecated
    REPLICATION_FINISHED,
    INTERNAL_RESPONSE, // responses to internal calls
    COUNTER_MUTATION,
    STREAMING_REPAIR_REQUEST, // Deprecated
    STREAMING_REPAIR_RESPONSE, // Deprecated
    SNAPSHOT, // Similar to nt snapshot
    MIGRATION_REQUEST,
    GOSSIP_SHUTDOWN,
    _TRACE,
    ECHO,
    REPAIR_MESSAGE,
    PAXOS_PREPARE,
    PAXOS_PROPOSE,
    PAXOS_COMMIT,
    PAGED_RANGE,
    UNUSED_1,
    UNUSED_2,
    UNUSED_3,
    // Used by streaming
    STREAM_INIT_MESSAGE,
    PREPARE_MESSAGE,
    INCOMING_FILE_MESSAGE,
    OUTGOING_FILE_MESSAGE,
    RECEIVED_MESSAGE,
    RETRY_MESSAGE,
    COMPLETE_MESSAGE,
    SESSION_FAILED_MESSAGE,
    LAST,
};

} // namespace net

namespace std {
template <>
class hash<net::messaging_verb> {
public:
    size_t operator()(const net::messaging_verb& x) const {
        return hash<int32_t>()(int32_t(x));
    }
};
} // namespace std

namespace net {

future<> ser_messaging_verb(output_stream<char>& out, messaging_verb& v);
future<> des_messaging_verb(input_stream<char>& in, messaging_verb& v);
future<> ser_sstring(output_stream<char>& out, sstring& v);
future<> des_sstring(input_stream<char>& in, sstring& v);
future<> ser_frozen_mutation(output_stream<char>& out, const frozen_mutation& v);
future<> des_frozen_mutation(input_stream<char>& in, frozen_mutation& v);

// NOTE: operator(input_stream<char>&, T&) takes a reference to uninitialized
//       T object and should use placement new in case T is non POD
struct serializer {
    // For integer type
    template<typename T>
    inline auto operator()(output_stream<char>& out, T&& v, std::enable_if_t<std::is_integral<std::remove_reference_t<T>>::value, void*> = nullptr) {
        auto v_ = net::hton(v);
        return out.write(reinterpret_cast<const char*>(&v_), sizeof(T));
    }
    template<typename T>
    inline auto operator()(input_stream<char>& in, T& v, std::enable_if_t<std::is_integral<T>::value, void*> = nullptr) {
        return in.read_exactly(sizeof(v)).then([&v] (temporary_buffer<char> buf) mutable {
            if (buf.size() != sizeof(v)) {
                throw rpc::closed_error();
            }
            v = net::ntoh(*reinterpret_cast<const net::packed<T>*>(buf.get()));
        });
    }

    // For vectors
    template<typename T>
    inline auto operator()(output_stream<char>& out, std::vector<T>& v) {
        return operator()(out, v.size()).then([&out, &v, this] {
            return do_for_each(v.begin(), v.end(), [&out, this] (T& e) {
                return operator()(out, e);
            });
        });
    }
    template<typename T>
    inline auto operator()(input_stream<char>& in, std::vector<T>& v) {
        using size_type = typename  std::vector<T>::size_type;
        return in.read_exactly(sizeof(size_type)).then([&v, &in, this] (temporary_buffer<char> buf) {
            if (buf.size() != sizeof(size_type)) {
                throw rpc::closed_error();
            }
            size_type c = net::ntoh(*reinterpret_cast<const net::packed<size_type>*>(buf.get()));
            new (&v) std::vector<T>;
            v.reserve(c);
            union U {
                U(){}
                ~U(){}
                U(U&&) {}
                T v;
            };
            return do_with(U(), [c, &v, &in, this] (U& u) {
                return do_until([c = c] () mutable {return !c--;}, [&v, &in, &u, this] () mutable {
                    return operator()(in, u.v).then([&u, &v] {
                        v.emplace_back(std::move(u.v));
                    });
                });
            });
        });
    }

    // For messaging_verb
    inline auto operator()(output_stream<char>& out, messaging_verb& v) {
        return ser_messaging_verb(out, v);
    }
    inline auto operator()(input_stream<char>& in, messaging_verb& v) {
        return des_messaging_verb(in, v);
    }

    // For sstring
    inline auto operator()(output_stream<char>& out, sstring& v) {
        return ser_sstring(out, v);
    }
    inline auto operator()(input_stream<char>& in, sstring& v) {
        return des_sstring(in, v);
    }

    // For frozen_mutation
    inline auto operator()(output_stream<char>& out, const frozen_mutation& v) {
        return ser_frozen_mutation(out, v);
    }
    inline auto operator()(output_stream<char>& out, frozen_mutation& v) {
        return operator()(out, const_cast<const frozen_mutation&>(v));
    }
    inline auto operator()(input_stream<char>& in, frozen_mutation& v) {
        return des_frozen_mutation(in, v);
    }

    // For complex types which have serialize()/deserialize(),  e.g. gms::gossip_digest_syn, gms::gossip_digest_ack2
    template<typename T>
    inline auto operator()(output_stream<char>& out, T&& v, std::enable_if_t<!std::is_integral<std::remove_reference_t<T>>::value &&
                                                                             !std::is_enum<std::remove_reference_t<T>>::value, void*> = nullptr) {
        auto sz = serialize_int32_size + v.serialized_size();
        bytes b(bytes::initialized_later(), sz);
        auto _out = b.begin();
        serialize_int32(_out, int32_t(sz - serialize_int32_size));
        v.serialize(_out);
        return out.write(reinterpret_cast<const char*>(b.c_str()), sz);
    }
    template<typename T>
    inline auto operator()(input_stream<char>& in, T& v, std::enable_if_t<!std::is_integral<T>::value &&
                                                                          !std::is_enum<T>::value, void*> = nullptr) {
        return in.read_exactly(serialize_int32_size).then([&in, &v] (temporary_buffer<char> buf) mutable {
            if (buf.size() != serialize_int32_size) {
                throw rpc::closed_error();
            }
            size_t sz = net::ntoh(*reinterpret_cast<const net::packed<int32_t>*>(buf.get()));
            return in.read_exactly(sz).then([sz, &v] (temporary_buffer<char> buf) mutable {
                if (buf.size() != sz) {
                    throw rpc::closed_error();
                }
                bytes_view bv(reinterpret_cast<const int8_t*>(buf.get()), sz);
                new (&v) T(T::deserialize(bv));
                assert(bv.size() == 0);
                return make_ready_future<>();
            });
        });
    }
};

class messaging_service {
public:
    // FIXME: messaging service versioning
    static constexpr int32_t current_version = 0;

    struct shard_id {
        gms::inet_address addr;
        uint32_t cpu_id;
        friend inline bool operator==(const shard_id& x, const shard_id& y) {
            return x.addr == y.addr && x.cpu_id == y.cpu_id ;
        }
        friend inline bool operator<(const shard_id& x, const shard_id& y) {
            if (x.addr < y.addr) {
                return true;
            } else if (y.addr < x.addr) {
                return false;
            } else {
                return x.cpu_id < y.cpu_id;
            }
        }
        friend inline std::ostream& operator<<(std::ostream& os, const shard_id& x) {
            return os << x.addr << ":" << x.cpu_id;
        }
        struct hash {
            size_t operator()(const shard_id& id) const {
                return std::hash<uint32_t>()(id.cpu_id) + std::hash<uint32_t>()(id.addr.raw_addr());
            }
        };
    };
    struct shard_info {
        shard_info(std::unique_ptr<rpc::protocol<serializer, messaging_verb>::client>&& client)
            : rpc_client(std::move(client)) {
        }
        std::unique_ptr<rpc::protocol<serializer, messaging_verb>::client> rpc_client;
    };

    void foreach_client(std::function<void(const messaging_service::shard_id& id,
                    const messaging_service::shard_info& info)> f) const {
        for (auto i = _clients.cbegin(); i != _clients.cend(); i++) {
            f(i->first, i->second);
        }
    }

    void increment_dropped_messages(messaging_verb verb) {
        _dropped_messages[static_cast<int32_t>(verb)]++;
    }

    uint64_t get_dropped_messages(messaging_verb verb) const {
        return _dropped_messages[static_cast<int32_t>(verb)];
    }

    const uint64_t* get_dropped_messages() const {
        return _dropped_messages;
    }

    int32_t get_raw_version(const gms::inet_address& endpoint) const {
        // FIXME: messaging service versioning
        return current_version;
    }

    bool knows_version(const gms::inet_address& endpoint) const {
        // FIXME: messaging service versioning
        return true;
    }

private:
    static constexpr uint16_t _default_port = 7000;
    gms::inet_address _listen_address;
    uint16_t _port;
    rpc::protocol<serializer, messaging_verb> _rpc;
    rpc::protocol<serializer, messaging_verb>::server _server;
    std::unordered_map<shard_id, shard_info, shard_id::hash> _clients;
    uint64_t _dropped_messages[static_cast<int32_t>(messaging_verb::LAST)] = {};
public:
    messaging_service(gms::inet_address ip = gms::inet_address("0.0.0.0"))
        : _listen_address(ip)
        , _port(_default_port)
        , _rpc(serializer{})
        , _server(_rpc, ipv4_addr{_listen_address.raw_addr(), _port}) {
    }
public:
    uint16_t port() {
        return _port;
    }
    auto listen_address() {
        return _listen_address;
    }
    future<> stop() {
        return when_all(_server.stop(),
            parallel_for_each(_clients, [](std::pair<const shard_id, shard_info>& c) {
                return c.second.rpc_client->stop();
            })
        ).discard_result();
    }

    static auto no_wait() {
        return rpc::no_wait;
    }
public:
    // Register a handler (a callback lambda) for verb
    template <typename Func>
    void register_handler(messaging_verb verb, Func&& func) {
        _rpc.register_handler(verb, std::move(func));
    }

    // Send a message for verb
    template <typename MsgIn, typename... MsgOut>
    auto send_message(messaging_verb verb, shard_id id, MsgOut&&... msg) {
        auto& rpc_client = get_rpc_client(id);
        auto rpc_handler = _rpc.make_client<MsgIn(MsgOut...)>(verb);
        return rpc_handler(rpc_client, std::forward<MsgOut>(msg)...).then_wrapped([this, id, verb] (auto&& f) {
            try {
                if (f.failed()) {
                    this->increment_dropped_messages(verb);
                    f.get();
                    assert(false); // never reached
                }
                return std::move(f);
            } catch(...) {
                // FIXME: we need to distinguish between a transport error and
                // a server error.
                // remove_rpc_client(id);
                throw;
            }
        });
    }

    template <typename... MsgOut>
    auto send_message_oneway(messaging_verb verb, shard_id id, MsgOut&&... msg) {
        return send_message<rpc::no_wait_type>(std::move(verb), std::move(id), std::forward<MsgOut>(msg)...);
    }
private:
    // Return rpc::protocol::client for a shard which is a ip + cpuid pair.
    rpc::protocol<serializer, messaging_verb>::client& get_rpc_client(shard_id id) {
        auto it = _clients.find(id);
        if (it == _clients.end()) {
            auto remote_addr = ipv4_addr(id.addr.raw_addr(), _port);
            auto client = std::make_unique<rpc::protocol<serializer, messaging_verb>::client>(_rpc, remote_addr, ipv4_addr{_listen_address.raw_addr(), 0});
            it = _clients.emplace(id, shard_info(std::move(client))).first;
            return *it->second.rpc_client;
        } else {
            return *it->second.rpc_client;
        }
    }

    void remove_rpc_client(shard_id id) {
        _clients.erase(id);
    }
};

extern distributed<messaging_service> _the_messaging_service;

inline distributed<messaging_service>& get_messaging_service() {
    return _the_messaging_service;
}

inline messaging_service& get_local_messaging_service() {
    return _the_messaging_service.local();
}

future<> init_messaging_service(sstring listen_address, db::config::seed_provider_type seed_provider);
} // namespace net
<commit_msg>messaging_service: Add STREAM_MUTATION verb<commit_after>/*
 * Copyright (C) 2015 Cloudius Systems, Ltd.
 */

#pragma once

#include "core/reactor.hh"
#include "core/iostream.hh"
#include "core/distributed.hh"
#include "core/print.hh"
#include "core/sstring.hh"
#include "net/api.hh"
#include "util/serialization.hh"
#include "gms/inet_address.hh"
#include "rpc/rpc.hh"
#include <unordered_map>
#include "db/config.hh"
#include "frozen_mutation.hh"
#include "db/serializer.hh"

namespace net {

/* All verb handler identifiers */
enum class messaging_verb : int32_t {
    MUTATION,
    MUTATION_DONE,
    BINARY, // Deprecated
    READ_REPAIR,
    READ,
    READ_DATA,
    READ_DIGEST,
    REQUEST_RESPONSE, // client-initiated reads and writes
    STREAM_INITIATE, // Deprecated
    STREAM_INITIATE_DONE, // Deprecated
    STREAM_REPLY, // Deprecated
    STREAM_REQUEST, // Deprecated
    RANGE_SLICE,
    BOOTSTRAP_TOKEN, // Deprecated
    TREE_REQUEST, // Deprecated
    TREE_RESPONSE, // Deprecated
    JOIN, // Deprecated
    GOSSIP_DIGEST_SYN,
    GOSSIP_DIGEST_ACK,
    GOSSIP_DIGEST_ACK2,
    DEFINITIONS_ANNOUNCE, // Deprecated
    DEFINITIONS_UPDATE,
    TRUNCATE,
    SCHEMA_CHECK,
    INDEX_SCAN, // Deprecated
    REPLICATION_FINISHED,
    INTERNAL_RESPONSE, // responses to internal calls
    COUNTER_MUTATION,
    STREAMING_REPAIR_REQUEST, // Deprecated
    STREAMING_REPAIR_RESPONSE, // Deprecated
    SNAPSHOT, // Similar to nt snapshot
    MIGRATION_REQUEST,
    GOSSIP_SHUTDOWN,
    _TRACE,
    ECHO,
    REPAIR_MESSAGE,
    PAXOS_PREPARE,
    PAXOS_PROPOSE,
    PAXOS_COMMIT,
    PAGED_RANGE,
    UNUSED_1,
    UNUSED_2,
    UNUSED_3,
    // Used by streaming
    STREAM_INIT_MESSAGE,
    PREPARE_MESSAGE,
    STREAM_MUTATION,
    INCOMING_FILE_MESSAGE,
    OUTGOING_FILE_MESSAGE,
    RECEIVED_MESSAGE,
    RETRY_MESSAGE,
    COMPLETE_MESSAGE,
    SESSION_FAILED_MESSAGE,
    LAST,
};

} // namespace net

namespace std {
template <>
class hash<net::messaging_verb> {
public:
    size_t operator()(const net::messaging_verb& x) const {
        return hash<int32_t>()(int32_t(x));
    }
};
} // namespace std

namespace net {

future<> ser_messaging_verb(output_stream<char>& out, messaging_verb& v);
future<> des_messaging_verb(input_stream<char>& in, messaging_verb& v);
future<> ser_sstring(output_stream<char>& out, sstring& v);
future<> des_sstring(input_stream<char>& in, sstring& v);
future<> ser_frozen_mutation(output_stream<char>& out, const frozen_mutation& v);
future<> des_frozen_mutation(input_stream<char>& in, frozen_mutation& v);

// NOTE: operator(input_stream<char>&, T&) takes a reference to uninitialized
//       T object and should use placement new in case T is non POD
struct serializer {
    // For integer type
    template<typename T>
    inline auto operator()(output_stream<char>& out, T&& v, std::enable_if_t<std::is_integral<std::remove_reference_t<T>>::value, void*> = nullptr) {
        auto v_ = net::hton(v);
        return out.write(reinterpret_cast<const char*>(&v_), sizeof(T));
    }
    template<typename T>
    inline auto operator()(input_stream<char>& in, T& v, std::enable_if_t<std::is_integral<T>::value, void*> = nullptr) {
        return in.read_exactly(sizeof(v)).then([&v] (temporary_buffer<char> buf) mutable {
            if (buf.size() != sizeof(v)) {
                throw rpc::closed_error();
            }
            v = net::ntoh(*reinterpret_cast<const net::packed<T>*>(buf.get()));
        });
    }

    // For vectors
    template<typename T>
    inline auto operator()(output_stream<char>& out, std::vector<T>& v) {
        return operator()(out, v.size()).then([&out, &v, this] {
            return do_for_each(v.begin(), v.end(), [&out, this] (T& e) {
                return operator()(out, e);
            });
        });
    }
    template<typename T>
    inline auto operator()(input_stream<char>& in, std::vector<T>& v) {
        using size_type = typename  std::vector<T>::size_type;
        return in.read_exactly(sizeof(size_type)).then([&v, &in, this] (temporary_buffer<char> buf) {
            if (buf.size() != sizeof(size_type)) {
                throw rpc::closed_error();
            }
            size_type c = net::ntoh(*reinterpret_cast<const net::packed<size_type>*>(buf.get()));
            new (&v) std::vector<T>;
            v.reserve(c);
            union U {
                U(){}
                ~U(){}
                U(U&&) {}
                T v;
            };
            return do_with(U(), [c, &v, &in, this] (U& u) {
                return do_until([c = c] () mutable {return !c--;}, [&v, &in, &u, this] () mutable {
                    return operator()(in, u.v).then([&u, &v] {
                        v.emplace_back(std::move(u.v));
                    });
                });
            });
        });
    }

    // For messaging_verb
    inline auto operator()(output_stream<char>& out, messaging_verb& v) {
        return ser_messaging_verb(out, v);
    }
    inline auto operator()(input_stream<char>& in, messaging_verb& v) {
        return des_messaging_verb(in, v);
    }

    // For sstring
    inline auto operator()(output_stream<char>& out, sstring& v) {
        return ser_sstring(out, v);
    }
    inline auto operator()(input_stream<char>& in, sstring& v) {
        return des_sstring(in, v);
    }

    // For frozen_mutation
    inline auto operator()(output_stream<char>& out, const frozen_mutation& v) {
        return ser_frozen_mutation(out, v);
    }
    inline auto operator()(output_stream<char>& out, frozen_mutation& v) {
        return operator()(out, const_cast<const frozen_mutation&>(v));
    }
    inline auto operator()(input_stream<char>& in, frozen_mutation& v) {
        return des_frozen_mutation(in, v);
    }

    // For complex types which have serialize()/deserialize(),  e.g. gms::gossip_digest_syn, gms::gossip_digest_ack2
    template<typename T>
    inline auto operator()(output_stream<char>& out, T&& v, std::enable_if_t<!std::is_integral<std::remove_reference_t<T>>::value &&
                                                                             !std::is_enum<std::remove_reference_t<T>>::value, void*> = nullptr) {
        auto sz = serialize_int32_size + v.serialized_size();
        bytes b(bytes::initialized_later(), sz);
        auto _out = b.begin();
        serialize_int32(_out, int32_t(sz - serialize_int32_size));
        v.serialize(_out);
        return out.write(reinterpret_cast<const char*>(b.c_str()), sz);
    }
    template<typename T>
    inline auto operator()(input_stream<char>& in, T& v, std::enable_if_t<!std::is_integral<T>::value &&
                                                                          !std::is_enum<T>::value, void*> = nullptr) {
        return in.read_exactly(serialize_int32_size).then([&in, &v] (temporary_buffer<char> buf) mutable {
            if (buf.size() != serialize_int32_size) {
                throw rpc::closed_error();
            }
            size_t sz = net::ntoh(*reinterpret_cast<const net::packed<int32_t>*>(buf.get()));
            return in.read_exactly(sz).then([sz, &v] (temporary_buffer<char> buf) mutable {
                if (buf.size() != sz) {
                    throw rpc::closed_error();
                }
                bytes_view bv(reinterpret_cast<const int8_t*>(buf.get()), sz);
                new (&v) T(T::deserialize(bv));
                assert(bv.size() == 0);
                return make_ready_future<>();
            });
        });
    }
};

class messaging_service {
public:
    // FIXME: messaging service versioning
    static constexpr int32_t current_version = 0;

    struct shard_id {
        gms::inet_address addr;
        uint32_t cpu_id;
        friend inline bool operator==(const shard_id& x, const shard_id& y) {
            return x.addr == y.addr && x.cpu_id == y.cpu_id ;
        }
        friend inline bool operator<(const shard_id& x, const shard_id& y) {
            if (x.addr < y.addr) {
                return true;
            } else if (y.addr < x.addr) {
                return false;
            } else {
                return x.cpu_id < y.cpu_id;
            }
        }
        friend inline std::ostream& operator<<(std::ostream& os, const shard_id& x) {
            return os << x.addr << ":" << x.cpu_id;
        }
        struct hash {
            size_t operator()(const shard_id& id) const {
                return std::hash<uint32_t>()(id.cpu_id) + std::hash<uint32_t>()(id.addr.raw_addr());
            }
        };
    };
    struct shard_info {
        shard_info(std::unique_ptr<rpc::protocol<serializer, messaging_verb>::client>&& client)
            : rpc_client(std::move(client)) {
        }
        std::unique_ptr<rpc::protocol<serializer, messaging_verb>::client> rpc_client;
    };

    void foreach_client(std::function<void(const messaging_service::shard_id& id,
                    const messaging_service::shard_info& info)> f) const {
        for (auto i = _clients.cbegin(); i != _clients.cend(); i++) {
            f(i->first, i->second);
        }
    }

    void increment_dropped_messages(messaging_verb verb) {
        _dropped_messages[static_cast<int32_t>(verb)]++;
    }

    uint64_t get_dropped_messages(messaging_verb verb) const {
        return _dropped_messages[static_cast<int32_t>(verb)];
    }

    const uint64_t* get_dropped_messages() const {
        return _dropped_messages;
    }

    int32_t get_raw_version(const gms::inet_address& endpoint) const {
        // FIXME: messaging service versioning
        return current_version;
    }

    bool knows_version(const gms::inet_address& endpoint) const {
        // FIXME: messaging service versioning
        return true;
    }

private:
    static constexpr uint16_t _default_port = 7000;
    gms::inet_address _listen_address;
    uint16_t _port;
    rpc::protocol<serializer, messaging_verb> _rpc;
    rpc::protocol<serializer, messaging_verb>::server _server;
    std::unordered_map<shard_id, shard_info, shard_id::hash> _clients;
    uint64_t _dropped_messages[static_cast<int32_t>(messaging_verb::LAST)] = {};
public:
    messaging_service(gms::inet_address ip = gms::inet_address("0.0.0.0"))
        : _listen_address(ip)
        , _port(_default_port)
        , _rpc(serializer{})
        , _server(_rpc, ipv4_addr{_listen_address.raw_addr(), _port}) {
    }
public:
    uint16_t port() {
        return _port;
    }
    auto listen_address() {
        return _listen_address;
    }
    future<> stop() {
        return when_all(_server.stop(),
            parallel_for_each(_clients, [](std::pair<const shard_id, shard_info>& c) {
                return c.second.rpc_client->stop();
            })
        ).discard_result();
    }

    static auto no_wait() {
        return rpc::no_wait;
    }
public:
    // Register a handler (a callback lambda) for verb
    template <typename Func>
    void register_handler(messaging_verb verb, Func&& func) {
        _rpc.register_handler(verb, std::move(func));
    }

    // Send a message for verb
    template <typename MsgIn, typename... MsgOut>
    auto send_message(messaging_verb verb, shard_id id, MsgOut&&... msg) {
        auto& rpc_client = get_rpc_client(id);
        auto rpc_handler = _rpc.make_client<MsgIn(MsgOut...)>(verb);
        return rpc_handler(rpc_client, std::forward<MsgOut>(msg)...).then_wrapped([this, id, verb] (auto&& f) {
            try {
                if (f.failed()) {
                    this->increment_dropped_messages(verb);
                    f.get();
                    assert(false); // never reached
                }
                return std::move(f);
            } catch(...) {
                // FIXME: we need to distinguish between a transport error and
                // a server error.
                // remove_rpc_client(id);
                throw;
            }
        });
    }

    template <typename... MsgOut>
    auto send_message_oneway(messaging_verb verb, shard_id id, MsgOut&&... msg) {
        return send_message<rpc::no_wait_type>(std::move(verb), std::move(id), std::forward<MsgOut>(msg)...);
    }
private:
    // Return rpc::protocol::client for a shard which is a ip + cpuid pair.
    rpc::protocol<serializer, messaging_verb>::client& get_rpc_client(shard_id id) {
        auto it = _clients.find(id);
        if (it == _clients.end()) {
            auto remote_addr = ipv4_addr(id.addr.raw_addr(), _port);
            auto client = std::make_unique<rpc::protocol<serializer, messaging_verb>::client>(_rpc, remote_addr, ipv4_addr{_listen_address.raw_addr(), 0});
            it = _clients.emplace(id, shard_info(std::move(client))).first;
            return *it->second.rpc_client;
        } else {
            return *it->second.rpc_client;
        }
    }

    void remove_rpc_client(shard_id id) {
        _clients.erase(id);
    }
};

extern distributed<messaging_service> _the_messaging_service;

inline distributed<messaging_service>& get_messaging_service() {
    return _the_messaging_service;
}

inline messaging_service& get_local_messaging_service() {
    return _the_messaging_service.local();
}

future<> init_messaging_service(sstring listen_address, db::config::seed_provider_type seed_provider);
} // namespace net
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: score.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 03:08:14 $
 *
 *  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
 *
 ************************************************************************/
#include "score.hxx"
#include "strings.hrc"
#include "invader.hxx"

ScoreWindow::ScoreWindow(Window* Parent, WinBits wBits, ResMgr* pP) :
                    Window(Parent, wBits),
                    bPaintBack(FALSE),
                    pRes(pP),
                    nHero(-1),
                    nRockets(5),
                    nLives(3),
                    nScore(0L)
{
    SetBackground(Wallpaper( Color( COL_GRAY ) ) );
}

ScoreWindow::~ScoreWindow()
{
}

void ScoreWindow::Paint(const Rectangle& rRect)
{
    Font aFont = GetFont();
    aFont.SetColor(COL_WHITE);
    aFont.SetFillColor(COL_GRAY);
    SetFont(*&aFont);

    SetFillColor(COL_GRAY);

    if(bPaintBack)
    {
        Push( PUSH_LINECOLOR );
        SetLineColor();
        DrawRect(Rectangle(Point(0,0),GetOutputSizePixel()));
        Pop();
    }

    if(nHero)
        DrawText(Point(0,0),String(ResId(nHero, pRes)));

    DrawText(Point(180,0),String(ResId(STR_ROCKETS, pRes)));

    DrawText(Point(300,0),String(ResId(STR_FIGHTER, pRes)));
    DrawText(Point(370,0),String::CreateFromInt32(nLives));

    DrawText(Point(400,0),String(ResId(STR_LEVEL, pRes)));
    DrawText(Point(460,0),String::CreateFromInt32(nLevel));

    DrawText(Point(500,0),String(ResId(STR_SCORE, pRes)));
    String aString = String::CreateFromInt32(nScore);
    if ( aString.Len() < 7 )
    {
        for ( xub_StrLen i = aString.Len(); i < 7; ++i )
            aString.Insert( '0', 0 );
    }
    DrawText(Point(560,0),aString);

    for(long i=0; i<5;i++)
    {
        if(nRockets > i)
        {
            SetLineColor(COL_GREEN);
            SetFillColor(COL_GREEN);
        }
        else
        {
            SetLineColor(COL_RED);
            SetFillColor(COL_RED);
        }

        DrawRect(Rectangle(Point(250+i*8,5),Point(256+i*8,12)));
    }
    SetBackground(Wallpaper( Color( COL_GRAY ) ) );

    bPaintBack = FALSE;
}

void ScoreWindow::SetHero(long nName)
{
    nHero = nName;

    SetBackground();
    Invalidate();
}

void ScoreWindow::SetRockets(USHORT nWert)
{
    nRockets = nWert;

    SetBackground();
    Invalidate();
}

void ScoreWindow::SetLives(USHORT nWert)
{
    nLives = nWert;

//  SetBackground();
    Invalidate();
}

void ScoreWindow::SetScore(long nWert)
{
    nScore = nWert;

    SetBackground();
    Invalidate();
}

void ScoreWindow::SetLevel(long nWert)
{
    nLevel = nWert;

//  SetBackground();
    Invalidate();
}

void ScoreWindow::Show()
{
    bPaintBack = TRUE;

    Window::Show();
}
<commit_msg>INTEGRATION: CWS warnings01 (1.5.28); FILE MERGED 2005/11/16 16:42:23 pl 1.5.28.2: #i55991# removed warnings 2005/10/28 12:34:00 sj 1.5.28.1: #i55991# warning free code<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: score.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 21:51:40 $
 *
 *  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
 *
 ************************************************************************/
#include "score.hxx"
#include "strings.hrc"
#include "invader.hxx"

ScoreWindow::ScoreWindow(Window* Parent, WinBits wBits, ResMgr* pP) :
                    Window(Parent, wBits),
                    nHero(-1),
                    nRockets(5),
                    nLives(3),
                    nScore(0L),
                    pRes(pP),
                    bPaintBack(FALSE)
{
    SetBackground(Wallpaper( Color( COL_GRAY ) ) );
}

ScoreWindow::~ScoreWindow()
{
}

void ScoreWindow::Paint(const Rectangle&)
{
    Font aFont = GetFont();
    aFont.SetColor(COL_WHITE);
    aFont.SetFillColor(COL_GRAY);
    SetFont(*&aFont);

    SetFillColor(COL_GRAY);

    if(bPaintBack)
    {
        Push( PUSH_LINECOLOR );
        SetLineColor();
        DrawRect(Rectangle(Point(0,0),GetOutputSizePixel()));
        Pop();
    }

    if(nHero)
        DrawText(Point(0,0),String(ResId(nHero, pRes)));

    DrawText(Point(180,0),String(ResId(STR_ROCKETS, pRes)));

    DrawText(Point(300,0),String(ResId(STR_FIGHTER, pRes)));
    DrawText(Point(370,0),String::CreateFromInt32(nLives));

    DrawText(Point(400,0),String(ResId(STR_LEVEL, pRes)));
    DrawText(Point(460,0),String::CreateFromInt32(nLevel));

    DrawText(Point(500,0),String(ResId(STR_SCORE, pRes)));
    String aString = String::CreateFromInt32(nScore);
    if ( aString.Len() < 7 )
    {
        for ( xub_StrLen i = aString.Len(); i < 7; ++i )
            aString.Insert( '0', 0 );
    }
    DrawText(Point(560,0),aString);

    for(long i=0; i<5;i++)
    {
        if(nRockets > i)
        {
            SetLineColor(COL_GREEN);
            SetFillColor(COL_GREEN);
        }
        else
        {
            SetLineColor(COL_RED);
            SetFillColor(COL_RED);
        }

        DrawRect(Rectangle(Point(250+i*8,5),Point(256+i*8,12)));
    }
    SetBackground(Wallpaper( Color( COL_GRAY ) ) );

    bPaintBack = FALSE;
}

void ScoreWindow::SetHero(long nName)
{
    nHero = nName;

    SetBackground();
    Invalidate();
}

void ScoreWindow::SetRockets(USHORT nWert)
{
    nRockets = nWert;

    SetBackground();
    Invalidate();
}

void ScoreWindow::SetLives(USHORT nWert)
{
    nLives = nWert;

//  SetBackground();
    Invalidate();
}

void ScoreWindow::SetScore(long nWert)
{
    nScore = nWert;

    SetBackground();
    Invalidate();
}

void ScoreWindow::SetLevel(long nWert)
{
    nLevel = nWert;

//  SetBackground();
    Invalidate();
}

void ScoreWindow::ShowMe()
{
    bPaintBack = TRUE;

    Window::Show();
}
<|endoftext|>


<commit_before>/*
 @ Kingsley Chen
*/

#include "kbase\guid.h"

#include <objbase.h>

#include <array>
#include <cassert>

#include "kbase\strings\sys_string_encoding_conversions.h"

namespace kbase {

std::string GenerateGUID()
{
    GUID guid;
    auto rv = CoCreateGuid(&guid);
    assert(SUCCEEDED(rv));
    if (!SUCCEEDED(rv)) {
        return std::string();
    }

    const int kGUIDSize = 40;
    std::array<wchar_t, kGUIDSize> guid_str;
    int count_written = StringFromGUID2(guid, guid_str.data(), kGUIDSize);

    // Since GUID contains ASCII-only characters, it is safe to do this conversion.
    return count_written ? WideToASCII(guid_str.data()) : std::string();
}

}   // namespace kbase<commit_msg>GUID: strips off { and }.<commit_after>/*
 @ Kingsley Chen
*/

#include "kbase\guid.h"

#include <objbase.h>

#include <array>
#include <cassert>

#include "kbase\strings\string_piece.h"
#include "kbase\strings\sys_string_encoding_conversions.h"

namespace kbase {

std::string GenerateGUID()
{
    GUID guid;
    auto rv = CoCreateGuid(&guid);
    assert(SUCCEEDED(rv));
    if (!SUCCEEDED(rv)) {
        return std::string();
    }

    const int kGUIDSize = 40;
    std::array<wchar_t, kGUIDSize> guid_str;
    int count_written = StringFromGUID2(guid, guid_str.data(), kGUIDSize);

    // Since GUID contains ASCII-only characters, it is safe to do this conversion.
    // Strips off { and }.
    return count_written ?
        WideToASCII(WStringPiece(guid_str.data() + 1, count_written - 3)) :
        std::string();
}

}   // namespace kbase<|endoftext|>