static JSValueRef getTitleCallback(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception)
{
    JSRetainPtr<JSStringRef> title(Adopt, toAXElement(thisObject)->title());
    return JSValueMakeString(context, title.get());
}
Пример #2
0
////////////////////////////////////////////////////////
//
// SpriteMainScene
//
////////////////////////////////////////////////////////
void SpriteMainScene::initWithSubTest(int asubtest, int nNodes)
{
    //srandom(0);

    subtestNumber = asubtest;
    m_pSubTest = new SubTest;
    m_pSubTest->initWithSubTest(asubtest, this);

    CCSize s = CCDirector::sharedDirector()->getWinSize();

    lastRenderedCount = 0;
    quantityNodes = 0;

    CCMenuItemFont::setFontSize(65);
    CCMenuItemFont *decrease = CCMenuItemFont::create(" - ", this, menu_selector(SpriteMainScene::onDecrease));
    decrease->setColor(ccc3(0,200,20));
    CCMenuItemFont *increase = CCMenuItemFont::create(" + ", this, menu_selector(SpriteMainScene::onIncrease));
    increase->setColor(ccc3(0,200,20));

    CCMenu *menu = CCMenu::create(decrease, increase, NULL);
    menu->alignItemsHorizontally();
    menu->setPosition(ccp(s.width/2, s.height-65));
    addChild(menu, 1);

    CCLabelTTF *infoLabel = CCLabelTTF::create("0 nodes", "Marker Felt", 30);
    infoLabel->setColor(ccc3(0,200,20));
    infoLabel->setPosition(ccp(s.width/2, s.height-90));
    addChild(infoLabel, 1, kTagInfoLayer);

    // add menu
    SpriteMenuLayer* pMenu = new SpriteMenuLayer(true, TEST_COUNT, s_nSpriteCurCase);
    addChild(pMenu, 1, kTagMenuLayer);
    pMenu->release();

    // Sub Tests
    CCMenuItemFont::setFontSize(32);
    CCMenu* pSubMenu = CCMenu::create();
    for (int i = 1; i <= 9; ++i)
    {
        char str[10] = {0};
        sprintf(str, "%d ", i);
        CCMenuItemFont* itemFont = CCMenuItemFont::create(str, this, menu_selector(SpriteMainScene::testNCallback));
        itemFont->setTag(i);
        pSubMenu->addChild(itemFont, 10);

        if( i<= 3)
            itemFont->setColor(ccc3(200,20,20));
        else if(i <= 6)
            itemFont->setColor(ccc3(0,200,20));
        else
            itemFont->setColor(ccc3(0,20,200));
    }

    pSubMenu->alignItemsHorizontally();
    pSubMenu->setPosition(ccp(s.width/2, 80));
    addChild(pSubMenu, 2);

    // add title label
    CCLabelTTF *label = CCLabelTTF::create(title().c_str(), "Arial", 40);
    addChild(label, 1);
    label->setPosition(ccp(s.width/2, s.height-32));
    label->setColor(ccc3(255,255,40));

    while(quantityNodes < nNodes)
        onIncrease(this);
}
Пример #3
0
void DataCurve::loadData()
{
  Plot *plot = static_cast<Plot *>(this->plot());
  Graph *g = static_cast<Graph *>(plot->parent());
  if (!g)
    return;

  int xcol = d_table->colIndex(d_x_column);
  int ycol = d_table->colIndex(title().text());

  if (xcol < 0 || ycol < 0){
    remove();
    return;
  }

  int r = abs(d_end_row - d_start_row) + 1;
  QVarLengthArray<double> X(r), Y(r);
  int xColType = d_table->columnType(xcol);
  int yColType = d_table->columnType(ycol);

  QStringList xLabels, yLabels;// store text labels

//  int xAxis = QwtPlot::xBottom;
//  if (d_type == Graph::HorizontalBars)
//    xAxis = QwtPlot::yLeft;

  QTime time0;
  QDateTime date0;
  QString date_time_fmt = d_table->columnFormat(xcol);
  if (xColType == Table::Time){
    for (int i = d_start_row; i <= d_end_row; i++ ){
      QString xval=d_table->text(i,xcol);
      if (!xval.isEmpty()){
        time0 = QTime::fromString (xval, date_time_fmt);
        if (time0.isValid())
          break;
      }
    }
  } else if (xColType == Table::Date){
    for (int i = d_start_row; i <= d_end_row; i++ ){
      QString xval=d_table->text(i,xcol);
      if (!xval.isEmpty()){
        date0 = QDateTime::fromString (xval, date_time_fmt);
        if (date0.isValid())
          break;
      }
    }
  }

  int size = 0;
  for (int i = d_start_row; i <= d_end_row; i++ ){
    QString xval = d_table->text(i,xcol);
    QString yval = d_table->text(i,ycol);
    if (!xval.isEmpty() && !yval.isEmpty()){
      bool valid_data = true;
      if (xColType == Table::Text){
        xLabels << xval;
        X[size] = (double)(size + 1);
      } else if (xColType == Table::Time){
        QTime time = QTime::fromString (xval, date_time_fmt);
        if (time.isValid())
          X[size]= time0.msecsTo (time);
      } else if (xColType == Table::Date){
        QDateTime d = QDateTime::fromString (xval, date_time_fmt);
        if (d.isValid())
          X[size] = (double) date0.secsTo(d);
      } else
        X[size] = plot->locale().toDouble(xval, &valid_data);

      if (yColType == Table::Text){
        yLabels << yval;
        Y[size] = (double)(size + 1);
      } else
        Y[size] = plot->locale().toDouble(yval, &valid_data);

      if (valid_data)
        size++;
    }
  }

  X.resize(size);
  Y.resize(size);

  // The code for calculating the waterfall offsets, that is here in QtiPlot, has been moved up to
  // PlotCurve so that MantidCurve can access it as well.
  if (g->isWaterfallPlot())
  {
    // Calculate the offsets
    computeWaterfallOffsets();
  }
  // End re-jigged waterfall offset code

  if (!size){
    remove();
    return;
  } else {
    if (d_type == Graph::HorizontalBars){
      setData(Y.data(), X.data(), size);
      foreach(DataCurve *c, d_error_bars)
        c->setData(Y.data(), X.data(), size);
    } else {
      setData(X.data(), Y.data(), size);
      foreach(DataCurve *c, d_error_bars)
        c->setData(X.data(), Y.data(), size);
    }

    if (xColType == Table::Text){
      if (d_type == Graph::HorizontalBars)
        g->setLabelsTextFormat(QwtPlot::yLeft, ScaleDraw::Text, d_x_column, xLabels);
      else
        g->setLabelsTextFormat(QwtPlot::xBottom, ScaleDraw::Text, d_x_column, xLabels);
    } else if (xColType == Table::Time || xColType == Table::Date){
      int axis = QwtPlot::xBottom;
      if (d_type == Graph::HorizontalBars)
        axis = QwtPlot::yLeft;
      ScaleDraw *old_sd = static_cast<ScaleDraw *>(plot->axisScaleDraw(axis));
      ScaleDraw *sd = new ScaleDraw(plot, old_sd);
      if (xColType == Table::Date)
        sd->setDateTimeOrigin(date0);
      else
        sd->setDateTimeOrigin(QDateTime(QDate::currentDate(), time0));
      plot->setAxisScaleDraw(axis, sd);
    }

    if (yColType == Table::Text)
      g->setLabelsTextFormat(QwtPlot::yLeft, ScaleDraw::Text, title().text(), yLabels);
  }

  if (!d_labels_list.isEmpty()){
    (static_cast<Graph*>(plot->parent()))->updatePlot();
    loadLabels();
  }
}
Пример #4
0
  /*! Instead of sending molecules for output via AddChemObject(), they are
    saved in here in OBMoleculeFormat or discarded. By default they are 
    saved only if they are in the first input file. Parts of subsequent
    molecules, such as chemical structure, coordinates and OBGenericData
    can replace the parts in molecules with the same title that have already
    been stored, subject to a set of rules. After all input files have been
    read, the stored molecules (possibly now having augmented properties) are
    sent to the output format.
    
    Is a static function with <this> as parameter so that it can be called from other
    format classes like XMLMoleculeFormat which are not derived from OBMoleculeFormat. 
  */
  bool OBMoleculeFormat::DeferMolOutput(OBMol* pmol, OBConversion* pConv, OBFormat* pF )
  {
    static bool IsFirstFile;
    bool OnlyMolsInFirstFile=true;

    if(pConv->IsFirstInput())
      {
        IsFirstFile=true;
        IMols.clear();
      }
    else 
      {
        if((std::streamoff)pConv->GetInStream()->tellg()<=0)
          IsFirstFile=false;//File has changed
      }

    if (!pF->ReadMolecule(pmol,pConv))
      {
        delete pmol;
        return false;
      }
    const char* ptitle = pmol->GetTitle();
    if(*ptitle==0)
      obErrorLog.ThrowError(__FUNCTION__, "Molecule with no title ignored", obWarning);
    else
      {
        string title(ptitle);
        string::size_type pos = title.find_first_of("\t\r\n"); //some title have other data appended
        if(pos!=string::npos)
          title.erase(pos);
    
        map<std::string, OBMol*>::iterator itr;
        itr = IMols.find(title);
        if(itr!=IMols.end())
          {
            //Molecule with the same title has been input previously: update it
            OBMol* pNewMol = MakeCombinedMolecule(itr->second, pmol);
            if(pNewMol)
              {
                delete itr->second;
                IMols[title] = pNewMol;
              }
            else
              {
                //error: cleanup and return false
                delete pmol;
                return DeleteDeferredMols();
              }
          }
        else
          {
            //Molecule not already saved in IMols: save it if in first file
            if(!OnlyMolsInFirstFile || IsFirstFile)
              {
                IMols[title] = pmol;
                return true; //don't delete pmol
              }
          }
      }
    delete pmol;
    return true;
  }
Пример #5
0
  /** Attempts to read the index file datafilename.obindx successively
      from the following directories:
      - the current directory
      - that in the environment variable BABEL_DATADIR or in the macro BABEL_DATADIR
      if the environment variable is not set
      - in a subdirectory of the BABEL_DATADIR directory with the version of OpenBabel as its name
      An index of type NameIndexType is then constructed. NameIndexType is defined
      in obmolecformat.h and may be a std::tr1::unordered_map (a hash_map) or std::map.
      In any case it is searched by 
      @code
      NameIndexType::iterator itr = index.find(molecule_name);
      if(itr!=index.end())
      unsigned pos_in_datafile = itr->second;
      @endcode
      pos_in_datafile is used as a paramter in seekg() to read from the datafile

      If no index is found, it is constructed from the datafile by reading all of
      it using the format pInFormat, and written to the directory containing the datafile.
      This means that this function can be used without worrying whether there is an index.
      It will be slow to execute the first time, but subsequent uses get the speed benefit
      of indexed access to the datafile. 

      The serialization and de-serialization of the NameIndexType is entirely in
      this routine and could possibly be improved. Currently re-hashing is done 
      every time the index is read.
  **/
  bool OBMoleculeFormat::ReadNameIndex(NameIndexType& index,
                                       const string& datafilename, OBFormat* pInFormat)
  {
    struct headertype
    {
      char filename[256];
      unsigned size;
    } header;

    NameIndexType::iterator itr;

    ifstream indexstream;
    OpenDatafile(indexstream, datafilename + ".obindx");
    if(!indexstream)
      {
        //Need to prepare the index
        ifstream datastream;
        string datafilepath = OpenDatafile(datastream, datafilename);
        if(!datastream)
          {
            obErrorLog.ThrowError(__FUNCTION__, 
                                  datafilepath + " was not found or could not be opened",  obError);
            return false;
          }

        OBConversion Conv(&datastream,NULL);
        Conv.SetInFormat(pInFormat);
        OBMol mol;
        streampos pos;
        while(Conv.Read(&mol))
          {
            string name = mol.GetTitle();
            if(!name.empty())
              index.insert(make_pair(name, pos));
            mol.Clear();
            pos = datastream.tellg();
          }
        obErrorLog.ThrowError(__FUNCTION__, 
                              "Prepared an index for " + datafilepath, obAuditMsg);
        //Save index to file
        ofstream dofs((datafilepath + ".obindx").c_str(), ios_base::out|ios_base::binary);
        if(!dofs) return false;

        strncpy(header.filename,datafilename.c_str(), sizeof(header.filename));
        header.filename[sizeof(header.filename) - 1] = '\0';
        header.size = index.size();
        dofs.write((const char*)&header, sizeof(headertype));
	
        for(itr=index.begin();itr!=index.end();++itr)
          {
            //#chars; chars;  ofset(4bytes).
            const char n = itr->first.size();
            dofs.put(n);
            dofs.write(itr->first.c_str(),n);
            dofs.write((const char*)&itr->second,sizeof(unsigned));
          }			
      }
    else
      {
        //Read index data from file and put into hash_map
        indexstream.read((char*)&header,sizeof(headertype));
        itr=index.begin(); // for hint
        for(unsigned int i=0;i<header.size;++i)
          {
            char len;
            indexstream.get(len);
            string title(len, 0);
            unsigned pos;
            indexstream.read(&title[0],len);
            indexstream.read((char*)&pos,sizeof(unsigned));
            index.insert(itr, make_pair(title,pos));
          }
      }
    return true;
  }
TEST(SMRTTitleTest, test4)
{
    SMRTTitle title("m/1/10_20/3_7");
    EXPECT_EQ(title.isSMRTTitle, true);
    EXPECT_EQ(title.ToString(), "m/1/13_17");
}
Пример #7
0
BOOL CFilePatchesDlg::Init(GitPatch * pPatch, CPatchFilesDlgCallBack * pCallBack, CString sPath, CWnd * pParent)
{
	if (!pCallBack || !pPatch)
	{
		m_cFileList.DeleteAllItems();
		return FALSE;
	}
	m_arFileStates.RemoveAll();
	m_pPatch = pPatch;
	m_pCallBack = pCallBack;
	m_sPath = sPath;
	if (m_sPath.IsEmpty())
	{
		CString title(MAKEINTRESOURCE(IDS_DIFF_TITLE));
		SetWindowText(title);
	}
	else
	{
		CRect rect;
		GetClientRect(&rect);
		SetTitleWithPath(rect.Width());
		m_sPath.TrimRight(L'\\');
		m_sPath += L'\\';
	}

	SetWindowTheme(m_cFileList.GetSafeHwnd(), L"Explorer", nullptr);
	m_cFileList.SetExtendedStyle(LVS_EX_INFOTIP | LVS_EX_FULLROWSELECT | LVS_EX_DOUBLEBUFFER);
	m_cFileList.DeleteAllItems();
	int c = m_cFileList.GetHeaderCtrl()->GetItemCount() - 1;
	while (c>=0)
		m_cFileList.DeleteColumn(c--);
	m_cFileList.InsertColumn(0, CString(MAKEINTRESOURCE(IDS_PATH)));
	m_cFileList.InsertColumn(1, CString(MAKEINTRESOURCE(IDS_STATE)));

	m_cFileList.SetRedraw(false);

	for(int i=0; i<m_pPatch->GetNumberOfFiles(); i++)
	{
		CString sFile = CPathUtils::GetFileNameFromPath(m_pPatch->GetStrippedPath(i));

		int state;
		if (m_sPath.IsEmpty())
			state = 0;
		else
		{
			state = m_pPatch->GetFailedHunks(i);
		}
		if (m_pPatch->GetHasConflict(i))
			state = FPDLG_FILESTATE_CONFLICT;
		if (state > 0)
			state = FPDLG_FILESTATE_ERROR;
		m_arFileStates.Add(state);
		CString sFileName = GetFullPath(i);
		sFileName = CPathUtils::GetFileNameFromPath(sFileName);
		m_cFileList.InsertItem(i, sFile, SYS_IMAGE_LIST().GetPathIconIndex(sFileName));
		SetStateText(i, state);
	}
	int mincol = 0;
	int maxcol = m_cFileList.GetHeaderCtrl()->GetItemCount() - 1;
	int col;
	for (col = mincol; col <= maxcol; col++)
	{
		m_cFileList.SetColumnWidth(col,LVSCW_AUTOSIZE_USEHEADER);
	}

	m_cFileList.SetImageList(&SYS_IMAGE_LIST(), LVSIL_SMALL);
	m_cFileList.SetRedraw(true);

	RECT parentrect;
	pParent->GetWindowRect(&parentrect);
	RECT windowrect;
	GetWindowRect(&windowrect);

	int width = windowrect.right - windowrect.left;
	int height = windowrect.bottom - windowrect.top;
	windowrect.right = parentrect.left;
	windowrect.left = windowrect.right - width;
	windowrect.top = parentrect.top;
	windowrect.bottom = windowrect.top + height;
	auto hMonitor = MonitorFromRect(&windowrect, MONITOR_DEFAULTTONULL);
	if (hMonitor)
		SetWindowPos(nullptr, windowrect.left, windowrect.top, width, height, SWP_NOACTIVATE | SWP_NOZORDER);

	m_nWindowHeight = windowrect.bottom - windowrect.top;
	m_pMainFrame = pParent;
	return TRUE;
}
Пример #8
0
void DataCurve::loadData()
{
    Graph *g = (Graph *)plot();
    if (!g)
        return;

    int xcol = d_x_table->colIndex(d_x_column);
    int ycol = d_table->colIndex(title().text());
    if (xcol < 0 || ycol < 0) {
        remove();
        return;
    }

    int rows = d_table->numRows();
    if (d_end_row < 0 || d_end_row >= rows)
        d_end_row = rows - 1;

    int xColType = d_x_table->columnType(xcol);
    int yColType = d_table->columnType(ycol);
    int r = abs(d_end_row - d_start_row) + 1;

    QPolygonF data;
    data.reserve(r);

    QStringList xLabels, yLabels;// store text labels

    int xAxis = QwtPlot::xBottom;
    if (d_type == Graph::HorizontalBars)
        xAxis = QwtPlot::yLeft;

    QString date_time_fmt = d_table->columnFormat(xcol);
    int size = 0, from = 0;
    d_data_ranges.clear();
    for (int i = d_start_row; i <= d_end_row; i++ ) {
        QString xval = d_x_table->text(i, xcol);
        QString yval = d_table->text(i, ycol);
        if (!xval.isEmpty() && !yval.isEmpty()) {
            bool valid_data = true;
            QPointF p;
            if (xColType == Table::Text) {
                xLabels << xval;
                p.setX((double)(size + 1));
            } else if (xColType == Table::Time)
                p.setX(Table::fromTime(QTime::fromString(xval.trimmed(), date_time_fmt)));
            else if (xColType == Table::Date)
                p.setX(Table::fromDateTime(QDateTime::fromString(xval.trimmed(), date_time_fmt)));
            else
                p.setX(g->locale().toDouble(xval, &valid_data));

            if (yColType == Table::Text) {
                yLabels << yval;
                p.setY((double)(size + 1));
            } else
                p.setY(g->locale().toDouble(yval, &valid_data));

            if (valid_data) {
                data << p;
                size++;
            }
        } else if (from < size) {
            DataRange range;
            range.from = from;
            range.to = size - 1;
            d_data_ranges.push_back(range);
            from = size;
        }
    }

    if (d_data_ranges.size() && from < size) {
        DataRange range;
        range.from = from;
        range.to = size - 1;
        d_data_ranges.push_back(range);
    }

    if (!size) {
        remove();
        return;
    }
    data.resize(size);

    if (g->isWaterfallPlot()) {
        int index = g->curveIndex(this);
        int curves = g->curveCount();
        DataCurve *c = g->dataCurve(0);
        if (index > 0 && c) {
            double xmin = c->minXValue();
            double dx = index*g->waterfallXOffset()*0.01*g->canvas()->width()/(double)(curves - 1);
            d_x_offset = g->invTransform(xAxis, g->transform(xAxis, xmin) + dx) - xmin;

            double ymin = c->minYValue();
            double dy = index*g->waterfallYOffset()*0.01*g->canvas()->height()/(double)(curves - 1);
            d_y_offset = ymin - g->invTransform(yAxis(), g->transform(yAxis(), ymin) + dy);

            setZ(-index);
            setBaseline(d_y_offset);
            data.translate(d_x_offset, d_y_offset);
        } else {
            setZ(0);
            setBaseline(0.0);
        }
        if (g->grid())
            g->grid()->setZ(-g->curveCount() - 1);
    }

    double speedTol = g->getDouglasPeukerTolerance();
    if (speedTol != 0.0 && size >= g->speedModeMaxPoints()) {
        QwtWeedingCurveFitter *fitter = new QwtWeedingCurveFitter(speedTol);
        data = fitter->fitCurve(data);
        delete fitter;
    }

    if (d_type == Graph::HorizontalBars) {
        size = data.size();
        for (int i = 0; i < size; i++) {
            QPointF p = data.at(i);
            data[i] = QPointF(p.y(), p.x());
        }
    }

    setData(data);
    foreach(ErrorBarsCurve *c, d_error_bars)
        c->setData(data);

    if (xColType == Table::Text)
        g->setLabelsTextFormat(xAxis, ScaleDraw::Text, d_x_column, xLabels);
    if (yColType == Table::Text)
        g->setLabelsTextFormat(QwtPlot::yLeft, ScaleDraw::Text, title().text(), yLabels);

    setRenderHint(QwtPlotItem::RenderAntialiased, g->isCurveAntialiasingEnabled(this));

    if (!d_labels_list.isEmpty()) {
        ((Graph*)plot())->updatePlot();
        loadLabels();
    }
}
Пример #9
0
int DataCurve::tableRow(int point)
{
    if (!d_table)
        return -1;

    if (d_type == Graph::Pie) {
        double y_val = y(point);
        int ycol = d_table->colIndex(title().text());
        for (int i = d_start_row; i <= d_end_row; i++ ) {
            if (d_table->cell(i, ycol) == y_val)
                return i;
        }
    }

    int xcol = d_table->colIndex(d_x_column);
    int ycol = d_table->colIndex(title().text());

    if (xcol < 0 || ycol < 0)
        return -1;

    int xColType = d_table->columnType(xcol);
    if (xColType == Table::Date) {
        QString format = d_table->columnFormat(xcol);
        QDateTime date0 = QDateTime::fromString (d_table->text(d_start_row, xcol), format);
        for (int i = d_start_row; i <= d_end_row; i++ ) {
            QDateTime d = QDateTime::fromString (d_table->text(i, xcol), format);
            if (d.isValid()) {
                if (d_type == Graph::HorizontalBars && date0.secsTo(d) == y(point) && d_table->cell(i, ycol) == x(point))
                    return i;
                else if (date0.secsTo(d) == x(point) && d_table->cell(i, ycol) == y(point))
                    return i;
            }
        }
    } else if (xColType == Table::Time) {
        QString format = d_table->columnFormat(xcol);
        QTime t0 = QTime::fromString (d_table->text(d_start_row, xcol), format);
        for (int i = d_start_row; i <= d_end_row; i++ ) {
            QTime t = QTime::fromString (d_table->text(i, xcol), format);
            if (t.isValid()) {
                if (d_type == Graph::HorizontalBars && t0.msecsTo(t) == y(point) && d_table->cell(i, ycol) == x(point))
                    return i;
                if (t0.msecsTo(t) == x(point) && d_table->cell(i, ycol) == y(point))
                    return i;
            }
        }
    } else if (xColType == Table::Text) {
        double y_val = y(point);
        for (int i = d_start_row; i <= d_end_row; i++ ) {
            if (d_table->cell(i, ycol) == y_val)
                return i;
        }
    }

    double x_val = x(point);
    double y_val = y(point);
    for (int i = d_start_row; i <= d_end_row; i++ ) {
        if (d_table->cell(i, xcol) == x_val && d_table->cell(i, ycol) == y_val)
            return i;
    }

    return point;
}
Пример #10
0
//
// Create the guts of the dialog
//
Widget
FindDialog::createWorkArea(Widget dialog)
{
  // TODO - CHECK ERROR!!!
  Widget *label = new Widget[_num_text_fields]; 


  register unsigned int		offset;

  _name = GETMSG(DT_catd, 1, 192, "Mailer - Find");

  title(_name);

	// make this a modal dialog
	/*
	XtVaSetValues (dialog,
			XmNdialogStyle,	XmDIALOG_FULL_APPLICATION_MODAL,
			NULL);
	*/

  	printHelpId("dialog", dialog);

  /* add help callback */
  // XtAddCallback(dialog, XmNhelpCallback, HelpCB, helpId);

	Widget fd_pane = XtVaCreateWidget ("fd_pane",
				xmPanedWindowWidgetClass,
				dialog,
				XmNsashWidth,	1,
				XmNsashHeight,	1,
				NULL);

	printHelpId ("fd_pane", fd_pane);
	// add help callback
	// XtAddCallback (fd_pane, XmNhelpCallback, HelpCB, helpId);

	Widget	fd_form = XtVaCreateWidget ("fd_form",
				xmFormWidgetClass,
				fd_pane,
				XmNfractionBase,	100,
				NULL);

	printHelpId ("fd_form", fd_form);
	// add help callback
	// XtAddCallback (fd_form, XmNhelpCallback, HelpCB, helpId);


	Widget _fd_labelbox = XtVaCreateManagedWidget ("_fd_labelbox",
				xmRowColumnWidgetClass,
				fd_form,
				XmNtopAttachment,	XmATTACH_FORM,
				XmNleftAttachment,	XmATTACH_POSITION,
				XmNrightAttachment,	XmATTACH_POSITION,
				XmNleftPosition,	5,
				XmNrightPosition,	95,
				XmNpacking,		XmPACK_COLUMN,
				XmNnumColumns,		2,
				XmNorientation,		XmVERTICAL,
				XmNisAligned,		True,
				XmNentryAlignment,	XmALIGNMENT_END,
				XmNentryVerticalAlignment,	XmALIGNMENT_CENTER,
				NULL); 
	printHelpId ("_fd_labelbox", _fd_labelbox);
	// add help callback
	// XtAddCallback (_fd_labelbox, XmNhelpCallback, HelpCB, helpId);


	Widget	*_fd_labels = new Widget [_num_text_fields];

	int	_fd_i = 0;
	for (_fd_i = 0; _fd_i < _num_text_fields; _fd_i++)
	{
		_fd_labels [_fd_i] = XtVaCreateManagedWidget (
					_text_labels [_fd_i],
					xmLabelGadgetClass,
					_fd_labelbox,
					NULL);

		printHelpId ("_fd_labels [%s]", _fd_labels [_fd_i]);
		// naturally, this is bogus --must be fixed to return proper label
		// add help callback
		// XtAddCallback(_fd_labels [_fd_i], XmNhelpCallback, HelpCB, helpId);
	}

	for (_fd_i = 0; _fd_i < _num_text_fields; _fd_i++)
	{
		_text_fields [_fd_i] = XtVaCreateManagedWidget (
					_text_names [_fd_i],
					xmTextFieldWidgetClass,
					_fd_labelbox,
					NULL);
		printHelpId ("_text_fields [%s]", _text_fields [_fd_i]);
		// naturally, this is bogus --must be fixed to return proper label
		// add help callback
		// XtAddCallback(_text_fields [_fd_i], XmNhelpCallback, HelpCB, helpId);

		XtAddCallback(_text_fields [_fd_i], XmNactivateCallback,
			(XtCallbackProc)textFieldCallback, (XtPointer)this);
	}


  XmString	strForward = XmStringCreateLocalized(GETMSG(DT_catd, 1, 193, "Forward"));
  XmString	strBackward = XmStringCreateLocalized(GETMSG(DT_catd, 1, 194, "Backward"));

  Widget fd_direction
	= XmVaCreateSimpleRadioBox(fd_form,
				"Direction",
			       0,		// Initial selection
			       directionCallback,
				//NULL,
			       XmVaRADIOBUTTON, strForward, NULL, NULL, NULL,
			       XmVaRADIOBUTTON, strBackward, NULL, NULL, NULL,
			       XmNuserData,	this,
				XmNsensitive,	True,
				XmNtopAttachment,	XmATTACH_WIDGET,
				XmNtopWidget,		_fd_labelbox,
				XmNorientation,	XmHORIZONTAL,
				XmNleftAttachment,	XmATTACH_POSITION,
				XmNleftPosition,	33,
			       NULL);
	 printHelpId ("fd_direction", fd_direction);
	// add help callback
	//XtAddCallback (fd_direction, XmNhelpCallback, HelpCB, helpId);

  XmStringFree(strForward);
  XmStringFree(strBackward);

  //
  // Now create the Action Area.
  //
#define TIGHTNESS	20

  register Widget		widget;

  Widget fd_action = XtVaCreateWidget("actionArea",
				 xmFormWidgetClass,
				 fd_pane,
				 XmNleftAttachment,	XmATTACH_FORM,
				 XmNrightAttachment,	XmATTACH_FORM,
				 XmNfractionBase, TIGHTNESS * _num_buttons-1,
				 NULL);
	 printHelpId ("actionArea", fd_action);
	// add help callback
	//XtAddCallback (fd_action, XmNhelpCallback, HelpCB, helpId);

  for (offset = 0; offset < _num_buttons; offset++) 
  {  widget = XtVaCreateManagedWidget(_buttonData[offset].label,
				     xmPushButtonWidgetClass,	fd_action,

				     XmNleftAttachment,
				     offset ? XmATTACH_POSITION:XmATTACH_FORM,

				     XmNleftPosition,	TIGHTNESS * offset,
				     XmNtopAttachment,	XmATTACH_FORM,

				     XmNrightAttachment,
				     offset != _num_buttons - 1 ? XmATTACH_POSITION : XmATTACH_FORM,

				     XmNrightPosition,
				     TIGHTNESS * offset + (TIGHTNESS - 1),

				     XmNshowAsDefault,	offset == 0,
				     NULL);

	// again, bogus -- doesn't each one need a unique tag?
	 printHelpId ("widget", widget);
	// add help callback
	//XtAddCallback (widget, XmNhelpCallback, HelpCB, helpId);

    if (_buttonData[offset].callback != NULL) {
      XtAddCallback(widget, XmNactivateCallback,
		    _buttonData[offset].callback,
		    _buttonData[offset].data);
    }


    if (offset == 0) {
      Dimension		height;
      Dimension		margin;

      XtVaGetValues(fd_action, XmNmarginHeight, &margin, NULL);
      XtVaGetValues(widget, XmNheight, &height, NULL);
      height +=2 * margin;
      XtVaSetValues(fd_action,
		    XmNdefaultButton,	widget,
		    XmNpaneMaximum,	height,
		    XmNpaneMinimum,	height,
		    NULL);

    }
  }

  _status_text = XtVaCreateManagedWidget("StatusLabel",
					   xmLabelWidgetClass, fd_pane,
                                           XmNrightAttachment, XmATTACH_FORM,
                                           XmNleftAttachment, XmATTACH_FORM,
                                           XmNalignment, XmALIGNMENT_BEGINNING,
                                           NULL);
	    
  Dimension height;
  XtWidgetGeometry size;

  size.request_mode = CWHeight;
  XtQueryGeometry(_status_text, NULL, &size);
  XtVaSetValues(_status_text,
		XmNpaneMaximum, size.height,
		XmNpaneMinimum, size.height,
		NULL);
 
  clearStatus();

  XtManageChild (fd_form);
  XtManageChild (fd_direction);
  XtManageChild(fd_action);
  XtManageChild(fd_pane);

  XtManageChild(dialog);

  // Make sure get the height of the dialog after it has been
  // managed.
  XtVaGetValues(dialog, XmNheight, &height, NULL);
  XtVaSetValues(dialog, 
		XmNmappedWhenManaged, True,
		XmNminHeight, height,
		NULL);
  XtRealizeWidget(dialog);

  return (fd_pane);
}
Пример #11
0
bool TessPDFRenderer::EndDocumentHandler() {
  size_t n;
  char buf[kBasicBufSize];

  // We reserved the /Pages object number early, so that the /Page
  // objects could refer to their parent. We finally have enough
  // information to go fill it in. Using lower level calls to manipulate
  // the offset record in two spots, because we are placing objects
  // out of order in the file.

  // PAGES
  const long int kPagesObjectNumber = 2;
  offsets_[kPagesObjectNumber] = offsets_.back();  // manipulation #1
  n = snprintf(buf, sizeof(buf),
               "%ld 0 obj\n"
               "<<\n"
               "  /Type /Pages\n"
               "  /Kids [ ", kPagesObjectNumber);
  if (n >= sizeof(buf)) return false;
  AppendString(buf);
  size_t pages_objsize  = strlen(buf);
  for (size_t i = 0; i < pages_.size(); i++) {
    n = snprintf(buf, sizeof(buf),
                 "%ld 0 R ", pages_[i]);
    if (n >= sizeof(buf)) return false;
    AppendString(buf);
    pages_objsize += strlen(buf);
  }
  n = snprintf(buf, sizeof(buf),
               "]\n"
               "  /Count %d\n"
               ">>\n"
               "endobj\n", pages_.size());
  if (n >= sizeof(buf)) return false;
  AppendString(buf);
  pages_objsize += strlen(buf);
  offsets_.back() += pages_objsize;    // manipulation #2

  // INFO
  char* datestr = l_getFormattedDate();
  n = snprintf(buf, sizeof(buf),
               "%ld 0 obj\n"
               "<<\n"
               "  /Producer (Tesseract %s)\n"
               "  /CreationDate (D:%s)\n"
               "  /Title (%s)"
               ">>\n"
               "endobj\n", obj_, TESSERACT_VERSION_STR, datestr, title());
  lept_free(datestr);
  if (n >= sizeof(buf)) return false;
  AppendPDFObject(buf);
  n = snprintf(buf, sizeof(buf),
               "xref\n"
               "0 %ld\n"
               "0000000000 65535 f \n", obj_);
  if (n >= sizeof(buf)) return false;
  AppendString(buf);
  for (int i = 1; i < obj_; i++) {
    n = snprintf(buf, sizeof(buf), "%010ld 00000 n \n", offsets_[i]);
    if (n >= sizeof(buf)) return false;
    AppendString(buf);
  }
  n = snprintf(buf, sizeof(buf),
               "trailer\n"
               "<<\n"
               "  /Size %ld\n"
               "  /Root %ld 0 R\n"
               "  /Info %ld 0 R\n"
               ">>\n"
               "startxref\n"
               "%ld\n"
               "%%%%EOF\n",
               obj_,
               1L,               // catalog
               obj_ - 1,         // info
               offsets_.back());
  if (n >= sizeof(buf)) return false;
  AppendString(buf);
  return true;
}
Пример #12
0
bool QgsProject::write()
{
  clearError();

  // if we have problems creating or otherwise writing to the project file,
  // let's find out up front before we go through all the hand-waving
  // necessary to create all the Dom objects
  if ( !imp_->file.open( QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate ) )
  {
    imp_->file.close();         // even though we got an error, let's make
    // sure it's closed anyway

    setError( tr( "Unable to save to file %1" ).arg( imp_->file.fileName() ) );
    return false;
  }
  QFileInfo myFileInfo( imp_->file );
  if ( !myFileInfo.isWritable() )
  {
    // even though we got an error, let's make
    // sure it's closed anyway
    imp_->file.close();
    setError( tr( "%1 is not writable. Please adjust permissions (if possible) and try again." )
              .arg( imp_->file.fileName() ) );
    return false;
  }

  QDomImplementation DomImplementation;

  QDomDocumentType documentType =
    DomImplementation.createDocumentType( "qgis", "http://mrcc.com/qgis.dtd",
                                          "SYSTEM" );
  std::auto_ptr < QDomDocument > doc =
    std::auto_ptr < QDomDocument > ( new QDomDocument( documentType ) );


  QDomElement qgisNode = doc->createElement( "qgis" );
  qgisNode.setAttribute( "projectname", title() );
  qgisNode.setAttribute( "version", QString( "%1" ).arg( QGis::QGIS_VERSION ) );

  doc->appendChild( qgisNode );

  // title
  QDomElement titleNode = doc->createElement( "title" );
  qgisNode.appendChild( titleNode );

  QDomText titleText = doc->createTextNode( title() );  // XXX why have title TWICE?
  titleNode.appendChild( titleText );

  // let map canvas and legend write their information
  emit writeProject( *doc );

  // within top level node save list of layers
  QMap<QString, QgsMapLayer*> & layers = QgsMapLayerRegistry::instance()->mapLayers();

  // Iterate over layers in zOrder
  // Call writeXML() on each
  QDomElement projectLayersNode = doc->createElement( "projectlayers" );
  projectLayersNode.setAttribute( "layercount", qulonglong( layers.size() ) );

  QMap<QString, QgsMapLayer*>::iterator li = layers.begin();
  while ( li != layers.end() )
  {
    //QgsMapLayer *ml = QgsMapLayerRegistry::instance()->mapLayer(*li);
    QgsMapLayer* ml = li.value();

    if ( ml )
    {
      QString externalProjectFile = layerIsEmbedded( ml->id() );
      QHash< QString, QPair< QString, bool> >::const_iterator emIt = mEmbeddedLayers.find( ml->id() );
      if ( emIt == mEmbeddedLayers.constEnd() )
      {
        ml->writeXML( projectLayersNode, *doc );
      }
      else //layer defined in an external project file
      {
        //only save embedded layer if not managed by a legend group
        if ( emIt.value().second )
        {
          QDomElement mapLayerElem = doc->createElement( "maplayer" );
          mapLayerElem.setAttribute( "embedded", 1 );
          mapLayerElem.setAttribute( "project", writePath( emIt.value().first ) );
          mapLayerElem.setAttribute( "id", ml->id() );
          projectLayersNode.appendChild( mapLayerElem );
        }
      }
    }
    li++;
  }

  qgisNode.appendChild( projectLayersNode );

  // now add the optional extra properties

  dump_( imp_->properties_ );

  QgsDebugMsg( QString( "there are %1 property scopes" ).arg( static_cast<int>( imp_->properties_.count() ) ) );

  if ( !imp_->properties_.isEmpty() ) // only worry about properties if we
    // actually have any properties
  {
    imp_->properties_.writeXML( "properties", qgisNode, *doc );
  }

  // now wrap it up and ship it to the project file
  doc->normalize();             // XXX I'm not entirely sure what this does

  //QString xml = doc->toString(4); // write to string with indentation of four characters
  // (yes, four is arbitrary)

  // const char * xmlString = xml; // debugger probe point
  // qDebug( "project file output:\n\n" + xml );

  QTextStream projectFileStream( &imp_->file );

  //projectFileStream << xml << endl;
  doc->save( projectFileStream, 4 );  // save as utf-8
  imp_->file.close();

  // check if the text stream had no error - if it does
  // the user will get a message so they can try to resolve the
  // situation e.g. by saving project to a volume with more space
  //
  if ( projectFileStream.pos() == -1  || imp_->file.error() != QFile::NoError )
  {
    setError( tr( "Unable to save to file %1. Your project "
                  "may be corrupted on disk. Try clearing some space on the volume and "
                  "check file permissions before pressing save again." )
              .arg( imp_->file.fileName() ) );
    return false;
  }

  dirty( false );               // reset to pristine state

  return true;
} // QgsProject::write
Пример #13
0
  OBBase* OBMol::DoTransformations(const std::map<std::string, std::string>* pOptions)
  {
    // Perform any requested transformations
    // on a OBMol
    //The input map has option letters or name as the key and 
    //any associated text as the value.
    //For normal(non-filter) transforms:
    // returns a pointer to the OBMol (this) if ok or NULL if not.
    //For filters returns a pointer to the OBMol (this) if there is a  match,
    //and NULL when not and in addition the OBMol object is deleted NULL.

    //This is now a virtual function. The OBBase version just returns the OBMol pointer.
    //This is declared in mol.h

    //The filter options, s and v allow a obgrep facility. 
    //Used together they must both be true to allow a molecule through.

    //Parse GeneralOptions
    if(pOptions->empty())
      return this;

    // DoOps calls Do() for each of the plugin options in the map
    // It normally returns true, even if there are no options but
    // can return false if one of the options decides that the 
    // molecule should not be output
    bool fmatch = OBOp::DoOps(this, pOptions); 

    bool ret=true;

    map<string,string>::const_iterator itr, itr2;

    if(pOptions->find("b")!=pOptions->end())
      if(!ConvertDativeBonds())
        ret=false;

    if(pOptions->find("d")!=pOptions->end())
      if(!DeleteHydrogens())
        ret=false;

    if(pOptions->find("h")!=pOptions->end())
      if(!AddHydrogens(false, false))
        ret=false;

    if(pOptions->find("p")!=pOptions->end())
      if(!AddHydrogens(false, true))
        ret=false;

    if(pOptions->find("c")!=pOptions->end())
      Center();

    itr = pOptions->find("title"); //Replaces title
    if(itr!=pOptions->end())
      SetTitle(itr->second.c_str());

    itr = pOptions->find("addtotitle"); //Appends text to title
    if(itr!=pOptions->end())
      {
        string title(GetTitle());
        title += itr->second;
        SetTitle(title.c_str());
      }

    itr = pOptions->find("addformula"); //Appends tab + formula to title
    if(itr!=pOptions->end())
      {
        string title(GetTitle());
        title += '\t' + GetSpacedFormula(1,"");//actually unspaced
        SetTitle(title.c_str());
      }

    //Add an extra property to the molecule.
    //Parameter has atrribute and value separated by a space
    itr = pOptions->find("property");
    if(itr!=pOptions->end())
      {
        string txt(itr->second);
        string::size_type pos = txt.find(' ');
        if(pos==string::npos)
          {
            obErrorLog.ThrowError(__FUNCTION__, "Missing property value", obError);
            ret=false;
          }
        else
          {
            string attr(txt.substr(0,pos)), val(txt.substr(pos+1));
            //Update value if it already exists
            OBPairData* dp = dynamic_cast<OBPairData*>(GetData(attr));
            if(dp) {
              dp->SetValue(val);
              dp->SetOrigin(userInput);
            } 
            else {
              // Pair did not exist; make new one
              dp = new OBPairData;
              dp->SetAttribute(attr);
              dp->SetValue(val);
              dp->SetOrigin(userInput);
              SetData(dp);
            }
          }
      }

    itr = pOptions->find("add");  //adds new properties from descriptors in list
    if(itr!=pOptions->end())
      OBDescriptor::AddProperties(this, itr->second);
    
    itr = pOptions->find("delete"); //deletes the specified properties
    if(itr!=pOptions->end())
      OBDescriptor::DeleteProperties(this, itr->second);

    itr = pOptions->find("append"); //Appends values of descriptors or properties to title
    if(itr!=pOptions->end())
      {
        string title(GetTitle());
        title += OBDescriptor::GetValues(this, itr->second);
        SetTitle(Trim(title).c_str());
      }


    
      //Filter using OBDescriptor comparison and (older) SMARTS tests
    //Continue only if previous test was true.
    itr = pOptions->find("filter");
    if(itr!=pOptions->end())
      {
        std::istringstream optionText(itr->second);
        fmatch = OBDescriptor::FilterCompare(this, optionText, false);
      }

    if(fmatch)
      {
        itr = pOptions->find("v");
        if(itr!=pOptions->end())
          {
            //inverse match quoted SMARTS string which follows
            OBSmartsPattern sp;
            sp.Init(itr->second);
            fmatch = !sp.Match(*this); //(*pmol) ;
          }
      }
    if(fmatch)
    {
      itr = pOptions->find("s");
      if(itr!=pOptions->end())
        {
          //SMARTS filter
          //If exactmatch option set (probably in fastsearchformat) the
          //number of atoms in the pattern (passed as a string in the option text)
          //has to be the same as in the molecule.
          itr2 = pOptions->find("exactmatch");
          if(itr2!=pOptions->end() && NumHvyAtoms()!=atoi(itr2->second.c_str()))
            fmatch=false;
          else
          {
            //match quoted SMARTS string which follows
            OBSmartsPattern sp;
            sp.Init(itr->second.c_str());
            fmatch = sp.Match(*this); //(*pmol) ;
          }
        }
    }

    if(!fmatch)
      {
        //filter failed: delete OBMol and return NULL
        delete this;
        return NULL;
      }
    else
      {
        if(ret==false)
          {
            obErrorLog.ThrowError(__FUNCTION__, "Error executing an option", obError);
            delete this; //added 9March2006
            return NULL;
          }
        else
          return this;
      }
  }
Пример #14
0
/**
 * Resets the screen surfaces based on the current display options,
 * as they don't automatically take effect.
 * @param resetVideo Reset display surface.
 */
void Screen::resetDisplay(bool resetVideo)
{
	int width = Options::displayWidth;
	int height = Options::displayHeight;
#ifdef __linux__
	Uint32 oldFlags = _flags;
#endif
	makeVideoFlags();

	if (!_surface || (_surface->getSurface()->format->BitsPerPixel != _bpp ||
		_surface->getSurface()->w != _baseWidth ||
		_surface->getSurface()->h != _baseHeight)) // don't reallocate _surface if not necessary, it's a waste of CPU cycles
	{
		if (_surface) delete _surface;
		_surface = new Surface(_baseWidth, _baseHeight, 0, 0, Screen::use32bitScaler() ? 32 : 8); // only HQX/XBRZ needs 32bpp for this surface; the OpenGL class has its own 32bpp buffer
		if (_surface->getSurface()->format->BitsPerPixel == 8) _surface->setPalette(deferredPalette);
	}
	SDL_SetColorKey(_surface->getSurface(), 0, 0); // turn off color key! 

	if (resetVideo || _screen->format->BitsPerPixel != _bpp)
	{
#ifdef __linux__
		// Workaround for segfault when switching to opengl
		if (!(oldFlags & SDL_OPENGL) && (_flags & SDL_OPENGL))
		{
			Uint8 cursor = 0;
			char *_oldtitle = 0;
			SDL_WM_GetCaption(&_oldtitle, NULL);
			std::string title(_oldtitle);
			SDL_QuitSubSystem(SDL_INIT_VIDEO);
			SDL_InitSubSystem(SDL_INIT_VIDEO);
			SDL_ShowCursor(SDL_ENABLE);
			SDL_EnableUNICODE(1);
			SDL_WM_SetCaption(title.c_str(), 0);
			SDL_SetCursor(SDL_CreateCursor(&cursor, &cursor, 1,1,0,0));
		}
#endif
		Log(LOG_INFO) << "Attempting to set display to " << width << "x" << height << "x" << _bpp << "...";
		_screen = SDL_SetVideoMode(width, height, _bpp, _flags);
		if (_screen == 0)
		{
			Log(LOG_ERROR) << SDL_GetError();
			Log(LOG_INFO) << "Attempting to set display to default resolution...";
			_screen = SDL_SetVideoMode(640, 400, _bpp, _flags);
			if (_screen == 0)
			{
				if (_flags & SDL_OPENGL)
				{
					Options::useOpenGL = false;
				}
				throw Exception(SDL_GetError());
			}
		}
		Log(LOG_INFO) << "Display set to " << getWidth() << "x" << getHeight() << "x" << (int)_screen->format->BitsPerPixel << ".";
	}
	else
	{
		clear();
	}

	Options::displayWidth = getWidth();
	Options::displayHeight = getHeight();
	_scaleX = getWidth() / (double)_baseWidth;
	_scaleY = getHeight() / (double)_baseHeight;
	_clear.x = 0;
	_clear.y = 0;
	_clear.w = getWidth();
	_clear.h = getHeight();

	double pixelRatioY = 1.0;
	if (Options::nonSquarePixelRatio && !Options::allowResize)
	{
		pixelRatioY = 1.2;
	}
	bool cursorInBlackBands;
	if (!Options::keepAspectRatio)
	{
		cursorInBlackBands = false;
	}
	else if (Options::fullscreen)
	{
		cursorInBlackBands = Options::cursorInBlackBandsInFullscreen;
	}
	else if (!Options::borderless)
	{
		cursorInBlackBands = Options::cursorInBlackBandsInWindow;
	}
	else
	{
		cursorInBlackBands = Options::cursorInBlackBandsInBorderlessWindow;
	}

	if (_scaleX > _scaleY && Options::keepAspectRatio)
	{
		int targetWidth = (int)floor(_scaleY * (double)_baseWidth);
		_topBlackBand = _bottomBlackBand = 0;
		_leftBlackBand = (getWidth() - targetWidth) / 2;
		if (_leftBlackBand < 0)
		{
			_leftBlackBand = 0;
		}
		_rightBlackBand = getWidth() - targetWidth - _leftBlackBand;
		_cursorTopBlackBand = 0;

		if (cursorInBlackBands)
		{
			_scaleX = _scaleY;
			_cursorLeftBlackBand = _leftBlackBand;
		}
		else
		{
			_cursorLeftBlackBand = 0;
		}
	}
	else if (_scaleY > _scaleX && Options::keepAspectRatio)
	{
		int targetHeight = (int)floor(_scaleX * (double)_baseHeight * pixelRatioY);
		_topBlackBand = (getHeight() - targetHeight) / 2;
		if (_topBlackBand < 0)
		{
			_topBlackBand = 0;
		}
		_bottomBlackBand = getHeight() - targetHeight - _topBlackBand;
		if (_bottomBlackBand < 0)
		{
			_bottomBlackBand = 0;
		}
		_leftBlackBand = _rightBlackBand = 0;
		_cursorLeftBlackBand = 0;

		if (cursorInBlackBands)
		{
			_scaleY = _scaleX;
			_cursorTopBlackBand = _topBlackBand;
		}
		else
		{
			_cursorTopBlackBand = 0;
		}
	}
	else
	{
		_topBlackBand = _bottomBlackBand = _leftBlackBand = _rightBlackBand = _cursorTopBlackBand = _cursorLeftBlackBand = 0;
	}

	if (useOpenGL()) 
	{
#ifndef __NO_OPENGL
		OpenGL::checkErrors = Options::checkOpenGLErrors;
		glOutput.init(_baseWidth, _baseHeight);
		glOutput.linear = Options::useOpenGLSmoothing; // setting from shader file will override this, though
		if (!FileMap::isResourcesEmpty())
		{
			if (!glOutput.set_shader(FileMap::getFilePath(Options::useOpenGLShader).c_str()))
			{
				Options::useOpenGLShader = "";
			}
		}
		glOutput.setVSync(Options::vSyncForOpenGL);
#endif
	}

	if (_screen->format->BitsPerPixel == 8)
	{
		setPalette(getPalette());
	}
}
Пример #15
0
void Plot2DProfile::setId( const QString& id ){
    Plot2D::setId( id );
    QwtText dataTitle = title();
    dataTitle.setText( id );
    setTitle( dataTitle );
}
Пример #16
0
void DataCurve::loadLabels()
{
    if (!validCurveType())
        return;

    clearLabels();

    int xcol = d_table->colIndex(d_x_column);
    int ycol = d_table->colIndex(title().text());
    int labelsCol = d_table->colIndex(d_labels_column);
    int cols = d_table->numCols();
    if (xcol < 0 || ycol < 0 || labelsCol < 0 ||
            xcol >= cols || ycol >= cols || labelsCol >= cols)
        return;

    QwtPlot *d_plot = plot();
    if (!d_plot)
        return;

    int index = 0;
    for (int i = d_start_row; i <= d_end_row; i++) {
        if (d_table->text(i, xcol).isEmpty() ||
                d_table->text(i, ycol).isEmpty())
            continue;

        PlotMarker *m = new PlotMarker(index, d_labels_angle);

        QwtText t = QwtText(d_table->text(i, labelsCol));
        t.setColor(d_labels_color);
        t.setFont(d_labels_font);
        if (d_white_out_labels)
            t.setBackgroundBrush(QBrush(Qt::white));
        else
            t.setBackgroundBrush(QBrush(Qt::transparent));
        m->setLabel(t);

        int x_axis = xAxis();
        int y_axis = yAxis();
        m->setAxis(x_axis, y_axis);

        QSize size = t.textSize();
        int dx = int(d_labels_x_offset*0.01*size.height());
        int dy = -int((d_labels_y_offset*0.01 + 0.5)*size.height());
        int x2 = d_plot->transform(x_axis, x(index)) + dx;
        int y2 = d_plot->transform(y_axis, y(index)) + dy;
        switch(d_labels_align) {
        case Qt::AlignLeft:
            break;
        case Qt::AlignHCenter:
            x2 -= size.width()/2;
            break;
        case Qt::AlignRight:
            x2 -= size.width();
            break;
        }
        m->setXValue(d_plot->invTransform(x_axis, x2));
        m->setYValue(d_plot->invTransform(y_axis, y2));
        m->attach(d_plot);
        d_labels_list << m;
        index++;
    }

    d_show_labels = true;
}
TEST(SMRTTitleTest, test3)
{
    SMRTTitle title("m/1/3_4");
    EXPECT_EQ(title.isSMRTTitle, true);
    EXPECT_EQ(title.ToString(), "m/1/3_4");
}
Пример #18
0
	void setI(const unsigned &i)
	{
		m_i = i;
		setText(title());
	}
TEST(SMRTTitleTest, test1)
{
    SMRTTitle title("1");
    EXPECT_EQ(title.isSMRTTitle, false);
    EXPECT_EQ(title.ToString(), "");
}
Пример #20
0
int
main(int argc, char *argv[])
{
  /* *INDENT-OFF* */
  static MENU mainmenu[] = {
      { "Exit",                                              0 },
      { "Test of cursor movements",                          tst_movements },
      { "Test of screen features",                           tst_screen },
      { "Test of character sets",                            tst_characters },
      { "Test of double-sized characters",                   tst_doublesize },
      { "Test of keyboard",                                  tst_keyboard },
      { "Test of terminal reports",                          tst_reports },
      { "Test of VT52 mode",                                 tst_vt52 },
      { "Test of VT102 features (Insert/Delete Char/Line)",  tst_insdel },
      { "Test of known bugs",                                tst_bugs },
      { "Test of reset and self-test",                       tst_rst },
      { "Test non-VT100 (e.g., VT220, XTERM) terminals",     tst_nonvt100 },
      { "Modify test-parameters",                            tst_setup },
      { "",                                                  0 }
    };
  /* *INDENT-ON* */

  while (argc-- > 1) {
    const char *opt = *++argv;
    if (*opt == '-') {
      while (*++opt != '\0') {
        switch (*opt) {
        case 'f':
          if (!*++opt) {
            if (argc-- < 1)
              usage();
            opt = *++argv;
          }
          setup_softchars(opt);
          opt = "?";
          break;
        case 'l':
          enable_logging();
          break;
        case 'p':
          use_padding = TRUE;
          break;
        case 's':
          slow_motion = TRUE;
          break;
        case '8':
          output_8bits = TRUE;
          break;
        default:
          usage();
        }
      }
    } else {
      /*
       * Allow user to specify geometry of terminal to accommodate quasi-VT100
       * terminals such as Linux console and xterm.
       */
      char *p = argv[0];
      char *q;
      int values[3], n, m;
      for (n = 0; n < 3; n++) {
        if (!*p)
          break;
        if ((m = (int) strtol(p, &q, 10)) > 0) {
          values[n] = m;
          p = q;
          if (*p)
            p++;
        } else {
          break;
        }
      }
      switch (n) {
      case 3:
        max_cols = values[2];
        /* FALLTHRU */
      case 2:
        min_cols = values[1];
        /* FALLTHRU */
      case 1:
        max_lines = values[0];
        break;
      }
      if ((max_cols < min_cols) || (n == 0)) {
        usage();
      }
    }
  }

#ifdef UNIX
  initterminal(setjmp(intrenv));
  signal(SIGINT, onbrk);
  signal(SIGTERM, onterm);
  reading = FALSE;
#else
  initterminal(0);
#endif
  do {
    vt_clear(2);
    __(title(0), printf("VT100 test program, version %d.%d", RELEASE, PATCHLEVEL));
#ifdef PATCH_DATE
    if (PATCH_DATE)
      printf(" (%d)", PATCH_DATE);
#endif

    title(1);
    if (max_lines != 24
        || min_cols != 80
        || max_cols != 132)
      printf("Screen size %dx%d (%d max) ", max_lines, min_cols, max_cols);
    if (tty_speed != DEFAULT_SPEED)
      printf("Line speed %dbd ", tty_speed);
    if (use_padding)
      printf(" (padded)");

    __(title(2), println("Choose test type:"));
  } while (menu(mainmenu));
  bye();
  return EXIT_SUCCESS;
}
Пример #21
0
int
driver(const Box& global_box, Box& my_box,
       Parameters& params, YAML_Doc& ydoc)
{
    int global_nx = global_box[0][1];
    int global_ny = global_box[1][1];
    int global_nz = global_box[2][1];

    int numprocs = 1, myproc = 0;
#ifdef HAVE_MPI
    MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
    MPI_Comm_rank(MPI_COMM_WORLD, &myproc);
#endif

    if (params.load_imbalance > 0) {
        add_imbalance<GlobalOrdinal>(global_box, my_box, params.load_imbalance, ydoc);
    }

    float largest_imbalance = 0, std_dev = 0;
    compute_imbalance<GlobalOrdinal>(global_box, my_box, largest_imbalance,
                                     std_dev, ydoc, true);


    //Create a representation of the mesh:
    //Note that 'simple_mesh_description' is a virtual or conceptual
    //mesh that doesn't actually store mesh data.

    if (myproc==0) {
        std::cout.width(30);
        std::cout << "creating/filling mesh...";
        std::cout.flush();
    }

    timer_type t_start = mytimer();
    timer_type t0 = mytimer();

    simple_mesh_description<GlobalOrdinal> mesh(global_box, my_box);

    timer_type mesh_fill = mytimer() - t0;
    timer_type t_total = mytimer() - t_start;

    if (myproc==0) {
        std::cout << mesh_fill << "s, total time: " << t_total << std::endl;
    }

    //next we will generate the matrix structure.

    //Declare matrix object:

#if defined(MINIFE_ELL_MATRIX)
    typedef ELLMatrix<Scalar,LocalOrdinal,GlobalOrdinal> MatrixType;
#else
    typedef CSRMatrix<Scalar,LocalOrdinal,GlobalOrdinal> MatrixType;
#endif

    MatrixType A;

    timer_type gen_structure;
    RUN_TIMED_FUNCTION("generating matrix structure...",
                       generate_matrix_structure(mesh, A),
                       gen_structure, t_total);

    GlobalOrdinal local_nrows = A.rows.size();
    GlobalOrdinal my_first_row = local_nrows > 0 ? A.rows[0] : -1;

    Vector<Scalar,LocalOrdinal,GlobalOrdinal> b(my_first_row, local_nrows);
    Vector<Scalar,LocalOrdinal,GlobalOrdinal> x(my_first_row, local_nrows);

    //Assemble finite-element sub-matrices and sub-vectors into the global
    //linear system:

    timer_type fe_assembly;
    RUN_TIMED_FUNCTION("assembling FE data...",
                       assemble_FE_data(mesh, A, b, params),
                       fe_assembly, t_total);

    if (myproc == 0) {
        ydoc.add("Matrix structure generation","");
        ydoc.get("Matrix structure generation")->add("Mat-struc-gen Time",gen_structure);
        ydoc.add("FE assembly","");
        ydoc.get("FE assembly")->add("FE assembly Time",fe_assembly);
    }

#ifdef MINIFE_DEBUG
    write_matrix("A_prebc.mtx", A);
    write_vector("b_prebc.vec", b);
#endif

    //Now apply dirichlet boundary-conditions
    //(Apply the 0-valued surfaces first, then the 1-valued surface last.)

    timer_type dirbc_time;
    RUN_TIMED_FUNCTION("imposing Dirichlet BC...",
                       impose_dirichlet(0.0, A, b, global_nx+1, global_ny+1, global_nz+1, mesh.bc_rows_0), dirbc_time, t_total);
    RUN_TIMED_FUNCTION("imposing Dirichlet BC...",
                       impose_dirichlet(1.0, A, b, global_nx+1, global_ny+1, global_nz+1, mesh.bc_rows_1), dirbc_time, t_total);

#ifdef MINIFE_DEBUG
    write_matrix("A.mtx", A);
    write_vector("b.vec", b);
#endif

    //Transform global indices to local, set up communication information:

    timer_type make_local_time;
    RUN_TIMED_FUNCTION("making matrix indices local...",
                       make_local_matrix(A),
                       make_local_time, t_total);

#ifdef MINIFE_DEBUG
    write_matrix("A_local.mtx", A);
    write_vector("b_local.vec", b);
#endif

    size_t global_nnz = compute_matrix_stats(A, myproc, numprocs, ydoc);

    //Prepare to perform conjugate gradient solve:

    LocalOrdinal max_iters = 200;
    LocalOrdinal num_iters = 0;
    typedef typename TypeTraits<Scalar>::magnitude_type magnitude;
    magnitude rnorm = 0;
    magnitude tol = std::numeric_limits<magnitude>::epsilon();

    timer_type cg_times[NUM_TIMERS];

    typedef Vector<Scalar,LocalOrdinal,GlobalOrdinal> VectorType;

    t_total = mytimer() - t_start;

    bool matvec_with_comm_overlap = params.mv_overlap_comm_comp==1;

    int verify_result = 0;

#if MINIFE_KERNELS != 0
    if (myproc==0) {
        std::cout.width(30);
        std::cout << "Starting kernel timing loops ..." << std::endl;
    }

    max_iters = 500;
    x.coefs[0] = 0.9;
    if (matvec_with_comm_overlap) {
        time_kernels(A, b, x, matvec_overlap<MatrixType,VectorType>(), max_iters, rnorm, cg_times);
    }
    else {
        time_kernels(A, b, x, matvec_std<MatrixType,VectorType>(), max_iters, rnorm, cg_times);
    }
    num_iters = max_iters;
    std::string title("Kernel timings");
#else
    if (myproc==0) {
        std::cout << "Starting CG solver ... " << std::endl;
    }

    if (matvec_with_comm_overlap) {
#ifdef MINIFE_CSR_MATRIX
        rearrange_matrix_local_external(A);
        cg_solve(A, b, x, matvec_overlap<MatrixType,VectorType>(), max_iters, tol,
                 num_iters, rnorm, cg_times);
#else
        std::cout << "ERROR, matvec with overlapping comm/comp only works with CSR matrix."<<std::endl;
#endif
    }
    else {
        cg_solve(A, b, x, matvec_std<MatrixType,VectorType>(), max_iters, tol,
                 num_iters, rnorm, cg_times);
        if (myproc == 0) {
            std::cout << "Final Resid Norm: " << rnorm << std::endl;
        }

        if (params.verify_solution > 0) {
            double tolerance = 0.06;
            bool verify_whole_domain = false;
#ifdef MINIFE_DEBUG
            verify_whole_domain = true;
#endif
            if (myproc == 0) {
                if (verify_whole_domain) std::cout << "verifying solution..." << std::endl;
                else std::cout << "verifying solution at ~ (0.5, 0.5, 0.5) ..." << std::endl;
            }
            verify_result = verify_solution(mesh, x, tolerance, verify_whole_domain);
        }
    }

#ifdef MINIFE_DEBUG
    write_vector("x.vec", x);
#endif
    std::string title("CG solve");
#endif

    if (myproc == 0) {
        ydoc.get("Global Run Parameters")->add("ScalarType",TypeTraits<Scalar>::name());
        ydoc.get("Global Run Parameters")->add("GlobalOrdinalType",TypeTraits<GlobalOrdinal>::name());
        ydoc.get("Global Run Parameters")->add("LocalOrdinalType",TypeTraits<LocalOrdinal>::name());
        ydoc.add(title,"");
        ydoc.get(title)->add("Iterations",num_iters);
        ydoc.get(title)->add("Final Resid Norm",rnorm);

        GlobalOrdinal global_nrows = global_nx;
        global_nrows *= global_ny*global_nz;

        //flops-per-mv, flops-per-dot, flops-per-waxpy:
        double mv_flops = global_nnz*2.0;
        double dot_flops = global_nrows*2.0;
        double waxpy_flops = global_nrows*3.0;

#if MINIFE_KERNELS == 0
//if MINIFE_KERNELS == 0 then we did a CG solve, and in that case
//there were num_iters+1 matvecs, num_iters*2 dots, and num_iters*3+2 waxpys.
        mv_flops *= (num_iters+1);
        dot_flops *= (2*num_iters);
        waxpy_flops *= (3*num_iters+2);
#else
//if MINIFE_KERNELS then we did one of each operation per iteration.
        mv_flops *= num_iters;
        dot_flops *= num_iters;
        waxpy_flops *= num_iters;
#endif

        double total_flops = mv_flops + dot_flops + waxpy_flops;

        double mv_mflops = -1;
        if (cg_times[MATVEC] > 1.e-4)
            mv_mflops = 1.e-6 * (mv_flops/cg_times[MATVEC]);

        double dot_mflops = -1;
        if (cg_times[DOT] > 1.e-4)
            dot_mflops = 1.e-6 * (dot_flops/cg_times[DOT]);

        double waxpy_mflops = -1;
        if (cg_times[WAXPY] > 1.e-4)
            waxpy_mflops = 1.e-6 *  (waxpy_flops/cg_times[WAXPY]);

        double total_mflops = -1;
        if (cg_times[TOTAL] > 1.e-4)
            total_mflops = 1.e-6 * (total_flops/cg_times[TOTAL]);

        ydoc.get(title)->add("WAXPY Time",cg_times[WAXPY]);
        ydoc.get(title)->add("WAXPY Flops",waxpy_flops);
        if (waxpy_mflops >= 0)
            ydoc.get(title)->add("WAXPY Mflops",waxpy_mflops);
        else
            ydoc.get(title)->add("WAXPY Mflops","inf");

        ydoc.get(title)->add("DOT Time",cg_times[DOT]);
        ydoc.get(title)->add("DOT Flops",dot_flops);
        if (dot_mflops >= 0)
            ydoc.get(title)->add("DOT Mflops",dot_mflops);
        else
            ydoc.get(title)->add("DOT Mflops","inf");

        ydoc.get(title)->add("MATVEC Time",cg_times[MATVEC]);
        ydoc.get(title)->add("MATVEC Flops",mv_flops);
        if (mv_mflops >= 0)
            ydoc.get(title)->add("MATVEC Mflops",mv_mflops);
        else
            ydoc.get(title)->add("MATVEC Mflops","inf");

#ifdef MINIFE_FUSED
        ydoc.get(title)->add("MATVECDOT Time",cg_times[MATVECDOT]);
        ydoc.get(title)->add("MATVECDOT Flops",mv_flops);
        if (mv_mflops >= 0)
            ydoc.get(title)->add("MATVECDOT Mflops",mv_mflops);
        else
            ydoc.get(title)->add("MATVECDOT Mflops","inf");
#endif

#if MINIFE_KERNELS == 0
        ydoc.get(title)->add("Total","");
        ydoc.get(title)->get("Total")->add("Total CG Time",cg_times[TOTAL]);
        ydoc.get(title)->get("Total")->add("Total CG Flops",total_flops);
        if (total_mflops >= 0)
            ydoc.get(title)->get("Total")->add("Total CG Mflops",total_mflops);
        else
            ydoc.get(title)->get("Total")->add("Total CG Mflops","inf");
        ydoc.get(title)->add("Time per iteration",cg_times[TOTAL]/num_iters);
#endif
    }

    return verify_result;
}
Пример #22
0
void Histogram::print_header(outputStream* st) {
  st->print_cr("%s",title());
  st->print_cr("--------------------------------------------------");
}
Пример #23
0
  /*! Makes a new OBMol on the heap by combining two molecules according to the rule below. 
    If both have OBGenericData of the same type, or OBPairData with the
    same attribute,  the version from pFirst is used.
    Returns a pointer to a new OBMol which will need deleting by the calling program
    (probably by being sent to an output format). 
    If the molecules cannot be regarded as being the same structure a NULL
    pointer is returned and an error message logged.
    
    pFirst and pSecond and the objects they point to are not changed. (const
    modifiers difficult because class OBMol not designed appropriately)
    
    Combining molecules: rules for each of the three parts
    Title:
    Use the title of pFirst unless it has none, when use that of pSecond.
    Warning if neither molecule has a title.
    
    Structure
    - a structure with atoms replaces one with no atoms
    - a structure with bonds replaces one with no bonds,
    provided the formula is the same, else an error.
    - structures with atoms and bonds are compared by InChI; error if not the same. 
    - a structure with 3D coordinates replaces one with 2D coordinates
    - a structure with 2D coordinates replace one with 0D coordinates
    
    OBGenericData
    OBPairData
  */
  OBMol* OBMoleculeFormat::MakeCombinedMolecule(OBMol* pFirst, OBMol* pSecond)
  {
    string title("No title");
    if(*pFirst->GetTitle()!=0)
      title = pFirst->GetTitle();
    else
      {
        if(*pSecond->GetTitle()!=0)
          title = pSecond->GetTitle();
        else
          obErrorLog.ThrowError(__FUNCTION__,"Combined molecule has no title", obWarning);
      }

    bool swap=false;
    if(pFirst->NumAtoms()==0 && pSecond->NumAtoms()!=0)
      swap=true;
    else
      {
        if(pFirst->GetSpacedFormula()!=pSecond->GetSpacedFormula())
          {
            obErrorLog.ThrowError(__FUNCTION__, 
                                  "Molecules with name = " + title + " have different formula",obError);
            return NULL;
          }
        else
          {
            if(pSecond->NumBonds()!=0 && pFirst->NumBonds()==0)
              swap=true;
            else
              {
                //Compare by inchi; error if different NOT YET IMPLEMENTED
                //Use the one with the higher dimension
                if(pSecond->GetDimension() > pFirst->GetDimension())
                  swap=true;
              }
          }
      }

    OBMol* pNewMol = new OBMol;
    pNewMol->SetTitle(title);

    OBMol* pMain = swap ? pSecond : pFirst;
    OBMol* pOther = swap ? pFirst : pSecond;
    
    *pNewMol = *pMain; //Now copies all data 

    //Copy some OBGenericData from the OBMol which did not provide the structure
    vector<OBGenericData*>::iterator igd;
    for(igd=pOther->BeginData();igd!=pOther->EndData();++igd)
      {
        //copy only if not already data of the same type from molecule already copied to pNewMol
        unsigned datatype = (*igd)->GetDataType();
        OBGenericData* pData = pNewMol->GetData(datatype);
        if(datatype==OBGenericDataType::PairData)
          {
            if(pData->GetAttribute() == (*igd)->GetAttribute())
              continue;
          }
        else if(pNewMol->GetData(datatype)!=NULL)
          continue;

        OBGenericData* pCopiedData = (*igd)->Clone(pNewMol);
        pNewMol->SetData(pCopiedData);
      }
    return pNewMol;
  }
Пример #24
0
QString Fixture::status() const
{
    QString info;
    QString t;

    QString title("<TR><TD CLASS='hilite' COLSPAN='3'>%1</TD></TR>");
    QString subTitle("<TR><TD CLASS='subhi' COLSPAN='3'>%1</TD></TR>");
    QString genInfo("<TR><TD CLASS='emphasis'>%1</TD><TD COLSPAN='2'>%2</TD></TR>");

    /********************************************************************
     * General info
     ********************************************************************/

    info += "<TABLE COLS='3' WIDTH='100%'>";

    // Fixture title
    info += title.arg(name());

    if (m_fixtureDef != NULL && m_fixtureMode != NULL)
    {
        // Manufacturer
        info += genInfo.arg(tr("Manufacturer")).arg(m_fixtureDef->manufacturer());
        info += genInfo.arg(tr("Model")).arg(m_fixtureDef->model());
        info += genInfo.arg(tr("Mode")).arg(m_fixtureMode->name());
        info += genInfo.arg(tr("Type")).arg(m_fixtureDef->typeToString(m_fixtureDef->type()));
    }

    // Universe
    info += genInfo.arg(tr("Universe")).arg(universe() + 1);

    // Address
    QString range = QString("%1 - %2").arg(address() + 1).arg(address() + channels());
    info += genInfo.arg(tr("Address Range")).arg(range);

    // Channels
    info += genInfo.arg(tr("Channels")).arg(channels());

    // Binary address
    QString binaryStr = QString("%1").arg(address() + 1, 10, 2, QChar('0'));
    QString dipTable("<TABLE COLS='33' cellspacing='0'><TR><TD COLSPAN='33'><IMG SRC=\"" ":/ds_top.png\"></TD></TR>");
    dipTable += "<TR><TD><IMG SRC=\"" ":/ds_border.png\"></TD><TD><IMG SRC=\"" ":/ds_border.png\"></TD>";
    for (int i = 9; i >= 0; i--)
    {
        if (binaryStr.at(i) == '0')
            dipTable += "<TD COLSPAN='3'><IMG SRC=\"" ":/ds_off.png\"></TD>";
        else
            dipTable += "<TD COLSPAN='3'><IMG SRC=\"" ":/ds_on.png\"></TD>";
    }
    dipTable += "<TD><IMG SRC=\"" ":/ds_border.png\"></TD></TR>";
    dipTable += "<TR><TD COLSPAN='33'><IMG SRC=\"" ":/ds_bottom.png\"></TD></TR>";
    dipTable += "</TABLE>";

    info += genInfo.arg(tr("Binary Address (DIP)"))
            .arg(QString("%1").arg(dipTable));

    /********************************************************************
     * Channels
     ********************************************************************/

    // Title row
    info += QString("<TR><TD CLASS='subhi'>%1</TD>").arg(tr("Channel"));
    info += QString("<TD CLASS='subhi'>%1</TD>").arg(tr("DMX"));
    info += QString("<TD CLASS='subhi'>%1</TD></TR>").arg(tr("Name"));

    // Fill table with the fixture's channels
    for (quint32 ch = 0; ch < channels();	ch++)
    {
        QString chInfo("<TR><TD>%1</TD><TD>%2</TD><TD>%3</TD></TR>");
        info += chInfo.arg(ch + 1).arg(address() + ch + 1)
                .arg(channel(ch)->name());
    }

    /********************************************************************
     * Extended device information
     ********************************************************************/

    if (m_fixtureMode != NULL)
    {
        QLCPhysical physical = m_fixtureMode->physical();
        info += title.arg(tr("Physical"));

        float mmInch = 0.0393700787;
        float kgLbs = 2.20462262;
        QString mm("%1mm (%2\")");
        QString kg("%1kg (%2 lbs)");
        QString W("%1W");
        info += genInfo.arg(tr("Width")).arg(mm.arg(physical.width()))
                                        .arg(physical.width() * mmInch, 0, 'g', 4);
        info += genInfo.arg(tr("Height")).arg(mm.arg(physical.height()))
                                         .arg(physical.height() * mmInch, 0, 'g', 4);
        info += genInfo.arg(tr("Depth")).arg(mm.arg(physical.depth()))
                                        .arg(physical.depth() * mmInch, 0, 'g', 4);
        info += genInfo.arg(tr("Weight")).arg(kg.arg(physical.weight()))
                                         .arg(physical.weight() * kgLbs, 0, 'g', 4);
        info += genInfo.arg(tr("Power consumption")).arg(W.arg(physical.powerConsumption()));
        info += genInfo.arg(tr("DMX Connector")).arg(physical.dmxConnector());

        // Bulb
        QString K("%1K");
        QString lm("%1lm");
        info += subTitle.arg(tr("Bulb"));
        info += genInfo.arg(tr("Type")).arg(physical.bulbType());
        info += genInfo.arg(tr("Luminous Flux")).arg(lm.arg(physical.bulbLumens()));
        info += genInfo.arg(tr("Colour Temperature")).arg(K.arg(physical.bulbColourTemperature()));

        // Lens
        QString angle1("%1&deg;");
        QString angle2("%1&deg; &ndash; %2&deg;");

        info += subTitle.arg(tr("Lens"));
        info += genInfo.arg(tr("Name")).arg(physical.lensName());

        if (physical.lensDegreesMin() == physical.lensDegreesMax())
        {
            info += genInfo.arg(tr("Beam Angle"))
                .arg(angle1.arg(physical.lensDegreesMin()));
        }
        else
        {
            info += genInfo.arg(tr("Beam Angle"))
                .arg(angle2.arg(physical.lensDegreesMin())
                .arg(physical.lensDegreesMax()));
        }

        // Focus
        QString frange("%1&deg;");
        info += subTitle.arg(tr("Focus"));
        info += genInfo.arg(tr("Type")).arg(physical.focusType());
        info += genInfo.arg(tr("Pan Range")).arg(frange.arg(physical.focusPanMax()));
        info += genInfo.arg(tr("Tilt Range")).arg(frange.arg(physical.focusTiltMax()));
    }

    // HTML document & table closure
    info += "</TABLE>";

    if (m_fixtureDef != NULL)
    {
        info += "<HR>";
        info += "<DIV CLASS='author' ALIGN='right'>";
        info += tr("Fixture definition author: ") + m_fixtureDef->author();
        info += "</DIV>";
    }

    return info;
}
Пример #25
0
int main(int argc, char *argv[])
{
	title("Testing XmlDocument class");
	std::vector<std::pair<std::string, std::string>> vectorAttributePair;
	std::vector<std::shared_ptr<AbstractXmlElement>> vectorSharedPtr;
	// build parser first
	ConfigParseToConsole configure;
	Parser* pParser = configure.Build();
	configure.Attach(argv[1]);
	// now that parser is built, use it
	while (pParser->next())
		pParser->parse();
	std::shared_ptr < AbstractXmlElement > pDocElement;
	XmlProcessing::XmlDocument doc(configure.getRepository()->getRoot());
	pDocElement = doc.getRoot();
	//test and then display each method one by one 
	vectorSharedPtr = doc.findByNameAndValue("course","CSE681").select();
	std::cout << "\n\n" << "Displaying Functionality of Method:'findByNameAndValue' and Method:'select'" << "\n";
	std::cout << "\n\n" << "Query is:Find Collection of Elements with Name-Value Pair: 'course = CSE681'" << "\n" << "XML Portion found with specified ID is:";
	for (auto elem : vectorSharedPtr)
	{
		std::cout << "\n" << elem->toString() << "\n" << std::string(60, '-');
	}
	//On using the function select found Vector is moved
	vectorSharedPtr = doc.findById("LectureNote").select();
	std::cout << "\n\n" << "Displaying Functionality of Method:'findById' and Method: 'select'" << "\n";
	std::cout << "\n\n" << "Query is:Find Collection of Elements with tag: LectureNote"<<"\n"<<"XML Portion found with specified ID is:";
	for (auto elem : vectorSharedPtr)
	{
		std::cout << "\n" << elem->toString() << "\n" << std::string(60, '-');
	}

	std::cout << "\n\n" << "Displaying Functionality of Method:'addAttribute'" << "\n";
	std::cout << "\n\n" << "Query is: Add attribute with Name-Value: 'name = ojas' in tag: author" << "\n" << "Modified XML is:";
	doc.findById("author").addAttribute("name","ojas");
	std::cout << "\n\n" << pDocElement->toString() << "\n"<<std::string(60, '-');

	std::cout << "\n\n" << "Displaying Functionality of Method:'removeAttribute'" << "\n";
	std::cout << "\n\n" << "Query is: remove attribute with Name-Value: 'name = ojas' in tag: author" << "\n" << "Modified XML is:";
	doc.findById("author").removeAttribute("name", "ojas");
	std::cout << "\n\n" << pDocElement->toString() << "\n" << std::string(60, '-');

	std::cout << "\n\n" << "Displaying Functionality of Method:'addChild'" << "\n";
	std::cout << "\n\n" << "Query is: Add child with tag: 'children' in parent tag: author" << "\n" << "Modified XML is:";
	std::shared_ptr < AbstractXmlElement > sharedPtr = makeTaggedElement("children");
	doc.findById("author").addChild(sharedPtr);
	std::cout << "\n\n" << pDocElement->toString() << "\n" << std::string(60, '-');

	std::cout << "\n\n" << "Displaying Functionality of Method:'removeChild'" << "\n";
	std::cout << "\n\n" << "Query is: Remove child with tag: 'children' in parent tag: author" << "\n" << "Modified XML is:";
	doc.findById("author").removeChild("children");
	std::cout << "\n\n" << pDocElement->toString() <<"\n"<< std::string(60, '-');

	std::cout << "\n\n" << "Displaying Functionality of Method:'getAttributePairVector'" << "\n";
	std::cout << "\n\n" << "Query is: get attributePair by giving pointer to the element of Tag: LectureNote";
	vectorAttributePair = doc.getAttributePairVector(vectorSharedPtr[0]);
	std::cout << "\n""\n" << "Following Name-Value Attribute Pair Found:"<< "\n";
	for (auto elem : vectorAttributePair)
	{
		std::cout << elem.first.c_str() << " = " << elem.second.c_str() << "\n";
	}
	std::cout << std::string(60, '-');


	std::cout << "\n\n" << "Displaying Functionality of Method:'getChildrenVector'" << "\n";
	std::cout << "\n\n" << "Query is: get childrens by giving pointer to the element of Tag: LectureNote";
	for (auto elem : doc.getChildrenVector(vectorSharedPtr[0]))
	{
		std::cout << elem->value()  << "\n";
	}
	std::cout<<std::string(60, '-');

	std::cout << "\n\n" << "Displaying Functionality of Method:'addRoot'" << "\n";
	std::cout << "\n\n" << "Query is: adding root after deleting all the childs"<<"\n"<<"New Root Formed with Tagged element: 'newchild' is:";
	doc.findById("").removeChild("LectureNote");
	doc.findById("").removeChild("xml declaration");
	doc.findById("").removeChild("xml declaration");
	doc.findById("").removeChild("XML test case");
	doc.addRoot("newchild");
	std::cout << "\n\n" << doc.getRoot()->toString() <<"\n"<< std::string(60, '-');

	return 0;
	
}
Пример #26
0
void PageDef::writeDocumentation(OutputList &ol)
{
  static bool generateTreeView = Config_getBool(GENERATE_TREEVIEW);

  //outputList->disable(OutputGenerator::Man);
  QCString pageName,manPageName;
  pageName    = escapeCharsInString(name(),FALSE,TRUE);
  manPageName = escapeCharsInString(name(),TRUE,TRUE);

  //printf("PageDef::writeDocumentation: %s\n",getOutputFileBase().data());

  ol.pushGeneratorState();
  //1.{ 

  if (m_nestingLevel>0 
      //&& // a sub page
      //(Doxygen::mainPage==0 || getOuterScope()!=Doxygen::mainPage) // and not a subpage of the mainpage
     )
  {
    // do not generate sub page output for RTF and LaTeX, as these are
    // part of their parent page
    ol.disableAll();
    ol.enable(OutputGenerator::Man);
    ol.enable(OutputGenerator::Html);
  }

  ol.pushGeneratorState();
  //2.{ 
  ol.disableAllBut(OutputGenerator::Man);
  startFile(ol,getOutputFileBase(),manPageName,title(),HLI_Pages,!generateTreeView);
  ol.enableAll();
  ol.disable(OutputGenerator::Man);
  startFile(ol,getOutputFileBase(),pageName,title(),HLI_Pages,!generateTreeView);
  ol.popGeneratorState();
  //2.} 

  if (!generateTreeView)
  {
    if (getOuterScope()!=Doxygen::globalScope && !Config_getBool(DISABLE_INDEX))
    {
      getOuterScope()->writeNavigationPath(ol);
    }
    ol.endQuickIndices();
  }
  SectionInfo *si=Doxygen::sectionDict->find(name());

  // save old generator state and write title only to Man generator
  ol.pushGeneratorState();
  //2.{
  ol.disableAllBut(OutputGenerator::Man);
  ol.startTitleHead(manPageName);
  ol.endTitleHead(manPageName, manPageName);
  if (si)
  {
    ol.generateDoc(docFile(),docLine(),this,0,si->title,TRUE,FALSE,0,TRUE,FALSE);
    ol.endSection(si->label,si->type);
  }
  ol.popGeneratorState();
  //2.}

  // for Latex the section is already generated as a chapter in the index!
  ol.pushGeneratorState();
  //2.{
  ol.disable(OutputGenerator::Latex);
  ol.disable(OutputGenerator::RTF);
  ol.disable(OutputGenerator::Man);
  if (!title().isEmpty() && !name().isEmpty() && si!=0)
  {
    //ol.startSection(si->label,si->title,si->type);
    startTitle(ol,getOutputFileBase(),this);
    ol.generateDoc(docFile(),docLine(),this,0,si->title,TRUE,FALSE,0,TRUE,FALSE);
    //stringToSearchIndex(getOutputFileBase(),
    //                    theTranslator->trPage(TRUE,TRUE)+" "+si->title,
    //                    si->title);
    //ol.endSection(si->label,si->type);
    endTitle(ol,getOutputFileBase(),name());
  }
  ol.startContents();
  ol.popGeneratorState();
  //2.}

  if (m_showToc && hasSections())
  {
    writeToc(ol);
  }

  writePageDocumentation(ol);

  if (generateTreeView && getOuterScope()!=Doxygen::globalScope && !Config_getBool(DISABLE_INDEX))
  {
    ol.endContents();
    endFileWithNavPath(getOuterScope(),ol);
  }
  else
  {
    endFile(ol);
  }

  ol.popGeneratorState();
  //1.}

  Doxygen::indexList->addIndexItem(this,0,0,filterTitle(title()));
}
Пример #27
0
wxString mmReportChartStocks::getHTMLText()
{
    mmHTMLBuilder hb;
    hb.init();
    hb.addDivContainer();
    hb.addHeader(2, title());

    wxTimeSpan dtDiff = m_date_range->end_date() - m_date_range->start_date();
    if (m_date_range->is_with_date() && dtDiff.GetDays() <= 366)
        hb.DisplayDateHeading(m_date_range->start_date(), m_date_range->end_date(), true);
    hb.addHorizontalLine();

    int count = 0, heldAt = -1;
    bool pointDot = false, showGridLines = false;
    wxTimeSpan dist;
    wxDate dateDt, precDateDt = wxInvalidDateTime;
    for (const auto& stock : Model_Stock::instance().all(Model_Stock::COL_HELDAT))
    {
        int dataCount = 0, freq = 1;
        Model_StockHistory::Data_Set histData = Model_StockHistory::instance().find(Model_StockHistory::SYMBOL(stock.SYMBOL),
            Model_StockHistory::DATE(m_date_range->start_date(), GREATER_OR_EQUAL),
            Model_StockHistory::DATE(m_date_range->end_date(), LESS_OR_EQUAL));
        std::stable_sort(histData.begin(), histData.end(), SorterByDATE());
        if (histData.size() <= 30)
            showGridLines = pointDot = true;
        else if (histData.size() <= 366)
            showGridLines = true;
        else
            freq = histData.size() / 366;
        std::vector<ValueTrio> aData;
        for (const auto& hist : histData)
        {
            if (dataCount % freq == 0)
            {
                ValueTrio val;
                dateDt = Model_StockHistory::DATE(hist);
                if (histData.size() <= 30)
                    val.label = mmGetDateForDisplay(dateDt);
                else if (precDateDt.IsValid() && dateDt.GetMonth() != precDateDt.GetMonth())
                    val.label = dateDt.GetMonthName(dateDt.GetMonth());
                else
                    val.label = "";
                val.amount = hist.VALUE;
                aData.push_back(val);
                precDateDt = dateDt;
            }
            dataCount++;
        }
        if (!aData.empty())
        {
            hb.addDivRow();
            Model_Account::Data* account = Model_Account::instance().get(stock.HELDAT);
            hb.addHeader(1, wxString::Format("%s - (%s)", stock.STOCKNAME, account->ACCOUNTNAME));
            hb.addDivCol17_67();
            hb.addLineChart(aData, stock.STOCKNAME, count, 1000, 400, pointDot, showGridLines, true);
            hb.endDiv();
            hb.endDiv();
        }

        heldAt = stock.HELDAT;
        count++;
    }

    hb.endDiv();
    hb.end();

    Model_Report::outputReportFile(hb.getHTMLText());
    return "";
}
void configure::layout_children(const SDL_Rect& rect)
{
	DBG_MP << "laying out the children" << std::endl;

	ui::layout_children(rect);

	const int border_size = 6;
	const int column_border_size = 10;

	SDL_Rect ca = client_area();
	int xpos = ca.x;
	int ypos = ca.y;
	const int first_column_width = (ca.w - ca.x) / 2 - column_border_size;

	// Dialog title
	ypos += title().height() + border_size;

	// Name Entry
	name_entry_label_.set_location(xpos, ypos);
	name_entry_.set_location(xpos + name_entry_label_.width() + border_size, ypos);
	name_entry_.set_width(ca.w - name_entry_label_.width() - border_size);
	ypos += std::max<int>(name_entry_.height(), name_entry_label_.height()) + border_size;

	// Save ypos here (column top)
	int ypos_columntop = ypos;

	const int right_pane_height =
		ca.h - (ypos_columntop - ca.y + launch_game_.height() + border_size);

	// First column: non-gameplay settings
	options_pane_left_.set_location(xpos, ypos);
	options_pane_left_.set_width(first_column_width);
	options_pane_left_.set_height(right_pane_height - entry_points_label_.height());

	int slider_width = options_pane_left_.width() - 40;

	int xpos_left = 0;
	int ypos_left = 0;

	ypos_left += 2 * border_size;
	options_pane_left_.add_widget(&observers_game_, xpos_left, ypos_left);
	options_pane_left_.add_widget(&shuffle_sides_,
		xpos_left + (options_pane_left_.width() - xpos_left) / 2 + border_size, ypos_left);
	ypos_left += shuffle_sides_.height() + border_size;

	options_pane_left_.add_widget(&countdown_game_, xpos_left, ypos_left);

	if(!local_players_only_) {
		options_pane_left_.add_widget(&password_button_,
			(ca.x + first_column_width / 2) - 40, ypos_left);
	} else {
		password_button_.hide(true);
	}

	ypos_left += countdown_game_.height() + border_size;

	options_pane_left_.add_widget(&countdown_init_time_label_, xpos_left, ypos_left	);
	ypos_left += countdown_init_time_label_.height() + border_size;
	countdown_init_time_slider_.set_width(slider_width);
	options_pane_left_.add_widget(&countdown_init_time_slider_, xpos_left, ypos_left);
	ypos_left += countdown_init_time_slider_.height() + border_size;

	options_pane_left_.add_widget(&countdown_turn_bonus_label_, xpos_left, ypos_left);
	ypos_left += countdown_turn_bonus_label_.height() + border_size;
	countdown_turn_bonus_slider_.set_width(slider_width);
	options_pane_left_.add_widget(&countdown_turn_bonus_slider_, xpos_left, ypos_left);
	ypos_left += countdown_turn_bonus_slider_.height() + border_size;

	options_pane_left_.add_widget(&countdown_reservoir_time_label_, xpos_left, ypos_left);
	ypos_left += countdown_reservoir_time_label_.height() + border_size;
	countdown_reservoir_time_slider_.set_width(slider_width);
	options_pane_left_.add_widget(&countdown_reservoir_time_slider_, xpos_left, ypos_left);
	ypos_left += countdown_reservoir_time_slider_.height() + border_size;
	options_pane_left_.add_widget(&countdown_action_bonus_label_, xpos_left, ypos_left);
	ypos_left += countdown_action_bonus_label_.height() + border_size;
	countdown_action_bonus_slider_.set_width(slider_width);
	options_pane_left_.add_widget(&countdown_action_bonus_slider_, xpos_left, ypos_left);
	ypos_left += countdown_action_bonus_slider_.height() + border_size;

	if (show_entry_points_) {
		int x = ca.x;
		int y = ca.y + ca.h - entry_points_combo_.height();
		entry_points_combo_.set_location(x, y);
		y -= entry_points_label_.height() + border_size;
		entry_points_label_.set_location(x, y);
	}

	// Second column: gameplay settings
	xpos += first_column_width + column_border_size;
	ypos = ypos_columntop;

	options_pane_right_.set_location(xpos, ypos);
	options_pane_right_.set_width(ca.w - (xpos - ca.x));
	options_pane_right_.set_height(right_pane_height);

	slider_width = options_pane_right_.width() - 40;

	int xpos_right = 0;
	int ypos_right = 0;
	options_pane_right_.add_widget(&generic_label_, xpos_right, ypos_right);
	ypos_right += generic_label_.height() + border_size;

	options_pane_right_.add_widget(&use_map_settings_, xpos_right, ypos_right);
	options_pane_right_.add_widget(&fog_game_,
		xpos_right + (options_pane_right_.width() - xpos_right)/2 + 5, ypos_right);
	ypos_right += use_map_settings_.height() + border_size;

	options_pane_right_.add_widget(&random_start_time_, xpos_right, ypos_right);
	options_pane_right_.add_widget(&shroud_game_,
		xpos_right + (options_pane_right_.width() - xpos_right)/2 + 5, ypos_right);
	ypos_right += random_start_time_.height() + border_size;

	options_pane_right_.add_widget(&turns_label_, xpos_right, ypos_right);
	ypos_right += turns_label_.height() + border_size;
	turns_slider_.set_width(slider_width);
	options_pane_right_.add_widget(&turns_slider_, xpos_right, ypos_right);
	ypos_right += turns_slider_.height() + border_size;

	options_pane_right_.add_widget(&xp_modifier_label_, xpos_right, ypos_right);
	ypos_right += xp_modifier_label_.height() + border_size;
	xp_modifier_slider_.set_width(slider_width);
	options_pane_right_.add_widget(&xp_modifier_slider_, xpos_right, ypos_right);
	ypos_right += xp_modifier_slider_.height() + border_size;

	options_pane_right_.add_widget(&village_support_label_, xpos_right, ypos_right);
	ypos_right += village_support_label_.height() + border_size;
	village_support_slider_.set_width(slider_width);
	options_pane_right_.add_widget(&village_support_slider_, xpos_right, ypos_right);
	ypos_right += village_support_slider_.height() + border_size;

	options_pane_right_.add_widget(&village_gold_label_, xpos_right, ypos_right);
	ypos_right += village_gold_label_.height() + border_size;
	village_gold_slider_.set_width(slider_width);

	options_pane_right_.add_widget(&village_gold_slider_, xpos_right, ypos_right);
	ypos_right += village_gold_slider_.height() + 3 * border_size;

	options_manager_.layout_widgets(xpos_right, ypos_right);

	// OK / Cancel buttons
	gui::button* left_button = &launch_game_;
	gui::button* right_button = &cancel_game_;

#ifdef OK_BUTTON_ON_RIGHT
	std::swap(left_button,right_button);
#endif

	// Buttons
	right_button->set_location(ca.x + ca.w - right_button->width(),
	                           ca.y + ca.h - right_button->height());
	left_button->set_location(right_button->location().x - left_button->width() -
	                          gui::ButtonHPadding, ca.y + ca.h - left_button->height());
}
void QwtErrorPlotCurve::loadData()
{
	if (!d_master_curve)
		return;

    if (!plot())
        return;

	Table *mt = d_master_curve->table();
	if (!mt)
		return;

	int xcol = mt->colIndex(d_master_curve->xColumnName());
	int ycol = mt->colIndex(d_master_curve->title().text());
	int errcol = d_table->colIndex(title().text());
	if (xcol<0 || ycol<0 || errcol<0)
		return;

	int xColType = mt->columnType(xcol);
	int yColType = mt->columnType(ycol);

	d_start_row = d_master_curve->startRow();
	d_end_row = d_master_curve->endRow();
    int r = abs(d_end_row - d_start_row) + 1;
	QVector<double> X(r), Y(r), err(r);
    int data_size = 0;
    QLocale locale = ((Graph *)plot())->multiLayer()->locale();
	for (int i = d_start_row; i <= d_end_row; i++){
		QString xval = mt->text(i, xcol);
		QString yval = mt->text(i, ycol);
		QString errval = d_table->text(i, errcol);
		if (!xval.isEmpty() && !yval.isEmpty() && !errval.isEmpty()){
		    bool ok = true;
			if (xColType == Table::Text)
				X[data_size] = (double)(data_size + 1);
			else
				X[data_size] = locale.toDouble(xval, &ok);

			if (yColType == Table::Text)
				Y[data_size] = (double)(data_size + 1);
			else
				Y[data_size] = locale.toDouble(yval, &ok);

            if (!ok)
                continue;

			err[data_size] = locale.toDouble(errval, &ok);
			if (ok)
                data_size++;
		}
	}

	if (!data_size)
		remove();

    X.resize(data_size);
	Y.resize(data_size);
	err.resize(data_size);

	setData(X.data(), Y.data(), data_size);
	setErrors(err);
}
Пример #30
0
void cc2DLabel::drawMeOnly2D(CC_DRAW_CONTEXT& context)
{
	if (!m_dispIn2D)
		return;

	assert(!m_points.empty());

	//standard case: list names pushing
	bool pushName = MACRO_DrawEntityNames(context);
	if (pushName)
		glPushName(getUniqueID());

	//we should already be in orthoprojective & centered omde
	//glOrtho(-halfW,halfW,-halfH,halfH,-maxS,maxS);

	int strHeight = 0;
	int titleHeight = 0;
	QString title(getName());
	QStringList body;
	GLdouble arrowDestX=-1.0,arrowDestY=-1.0;
	QFont bodyFont,titleFont;
	if (!pushName)
	{
		/*** line from 2D point to label ***/

		//compute arrow head position
		CCVector3 arrowDest;
		m_points[0].cloud->getPoint(m_points[0].index,arrowDest);
		for (unsigned i=1;i<m_points.size();++i)
			arrowDest += *m_points[i].cloud->getPointPersistentPtr(m_points[i].index);
		arrowDest /= (PointCoordinateType)m_points.size();

		//project it in 2D screen coordinates
		int VP[4];
		context._win->getViewportArray(VP);
		const double* MM = context._win->getModelViewMatd(); //viewMat
		const double* MP = context._win->getProjectionMatd(); //projMat
		GLdouble zp;
		gluProject(arrowDest.x,arrowDest.y,arrowDest.z,MM,MP,VP,&arrowDestX,&arrowDestY,&zp);

		/*** label border ***/
		bodyFont = context._win->getTextDisplayFont();
		titleFont = QFont(context._win->getTextDisplayFont());
		titleFont.setBold(true);
		QFontMetrics titleFontMetrics(titleFont);
		QFontMetrics bodyFontMetrics(bodyFont);

		strHeight = bodyFontMetrics.height();
		titleHeight = titleFontMetrics.height();

		if (m_showFullBody)
			body = getLabelContent(context.dispNumberPrecision);

		//base box dimension
		int dx = 150;
		dx = std::max(dx,titleFontMetrics.width(title));

		int dy = c_margin;	//top vertical margin
		dy += titleHeight;	//title
		if (!body.empty())
		{
			dy += c_margin;	//vertical margin above separator
			for (int j=0;j<body.size();++j)
			{
				dx = std::max(dx,bodyFontMetrics.width(body[j]));
				dy += (c_margin+strHeight); //margin + body line height
			}
		}
		else
		{
			dy += c_margin;		// vertical margin (purely for aesthetics)
		}
		dy += c_margin;		// bottom vertical margin
		dx += c_margin*2;	// horizontal margins

		//main rectangle
		m_labelROI[0]=0;
		m_labelROI[1]=0;
		m_labelROI[2]=dx;
		m_labelROI[3]=dy;

		//close button
		/*m_closeButtonROI[2]=dx-c_margin;
		m_closeButtonROI[0]=m_closeButtonROI[2]-c_buttonSize;
		m_closeButtonROI[3]=c_margin;
		m_closeButtonROI[1]=m_closeButtonROI[3]+c_buttonSize;
		//*/

		//automatically elide the title
		//title = titleFontMetrics.elidedText(title,Qt::ElideRight,m_closeButtonROI[0]-2*c_margin);
	}

	int halfW = (context.glW>>1);
	int halfH = (context.glH>>1);

	//draw label rectangle
	int xStart = m_lastScreenPos[0] = (int)((float)context.glW * m_screenPos[0]);
	int yStart = m_lastScreenPos[1] = (int)((float)context.glH * (1.0f-m_screenPos[1]));

	//colors
	bool highlighted = (!pushName && isSelected());
	//default background color
	colorType defaultBkgColor[4];
	memcpy(defaultBkgColor,context.labelDefaultCol,sizeof(colorType)*3);
	defaultBkgColor[3]=(colorType)((float)context.labelsTransparency*(float)MAX_COLOR_COMP/100.0f);
	//default border color (mustn't be totally transparent!)
	colorType defaultBorderColor[4];
	if (highlighted)
		memcpy(defaultBorderColor,ccColor::red,sizeof(colorType)*3);
	else
		memcpy(defaultBorderColor,context.labelDefaultCol,sizeof(colorType)*3);
	defaultBorderColor[3]=(colorType)((float)(50+context.labelsTransparency/2)*(float)MAX_COLOR_COMP/100.0f);

	glPushAttrib(GL_COLOR_BUFFER_BIT);
	glEnable(GL_BLEND);

	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();
	glTranslatef(-halfW+xStart,-halfH+yStart,0);

	if (!pushName)
	{
		//compute arrow base position relatively to the label rectangle (for 0 to 8)
		int arrowBaseConfig = 0;
		int iArrowDestX = (int)arrowDestX-xStart;
		int iArrowDestY = (int)arrowDestY-yStart;
		{
			if (iArrowDestX < m_labelROI[0]) //left
				arrowBaseConfig += 0;
			else if (iArrowDestX > m_labelROI[2]) //Right
				arrowBaseConfig += 2;
			else  //Middle
				arrowBaseConfig += 1;

			if (iArrowDestY > -m_labelROI[1]) //Top
				arrowBaseConfig += 0;
			else if (iArrowDestY < -m_labelROI[3]) //Bottom
				arrowBaseConfig += 6;
			else  //Middle
				arrowBaseConfig += 3;
		}

		//we make the arrow base start from the nearest corner
		if (arrowBaseConfig != 4) //4 = label above point!
		{
			glColor4ubv(defaultBorderColor);
			glBegin(GL_TRIANGLE_FAN);
			glVertex2d(arrowDestX-xStart,arrowDestY-yStart);
			switch(arrowBaseConfig)
			{
			case 0: //top-left corner
				glVertex2i(m_labelROI[0], -m_labelROI[1]-2*c_arrowBaseSize);
				glVertex2i(m_labelROI[0], -m_labelROI[1]);
				glVertex2i(m_labelROI[0]+2*c_arrowBaseSize, -m_labelROI[1]);
				break;
			case 1: //top-middle edge
				glVertex2i(std::max(m_labelROI[0],iArrowDestX-c_arrowBaseSize), -m_labelROI[1]);
				glVertex2i(std::min(m_labelROI[2],iArrowDestX+c_arrowBaseSize), -m_labelROI[1]);
				break;
			case 2: //top-right corner
				glVertex2i(m_labelROI[2], -m_labelROI[1]-2*c_arrowBaseSize);
				glVertex2i(m_labelROI[2], -m_labelROI[1]);
				glVertex2i(m_labelROI[2]-2*c_arrowBaseSize, -m_labelROI[1]);
				break;
			case 3: //middle-left edge
				glVertex2i(m_labelROI[0], std::min(-m_labelROI[1],iArrowDestY+c_arrowBaseSize));
				glVertex2i(m_labelROI[0], std::max(-m_labelROI[3],iArrowDestY-c_arrowBaseSize));
				break;
			case 4: //middle of rectangle!
				break;
			case 5: //middle-right edge
				glVertex2i(m_labelROI[2], std::min(-m_labelROI[1],iArrowDestY+c_arrowBaseSize));
				glVertex2i(m_labelROI[2], std::max(-m_labelROI[3],iArrowDestY-c_arrowBaseSize));
				break;
			case 6: //bottom-left corner
				glVertex2i(m_labelROI[0], -m_labelROI[3]+2*c_arrowBaseSize);
				glVertex2i(m_labelROI[0], -m_labelROI[3]);
				glVertex2i(m_labelROI[0]+2*c_arrowBaseSize, -m_labelROI[3]);
				break;
			case 7: //bottom-middle edge
				glVertex2i(std::max(m_labelROI[0],iArrowDestX-c_arrowBaseSize), -m_labelROI[3]);
				glVertex2i(std::min(m_labelROI[2],iArrowDestX+c_arrowBaseSize), -m_labelROI[3]);
				break;
			case 8: //bottom-right corner
				glVertex2i(m_labelROI[2], -m_labelROI[3]+2*c_arrowBaseSize);
				glVertex2i(m_labelROI[2], -m_labelROI[3]);
				glVertex2i(m_labelROI[2]-2*c_arrowBaseSize, -m_labelROI[3]);
				break;
			}
			glEnd();
		}
	}

	//main rectangle
	glColor4ubv(defaultBkgColor);
    glBegin(GL_QUADS);
    glVertex2i(m_labelROI[0], -m_labelROI[1]);
    glVertex2i(m_labelROI[0], -m_labelROI[3]);
    glVertex2i(m_labelROI[2], -m_labelROI[3]);
    glVertex2i(m_labelROI[2], -m_labelROI[1]);
    glEnd();

	//if (highlighted)
	{
		glPushAttrib(GL_LINE_BIT);
		glLineWidth(3.0f);
		glColor4ubv(defaultBorderColor);
		glBegin(GL_LINE_LOOP);
		glVertex2i(m_labelROI[0], -m_labelROI[1]);
		glVertex2i(m_labelROI[0], -m_labelROI[3]);
		glVertex2i(m_labelROI[2], -m_labelROI[3]);
		glVertex2i(m_labelROI[2], -m_labelROI[1]);
		glEnd();
		glPopAttrib();
	}

	//draw close button
	/*glColor3ubv(ccColor::black);
    glBegin(GL_LINE_LOOP);
    glVertex2i(m_closeButtonROI[0],-m_closeButtonROI[1]);
    glVertex2i(m_closeButtonROI[0],-m_closeButtonROI[3]);
    glVertex2i(m_closeButtonROI[2],-m_closeButtonROI[3]);
    glVertex2i(m_closeButtonROI[2],-m_closeButtonROI[1]);
    glEnd();
    glBegin(GL_LINES);
    glVertex2i(m_closeButtonROI[0]+2,-m_closeButtonROI[1]+2);
    glVertex2i(m_closeButtonROI[2]-2,-m_closeButtonROI[3]-2);
    glVertex2i(m_closeButtonROI[2]-2,-m_closeButtonROI[1]+2);
    glVertex2i(m_closeButtonROI[0]+2,-m_closeButtonROI[3]-2);
    glEnd();
	//*/

	//display text
	if (!pushName)
	{
		int xStartRel = c_margin;
		int yStartRel = -c_margin;
		yStartRel -= titleHeight;

		const colorType* defaultTextColor = (context.labelsTransparency<40 ? context.textDefaultCol : ccColor::darkBlue);

		context._win->displayText(title,xStart+xStartRel,yStart+yStartRel,ccGenericGLDisplay::ALIGN_DEFAULT,0,defaultTextColor,&titleFont);
		yStartRel -= c_margin;

		if (!body.empty())
		{
			//line separation
			glColor4ubv(defaultBorderColor);
			glBegin(GL_LINES);
			glVertex2i(xStartRel,yStartRel);
			glVertex2i(xStartRel+m_labelROI[2]-m_labelROI[0]-2*c_margin,yStartRel);
			glEnd();

			//display body
			yStartRel -= c_margin;
			for (int i=0;i<body.size();++i)
			{
				yStartRel -= strHeight;
				context._win->displayText(body[i],xStart+xStartRel,yStart+yStartRel,ccGenericGLDisplay::ALIGN_DEFAULT,0,defaultTextColor,&bodyFont);
			}
		}
	}

	glPopAttrib();

	glPopMatrix();

	if (pushName)
		glPopName();
}