Example #1
0
Fraction XmlReader::readFraction()
      {
      Q_ASSERT(tokenType() == QXmlStreamReader::StartElement);
      int z = attribute("z", "0").toInt();
      int n = attribute("n", "1").toInt();
      const QString& s(readElementText());
      if (!s.isEmpty()) {
            int i = s.indexOf('/');
            if (i == -1)
                  qFatal("illegal fraction <%s>", qPrintable(s));
            else {
                  z = s.left(i).toInt();
                  n = s.mid(i+1).toInt();
                  }
            }
      return Fraction(z, n);
      }
Example #2
0
Polynom& Polynom::operator -= (const Polynom& _another) {
	Polynom result;
	result.a.resize(max(pow(), _another.pow()) + 1, Fraction(0, 1)); //0 instead of Fraction(0,1) gives really strange results

	for(int i = 0; i <= pow(); i++) {
		result.a[i] += a[i];
	}
	for(int i = 0; i <= _another.pow(); i++) {
		result.a[i] -= _another.a[i];
	}

	a = result.a;

	simplify();

	return *this;
}
Example #3
0
Polynom& Polynom::operator += (const Polynom& _another) {
	Polynom result;
	result.a.resize(max(pow(), _another.pow()) + 1, Fraction(0, 1));

	for(int i = 0; i <= pow(); i++) {
		result.a[i] += a[i];
	}
	for(int i = 0; i <= _another.pow(); i++) {
		result.a[i] += _another.a[i];
	}

	a = result.a;

	simplify();

	return *this;
}
Example #4
0
std::vector<TDuration> toDurationList(Fraction l, bool useDots, int maxDots, bool printRestRemains)
      {
      std::vector<TDuration> dList;
      dList.reserve(8);

      if (useDots) {
            for (TDuration d = TDuration(TDuration::DurationType::V_LONG); d.isValid() && (l.numerator() != 0);) {
                  int dots = maxDots;
                  for ( ; dots > 0; --dots) {
                        d.setDots(dots);
                        Fraction ff = l - d.fraction();
                        if (ff.numerator() >= 0) {
                              dList.push_back(d);
                              l -= d.fraction();
                              break;
                              }
                        }
                  if (dots > 0)
                        continue;
                  d.setDots(0);
                  Fraction ff = l - d.fraction();
                  if (ff.numerator() < 0)
                        d = d.shift(1);
                  else {
                        dList.push_back(d);
                        l -= d.fraction();
                        }
                  }
            }
      else {
            for (TDuration d = TDuration(TDuration::DurationType::V_LONG); d.isValid() && (l.numerator() != 0);) {
                  Fraction ff(l - d.fraction());
                  if (ff.numerator() < 0) {
                        d = d.shift(1);
                        continue;
                        }
                  l -= d.fraction();
                  dList.push_back(d);
                  }
            }
      if (printRestRemains && l != Fraction())
            qDebug("toDurationList:: rest remains %d/%d", l.numerator(), l.denominator());

      return dList;
      }
Example #5
0
QList<TDuration> toDurationList(Fraction l, bool useDottedValues)
      {
      QList<TDuration> dList;
      if (useDottedValues) {
            for (TDuration d = TDuration(TDuration::V_LONG); d.isValid() && (l.numerator() != 0);) {
                  d.setDots(2);
                  Fraction ff(l - d.fraction());
                  if (ff.numerator() >= 0) {
                        dList.append(d);
                        l -= d.fraction();
                        continue;
                        }
                  d.setDots(1);
                  ff = l - d.fraction();
                  if (ff.numerator() >= 0) {
                        dList.append(d);
                        l -= d.fraction();
                        continue;
                        }
                  d.setDots(0);
                  ff = l - d.fraction();
                  if (ff.numerator() < 0) {
                        d = d.shift(1);
                        }
                  else {
                        l -= d.fraction();
                        dList.append(d);
                        }
                  }
            }
      else {
            for (TDuration d = TDuration(TDuration::V_LONG); d.isValid() && (l.numerator() != 0);) {
                  Fraction ff(l - d.fraction());
                  if (ff.numerator() < 0) {
                        d = d.shift(1);
                        continue;
                        }
                  l -= d.fraction();
                  dList.append(d);
                  }
            }
      if (l != Fraction())
            qDebug("toDurationList:: rest remains %d/%d", l.numerator(), l.denominator());
      return dList;
      }
Example #6
0
void TimeDialog::addClicked()
      {
      TimeSig* ts = new TimeSig(gscore);
      ts->setSig(Fraction(zNominal->value(), denominator()));
      ts->setGroups(groups->groups());

      // check for special text
      if ((QString("%1").arg(zNominal->value()) != zText->text())
         || (QString("%1").arg(denominator()) != nText->text())) {
            ts->setNumeratorString(zText->text());
            ts->setDenominatorString(nText->text());
            }
      // extend palette:
      sp->append(ts, "");
      _dirty = true;
      sp->updateGeometry();
      _timePalette->adjustSize();
      }
static void
gst_qt_quick2_video_sink_set_property (GObject *object,
                                       guint property_id,
                                       const GValue *value,
                                       GParamSpec *pspec)
{
    GstQtQuick2VideoSink *self = GST_QT_QUICK2_VIDEO_SINK (object);

    switch (property_id) {
    case PROP_PIXEL_ASPECT_RATIO:
      {
        GValue tmp;
        std::memset(&tmp, 0, sizeof(GValue));
        g_value_init(&tmp, GST_TYPE_FRACTION);
        if (g_value_transform(value, &tmp)) {
            int n = gst_value_get_fraction_numerator(&tmp);
            int d = gst_value_get_fraction_denominator(&tmp);
            self->priv->delegate->setPixelAspectRatio(Fraction(n, d));
        } else {
            GST_WARNING_OBJECT(object, "Could not transform string to aspect ratio");
        }
        g_value_unset(&tmp);
        break;
      }
    case PROP_FORCE_ASPECT_RATIO:
        self->priv->delegate->setForceAspectRatio(g_value_get_boolean(value));
        break;
    case PROP_CONTRAST:
        self->priv->delegate->setContrast(g_value_get_int(value));
        break;
    case PROP_BRIGHTNESS:
        self->priv->delegate->setBrightness(g_value_get_int(value));
        break;
    case PROP_HUE:
        self->priv->delegate->setHue(g_value_get_int(value));
        break;
    case PROP_SATURATION:
        self->priv->delegate->setSaturation(g_value_get_int(value));
        break;
    default:
        G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
        break;
    }
}
Example #8
0
QList<TDuration> toDurationList(Fraction l, bool useDots, int maxDots)
      {
      QList<TDuration> dList;
      if (useDots) {
            for (TDuration d = TDuration(TDuration::V_LONG); d.isValid() && (l.numerator() != 0);) {
                  int dots = maxDots;
                  for ( ; dots > 0; --dots) {
                        d.setDots(dots);
                        Fraction ff = l - d.fraction();
                        if (ff.numerator() >= 0) {
                              dList.append(d);
                              l -= d.fraction();
                              break;
                              }
                        }
                  if (dots > 0)
                        continue;
                  d.setDots(0);
                  Fraction ff = l - d.fraction();
                  if (ff.numerator() < 0) {
                        d = d.shift(1);
                        }
                  else {
                        dList.append(d);
                        l -= d.fraction();
                        }
                  }
            }
      else {
            for (TDuration d = TDuration(TDuration::V_LONG); d.isValid() && (l.numerator() != 0);) {
                  Fraction ff(l - d.fraction());
                  if (ff.numerator() < 0) {
                        d = d.shift(1);
                        continue;
                        }
                  l -= d.fraction();
                  dList.append(d);
                  }
            }
      if (l != Fraction())
            qDebug("toDurationList:: rest remains %d/%d", l.numerator(), l.denominator());
      return dList;
      }
Example #9
0
int main()
{
    while (true) {
        scanf("%d", &n);
        if (n == 0) break;

        Fraction f(1, n);
        Fraction s(1, n);

        for (int i = 2, d = n - 1; i <= n; ++i, --d) {
            f = s * Fraction(1, d);
            s = s + f;
        }

        printf("%d/%d\n", f.p, f.q);
    }

    return 0;
}
Example #10
0
CNtpTime::operator SYSTEMTIME() const
{
//	Currently this function only operates correctly in
//	the 1900- 2036 primary epoch defined by NTP
	SYSTEMTIME st;
	DWORD s	= Seconds();
	st.wSecond	= (WORD)( s % 60 );
	s	/= 60;
	st.wMinute	= (WORD)( s % 60 );
	s	/= 60;
	st.wHour	= (WORD)( s % 24 );
	s	/= 24;
	long JD	= s + JAN_1ST_1900;
	st.wDayOfWeek	= (WORD)( ( JD + 1 ) % 7 );
	GetGregorianDate( JD, st.wYear, st.wMonth, st.wDay );
	st.wMilliseconds	= NtpFractionToMs( Fraction() );

	return st;
}
void kcs::Row::doReverseEliminate(Row & two){
    int second=0;
    Fraction** twoNums =two.getNumbers();
     for(int i=0;i<length;i++){
        if(!twoNums[i]->isEqual(0)){

            second=i;
            break;
        }
    }

    Fraction theMain = Fraction(numbers[second]->getNumerator(),numbers[second]->getDnumerator());

    for(int i=second;i<length;i++){
        Fraction tmp =(twoNums[i]->doMultiply(theMain));
        numbers[i] ->doMinus(  tmp   );
    }


}
void FractionCalculator::compute(void)
{
	switch(this->operation)
	{
		case '+':
			this->result = this->f1 + this->f2;
			break;
		case '-':
			this->result = this->f1 - this->f2;
			break;
		case '*':
			this->result = this->f1 * this->f2;
			break;
		case '/':
			this->result = this->f1 / this->f2;
			break;
		default:
			this->result = Fraction();	// set to a Fraction(0) if invalid operation
	}
	return;
}
Example #13
0
void TimeSig::write(XmlWriter& xml) const
      {
      xml.stag("TimeSig");
      writeProperty(xml, P_ID::TIMESIG_TYPE);
      Element::writeProperties(xml);

      xml.tag("sigN",  _sig.numerator());
      xml.tag("sigD",  _sig.denominator());
      if (stretch() != Fraction(1,1)) {
            xml.tag("stretchN", stretch().numerator());
            xml.tag("stretchD", stretch().denominator());
            }
      writeProperty(xml, P_ID::NUMERATOR_STRING);
      writeProperty(xml, P_ID::DENOMINATOR_STRING);
      if (!_groups.empty())
            _groups.write(xml);
      writeProperty(xml, P_ID::SHOW_COURTESY);
      writeProperty(xml, P_ID::SCALE);

      xml.etag();
      }
Example #14
0
SymId Rest::getSymbol(TDuration::DurationType type, int line, int lines, int* yoffset)
      {
      *yoffset = 2;
      switch(type) {
            case TDuration::DurationType::V_LONG:
                  return SymId::restLonga;
            case TDuration::DurationType::V_BREVE:
                  return SymId::restDoubleWhole;
            case TDuration::DurationType::V_MEASURE:
                  if (duration() >= Fraction(2, 1))
                        return SymId::restDoubleWhole;
                  // fall trough
            case TDuration::DurationType::V_WHOLE:
                  *yoffset = 1;
                  return (line <= -2 || line >= (lines - 1)) ? SymId::restWholeLegerLine : SymId::restWhole;
            case TDuration::DurationType::V_HALF:
                  return (line <= -3 || line >= (lines - 2)) ? SymId::restHalfLegerLine : SymId::restHalf;
            case TDuration::DurationType::V_QUARTER:
                  return SymId::restQuarter;
            case TDuration::DurationType::V_EIGHT:
                  return SymId::rest8th;
            case TDuration::DurationType::V_16TH:
                  return SymId::rest16th;
            case TDuration::DurationType::V_32ND:
                  return SymId::rest32nd;
            case TDuration::DurationType::V_64TH:
                  return SymId::rest64th;
            case TDuration::DurationType::V_128TH:
                  return SymId::rest128th;
            case TDuration::DurationType::V_256TH:
                  return SymId::rest256th;
            case TDuration::DurationType::V_512TH:
                  return SymId::rest512th;
            case TDuration::DurationType::V_1024TH:
                  return SymId::rest1024th;
            default:
                  qDebug("unknown rest type %d", type);
                  return SymId::restQuarter;
            }
      }
void SwingDetector::applySwing()
      {
      if (elements.size() != 2 && elements.size() != 3)
            return;

      Tuplet *tuplet = nullptr;
      for (ChordRest *el: elements) {
            el->setDurationType(TDuration::DurationType::V_EIGHTH);
            el->setTicks(Fraction(1, 8));
            el->setDots(0);
            if (el->tuplet()) {
                  if (!tuplet)
                        tuplet = el->tuplet();
                  tuplet->remove(el);
                  el->setTuplet(nullptr);
                  }
            }

      const ChordRest *first = elements.front();
      const int startTick = first->segment()->tick().ticks();
      ChordRest *last = elements.back();
      last->segment()->remove(last);
      Segment *s = last->measure()->getSegment(SegmentType::ChordRest, Fraction::fromTicks(startTick + MScore::division / 2));
      s->add(last);

      if (elements.size() == 3) {
                  // remove central rest
            ChordRest *cr = elements[1];
            cr->score()->removeElement(cr);
            delete cr;
            }

      if (tuplet) {
                  // delete tuplet
            delete tuplet;
            tuplet = nullptr;
            }
      if (!swingApplied)
            swingApplied = true;
      }
Example #16
0
int Rest::getSymbol(TDuration::DurationType type, int line, int lines, int* yoffset)
      {
      *yoffset = 2;
      switch(type) {
            case TDuration::V_LONG:
                  return longarestSym;
            case TDuration::V_BREVE:
                  return breverestSym;
            case TDuration::V_MEASURE:
                  if (duration() >= Fraction(2, 1))
                        return breverestSym;
                  // fall trough
            case TDuration::V_WHOLE:
                  *yoffset = 1;
                  return (line <= -2 || line >= (lines - 1)) ? outsidewholerestSym : wholerestSym;
            case TDuration::V_HALF:
                  return (line <= -3 || line >= (lines - 2)) ? outsidehalfrestSym : halfrestSym;
            case TDuration::V_QUARTER:
                  return rest4Sym;
            case TDuration::V_EIGHT:
                  return rest8Sym;
            case TDuration::V_16TH:
                  return rest16Sym;
            case TDuration::V_32ND:
                  return rest32Sym;
            case TDuration::V_64TH:
                  return rest64Sym;
            case TDuration::V_128TH:
                  return rest128Sym;
            case TDuration::V_256TH:
                  qDebug("Rest: no symbol for 1/256");
                  return rest128Sym;
            default:
                  qDebug("unknown rest type %d", type);
                  return rest4Sym;
            }
      }
Example #17
0
Fraction SPTGSolver::nextEventPoint(){
	cout << "====NextEventPoint===" << endl;
	Fraction min(ifnty);

	for (unsigned int state = 1; state < size; ++state){
		//     First we have to check if an epsilon can be found using the lambda transition
		Fraction tempMin(ifnty);
		if((*vals)[state][0] != lambdas[state][0] && lambdas[state][1] != (*vals)[state][1]){
			tempMin = ((*vals)[state][0] - lambdas[state][0])/(lambdas[state][1] - (*vals)[state][1]);
			if(tempMin < 0)
				tempMin = ifnty;
			if( time - tempMin < min)
				min = tempMin;
		}

		for (unsigned int nextState = 0; nextState < size; ++nextState){
			//       Then we need to check if there is another epsilon that can be found using the other transitions
			tempMin = Fraction(ifnty);
			if(sptg->getTransition(state, nextState) != -1 && ((*vals)[state][0] != (*vals)[nextState][0] + sptg->getTransition(state, nextState)) &&
					((*vals)[nextState][1] != (*vals)[state][1]))
			{

				tempMin = ((*vals)[state][0] - ((*vals)[nextState][0]+sptg->getTransition(state, nextState)))/((*vals)[nextState][1] - (*vals)[state][1]);

				if(tempMin < 0)
					tempMin = ifnty;

				if(tempMin < min)
					min = tempMin;
			}

		}

	}
	return min;
}
Example #18
0
void MsScWriter::doTriplet(Chord* cr, StartStop triplet)
      {
      qDebug() << "MsScWriter::doTriplet(" << triplet << ")"
      ;

      if (triplet == ST_START) {
            tuplet = new Tuplet(score);
            tuplet->setTrack(0);
            tuplet->setRatio(Fraction(3, 2));
            tuplet->setTick(tick);
            currentMeasure->add(tuplet);
            }
      else if (triplet == ST_STOP) {
            if (tuplet) {
                  cr->setTuplet(tuplet);
                  tuplet->add(cr);
                  tuplet = 0;
                  }
            else
                  qDebug("BWW::import: triplet stop without triplet start\n");
            }
      else if (triplet == ST_CONTINUE) {
            if (!tuplet)
                  qDebug("BWW::import: triplet continue without triplet start\n");
            }
      else if (triplet == ST_NONE) {
            if (tuplet)
                  qDebug("BWW::import: triplet none inside triplet\n");
            }
      else
            qDebug("unknown triplet type %d\n", triplet);
      if (tuplet) {
            cr->setTuplet(tuplet);
            tuplet->add(cr);
            }
      }
Example #19
0
void TimeSig::write(XmlWriter& xml) const
      {
      xml.stag("TimeSig");
      if (timeSigType() != TimeSigType::NORMAL)
            xml.tag("subtype", int(timeSigType()));
      Element::writeProperties(xml);

      xml.tag("sigN",  _sig.numerator());
      xml.tag("sigD",  _sig.denominator());
      if (stretch() != Fraction(1,1)) {
            xml.tag("stretchN", stretch().numerator());
            xml.tag("stretchD", stretch().denominator());
            }
      if (customText) {
            if (!_numeratorString.isEmpty())
                  xml.tag("textN", _numeratorString);
            if (!_denominatorString.isEmpty())
                  xml.tag("textD", _denominatorString);
            }
      if (!_groups.empty())
            _groups.write(xml);
      xml.tag("showCourtesySig", _showCourtesySig);
      xml.etag();
      }
Example #20
0
Palette* MuseScore::newTimePalette()
      {
      struct TS {
            int numerator;
            int denominator;
            TimeSigType type;
            QString name;
            };

      TS tsList[] = {
            { 2,  4, TimeSigType::NORMAL, "2/4" },
            { 3,  4, TimeSigType::NORMAL, "3/4" },
            { 4,  4, TimeSigType::NORMAL, "4/4" },
            { 5,  4, TimeSigType::NORMAL, "5/4" },
            { 6,  4, TimeSigType::NORMAL, "6/4" },
            { 3,  8, TimeSigType::NORMAL, "3/8" },
            { 6,  8, TimeSigType::NORMAL, "6/8" },
            { 9,  8, TimeSigType::NORMAL, "9/8" },
            { 12, 8, TimeSigType::NORMAL, "12/8" },
            { 4,  4, TimeSigType::FOUR_FOUR,  tr("4/4 common time") },
            { 2,  2, TimeSigType::ALLA_BREVE, tr("2/2 alla breve") }
            };

      Palette* sp = new Palette;
      sp->setName(QT_TRANSLATE_NOOP("Palette", "Time Signatures"));
      sp->setMag(.8);
      sp->setGrid(42, 38);

      for (unsigned i = 0; i < sizeof(tsList)/sizeof(*tsList); ++i) {
            TimeSig* ts;
            ts = new TimeSig(gscore);
            ts->setSig(Fraction(tsList[i].numerator, tsList[i].denominator), tsList[i].type);
            sp->append(ts, tsList[i].name);
            }
      return sp;
      }
Example #21
0
void SPTGSolver::init(){

	//   Initialization of all vectors and variables used by the solver
	size = sptg->getSize();
	if(size != 0){
		vals = new vector<vector<Fraction> >();
		vals->push_back(vector<Fraction>());
		(*vals)[0].push_back(Fraction(0));
		(*vals)[0].push_back(Fraction(0));

		strategies = new list<Strategy> ();
		(*strategies).push_front(Strategy(size, time, false));
		(*strategies).front().insert(0,0,0);

		pathsLengths = new vector<unsigned int>();
		pathsLengths->push_back(0);

		lambdas.push_back(vector<Fraction>());
		lambdas[0].push_back(Fraction(0));
		lambdas[0].push_back(Fraction(0));

		valueFcts = new vector<list<Point> >();
		valueFcts->push_back(list<Point>());

		// Fill the initial valors, strategies and the ensemble of states
		for (unsigned int i = 1; i < size; ++i){
			vals->push_back(vector<Fraction>());
			(*vals)[i].push_back(Fraction(ifnty));
			(*vals)[i].push_back(Fraction(0));

			strategies->front().insert(i, -1, 0);
			pathsLengths->push_back(0);

			lambdas.push_back(vector<Fraction>());
			lambdas[i].push_back(0);
			lambdas[i].push_back(0);

			valueFcts->push_back(list<Point>());
		}
	}
}
Example #22
0
Fraction Fraction:: operator * (const Fraction& other)
{
    return Fraction(n*other.n, d*other.d);
}
Example #23
0
void ContinuousPanel::paint(const QRect&, QPainter& painter)
      {
      qreal _offsetPanel = 0;
      qreal _y = 0;
      qreal _oldWidth = 0;        // The last final panel width
      qreal _newWidth = 0;        // New panel width
      qreal _height = 0;
      qreal _leftMarginTotal = 0; // Sum of all elments left margin
      qreal _panelRightPadding = 5;  // Extra space for the panel after last element

      Measure* measure = _score->firstMeasure();

      if (!_active || !measure) {
            _visible = false;
            return;
            }

      if (measure->mmRest()) {
            measure = measure->mmRest();
            }

      System* system   = measure->system();
      if (system == 0) {
            _visible = false;
            return;
            }

      Segment* s      = measure->first();
      double _spatium = _score->spatium();
      if (_width <= 0)
            _width  = s->x();

      //
      // Set panel height for whole system
      //
      _height = 6 * _spatium;
      _y = system->staffYpage(0) + system->page()->pos().y();
      double y2 = 0.0;
      for (int i = 0; i < _score->nstaves(); ++i) {
            SysStaff* ss = system->staff(i);
            if (!ss->show() || !_score->staff(i)->show())
                  continue;
            y2 = ss->y() + ss->bbox().height();
            }
      _height += y2 + 6*_spatium;
      _y -= 6 * _spatium;

      //
      // Check elements at current panel position
      //
      _offsetPanel = -(_sv->xoffset()) / _sv->mag();
      _rect        = QRect(_offsetPanel + _width, _y, 1, _height);
      Page* page   = _score->pages().front();
      QList<Element*> el = page->items(_rect);
      if (el.empty()) {
            _visible = false;
            return;
            }
      qStableSort(el.begin(), el.end(), elementLessThan);

      const Measure*_currentMeasure = 0;
      for (const Element* e : el) {
            e->itemDiscovered = 0;
            if (!e->visible() && !_score->showInvisible())
                  continue;

            if (e->isMeasure()) {
                  _currentMeasure = toMeasure(e);
                  break;
                  }
            }
      if (!_currentMeasure)
            return;

      // Don't show panel if staff names are visible
      if (_currentMeasure == _score->firstMeasure() && _sv->toPhysical(_currentMeasure->canvasPos()).x() > 0) {
            _visible = false;
            return;
            }

      qreal _xPosMeasure       = _currentMeasure->canvasX();
      qreal _measureWidth      = _currentMeasure->width();
      int tick                 = _currentMeasure->tick();
      Fraction _currentTimeSig = _currentMeasure->timesig();
      //qDebug() << "_sv->xoffset()=" <<_sv->xoffset() << " _sv->mag()="<< _sv->mag() <<" s->x=" << s->x() << " width=" << _width << " currentMeasure=" << _currentMeasure->x() << " _xPosMeasure=" << _xPosMeasure;

      //---------------------------------------------------------
      //   findElementWidths
      //      determines the max width for each element types
      //---------------------------------------------------------

      // The first pass serves to get the maximum width for each elements

      qreal lineWidthName = 0;
      qreal _widthClef    = 0;
      qreal _widthKeySig  = 0;
      qreal _widthTimeSig = 0;
      qreal _xPosTimeSig  = 0;

      for (const Element* e : el) {
            e->itemDiscovered = 0;
            if (!e->visible() && !_score->showInvisible())
                  continue;

            if (e->isRest() && toRest(e)->isGap())
                  continue;

            if (e->isStaffLines()) {
                  Staff* currentStaff = _score->staff(e->staffIdx());
                  Segment* parent = _score->tick2segment(tick);

                  // Find maximum width for the staff name
                  QList<StaffName>& staffNamesLong = currentStaff->part()->instrument()->longNames();
                  QString staffName = staffNamesLong.isEmpty() ? " " : staffNamesLong[0].name();
                  if (staffName == "") {
                        QList<StaffName>& staffNamesShort = currentStaff->part()->instrument()->shortNames();
                        staffName = staffNamesShort.isEmpty() ? "" : staffNamesShort[0].name();
                        }
                  Text* newName = new Text(_score);
                  newName->setXmlText(staffName);
                  newName->setParent(parent);
                  newName->setTrack(e->track());
                  newName->textStyle().setFamily("FreeSans");
                  newName->textStyle().setSizeIsSpatiumDependent(true);
                  newName->layout();
                  newName->setPlainText(newName->plainText());
                  newName->layout();

                  // Find maximum width for the current Clef
                  Clef* newClef = new Clef(_score);
                  ClefType currentClef = currentStaff->clef(tick);
                  newClef->setClefType(currentClef);
                  newClef->setParent(parent);
                  newClef->setTrack(e->track());
                  newClef->layout();
                  if (newClef->width() > _widthClef)
                        _widthClef = newClef->width();

                  // Find maximum width for the current KeySignature
                  KeySig* newKs = new KeySig(_score);
                  KeySigEvent currentKeySigEvent = currentStaff->keySigEvent(tick);
                  newKs->setKeySigEvent(currentKeySigEvent);
                  // The Parent and the Track must be set to have the key signature layout adjusted to different clefs
                  // This also adds naturals to the key signature (if set in the score style)
                  newKs->setParent(parent);
                  newKs->setTrack(e->track());
                  newKs->setHideNaturals(true);
                  newKs->layout();
                  if (newKs->width() > _widthKeySig)
                        _widthKeySig = newKs->width();

                  // Find maximum width for the current TimeSignature
                  TimeSig* newTs = new TimeSig(_score);

                  // Try to get local time signature, if not, get the current measure one
                  TimeSig* currentTimeSig = currentStaff->timeSig(tick);
                  if (currentTimeSig)
                        newTs->setFrom(currentTimeSig);
                  else
                        newTs->setSig(Fraction(_currentTimeSig.numerator(), _currentTimeSig.denominator()), TimeSigType::NORMAL);
                  newTs->setParent(parent);
                  newTs->setTrack(e->track());
                  newTs->layout();

                  if ((newName->width() > lineWidthName) && (newName->xmlText() != ""))
                        lineWidthName = newName->width();

                  if (newTs->width() > _widthTimeSig)
                        _widthTimeSig = newTs->width();

                  delete newClef;
                  delete newName;
                  delete newKs;
                  delete newTs;
                 }
            }

      _leftMarginTotal = _score->styleP(StyleIdx::clefLeftMargin);
      _leftMarginTotal += _score->styleP(StyleIdx::keysigLeftMargin);
      _leftMarginTotal += _score->styleP(StyleIdx::timesigLeftMargin);

      _newWidth = _widthClef + _widthKeySig + _widthTimeSig + _leftMarginTotal + _panelRightPadding;
      _xPosMeasure -= _offsetPanel;

      lineWidthName += _score->spatium() + _score->styleP(StyleIdx::clefLeftMargin) + _widthClef;
      if (_newWidth < lineWidthName) {
            _newWidth = lineWidthName;
            _oldWidth = 0;
            }
      if (_oldWidth == 0) {
            _oldWidth = _newWidth;
            _width = _newWidth;
            }
      else if (_newWidth > 0) {
            if (_newWidth == _width) {
                  _oldWidth = _width;
                  _width = _newWidth;
                  }
            else if (((_xPosMeasure <= _newWidth) && (_xPosMeasure >= _oldWidth)) ||
                     ((_xPosMeasure >= _newWidth) && (_xPosMeasure <= _oldWidth)))
                        _width = _xPosMeasure;
            else if (((_xPosMeasure+_measureWidth <= _newWidth) && (_xPosMeasure+_measureWidth >= _oldWidth)) ||
                     ((_xPosMeasure+_measureWidth >= _newWidth) && (_xPosMeasure+_measureWidth <= _oldWidth)))
                        _width = _xPosMeasure+_measureWidth;
            else {
                  _oldWidth = _width;
                  _width = _newWidth;
                  }
            }

      _rect = QRect(0, _y, _width, _height);

      //====================

      painter.save();

      // Draw colored rectangle
      painter.setClipping(false);
      QPointF pos(_offsetPanel, 0);

      painter.translate(pos);
      QPen pen;
      pen.setWidthF(0.0);
      pen.setStyle(Qt::NoPen);
      painter.setPen(pen);
      painter.setBrush(preferences.fgColor);
      QRectF bg(_rect);

      bg.setWidth(_widthClef + _widthKeySig + _widthTimeSig + _leftMarginTotal + _panelRightPadding);
      QPixmap* fgPixmap = _sv->fgPixmap();
      if (fgPixmap == 0 || fgPixmap->isNull())
            painter.fillRect(bg, preferences.fgColor);
      else {
            painter.setMatrixEnabled(false);
            painter.drawTiledPixmap(bg, *fgPixmap, bg.topLeft()
               - QPoint(lrint(_sv->matrix().dx()), lrint(_sv->matrix().dy())));
            painter.setMatrixEnabled(true);
            }

      painter.setClipRect(_rect);
      painter.setClipping(true);

      QColor color(MScore::layoutBreakColor);

      // Draw measure text number
      QString text = QString("#%1").arg(_currentMeasure->no()+1);
      Text* newElement = new Text(_score);
      newElement->setTextStyleType(TextStyleType::DEFAULT);
      newElement->setFlag(ElementFlag::MOVABLE, false);
      newElement->setXmlText(text);
      newElement->textStyle().setFamily("FreeSans");
      newElement->textStyle().setSizeIsSpatiumDependent(true);
      newElement->setColor(color);
      newElement->sameLayout();
      pos = QPointF(_score->styleP(StyleIdx::clefLeftMargin) + _widthClef, _y + newElement->height());
      painter.translate(pos);
      newElement->draw(&painter);
      pos += QPointF(_offsetPanel, 0);
      painter.translate(-pos);
      delete newElement;

      // This second pass draws the elements spaced evently using the width of the largest element
      for (const Element* e : el) {
            if (!e->visible() && !_score->showInvisible())
                  continue;

            if (e->isRest() && toRest(e)->isGap())
                  continue;

            if (e->isStaffLines()) {
                  painter.save();
                  Staff* currentStaff = _score->staff(e->staffIdx());
                  Segment* parent = _score->tick2segmentMM(tick);

                  pos = QPointF (_offsetPanel, e->pagePos().y());
                  painter.translate(pos);

                  // Draw staff lines
                  StaffLines newStaffLines(*toStaffLines(e));
                  newStaffLines.setParent(parent);
                  newStaffLines.setTrack(e->track());
                  newStaffLines.layout();
                  newStaffLines.setColor(color);
                  newStaffLines.setWidth(bg.width());
                  newStaffLines.draw(&painter);

                  // Draw barline
                  BarLine barLine(_score);
                  barLine.setBarLineType(BarLineType::NORMAL);
                  barLine.setParent(parent);
                  barLine.setTrack(e->track());
                  barLine.setSpan(currentStaff->barLineSpan());
                  barLine.setSpanFrom(currentStaff->barLineFrom());
                  barLine.setSpanTo(currentStaff->barLineTo());
                  barLine.layout();
                  barLine.setColor(color);
                  barLine.draw(&painter);

                  // Draw the current staff name
                  QList<StaffName>& staffNamesLong = currentStaff->part()->instrument()->longNames();
                  QString staffName = staffNamesLong.isEmpty() ? " " : staffNamesLong[0].name();
                  if (staffName == "") {
                        QList<StaffName>& staffNamesShort = currentStaff->part()->instrument()->shortNames();
                        staffName = staffNamesShort.isEmpty() ? "" : staffNamesShort[0].name();
                        }

                  Text* newName = new Text(_score);
                  newName->setXmlText(staffName);
                  newName->setParent(parent);
                  newName->setTrack(e->track());
                  newName->setColor(color);
                  newName->textStyle().setFamily("FreeSans");
                  newName->textStyle().setSizeIsSpatiumDependent(true);
                  newName->layout();
                  newName->setPlainText(newName->plainText());
                  newName->layout();
                  if (currentStaff->part()->staff(0) == currentStaff) {
                        double _spatium = _score->spatium();
                        pos = QPointF (_score->styleP(StyleIdx::clefLeftMargin) + _widthClef, -_spatium * 2);
                        painter.translate(pos);
                        newName->draw(&painter);
                        painter.translate(-pos);
                        }
                  delete newName;

                  qreal posX = 0.0;

                  // Draw the current Clef
                  Clef clef(_score);
                  clef.setClefType(currentStaff->clef(tick));
                  clef.setParent(parent);
                  clef.setTrack(e->track());
                  clef.setColor(color);
                  clef.layout();
                  posX += _score->styleP(StyleIdx::clefLeftMargin);
                  clef.drawAt(&painter, QPointF(posX, clef.pos().y()));
                  posX += _widthClef;

                  // Draw the current KeySignature
                  KeySig newKs(_score);
                  newKs.setKeySigEvent(currentStaff->keySigEvent(tick));

                  // The Parent and the track must be set to have the key signature layout adjusted to different clefs
                  // This also adds naturals to the key signature (if set in the score style)
                  newKs.setParent(parent);
                  newKs.setTrack(e->track());
                  newKs.setColor(color);
                  newKs.setHideNaturals(true);
                  newKs.layout();
                  posX += _score->styleP(StyleIdx::keysigLeftMargin);
                  newKs.drawAt(&painter, QPointF(posX, 0.0));

                  posX += _widthKeySig + _xPosTimeSig;

                  // Draw the current TimeSignature
                  TimeSig newTs(_score);

                  // Try to get local time signature, if not, get the current measure one
                  TimeSig* currentTimeSig = currentStaff->timeSig(tick);
                  if (currentTimeSig) {
                        newTs.setFrom(currentTimeSig);
                        newTs.setParent(parent);
                        newTs.setTrack(e->track());
                        newTs.setColor(color);
                        newTs.layout();
                        posX += _score->styleP(StyleIdx::timesigLeftMargin);
                        newTs.drawAt(&painter, QPointF(posX, 0.0));
                        }
                  painter.restore();
                  }
            }
      painter.restore();
      _visible = true;
      }
Example #24
0
void Score::readStaff(XmlReader& e)
      {
      int staff = e.intAttribute("id", 1) - 1;
      int measureIdx = 0;
      e.setCurrentMeasureIndex(0);
      e.initTick(0);
      e.setTrack(staff * VOICES);

      if (staff == 0) {
            while (e.readNextStartElement()) {
                  const QStringRef& tag(e.name());

                  if (tag == "Measure") {
                        Measure* measure = 0;
                        measure = new Measure(this);
                        measure->setTick(e.tick());
                        e.setCurrentMeasureIndex(measureIdx++);
                        //
                        // inherit timesig from previous measure
                        //
                        Measure* m = e.lastMeasure(); // measure->prevMeasure();
                        Fraction f(m ? m->timesig() : Fraction(4,4));
                        measure->setLen(f);
                        measure->setTimesig(f);

                        measure->read(e, staff);
                        measure->checkMeasure(staff);
                        if (!measure->isMMRest()) {
                              measures()->add(measure);
                              e.setLastMeasure(measure);
                              e.initTick(measure->tick() + measure->ticks());
                              }
                        else {
                              // this is a multi measure rest
                              // always preceded by the first measure it replaces
                              Measure* m1 = e.lastMeasure();

                              if (m1) {
                                    m1->setMMRest(measure);
                                    measure->setTick(m1->tick());
                                    }
                              }
                        }
                  else if (tag == "HBox" || tag == "VBox" || tag == "TBox" || tag == "FBox") {
                        MeasureBase* mb = toMeasureBase(Element::name2Element(tag, this));
                        mb->read(e);
                        mb->setTick(e.tick());
                        measures()->add(mb);
                        }
                  else if (tag == "tick")
                        e.initTick(fileDivision(e.readInt()));
                  else
                        e.unknown();
                  }
            }
      else {
            Measure* measure = firstMeasure();
            while (e.readNextStartElement()) {
                  const QStringRef& tag(e.name());

                  if (tag == "Measure") {
                        if (measure == 0) {
                              qDebug("Score::readStaff(): missing measure!");
                              measure = new Measure(this);
                              measure->setTick(e.tick());
                              measures()->add(measure);
                              }
                        e.initTick(measure->tick());
                        e.setCurrentMeasureIndex(measureIdx++);
                        measure->read(e, staff);
                        measure->checkMeasure(staff);
                        if (measure->isMMRest())
                              measure = e.lastMeasure()->nextMeasure();
                        else {
                              e.setLastMeasure(measure);
                              if (measure->mmRest())
                                    measure = measure->mmRest();
                              else
                                    measure = measure->nextMeasure();
                              }
                        }
                  else if (tag == "tick")
                        e.initTick(fileDivision(e.readInt()));
                  else
                        e.unknown();
                  }
            }
      }
void InfoShape::draw(const DrawBuf &buf) const
 {
  if( !pane ) return;

  Smooth::DrawArt art(buf);

  VColor text=enable?+cfg.text:+cfg.inactive;

  Point space=+cfg.space;

  // decor

  {
   MPane p(pane);

   MCoord width=+cfg.width;
   MCoord dx=Fraction(space.x)-width;
   MCoord dy=Fraction(space.y)-width;

   if( focus )
     {
      FigureBox fig(p.shrink(Fraction(space.x)/2,Fraction(space.y)/2));

      fig.loop(art,width,+cfg.focus);
     }

   if( xoff>0 )
     {
      FigureLeftMark fig(p,dx);

      fig.solid(art,text);
     }

   if( xoff<xoffMax )
     {
      FigureRightMark fig(p,dx);

      fig.solid(art,text);
     }

   if( yoff>0 )
     {
      FigureUpMark fig(p,dy);

      fig.solid(art,text);
     }

   if( yoff<yoffMax )
     {
      FigureDownMark fig(p,dy);

      fig.solid(art,text);
     }
  }

  // text

  {
   Pane inner=pane.shrink(space);

   if( !inner ) return;

   ulen count=info->getLineCount();
   ulen index=yoff;

   Font font=cfg.font.get();

   FontSize fs=font->getSize();

   DrawBuf tbuf=buf.cutRebase(inner);

   Pane row(-xoff,0,IntAdd(xoff,inner.dx),fs.dy);

   for(; index<count && row.y+row.dy<=inner.dy ;index++,row.y+=row.dy)
     {
      font->text(tbuf,row,TextPlace(AlignX_Left,AlignY_Top),info->getLine(index),text);
     }
  }
 }
void ButtonShape::draw(const DrawBuf &buf) const
 {
  MPane p(pane);

  if( !p ) return;

  Smooth::DrawArt art(buf);

  Font font=cfg.font.get();

  // figure

  MCoord width=+cfg.width;

  FontSize fs=font->getSize();

  MCoord ex=(Fraction(fs.dy)+2*width)/4;

  FigureButton fig(p,ex);

  VColor bottom=+cfg.bottom;

  // body

  if( down )
    {
     fig.curveSolid(art,bottom);
    }
  else
    {
     VColor top;

     if( mover && enable )
       top=+cfg.topUp;
     else
       top=+cfg.top;

     fig.curveSolid(art,TwoField(p.getTopLeft(),top,p.getBottomLeft(),bottom));
    }

  // text

  {
   Coord dx=RoundUpLen(ex);
   Coord dy=RoundUpLen(width);

   Point shift=Null;

   if( down ) shift=Point::Diag( (dy+1)/2 );

   VColor text=enable?+cfg.text:bottom;

   font->text(buf,pane.shrink(dx,dy)+shift,TextPlace(AlignX_Center,AlignY_Center),Range(face),text);
  }

  // border

  {
   VColor border;

   if( focus )
     {
      border=+cfg.focus;
     }
   else
     {
      if( enable )
        border=+cfg.border;
      else
        border=bottom;
     }

   fig.curveLoop(art,HalfPos,width,border);
  }
 }
Fraction operator/(const Fraction &l, const Fraction &r)
{
    return Fraction(l.n*r.d, l.d*r.n);
}
Fraction operator*(const Fraction &l, const Fraction &r)
{
    return Fraction(l.n*r.n, l.d*r.d);
}
Fraction operator-(const Fraction &l, const Fraction &r)
{
    return Fraction(l.n*r.d-r.n*l.d, l.d*r.d);
}
 Fraction operator-() const { return Fraction(-this->n, this->d); }