Пример #1
0
void TreeDiagram::computeLayout()
{
  QListIterator<DiagramRow> it(*this);
  DiagramRow *row;
  for (;(row=it.current()) && row->count()<maxTreeWidth;++it) {}
  if (row)
  {
    //printf("computeLayout() list row at %d\n",row->number());
    QListIterator<DiagramItem> rit(*row);
    DiagramItem *di;
    DiagramItem *opi=0;
    int delta=0;
    bool first=TRUE;
    for (;(di=rit.current());++rit)
    {
      DiagramItem *pi=di->parentItem();
      if (pi==opi && !first) { delta-=gridWidth; }
      first = pi!=opi;
      opi=pi;
      di->move(delta,0); // collapse all items in the same
                         // list (except the first)
      di->putInList();
    }
  }

  // re-organize the diagram items
  DiagramItem *root=getFirst()->getFirst();
  while (layoutTree(root,0)) { }

  // move first items of the lists
  if (row)
  {
    QListIterator<DiagramItem> rit(*row);
    DiagramItem *di;
    while ((di=rit.current()))
    {
      DiagramItem *pi=di->parentItem();
      if (pi->getChildren()->count()>1)
      {
        di->move(gridWidth,0);
        while (di && di->parentItem()==pi) { ++rit; di=rit.current(); }
      }
      else
      {
        ++rit;
      }
    }
  }
}
Пример #2
0
void FileScanner::ScanFileCpp11(const std::regex& /*expression*/, const char */*file_data*/, size_t /*file_size*/, MatchList& /*ml*/)
{
#ifndef HAVE_LIBPCRE
	// Scan the mmapped file for the regex.
	std::regex_iterator<const char *> rit(file_data, file_data+file_size, expression);
	std::regex_iterator<const char *> rend;
	while(rit != rend)
	{
		//std::cout << "Match in file " << next_string << std::endl;

		long long lineno = 1+std::count(file_data, file_data+rit->position(), '\n');
		auto line_ending = "\n";
		auto line_start = std::find_end(file_data, file_data+rit->position(),
				line_ending, line_ending+1);
		if(line_start == file_data+rit->position())
		{
			// The line has no starting '\n', so it must be the first line.
			line_start = file_data;
		}
		else
		{
			// The line had a starting '\n', clip it off.
			++line_start;
		}
		auto line_end = std::find(file_data+rit->position(), file_data+file_size, '\n');
		auto pre_match = std::string(line_start, file_data+rit->position());
		auto match = std::string(rit->begin()->str());
		auto post_match = std::string(file_data+rit->position()+rit->length(), line_end);
		Match m = { pre_match, match, post_match };
		ml.AddMatch(lineno, m);

		++rit;
	}
#endif
}
Пример #3
0
uint TreeDiagram::computeRows()
{
  //printf("TreeDiagram::computeRows()=%d\n",count());
  int count=0;
  QListIterator<DiagramRow> it(*this);
  DiagramRow *row;
  for (;(row=it.current()) && !row->getFirst()->isInList();++it)
  {
    count++;
  }
  //printf("count=%d row=%p\n",count,row);
  if (row)
  {
    int maxListLen=0;
    int curListLen=0;
    DiagramItem *opi=0;
    QListIterator<DiagramItem> rit(*row);
    DiagramItem *di;
    for (;(di=rit.current());++rit)
    {
      if (di->parentItem()!=opi) curListLen=1; else curListLen++; 
      if (curListLen>maxListLen) maxListLen=curListLen;
      opi=di->parentItem();
    }
    //printf("maxListLen=%d\n",maxListLen);
    count+=maxListLen;
  }
  return count;
}
Пример #4
0
TEST(range_iterator, first)
{
   std::vector<int> v = {1,2,3,4};
   mzlib::range_iterator rit(v.begin(), v.end(), 2);
   mzlib::range r = rit.first();
   ASSERT_EQ(v.begin(), r.begin());
   ASSERT_EQ(v.begin()+3, r.end());
}
Пример #5
0
Object* ObjectListInterface::GetListFirstBackward(Object *startFrom, const std::type_info *elementType)
{
    ListOfObjects::iterator it = m_list.begin();
    std::advance(it, GetListIndex(startFrom));
    ListOfObjects::reverse_iterator rit(it);
    rit = std::find_if(rit, m_list.rend(), ObjectComparison( elementType ) );
    return (rit == m_list.rend()) ? NULL : *rit;
}
Пример #6
0
TEST(range_iterator, end_isnt_because_in_the_middle)
{
   std::vector<int> v = {1,2,3,4,5};
   mzlib::range assumed_current(v.begin()+1, v.begin()+3);
   
   mzlib::range_iterator rit(v.begin(), v.end(), 2);
   
   ASSERT_FALSE(rit.end(assumed_current));
}
Пример #7
0
TEST(range_iterator, end_isnt_because_not_yet_min_range_size)
{
   std::vector<int> v = {1,2,3,4};
   mzlib::range assumed_current(v.begin()+1, v.end());
   
   mzlib::range_iterator rit(v.begin(), v.end(), 2);
   
   ASSERT_FALSE(rit.end(assumed_current));
}
Пример #8
0
TEST(range_iterator, next_transition_to_lower_size)
{
   std::vector<int> v = {1,2,3,4};
   mzlib::range assumed_current(v.begin()+1, v.end());
   
   mzlib::range_iterator rit(v.begin(), v.end(), 2);
   auto next = rit.next(assumed_current);
   
   ASSERT_EQ(v.begin(), next.begin());
   ASSERT_EQ(v.begin()+2, next.end());
}
Пример #9
0
TEST(range_iterator, end_isnt_the_last_one_still_counts)
{
   std::vector<int> v = {1,2,3,4};
   
   mzlib::range assumed_current(
      v.begin()+2, v.end());
   
   mzlib::range_iterator rit(v.begin(), v.end(), 2);
   
   ASSERT_FALSE(rit.end(assumed_current));
}
Пример #10
0
int main(){
    while(scanf("%d",&n)!=EOF){
        for(i=0;i<n;++i){
            a[i]=rit();
        }
        std::sort(a,a+n);
        for(i=0;i<n;++i){
            if(i)putchar_unlocked(' ');
            printf("%d",a[i]);
        }
        putchar_unlocked('\n');
    }
}
Пример #11
0
optional <const BEZIER *> ROADSTRIP::FindBezierAtOffset(const BEZIER * bezier, int offset) const
{
	std::vector<ROADPATCH>::const_iterator it = patches.end(); //this iterator will hold the found ROADPATCH

	//search for the roadpatch containing the bezier and store an iterator to it in "it"
	for (std::vector<ROADPATCH>::const_iterator i = patches.begin(); i != patches.end(); ++i)
	{
		if (&i->GetPatch() == bezier)
		{
			it = i;
			break;
		}
	}

	if (it == patches.end())
		return optional <const BEZIER *>(); //return nothing
	else
	{
		//now do the offset
		int curoffset = offset;
		while (curoffset != 0)
		{
			if (curoffset < 0)
			{
				//why is this so difficult?  all i'm trying to do is make the iterator loop around
				std::vector<ROADPATCH>::const_reverse_iterator rit(it);
				if (rit == patches.rend())
					rit = patches.rbegin();
				rit++;
				if (rit == patches.rend())
					rit = patches.rbegin();
				it = rit.base();
				if (it == patches.end())
					it = patches.begin();

				curoffset++;
			}
			else if (curoffset > 0)
			{
				it++;
				if (it == patches.end())
					it = patches.begin();

				curoffset--;
			}
		}

		assert(it != patches.end());
		return optional <const BEZIER *>(&it->GetPatch());
	}
}
Пример #12
0
void StoryQuery::query(AllData& output) {
	// Sample to hard-code data:
	ds::model::StoryRef newStory;
	newStory.setId(1);
	newStory.setTitle(L"Sample Story");
	newStory.setBody(L"Sample body");
	newStory.setPrimaryResource(ds::Resource(ds::Environment::expand("%APP%/data/images/temp/sample_image.png")));
	output.mStories.push_back(newStory);



	// Sample to query from a db.
	// You'll need to set resource_location and resource_db in engine.xml for this to work (or supply your own db path)
	// resource_db is a relative path to resource_location
	/* 

	*/
	const ds::Resource::Id cms(ds::Resource::Id::CMS_TYPE, 0);
	ds::query::Result result;
	ds::query::Result recResult;
	std::string dbPath = cms.getDatabasePath();
	std::string resourcesPath = cms.getResourcePath();

	std::map<int, ds::Resource> allResources;
	//									0			1				2				3				4				5					6			7
	std::string recyQuery = "SELECT resourcesid, resourcestype,resourcesduration,resourceswidth,resourcesheight,resourcesfilename,resourcespath,resourcesthumbid FROM Resources";
	if(ds::query::Client::query(dbPath, recyQuery, recResult)) {
		ds::query::Result::RowIterator	rit(recResult);
		while(rit.hasValue()) {
			ds::Resource reccy;
			int mediaId = rit.getInt(0);
			reccy.setDbId(mediaId);
			reccy.setTypeFromString(rit.getString(1));
			reccy.setDuration(rit.getFloat(2));
			reccy.setWidth(rit.getFloat(3));
			reccy.setHeight(rit.getFloat(4));
			if(reccy.getType() == ds::Resource::WEB_TYPE){
				reccy.setLocalFilePath(rit.getString(5));
			} else {
				std::stringstream loclPath;
				loclPath << resourcesPath << rit.getString(6) << rit.getString(5);
				reccy.setLocalFilePath(loclPath.str());
			}
			reccy.setThumbnailId(rit.getInt(7));
			allResources[mediaId] = reccy;
			++rit;
		}
		}

}
Пример #13
0
TEST(range_iterator, complete_run)
{
   std::vector<int> v = {1,2,3,4,5};
   mzlib::range_iterator rit(v.begin(), v.end(), 2);
   auto v1 = v.begin();
   auto v2 = v.begin()+1;
   auto v3 = v.begin()+2;
   auto v4 = v.begin()+3;
   auto v5 = v.begin()+4;
   auto v_end = v.end();
   
   using range_type = mzlib::range<std::vector<int>::iterator>;
   std::vector<range_type> ranges;
   for (auto r = rit.first(); !rit.end(r); r = rit.next(r)) {
      ranges.push_back(r);
   }
   
   ASSERT_EQ(9, ranges.size());
   
   // 2 x range size 4
   ASSERT_EQ(ranges[0].begin(), v1);
   ASSERT_EQ(ranges[0].end(), v5);
   
   ASSERT_EQ(ranges[1].begin(), v2);
   ASSERT_EQ(ranges[1].end(), v_end);
   
   // 3 x range size 3
   ASSERT_EQ(ranges[2].begin(), v1);
   ASSERT_EQ(ranges[2].end(), v4);
   
   ASSERT_EQ(ranges[3].begin(), v2);
   ASSERT_EQ(ranges[3].end(), v5);
   
   ASSERT_EQ(ranges[4].begin(), v3);
   ASSERT_EQ(ranges[4].end(), v_end);
   
   // 5 x range size 2
   ASSERT_EQ(ranges[5].begin(), v1);
   ASSERT_EQ(ranges[5].end(), v3);
   
   ASSERT_EQ(ranges[6].begin(), v2);
   ASSERT_EQ(ranges[6].end(), v4);
   
   ASSERT_EQ(ranges[7].begin(), v3);
   ASSERT_EQ(ranges[7].end(), v5);
   
   ASSERT_EQ(ranges[8].begin(), v4);
   ASSERT_EQ(ranges[8].end(), v_end);
}
Пример #14
0
	std::vector<OGL4ShaderCompiler::IncludeInfo> OGL4ShaderCompiler::ExtractIncludeList(const std::string& source)
	{
		std::regex r("#pragma include .*");

		std::string str = source;
		std::regex_iterator<std::string::iterator> rit(str.begin(), str.end(), r);
		std::regex_iterator<std::string::iterator> rend;

		std::vector<std::string> result;

		for(;rit != rend; ++rit)
		{
			result.push_back(rit->str());
		}

		std::vector<IncludeInfo> inc_list;
		for(auto v : result)
		{
			std::regex r("\".*\"");

			std::regex_iterator<std::string::iterator> rit(v.begin(), v.end(), r);
			std::regex_iterator<std::string::iterator> rend;

			if(rit == rend || rit->str().length() <= 2)
			{
				continue;
			}
			IncludeInfo inc;
			inc.file = rit->str().substr(1, rit->str().length() - 2);
			inc.lines = 0;
			
			inc_list.push_back(inc);
		}

		return inc_list;
	}
Пример #15
0
	std::string OGL4ShaderCompiler::ClearVersionComment(const std::string& source)
	{
		std::regex r("#version .*");

		std::string str = source;
		std::regex_iterator<std::string::iterator> rit(str.begin(), str.end(), r);
		std::regex_iterator<std::string::iterator> rend;

		std::string first = rit->str();

		std::regex rv("#version .*");

		std::string fmt = "";

		std::string result = std::regex_replace(source, rv, fmt);

		return first + result;
	}
Пример #16
0
double gMatrixSparse::gColumnSparse::dot(gColumnSparse &right)
{
    double sum = 0.0;
    iterator lit(*this), rit(right);
    
    while (lit.good() && rit.good()) {
        if (lit < rit) {
            lit.next();
        } else if (lit == rit) {
            sum += lit.val * rit.val;
            lit.next(); rit.next();
        } else {
            rit.next();
        }
    }
    
    return sum;
}
Пример #17
0
Table itemArrayFromCSV(const std::string& csv)
{
	Table table;
	std::vector<std::string> cell;
	std::regex e ("([A-Z])([a-z]*)|[[:digit:]]|(\\x2d)");
	std::sregex_iterator rit ( csv.begin(), csv.end(), e );
	std::sregex_iterator rend;
	while(rit!=rend) {
		if (rit->str()[0] == '1' || rit->str()[0] == '2' || rit->str()[0] == '3') {
			table.push_back(cell);
			cell.clear();
			//std::cout << std::endl;
		}
		cell.push_back(rit->str());
		//std::cout << rit->str() << " | ";
		++rit;
	}
	
	return table;
}
Пример #18
0
void gMatrixSparse::dualMap(gMatrixSparse &left, gMatrixSparse &right, dualMapper &mapper)
{
    assert(left.numRows == right.numRows && left.numCols == right.numCols);
    
    iterator lit(left), rit(right);
    while (lit.good() || rit.good()) {
        bool both = lit.good() && rit.good();
        if (!rit.good() || (both && lit < rit)) {
            mapper.map(lit.row, lit.col, lit.val, 0.0);
            lit.next();
        } else if (both && lit == rit) {
            mapper.map(lit.row, lit.col, lit.val, rit.val);
            lit.next();
            rit.next();
        } else {
            mapper.map(rit.row, rit.col, 0.0, rit.val);
            rit.next();
        }
    }
}
Пример #19
0
void TreeDiagram::computeExtremes(uint *maxLabelLen,uint *maxXPos)
{
  uint ml=0,mx=0;
  QListIterator<DiagramRow> it(*this);
  DiagramRow *dr;
  bool done=FALSE;
  for (;(dr=it.current()) && !done;++it)
  {
    QListIterator<DiagramItem> rit(*dr);
    DiagramItem *di;
    for (;(di=rit.current());++rit)
    {
      if (di->isInList()) done=TRUE;
      if (maxXPos) mx=QMAX(mx,(uint)di->xPos());
      if (maxLabelLen) ml=QMAX(ml,Image::stringLength(di->label()));
    }
  }
  if (maxLabelLen) *maxLabelLen=ml;
  if (maxXPos)     *maxXPos=mx;
}
Пример #20
0
const ConnVector& ConnFinder::GetConnections()
{
    // Start by looping through each peak.
    for (PeakVector::RectangleVector::const_iterator pk =
            m_peaks.GetVector().begin();
            pk != m_peaks.GetVector().end(); pk++)
    {
        // Iterate over the outside of the rectangle. Start at the top right 
        // corner for the 3 o'clock port numbering convention.
        for (OutsideRectangleIterator rit(
                    Space(m_src.width, m_src.height),
                    (*pk),
                    Point(pk->GetX()+pk->GetWidth(), pk->GetY()));
                rit.More(); rit++)
        {
            // If it's a dark cell...
            uint8_t* data = Point::GetDataByPoint(m_src, rit.GetCurrent());
            if (data[0] < 0x7f || data[1] < 0x7f || data[2] < 0x7f)
            {
                // Add a green border to this edge (green "from" red "to").
                m_pwhite.GreenoutBorder(*pk, rit.GetCurrent(), true);
                data[0] = 0x00; data[1] = 0x00; data[2] = 0x00;
                m_pwhite.GreenoutBorder(*pk, rit.GetCurrent(), false);
                data[0] = 0x00; data[1] = 0x00; data[2] = 0x00;

                // Find the connections associated with this cell.
                m_cwhite.GreyoutConnection(rit.GetCurrent());

                // Leave it blue, not gray.
                data[0] = 0xff; data[1] = 0x7f; data[2] = 0x7f;
            }
        }
    }

    // Return what is currently cached in the cwhite object.
    return m_cwhite.GetConnections();
}
Пример #21
0
void BidBook::addTransactions(map<float, int>::const_iterator it,
                              map<float, int>::const_iterator end)
{
    if (it == end) return;

    map<float, int>::const_reverse_iterator rit(end);
    map<float, int>::const_reverse_iterator rend(it);

    auto o_it = open_orders.rbegin();
    for (; rit != rend; ++rit) {
        float price = it->first,
              volume = it->second;

        transaction_volume += volume;
        transactions[price] += volume;

        while (o_it != open_orders.rend() and o_it->first >= price) {
            volume = o_it->second->doTransaction(volume);

            if (volume <= 0) break;
            else o_it++;
        }
    }
}
Пример #22
0
inline bool rit(varType &inp,Args &...args){
    return rit(inp)&&rit(args...);
}
Пример #23
0
int main(){
    rit(k,n);
    k=2*k+1;
    for(int i=0;i<n;i++){
        int S=rit();
        for(int j=0;j<3;j++){
            for(int l=0;l<k;l++){
                scanf("%d",&p[j][S][l]);
            }
        }
    }
    for(int i=n;i>0;i--){
        for(int j=1;j<=n;j++){
                // cout<<"NM "<<i<<" "<<j<<endl;
            if(i==j)continue;
            int ii=0,ji=0,win=0;
            while(ii<k && ji<k){
                if(p[0][i][ii]>p[0][j][ji]){
                    ii++,ji++,win++;
                }
                else if(p[0][i][ii]<p[0][j][ji]){
                    ji++;
                }
                else{
                    if(i>j){
                        ji++;
                    }
                    else{
                        ii++,ji++,win++;
                    }
                }
            }
            if(win<=(k>>1))goto thisIjizz;
        }
        printf("%d ",i);
        break;
        thisIjizz:;
    }
    for(int i=n;i>0;i--){
        for(int j=1;j<=n;j++){
            if(i==j)continue;
            int ii=0,ji=0,win=0;
            while(ii<k && ji<k){
                if(p[1][i][ii]>p[2][j][ji]){
                    ii++,ji++,win++;
                }
                else if(p[1][i][ii]<p[2][j][ji]){
                    ji++;
                }
                else{
                    if(i>j){
                        ji++;
                    }
                    else{
                        ii++,ji++,win++;
                    }
                }
            }
            if(win<=(k>>1))goto thisIjizz_;
        }
        printf("%d\n",i);
        break;
        thisIjizz_:;
    }
}
Пример #24
0
void tGraph::draw(QPainter & paint) {
    //QPainter paint(this);
    paint.save();

    int gx1 = hPadding() + _rect.x();
    int gy1 = vPadding() + _rect.y();
    int gx2 = _rect.x() + width() - hPadding();
    int gy2 = _rect.y() + height() - vPadding();

    //paint.drawRect(gx1, gy1, gx2 - gx1, gy2 - gy1);

    QFontMetrics fm(font());
    //QRect brect;

    // get the dimensions of the title label and then draw it
    if(title().length() > 0) {
        fm = QFontMetrics(titleFont());
        //brect = fm.boundingRect(title());
        paint.setFont(titleFont());
        paint.drawText(gx1, gy1, gx2 - gx1, fm.height(), titleAlignment(), title());
        gy1 += fm.height();
    }

    // we need to do some drawing that depends on some other elements having
    // already been placed... since those require that these have already been
    // placed we will just save the old value of gy2 and then calculate the
    // value that we should have after the other code runs without actually
    // drawing anything right now
    int gy2_old = gy2;
    if(dataLabel().length() > 0) {
        fm = QFontMetrics(dataLabelFont());
        gy2 -= fm.height();
    }
    fm = QFontMetrics(dataFont());
    double tlh = 0.0;
    
    QMapIterator<int, GReference> dlit(_data);
    while(dlit.hasNext())
    {
        dlit.next();
        tlh = QMAX(sin45deg * fm.width(dlit.value().first), tlh);
    }
    // don't change this variable as we use it later
    int th = (tlh == 0.0 ? 0 : (int)(tlh + (fm.height() * sin45deg)) + 2);
    gy2 -= th;


    // get the dimensions of the value label then draw it
    if(valueLabel().length() > 0) {
        fm = QFontMetrics(valueLabelFont());
        //brect = fm.boundingRect(valueLabel());
        paint.setFont(valueLabelFont());
        paint.save();
        paint.rotate(-90);
        paint.drawText(-gy2, gx1, gy2 - gy1, fm.height(), valueLabelAlignment(), valueLabel());
        paint.restore();
        gx1 += fm.height();
    }

    fm = QFontMetrics(valueFont());

    QString min_str = QString().sprintf("%-.0f",minValue());
    QString org_str = ( minValue() == 0.0 ? QString::null : QString("0") );
    QString max_str = QString().sprintf("%-.0f",maxValue());

    int width = QMAX(fm.width(min_str), fm.width(max_str));
    if(org_str.length() > 0) width = QMAX(width, fm.width(org_str));

    gx1 += width;

    int gy_max = gy1;
    int gy_min = gy2 - 1;
    int gy_org = gy_min;

    paint.setFont(valueFont());
    int tfa = Qt::AlignTop | Qt::AlignRight;
    paint.drawText(gx1 - fm.width(min_str), gy_min, fm.width(min_str), fm.height(), tfa, min_str);
    paint.drawLine(gx1 - 3, gy_min, gx1 + 2, gy_min);
    paint.drawText(gx1 - fm.width(max_str), gy_max, fm.width(max_str), fm.height(), tfa, max_str);
    paint.drawLine(gx1 - 3, gy_max, gx1 + 2, gy_max);
    int gheight = gy2 - gy1;
    double grng = maxValue() - minValue();
    if(org_str.length() > 0) {
        double perc = (0 - minValue()) / grng;
        gy_org = gy2 - (int)(perc * (double)gheight);
        paint.drawText(gx1 - fm.width(org_str), gy_org, fm.width(org_str), fm.height(), tfa, org_str);
        paint.drawLine(gx1 - 3, gy_org, gx1 + 2, gy_org);
    }

    gx1 += 3;

    // put the old value back so all the code to come draw correctly!
    gy2 = gy2_old;

    // get the dimensions of the data label then draw it
    if(dataLabel().length() > 0) {
        fm = QFontMetrics(dataLabelFont());
        //brect = fm.boundingRect(dataLabel());
        paint.setFont(dataLabelFont());
        gy2 -= fm.height();
        paint.drawText(gx1, gy2, gx2 - gx1, fm.height(), dataLabelAlignment(), dataLabel());
    }

    gy2 -= th;

    int ref_cnt = _data.count();
    int gwidth = gx2 - gx1;
    gheight = gy2 - gy1;

    if(ref_cnt > 0) {
        paint.save();
        fm = QFontMetrics(dataFont());
        paint.setFont(dataFont());
        int refwidth = QMAX(1, gwidth / ref_cnt);
        int buf = (int)(refwidth / 5);
        int buf2 = buf * 2;
        int pos = gx1 + (int)((gwidth - (refwidth * ref_cnt)) / 2);
        int bar_height;
        int fmheight = fm.height();
        int fmheight_div_2 = fmheight / 2;
        int refwidth_div_2 = refwidth / 2;
        int label_offset = (int)(fmheight_div_2 * cos45deg);
        int last_label_at = -1000;
        QMap<int, double> last_map;
        QMap<int, double> this_map;
        QMapIterator<int, GReference> rit(_data);
        while(rit.hasNext())
        {
            rit.next();
            GReference ref = rit.value();
            QString label = ref.first;
            if(label.length() > 0 && ((pos + refwidth_div_2) - last_label_at) > ((label_offset * 2) + 1)) {
                last_label_at = pos + refwidth_div_2;
                int lx = (int)(((pos + refwidth_div_2) * cos45deg) - ((gy2 + label_offset) * sin45deg));
                int ly = (int)(((pos + refwidth_div_2) * sin45deg) + ((gy2 + label_offset) * cos45deg));
                int fmwidth = fm.width(label);
                paint.save();
                paint.rotate(-45);
                paint.drawText(lx - fmwidth, ly - fmheight_div_2, fmwidth, fmheight, Qt::AlignRight | Qt::AlignTop, label);
                paint.restore();
            }

            QMapIterator<int, double> sit(ref.second);
            paint.save();
            if(drawBars() == TRUE) {
                TSetValue tval;
                QMap<double, TSetValue> sort_map;
                sit = ref.second;
                while(sit.hasNext())
                {
                    sit.next();
                    if(sit.value() != 0.0 && _setStyle[sit.key()].bar == TRUE) {
                        tval.first = sit.key();
                        tval.second = sit.value();
                        sort_map[(tval.second < 0.0 ? minValue() : maxValue()) - (tval.second < 0.0 ? -tval.second : tval.second)] = tval;
                    }
                }
                QMapIterator<double, TSetValue> it(sort_map);
                while(it.hasNext())
                {
                    it.next();
                    tval = it.value();
                    if(tval.second != 0.0) {
                        if(tval.second < 0) {
                            bar_height = (int)((tval.second / minValue()) * (gy_org - gy_min));
                        } else {
                            bar_height = (int)((tval.second / maxValue()) * (gy_org - gy_max));
                        } 
                        paint.fillRect(pos + buf, gy_org - bar_height, refwidth - buf2, bar_height, getSetColor(tval.first));
                    }
                }
            }
            if(drawLines() == TRUE) {
                this_map.clear();
                sit = ref.second;
                while(sit.hasNext())
                {
                    sit.next();
                    if(_setStyle[sit.key()].line == TRUE) {
                        this_map[sit.key()] = sit.value();
                        if(last_map.contains(sit.key())) {
                            paint.setPen(getSetColor(sit.key()));
                            double old_val = last_map[sit.key()];
                            double new_val = sit.value();
                            int ly1;
                            if(old_val < 0.0) ly1 = (int)((old_val / minValue()) * (gy_org - gy_min));
                            else              ly1 = (int)((old_val / maxValue()) * (gy_org - gy_max));
                            ly1 = gy_org - ly1;
                            int lx1 = pos - refwidth_div_2;
                            int ly2;
                            if(new_val < 0.0) ly2 = (int)((new_val / minValue()) * (gy_org - gy_min));
                            else              ly2 = (int)((new_val / maxValue()) * (gy_org - gy_max));
                            ly2 = gy_org - ly2;
                            int lx2 = pos + refwidth_div_2;
                            paint.drawLine(lx1, ly1, lx2, ly2);
                        }
                    }
                }
                last_map = this_map;
            }
            if(drawPoints() == TRUE) {
                sit = ref.second;
                while(sit.hasNext())
                {
                    sit.next();
                    if(_setStyle[sit.key()].point == TRUE) {
                        paint.setBrush(getSetColor(sit.key()));
                        paint.setPen(QColor(0,0,0));
                        int ly1;
                        if(sit.value() < 0.0) ly1 = (int)((sit.value() / minValue()) * (gy_org - gy_min));
                        else                  ly1 = (int)((sit.value() / maxValue()) * (gy_org - gy_max));
                        ly1 = gy_org - ly1;
                        int lx1 = pos + refwidth_div_2;
                        paint.drawEllipse(lx1 - 2, ly1 - 2, 5, 5);
                    }
                }
            }
            paint.restore();
            pos += refwidth;
        }
        paint.restore();
    }

    paint.drawLine(gx1, gy_org, gx2 - 1, gy_org);
    paint.drawRect(gx1, gy1, gx2 - gx1, gy2 - gy1);


    // Now that we are done return the paint device back to the state
    // it was when we started to mess with it
    paint.restore();
}
Пример #25
0
bool EffectTruncSilence::Process()
{
   // Typical fraction of total time taken by detection (better to guess low)
   const double detectFrac = .4;

   // Copy tracks
   this->CopyInputTracks(Track::All);

   // Lower bound on the amount of silence to find at a time -- this avoids
   // detecting silence repeatedly in low-frequency sounds.
   const double minTruncMs = 0.001;
   double truncDbSilenceThreshold = Enums::Db2Signal[mTruncDbChoiceIndex];

   // Master list of silent regions; it is responsible for deleting them.
   // This list should always be kept in order.
   RegionList silences;
   silences.DeleteContents(true);

   // Start with the whole selection silent
   Region *sel = new Region;
   sel->start = mT0;
   sel->end = mT1;
   silences.push_back(sel);

   // Remove non-silent regions in each track
   SelectedTrackListOfKindIterator iter(Track::Wave, mTracks);
   int whichTrack = 0;
   for (Track *t = iter.First(); t; t = iter.Next())
   {
      WaveTrack *wt = (WaveTrack *)t;

      // Smallest silent region to detect in frames
      sampleCount minSilenceFrames =
            sampleCount(wxMax( mInitialAllowedSilence, minTruncMs) *
                  wt->GetRate());

      //
      // Scan the track for silences
      //
      RegionList trackSilences;
      trackSilences.DeleteContents(true);
      sampleCount blockLen = wt->GetMaxBlockSize();
      sampleCount start = wt->TimeToLongSamples(mT0);
      sampleCount end = wt->TimeToLongSamples(mT1);

      // Allocate buffer
      float *buffer = new float[blockLen];

      sampleCount index = start;
      sampleCount silentFrames = 0;
      bool cancelled = false;

      // Keep position in overall silences list for optimization
      RegionList::iterator rit(silences.begin());

      while (index < end) {
         // Show progress dialog, test for cancellation
         cancelled = TotalProgress(
               detectFrac * (whichTrack + index / (double)end) /
               (double)GetNumWaveTracks());
         if (cancelled)
            break;

         //
         // Optimization: if not in a silent region skip ahead to the next one
         //
         double curTime = wt->LongSamplesToTime(index);
         for ( ; rit != silences.end(); ++rit)
         {
            // Find the first silent region ending after current time
            if ((*rit)->end >= curTime)
               break;
         }

         if (rit == silences.end()) {
            // No more regions -- no need to process the rest of the track
            break;
         }
         else if ((*rit)->start > curTime) {
            // End current silent region, skip ahead
            if (silentFrames >= minSilenceFrames) {
               Region *r = new Region;
               r->start = wt->LongSamplesToTime(index - silentFrames);
               r->end = wt->LongSamplesToTime(index);
               trackSilences.push_back(r);
            }
            silentFrames = 0;

            index = wt->TimeToLongSamples((*rit)->start);
         }
         //
         // End of optimization
         //

         // Limit size of current block if we've reached the end
         sampleCount count = blockLen;
         if ((index + count) > end) {
            count = end - index;
         }

         // Fill buffer
         wt->Get((samplePtr)(buffer), floatSample, index, count);

         // Look for silences in current block
         for (sampleCount i = 0; i < count; ++i) {
            if (fabs(buffer[i]) < truncDbSilenceThreshold) {
               ++silentFrames;
            }
            else {
               if (silentFrames >= minSilenceFrames)
               {
                  // Record the silent region
                  Region *r = new Region;
                  r->start = wt->LongSamplesToTime(index + i - silentFrames);
                  r->end = wt->LongSamplesToTime(index + i);
                  trackSilences.push_back(r);
               }
               silentFrames = 0;
            }
         }

         // Next block
         index += count;
      }

      delete [] buffer;

      // Buffer has been freed, so we're OK to return if cancelled
      if (cancelled)
      {
         ReplaceProcessedTracks(false);
         return false;
      }

      if (silentFrames >= minSilenceFrames)
      {
         // Track ended in silence -- record region
         Region *r = new Region;
         r->start = wt->LongSamplesToTime(index - silentFrames);
         r->end = wt->LongSamplesToTime(index);
         trackSilences.push_back(r);
      }

      // Intersect with the overall silent region list
      Intersect(silences, trackSilences);
      whichTrack++;
   }

   //
   // Now remove the silent regions from all selected / sync-lock selected tracks.
   //

   // Loop over detected regions in reverse (so cuts don't change time values
   // down the line)
   int whichReg = 0;
   RegionList::reverse_iterator rit;
   double totalCutLen = 0.0;  // For cutting selection at the end
   for (rit = silences.rbegin(); rit != silences.rend(); ++rit) {
      Region *r = *rit;

      // Progress dialog and cancellation. Do additional cleanup before return.
      if (TotalProgress(detectFrac + (1 - detectFrac) * whichReg / (double)silences.size()))
      {
         ReplaceProcessedTracks(false);
         return false;
      }

      // Intersection may create regions smaller than allowed; ignore them.
      // Allow one nanosecond extra for consistent results with exact milliseconds of allowed silence.
      if ((r->end - r->start) < (mInitialAllowedSilence - 0.000000001))
         continue;

      // Find new silence length as requested
      double inLength = r->end - r->start;
      double outLength;

      switch (mProcessIndex) {
      case 0:
         outLength = wxMin(mTruncLongestAllowedSilence, inLength);
         break;
      case 1:
         outLength = mInitialAllowedSilence +
                        (inLength - mInitialAllowedSilence) * mSilenceCompressPercent / 100.0;
         break;
      default: // Not currently used.
         outLength = wxMin(mInitialAllowedSilence +
                              (inLength - mInitialAllowedSilence) * mSilenceCompressPercent / 100.0,
                           mTruncLongestAllowedSilence);
      }

      double cutLen = inLength - outLength;
      totalCutLen += cutLen;

      TrackListIterator iterOut(mOutputTracks);
      for (Track *t = iterOut.First(); t; t = iterOut.Next())
      {
         // Don't waste time past the end of a track
         if (t->GetEndTime() < r->start)
            continue;

         if (t->GetKind() == Track::Wave && (
                  t->GetSelected() || t->IsSyncLockSelected()))
         {
            // In WaveTracks, clear with a cross-fade
            WaveTrack *wt = (WaveTrack *)t;
            sampleCount blendFrames = mBlendFrameCount;
            double cutStart = (r->start + r->end - cutLen) / 2;
            double cutEnd = cutStart + cutLen;
            // Round start/end times to frame boundaries
            cutStart = wt->LongSamplesToTime(wt->TimeToLongSamples(cutStart));
            cutEnd = wt->LongSamplesToTime(wt->TimeToLongSamples(cutEnd));

            // Make sure the cross-fade does not affect non-silent frames
            if (wt->LongSamplesToTime(blendFrames) > inLength) {
               blendFrames = wt->TimeToLongSamples(inLength);
            }

            // Perform cross-fade in memory
            float *buf1 = new float[blendFrames];
            float *buf2 = new float[blendFrames];
            sampleCount t1 = wt->TimeToLongSamples(cutStart) - blendFrames / 2;
            sampleCount t2 = wt->TimeToLongSamples(cutEnd) - blendFrames / 2;

            wt->Get((samplePtr)buf1, floatSample, t1, blendFrames);
            wt->Get((samplePtr)buf2, floatSample, t2, blendFrames);

            for (sampleCount i = 0; i < blendFrames; ++i) {
               buf1[i] = ((blendFrames-i) * buf1[i] + i * buf2[i]) /
                         (double)blendFrames;
            }

            // Perform the cut
            wt->Clear(cutStart, cutEnd);

            // Write cross-faded data
            wt->Set((samplePtr)buf1, floatSample, t1, blendFrames);

            delete [] buf1;
            delete [] buf2;
         }
         else if (t->GetSelected() || t->IsSyncLockSelected())
         {
            // Non-wave tracks: just do a sync-lock adjust
            double cutStart = (r->start + r->end - cutLen) / 2;
            double cutEnd = cutStart + cutLen;
            t->SyncLockAdjust(cutEnd, cutStart);
         }
      }
      ++whichReg;
   }

   mT1 -= totalCutLen;

   ReplaceProcessedTracks(true);

   return true;
}
Пример #26
0
void ClassDiagram::writeFigure(FTextStream &output,const char *path,
                               const char *fileName) const
{
  uint baseRows=base->computeRows();
  uint superRows=super->computeRows();
  uint baseMaxX, baseMaxLabelWidth, superMaxX, superMaxLabelWidth;
  base->computeExtremes(&baseMaxLabelWidth,&baseMaxX);
  super->computeExtremes(&superMaxLabelWidth,&superMaxX);

  uint rows=baseRows+superRows-1;
  uint cols=(QMAX(baseMaxX,superMaxX)+gridWidth*2-1)/gridWidth;
  
  // Estimate the image aspect width and height in pixels.
  uint estHeight = rows*40;
  uint estWidth  = cols*(20+QMAX(baseMaxLabelWidth,superMaxLabelWidth));
  //printf("Estimated size %d x %d\n",estWidth,estHeight);
  
  const float pageWidth = 14.0f; // estimated page width in cm.
                                 // Somewhat lower to deal with estimation
                                 // errors. 
  
  // compute the image height in centimeters based on the estimates
  float realHeight = QMIN(rows,12); // real height in cm
  float realWidth  = realHeight * estWidth/(float)estHeight;
  if (realWidth>pageWidth) // assume that the page width is about 15 cm
  {
    realHeight*=pageWidth/realWidth; 
    realWidth=pageWidth;
  }

  //output << "}\n";
  output << "\\begin{figure}[H]\n"
            "\\begin{center}\n"
            "\\leavevmode\n";
  output << "\\includegraphics[height=" << realHeight << "cm]{" 
                                        << fileName << "}" << endl;
  output << "\\end{center}\n"
            "\\end{figure}\n";
  
  //printf("writeFigure rows=%d cols=%d\n",rows,cols);

  QCString epsBaseName=(QCString)path+"/"+fileName;
  QCString epsName=epsBaseName+".eps";
  QFile f1;
  f1.setName(epsName.data());
  if (!f1.open(IO_WriteOnly))
  {
    err("Could not open file %s for writing\n",f1.name().data());
    exit(1);
  }
  FTextStream t(&f1);
  
  //printf("writeEPS() rows=%d cols=%d\n",rows,cols);
  
  // generate EPS header and postscript variables and procedures
  
  t << "%!PS-Adobe-2.0 EPSF-2.0\n";
  t << "%%Title: ClassName\n";
  t << "%%Creator: Doxygen\n";
  t << "%%CreationDate: Time\n";
  t << "%%For: \n";
  t << "%Magnification: 1.00\n";
  t << "%%Orientation: Portrait\n";
  t << "%%BoundingBox: 0 0 500 " << estHeight*500.0/(float)estWidth << "\n";
  t << "%%Pages: 0\n";
  t << "%%BeginSetup\n";
  t << "%%EndSetup\n";
  t << "%%EndComments\n";
  t << "\n";
  t << "% ----- variables -----\n";
  t << "\n";
  t << "/boxwidth 0 def\n";
  t << "/boxheight 40 def\n";
  t << "/fontheight 24 def\n";
  t << "/marginwidth 10 def\n";
  t << "/distx 20 def\n";
  t << "/disty 40 def\n";
  t << "/boundaspect " << estWidth/(float)estHeight << " def  % aspect ratio of the BoundingBox (width/height)\n";
  t << "/boundx 500 def\n";
  t << "/boundy boundx boundaspect div def\n";
  t << "/xspacing 0 def\n";
  t << "/yspacing 0 def\n";
  t << "/rows " << rows << " def\n";
  t << "/cols " << cols << " def\n";
  t << "/scalefactor 0 def\n";
  t << "/boxfont /Times-Roman findfont fontheight scalefont def\n";
  t << "\n";
  t << "% ----- procedures -----\n";
  t << "\n";
  t << "/dotted { [1 4] 0 setdash } def\n";
  t << "/dashed { [5] 0 setdash } def\n";
  t << "/solid  { [] 0 setdash } def\n";
  t << "\n";
  t << "/max % result = MAX(arg1,arg2)\n";
  t << "{\n";
  t << "  /a exch def\n";
  t << "  /b exch def\n";
  t << "  a b gt {a} {b} ifelse\n";
  t << "} def\n";
  t << "\n";
  t << "/xoffset % result = MAX(0,(scalefactor-(boxwidth*cols+distx*(cols-1)))/2)\n";
  t << "{\n";
  t << "  0 scalefactor boxwidth cols mul distx cols 1 sub mul add sub 2 div max\n";
  t << "} def\n";
  t << "\n";
  t << "/cw % boxwidth = MAX(boxwidth, stringwidth(arg1))\n";
  t << "{\n";
  t << "  /str exch def\n";
  t << "  /boxwidth boxwidth str stringwidth pop max def\n";
  t << "} def\n";
  t << "\n";
  t << "/box % draws a box with text `arg1' at grid pos (arg2,arg3)\n";
  t << "{ gsave\n";
  t << "  2 setlinewidth\n";
  t << "  newpath\n";
  t << "  exch xspacing mul xoffset add\n";
  t << "  exch yspacing mul\n";
  t << "  moveto\n";
  t << "  boxwidth 0 rlineto \n";
  t << "  0 boxheight rlineto \n";
  t << "  boxwidth neg 0 rlineto \n";
  t << "  0 boxheight neg rlineto \n";
  t << "  closepath\n";
  t << "  dup stringwidth pop neg boxwidth add 2 div\n";
  t << "  boxheight fontheight 2 div sub 2 div\n";
  t << "  rmoveto show stroke\n";
  t << "  grestore\n";
  t << "} def  \n";
  t << "\n";
  t << "/mark\n";
  t << "{ newpath\n";
  t << "  exch xspacing mul xoffset add boxwidth add\n";
  t << "  exch yspacing mul\n";
  t << "  moveto\n";
  t << "  0 boxheight 4 div rlineto\n";
  t << "  boxheight neg 4 div boxheight neg 4 div rlineto\n";
  t << "  closepath\n";
  t << "  eofill\n";
  t << "  stroke\n";
  t << "} def\n";
  t << "\n";
  t << "/arrow\n";
  t << "{ newpath\n";
  t << "  moveto\n";
  t << "  3 -8 rlineto\n";
  t << "  -6 0 rlineto\n";
  t << "  3 8 rlineto\n";
  t << "  closepath\n";
  t << "  eofill\n";
  t << "  stroke\n";
  t << "} def\n";
  t << "\n";
  t << "/out % draws an output connector for the block at (arg1,arg2)\n";
  t << "{\n";
  t << "  newpath\n";
  t << "  exch xspacing mul xoffset add boxwidth 2 div add\n";
  t << "  exch yspacing mul boxheight add\n";
  t << "  /y exch def\n";
  t << "  /x exch def\n";
  t << "  x y moveto\n";
  t << "  0 disty 2 div rlineto \n";
  t << "  stroke\n";
  t << "  1 eq { x y disty 2 div add arrow } if\n";
  t << "} def\n";
  t << "\n";
  t << "/in % draws an input connector for the block at (arg1,arg2)\n";
  t << "{\n";
  t << "  newpath\n";
  t << "  exch xspacing mul xoffset add boxwidth 2 div add\n";
  t << "  exch yspacing mul disty 2 div sub\n";
  t << "  /y exch def\n";
  t << "  /x exch def\n";
  t << "  x y moveto\n";
  t << "  0 disty 2 div rlineto\n";
  t << "  stroke\n";
  t << "  1 eq { x y disty 2 div add arrow } if\n";
  t << "} def\n";
  t << "\n";
  t << "/hedge\n";
  t << "{\n";
  t << "  exch xspacing mul xoffset add boxwidth 2 div add\n";
  t << "  exch yspacing mul boxheight 2 div sub\n";
  t << "  /y exch def\n";
  t << "  /x exch def\n";
  t << "  newpath\n";
  t << "  x y moveto\n";
  t << "  boxwidth 2 div distx add 0 rlineto\n";
  t << "  stroke\n";
  t << "  1 eq\n";
  t << "  { newpath x boxwidth 2 div distx add add y moveto\n";
  t << "    -8 3 rlineto\n";
  t << "    0 -6 rlineto\n";
  t << "    8 3 rlineto\n";
  t << "    closepath\n";
  t << "    eofill\n";
  t << "    stroke\n";
  t << "  } if\n";
  t << "} def\n";
  t << "\n";
  t << "/vedge\n";
  t << "{\n";
  t << "  /ye exch def\n";
  t << "  /ys exch def\n";
  t << "  /xs exch def\n";
  t << "  newpath\n";
  t << "  xs xspacing mul xoffset add boxwidth 2 div add dup\n";
  t << "  ys yspacing mul boxheight 2 div sub\n";
  t << "  moveto\n";
  t << "  ye yspacing mul boxheight 2 div sub\n";
  t << "  lineto\n";
  t << "  stroke\n";
  t << "} def\n";
  t << "\n";
  t << "/conn % connections the blocks from col `arg1' to `arg2' of row `arg3'\n";
  t << "{\n";
  t << "  /ys exch def\n";
  t << "  /xe exch def\n";
  t << "  /xs exch def\n";
  t << "  newpath\n";
  t << "  xs xspacing mul xoffset add boxwidth 2 div add\n";
  t << "  ys yspacing mul disty 2 div sub\n";
  t << "  moveto\n";
  t << "  xspacing xe xs sub mul 0\n";
  t << "  rlineto\n";
  t << "  stroke\n";
  t << "} def\n";
  t << "\n";
  t << "% ----- main ------\n";
  t << "\n";
  t << "boxfont setfont\n";
  t << "1 boundaspect scale\n";


  bool done=FALSE;
  QListIterator<DiagramRow> bit(*base);
  DiagramRow *dr;
  for (;(dr=bit.current()) && !done;++bit)
  {
    QListIterator<DiagramItem> rit(*dr);
    DiagramItem *di;
    for (;(di=rit.current());++rit)
    {
      done=di->isInList();
      t << "(" << di->label() << ") cw\n";
    }
  }
  QListIterator<DiagramRow> sit(*super);
  ++sit;
  done=FALSE;
  for (;(dr=sit.current()) && !done;++sit)
  {
    QListIterator<DiagramItem> rit(*dr);
    DiagramItem *di;
    for (;(di=rit.current());++rit)
    {
      done=di->isInList();
      t << "(" << di->label() << ") cw\n";
    }
  }

  t << "/boxwidth boxwidth marginwidth 2 mul add def\n"
    << "/xspacing boxwidth distx add def\n"
    << "/yspacing boxheight disty add def\n"
    << "/scalefactor \n"
    << "  boxwidth cols mul distx cols 1 sub mul add\n"
    << "  boxheight rows mul disty rows 1 sub mul add boundaspect mul \n"
    << "  max def\n"
    << "boundx scalefactor div boundy scalefactor div scale\n";
  
  t << "\n% ----- classes -----\n\n";
  base->drawBoxes(t,0,TRUE,FALSE,baseRows,superRows,0,0);
  super->drawBoxes(t,0,FALSE,FALSE,baseRows,superRows,0,0);
  
  t << "\n% ----- relations -----\n\n";
  base->drawConnectors(t,0,TRUE,FALSE,baseRows,superRows,0,0);
  super->drawConnectors(t,0,FALSE,FALSE,baseRows,superRows,0,0);

  f1.close();
  if (Config_getBool(USE_PDFLATEX))
  {
    QCString epstopdfArgs(4096);
    epstopdfArgs.sprintf("\"%s.eps\" --outfile=\"%s.pdf\"",
                   epsBaseName.data(),epsBaseName.data());
    //printf("Converting eps using `%s'\n",epstopdfArgs.data());
    portable_sysTimerStart();
    if (portable_system("epstopdf",epstopdfArgs)!=0)
    {
       err("Problems running epstopdf. Check your TeX installation!\n");
       portable_sysTimerStop();
       return;
    }
    portable_sysTimerStop();
  }
}
Пример #27
0
void TreeDiagram::drawConnectors(FTextStream &t,Image *image,
                                 bool doBase,bool bitmap,
                                 uint baseRows,uint superRows,
                                 uint cellWidth,uint cellHeight)
{
  QListIterator<DiagramRow> it(*this);
  DiagramRow *dr;
  bool done=FALSE;
  for (;(dr=it.current()) && !done;++it) // for each row
  {
    QListIterator<DiagramItem> rit(*dr);
    DiagramItem *di = rit.current();
    if (di->isInList()) // row consists of list connectors
    {
      int x=0,y=0,ys=0;
      float xf=0.0f,yf=0.0f,ysf=0.0f;
      for (;(di=rit.current());++rit)
      {
        DiagramItem *pi=di->parentItem();
        DiagramItemList *dil=pi->getChildren();
        DiagramItem *last=dil->getLast();
        if (di==last) // single child
        {
          if (bitmap) // draw pixels
          {
            x = di->xPos()*(cellWidth+labelHorSpacing)/gridWidth + cellWidth/2;
            if (doBase) // base classes
            {
              y = image->getHeight()-
                (superRows-1)*(cellHeight+labelVertSpacing)-
                di->yPos()*(cellHeight+labelVertSpacing)/gridHeight;
              image->drawVertArrow(x,y,y+labelVertSpacing/2,
                                   protToColor(di->protection()),
                                   protToMask(di->protection()));
            }
            else // super classes
            {
              y = (baseRows-1)*(cellHeight+labelVertSpacing)-
                labelVertSpacing/2+
                di->yPos()*(cellHeight+labelVertSpacing)/gridHeight;
              image->drawVertLine(x,y,y+labelVertSpacing/2,
                                  protToColor(di->protection()),
                                  protToMask(di->protection()));
            }
          }
          else // draw vectors
          {
            t << protToString(di->protection()) << endl;
            if (doBase)
            {
              t << "1 " << (di->xPos()/(float)gridWidth) << " " 
                << (di->yPos()/(float)gridHeight+superRows-1) << " in\n";
            }
            else
            {
              t << "0 " << (di->xPos()/(float)gridWidth) << " " 
                << ((float)superRows-0.25-di->yPos()/(float)gridHeight)
                << " in\n";
            }
          }
        }
        else // multiple children, put them in a vertical list
        {
          if (bitmap)
          {
            x = di->parentItem()->xPos()*
              (cellWidth+labelHorSpacing)/gridWidth+cellWidth/2;
            if (doBase) // base classes
            {
              ys = image->getHeight()-
                (superRows-1)*(cellHeight+labelVertSpacing)-
                di->yPos()*(cellHeight+labelVertSpacing)/gridHeight;
              y = ys - cellHeight/2;
            }
            else // super classes
            {
              ys = (baseRows-1)*(cellHeight+labelVertSpacing)+
                di->yPos()*(cellHeight+labelVertSpacing)/gridHeight;
              y = ys + cellHeight/2;
            }
          }
          else
          {
            xf = di->parentItem()->xPos()/(float)gridWidth;
            if (doBase)
            {
              ysf = di->yPos()/(float)gridHeight+superRows-1;
              yf = ysf + 0.5f;
            }
            else
            {
              ysf = (float)superRows-0.25f-di->yPos()/(float)gridHeight;
              yf = ysf - 0.25f;
            }
          }
          while (di!=last) // more children to add
          {
            if (bitmap)
            {
              if (doBase) // base classes
              {
                image->drawHorzArrow(y,x,x+cellWidth/2+labelHorSpacing,
                    protToColor(di->protection()),
                    protToMask(di->protection()));
                y -= cellHeight+labelVertSpacing;
              }
              else // super classes
              {
                image->drawHorzLine(y,x,x+cellWidth/2+labelHorSpacing,
                    protToColor(di->protection()),
                    protToMask(di->protection()));
                y += cellHeight+labelVertSpacing;
              }
            }
            else
            {
              t << protToString(di->protection()) << endl;
              if (doBase)
              {
                t << "1 " << xf << " " << yf << " hedge\n";
                yf += 1.0f;
              }
              else
              {
                t << "0 " << xf << " " << yf << " hedge\n";
                yf -= 1.0f;
              }
            }
            ++rit; di=rit.current();
          }
          // add last horizonal line and a vertical connection line
          if (bitmap)
          {
            if (doBase) // base classes
            {
              image->drawHorzArrow(y,x,x+cellWidth/2+labelHorSpacing,
                  protToColor(di->protection()),
                  protToMask(di->protection()));
              image->drawVertLine(x,y,ys+labelVertSpacing/2,
                  protToColor(getMinProtectionLevel(dil)),
                  protToMask(getMinProtectionLevel(dil)));
            }
            else // super classes
            {
              image->drawHorzLine(y,x,x+cellWidth/2+labelHorSpacing,
                  protToColor(di->protection()),
                  protToMask(di->protection()));
              image->drawVertLine(x,ys-labelVertSpacing/2,y,
                  protToColor(getMinProtectionLevel(dil)),
                  protToMask(getMinProtectionLevel(dil)));
            }
          }
          else
          {
            t << protToString(di->protection()) << endl;
            if (doBase)
            {
              t << "1 " << xf << " " << yf << " hedge\n";
            }
            else
            {
              t << "0 " << xf << " " << yf << " hedge\n";
            }
            t << protToString(getMinProtectionLevel(dil)) << endl;
            if (doBase)
            {
              t << xf << " " << ysf << " " << yf << " vedge\n";
            }
            else
            {
              t << xf << " " << (ysf + 0.25) << " " << yf << " vedge\n";
            }
          }
        }
      }
      done=TRUE; // the tree is drawn now
    }
    else // normal tree connector
    {
      for (;(di=rit.current());++rit)
      {
        int x=0,y=0;
        DiagramItemList *dil = di->getChildren();
        DiagramItem *parent  = di->parentItem();
        if (parent) // item has a parent -> connect to it
        {
          if (bitmap) // draw pixels
          {
            x = di->xPos()*(cellWidth+labelHorSpacing)/gridWidth + cellWidth/2;
            if (doBase) // base classes
            {
              y = image->getHeight()-
                (superRows-1)*(cellHeight+labelVertSpacing)-
                di->yPos()*(cellHeight+labelVertSpacing)/gridHeight;
              /* write input line */
              image->drawVertArrow(x,y,y+labelVertSpacing/2,
                  protToColor(di->protection()),
                  protToMask(di->protection()));
            }
            else // super classes
            {
              y = (baseRows-1)*(cellHeight+labelVertSpacing)-
                labelVertSpacing/2+
                di->yPos()*(cellHeight+labelVertSpacing)/gridHeight;
              /* write output line */
              image->drawVertLine(x,y,y+labelVertSpacing/2,
                  protToColor(di->protection()),
                  protToMask(di->protection()));
            }
          }
          else // draw pixels
          {
            t << protToString(di->protection()) << endl;
            if (doBase)
            {
              t << "1 " << di->xPos()/(float)gridWidth << " " 
                << (di->yPos()/(float)gridHeight+superRows-1) << " in\n";
            }
            else
            {
              t << "0 " << di->xPos()/(float)gridWidth << " " 
                << ((float)superRows-0.25-di->yPos()/(float)gridHeight)
                << " in\n";
            }
          }
        }
        if (dil->count()>0)
        {
          Protection p=getMinProtectionLevel(dil);
          uint mask=protToMask(p);
          uint col=protToColor(p);
          if (bitmap)
          {
            x = di->xPos()*(cellWidth+labelHorSpacing)/gridWidth + cellWidth/2;
            if (doBase) // base classes
            {
              y = image->getHeight()-
                (superRows-1)*(cellHeight+labelVertSpacing)-
                cellHeight-labelVertSpacing/2-
                di->yPos()*(cellHeight+labelVertSpacing)/gridHeight;
              image->drawVertLine(x,y,y+labelVertSpacing/2-1,col,mask);
            }
            else // super classes
            {
              y = (baseRows-1)*(cellHeight+labelVertSpacing)+
                cellHeight+
                di->yPos()*(cellHeight+labelVertSpacing)/gridHeight;
              image->drawVertArrow(x,y,y+labelVertSpacing/2-1,col,mask);
            }
          }
          else
          {
            t << protToString(p) << endl;
            if (doBase)
            {
              t << "0 " << di->xPos()/(float)gridWidth  << " " 
                << (di->yPos()/(float)gridHeight+superRows-1) << " out\n";
            }
            else
            {
              t << "1 " << di->xPos()/(float)gridWidth  << " " 
                << ((float)superRows-1.75-di->yPos()/(float)gridHeight)
                << " out\n";
            }
          }
          /* write input line */
          DiagramItem *first = dil->getFirst();
          DiagramItem *last  = dil->getLast();
          if (first!=last && !first->isInList()) /* connect with all base classes */
          {
            if (bitmap)
            {
              int xs = first->xPos()*(cellWidth+labelHorSpacing)/gridWidth
                + cellWidth/2;
              int xe = last->xPos()*(cellWidth+labelHorSpacing)/gridWidth
                + cellWidth/2; 
              if (doBase) // base classes
              {
                image->drawHorzLine(y,xs,xe,col,mask); 
              }
              else // super classes
              {
                image->drawHorzLine(y+labelVertSpacing/2,xs,xe,col,mask); 
              }
            }
            else
            {
              t << protToString(p) << endl;
              if (doBase)
              {
                t << first->xPos()/(float)gridWidth << " " 
                  << last->xPos()/(float)gridWidth << " "
                  << (first->yPos()/(float)gridHeight+superRows-1) 
                  << " conn\n";
              }
              else
              {
                t << first->xPos()/(float)gridWidth << " " 
                  << last->xPos()/(float)gridWidth << " "
                  << ((float)superRows-first->yPos()/(float)gridHeight)
                  << " conn\n";
              }
            }
          }
        }
      }
    }
  }
}
Пример #28
0
U8* LLBufferArray::seek(
	S32 channel,
	U8* start,
	S32 delta) const
{
	LLMemType m1(LLMemType::MTYPE_IO_BUFFER);
	const_segment_iterator_t it;
	const_segment_iterator_t end = mSegments.end();
	U8* rv = start;
	if(0 == delta)
	{
		if((U8*)npos == start)
		{
			// someone is looking for end of data. 
			segment_list_t::const_reverse_iterator rit = mSegments.rbegin();
			segment_list_t::const_reverse_iterator rend = mSegments.rend();
			while(rit != rend)
			{
				if(!((*rit).isOnChannel(channel)))
				{
					++rit;
					continue;
				}
				rv = (*rit).data() + (*rit).size();
				break;
			}
		}
		else if(start)
		{
			// This is sort of a weird case - check if zero bytes away
			// from current position is on channel and return start if
			// that is true. Otherwise, return NULL.
			it = getSegment(start);
			if((it == end) || !(*it).isOnChannel(channel))
			{
				rv = NULL;
			}
		}
		else
		{
			// Start is NULL, so return the very first byte on the
			// channel, or NULL.
			it = mSegments.begin();
			while((it != end) && !(*it).isOnChannel(channel))
			{
				++it;
			}
			if(it != end)
			{
				rv = (*it).data();
			}
		}
		return rv;
	}
	if(start)
	{
		it = getSegment(start);
		if((it != end) && (*it).isOnChannel(channel))
		{
			if(delta > 0)
			{
				S32 bytes_in_segment = (*it).size() - (start - (*it).data());
				S32 local_delta = llmin(delta, bytes_in_segment);
				rv += local_delta;
				delta -= local_delta;
				++it;
			}
			else
			{
				S32 bytes_in_segment = start - (*it).data();
				S32 local_delta = llmin(llabs(delta), bytes_in_segment);
				rv -= local_delta;
				delta += local_delta;
			}
		}
	}
	else if(delta < 0)
	{
		// start is NULL, and delta indicates seeking backwards -
		// return NULL.
		return NULL;
	}
	else
	{
		// start is NULL and delta > 0
		it = mSegments.begin();
	}
	if(delta > 0)
	{
		// At this point, we have an iterator into the segments, and
		// are seeking forward until delta is zero or we run out
		while(delta && (it != end))
		{
			if(!((*it).isOnChannel(channel)))
			{
				++it;
				continue;
			}
			if(delta <= (*it).size())
			{
				// it's in this segment
				rv = (*it).data() + delta;
			}
			delta -= (*it).size();
			++it;
		}
		if(delta && (it == end))
		{
			// Whoops - sought past end.
			rv = NULL;
		}
	}
	else //if(delta < 0)
	{
		// We are at the beginning of a segment, and need to search
		// backwards.
		segment_list_t::const_reverse_iterator rit(it);
		segment_list_t::const_reverse_iterator rend = mSegments.rend();
		while(delta && (rit != rend))
		{
			if(!((*rit).isOnChannel(channel)))
			{
				++rit;
				continue;
			}
			if(llabs(delta) <= (*rit).size())
			{
				// it's in this segment.
				rv = (*rit).data() + (*rit).size() + delta;
				delta = 0;
			}
			else
			{
				delta += (*rit).size();
			}
			++rit;
		}
		if(delta && (rit == rend))
		{
			// sought past the beginning.
			rv = NULL;
		}
	}
	return rv;
}
Пример #29
0
bool EffectTruncSilence::Analyze(RegionList& silenceList,
                                 RegionList& trackSilences,
                                 WaveTrack* wt,
                                 sampleCount* silentFrame,
                                 sampleCount* index,
                                 int whichTrack,
                                 double* inputLength /*= NULL*/,
                                 double* minInputLength /*= NULL*/)
{
   // Smallest silent region to detect in frames
   sampleCount minSilenceFrames = sampleCount(std::max( mInitialAllowedSilence, DEF_MinTruncMs) * wt->GetRate());

   double truncDbSilenceThreshold = Enums::Db2Signal[mTruncDbChoiceIndex];
   sampleCount blockLen = wt->GetMaxBlockSize();
   sampleCount start = wt->TimeToLongSamples(mT0);
   sampleCount end = wt->TimeToLongSamples(mT1);
   sampleCount outLength = 0;

   double previewLength;
   gPrefs->Read(wxT("/AudioIO/EffectsPreviewLen"), &previewLength, 6.0);
   // Minimum required length in samples.
   const sampleCount previewLen = previewLength * wt->GetRate();

   // Keep position in overall silences list for optimization
   RegionList::iterator rit(silenceList.begin());

   // Allocate buffer
   float *buffer = new float[blockLen];

   // Loop through current track
   while (*index < end) {
      if (inputLength && ((outLength >= previewLen) || (*index - start > wt->TimeToLongSamples(*minInputLength)))) {
         *inputLength = std::min<double>(*inputLength, *minInputLength);
         if (outLength >= previewLen) {
            *minInputLength = *inputLength;
         }
         return true;
      }

      if (!inputLength) {
         // Show progress dialog, test for cancellation
         bool cancelled = TotalProgress(
               detectFrac * (whichTrack + (*index - start) / (double)(end - start)) /
               (double)GetNumWaveTracks());
         if (cancelled) {
            delete [] buffer;
            return false;
         }
      }

      // Optimization: if not in a silent region skip ahead to the next one

      double curTime = wt->LongSamplesToTime(*index);
      for ( ; rit != silenceList.end(); ++rit) {
         // Find the first silent region ending after current time
         if (rit->end >= curTime) {
            break;
         }
      }

      if (rit == silenceList.end()) {
         // No more regions -- no need to process the rest of the track
         if (inputLength) {
            // Add available samples up to previewLength.
            sampleCount remainingTrackSamples = wt->TimeToLongSamples(wt->GetEndTime()) - *index;
            sampleCount requiredTrackSamples = previewLen - outLength;
            outLength += (remainingTrackSamples > requiredTrackSamples)? requiredTrackSamples : remainingTrackSamples;
         }

         break;
      }
      else if (rit->start > curTime) {
         // End current silent region, skip ahead
         if (*silentFrame >= minSilenceFrames)  {
            trackSilences.push_back(Region(
               wt->LongSamplesToTime(*index - *silentFrame),
               wt->LongSamplesToTime(*index)
            ));
         }
         *silentFrame = 0;
         sampleCount newIndex = wt->TimeToLongSamples(rit->start);
         if (inputLength) {
            sampleCount requiredTrackSamples = previewLen - outLength;
            // Add non-silent sample to outLength
            outLength += ((newIndex - *index) > requiredTrackSamples)? requiredTrackSamples : newIndex - *index;
         }

         *index = newIndex;
      }
      // End of optimization

      // Limit size of current block if we've reached the end
      sampleCount count = blockLen;
      if ((*index + count) > end) {
         count = end - *index;
      }

      // Fill buffer
      wt->Get((samplePtr)(buffer), floatSample, *index, count);

      // Look for silenceList in current block
      for (sampleCount i = 0; i < count; ++i) {
         if (inputLength && ((outLength >= previewLen) || (outLength > wt->TimeToLongSamples(*minInputLength)))) {
            *inputLength = wt->LongSamplesToTime(*index + i) - wt->LongSamplesToTime(start);
            break;
         }

         if (fabs(buffer[i]) < truncDbSilenceThreshold) {
            (*silentFrame)++;
         }
         else {
            sampleCount allowed = 0;
            if (*silentFrame >= minSilenceFrames) {
               if (inputLength) {
                  switch (mActionIndex) {
                     case kTruncate:
                        outLength += wt->TimeToLongSamples(mTruncLongestAllowedSilence);
                        break;
                     case kCompress:
                        allowed = wt->TimeToLongSamples(mInitialAllowedSilence);
                        outLength += allowed +
                                       (*silentFrame - allowed) * mSilenceCompressPercent / 100.0;
                        break;
                     // default: // Not currently used.
                  }
               }

               // Record the silent region
               Region *r = new Region;
               r->start = wt->LongSamplesToTime(*index + i - *silentFrame);
               r->end = wt->LongSamplesToTime(*index + i);
               trackSilences.push_back(Region(
                  wt->LongSamplesToTime(*index + i - *silentFrame),
                  wt->LongSamplesToTime(*index + i)
               ));
            }
            else if (inputLength) {   // included as part of non-silence
               outLength += *silentFrame;
            }
            *silentFrame = 0;
            if (inputLength) {
                ++outLength;   // Add non-silent sample to outLength
            }
         }
      }
      // Next block
      *index += count;
   }
   delete [] buffer;

   if (inputLength) {
      *inputLength = std::min<double>(*inputLength, *minInputLength);
      if (outLength >= previewLen) {
         *minInputLength = *inputLength;
      }
   }

   return true;
}
Пример #30
0
void TreeDiagram::drawBoxes(FTextStream &t,Image *image, 
                            bool doBase,bool bitmap,
                            uint baseRows,uint superRows,
                            uint cellWidth,uint cellHeight,
                            QCString relPath,
                            bool generateMap)
{
  QListIterator<DiagramRow> it(*this);
  DiagramRow *dr;
  if (!doBase) ++it;
  bool done=FALSE;
  bool firstRow = doBase;
  for (;(dr=it.current()) && !done;++it)
  {
    int x=0,y=0;
    float xf=0.0f,yf=0.0f;
    QListIterator<DiagramItem> rit(*dr);
    DiagramItem *di = rit.current();
    if (di->isInList()) // put boxes in a list
    {
      DiagramItem *opi=0;
      if (doBase) rit.toLast(); else rit.toFirst();
      while ((di=rit.current()))
      {
        if (di->parentItem()==opi)
        {
          if (bitmap)
          {
            if (doBase) y -= cellHeight+labelVertSpacing;
            else        y += cellHeight+labelVertSpacing;
          }
          else
          {
            if (doBase) yf += 1.0f;
            else        yf -= 1.0f;
          }
        }
        else
        {
          if (bitmap)
          {
            x = di->xPos()*(cellWidth+labelHorSpacing)/gridWidth;
            if (doBase)
            {
              y = image->getHeight()-
                superRows*cellHeight-
                (superRows-1)*labelVertSpacing-
                di->yPos()*(cellHeight+labelVertSpacing)/gridHeight;
            }
            else
            {
              y = (baseRows-1)*(cellHeight+labelVertSpacing)+
                di->yPos()*(cellHeight+labelVertSpacing)/gridHeight;
            }
          }
          else
          {
            xf = di->xPos()/(float)gridWidth;
            if (doBase)
            {
              yf = di->yPos()/(float)gridHeight+superRows-1;
            }
            else
            {
              yf = superRows-1-di->yPos()/(float)gridHeight;
            }
          }
        }
        opi=di->parentItem();
        
        if (bitmap)
        {
          bool hasDocs=di->getClassDef()->isLinkable();
          writeBitmapBox(di,image,x,y,cellWidth,cellHeight,firstRow,
              hasDocs,di->getChildren()->count()>0); 
          if (!firstRow && generateMap) 
            writeMapArea(t,di->getClassDef(),relPath,x,y,cellWidth,cellHeight);
        }
        else
        {
          writeVectorBox(t,di,xf,yf,di->getChildren()->count()>0);
        }
        
        if (doBase) --rit; else ++rit;
      }
      done=TRUE;
    }
    else // draw a tree of boxes
    {
      for (rit.toFirst();(di=rit.current());++rit)
      {
        if (bitmap)
        {
          x = di->xPos()*(cellWidth+labelHorSpacing)/gridWidth;
          if (doBase)
          {
            y = image->getHeight()-
              superRows*cellHeight-
              (superRows-1)*labelVertSpacing-
              di->yPos()*(cellHeight+labelVertSpacing)/gridHeight;
          }
          else
          {
            y = (baseRows-1)*(cellHeight+labelVertSpacing)+
              di->yPos()*(cellHeight+labelVertSpacing)/gridHeight;
          }
          bool hasDocs=di->getClassDef()->isLinkable();
          writeBitmapBox(di,image,x,y,cellWidth,cellHeight,firstRow,hasDocs); 
          if (!firstRow && generateMap) 
            writeMapArea(t,di->getClassDef(),relPath,x,y,cellWidth,cellHeight);
        }
        else
        {
          xf=di->xPos()/(float)gridWidth;
          if (doBase)
          {
            yf = di->yPos()/(float)gridHeight+superRows-1;
          }
          else
          {
            yf = superRows-1-di->yPos()/(float)gridHeight;
          }
          writeVectorBox(t,di,xf,yf);
        }
      }
    }
    firstRow=FALSE;
  }
}