Esempio n. 1
0
void ScoreView::editKey(QKeyEvent* ev)
      {
      int key                         = ev->key();
      Qt::KeyboardModifiers modifiers = ev->modifiers();
      QString s                       = ev->text();

      if (MScore::debugMode)
            qDebug("keyPressEvent key 0x%02x(%c) mod 0x%04x <%s>\n",
               key, key, int(modifiers), qPrintable(s));

      if (!editObject)
            return;

      if (editObject->type() == Element::LYRICS) {
            if (editKeyLyrics(ev)) {
                  ev->accept();
                  return;
                  }
            }
      else if (editObject->type() == Element::HARMONY) {
/*
            if (key == Qt::Key_Tab || key == Qt::Key_Backtab) {
                  harmonyTab(key == Qt::Key_Backtab ? true : (modifiers & Qt::ShiftModifier));
                  ev->accept();
                  return;
                  }
*/
            if (key == Qt::Key_Space && !(modifiers & CONTROL_MODIFIER)) {
                  harmonyBeatsTab(true, modifiers & Qt::ShiftModifier);
                  ev->accept();
                  return;
                  }
/*
            if (key == Qt::Key_Semicolon || key == Qt::Key_Colon) {
                  harmonyBeatsTab(false, key == Qt::Key_Colon);
                  ev->accept();
                  return;
                  }
            if (key >= Qt::Key_1 && key <= Qt::Key_9 && (modifiers & CONTROL_MODIFIER)) {
                  int ticks = (MScore::division >> 4) << (key - Qt::Key_1);
                  harmonyTicksTab(ticks);
                  ev->accept();
                  return;
                  }
*/
            }
      else if (editObject->type() == Element::FIGURED_BASS) {
            int found = false;
            if (key == Qt::Key_Space && !(modifiers & CONTROL_MODIFIER)) {
                  figuredBassTab(false, modifiers & Qt::ShiftModifier);
                  found = true;
                  }
            /*
            if (key == Qt::Key_Tab || key == Qt::Key_Backtab) {
                  figuredBassTab(true, key == Qt::Key_Backtab ? true : (modifiers & Qt::ShiftModifier) );
                  found = true;
                  }
            if (key >= Qt::Key_1 && key <= Qt::Key_9 && (modifiers & CONTROL_MODIFIER)) {
                  int ticks = (MScore::division >> 4) << (key - Qt::Key_1);
                  figuredBassTicksTab(ticks);
                  found = true;
                  }
*/
            if (found) {
                  ev->accept();
                  return;
                  }
            }

      if (!((modifiers & Qt::ShiftModifier) && (key == Qt::Key_Backtab))) {
            if (editObject->edit(this, curGrip, key, modifiers, s)) {
                  if (editObject->isText())
                        mscore->textTools()->updateTools();
                  updateGrips();
                  ev->accept();
                  _score->update();
                  mscore->endCmd();
                  return;
                  }
            if (editObject->isText() && (key == Qt::Key_Left || key == Qt::Key_Right)) {
                  ev->accept();
                  _score->end();
                  mscore->endCmd();
                  //return;
                  }
            }
      QPointF delta;
      qreal _spatium = editObject->spatium();

      qreal xval, yval;
      if (editObject->type() == Element::BEAM) {
            xval = 0.25 * _spatium;
            if (modifiers & Qt::ControlModifier)
                  xval = _spatium;
            else if (modifiers & Qt::AltModifier)
                  xval = 4 * _spatium;
            }
      else {
            xval = MScore::nudgeStep * _spatium;
            if (modifiers & Qt::ControlModifier)
                  xval = MScore::nudgeStep10 * _spatium;
            else if (modifiers & Qt::AltModifier)
                  xval = MScore::nudgeStep50 * _spatium;
            }
      yval = xval;

      if (mscore->vRaster()) {
            qreal vRaster = _spatium / MScore::vRaster();
            if (yval < vRaster)
                  yval = vRaster;
            }
      if (mscore->hRaster()) {
            qreal hRaster = _spatium / MScore::hRaster();
            if (xval < hRaster)
                  xval = hRaster;
            }
      // TODO: if raster, then xval/yval should be multiple of raster

      switch (key) {
            case Qt::Key_Left:
                  delta = QPointF(-xval, 0);
                  break;
            case Qt::Key_Right:
                  delta = QPointF(xval, 0);
                  break;
            case Qt::Key_Up:
                  delta = QPointF(0, -yval);
                  break;
            case Qt::Key_Down:
                  delta = QPointF(0, yval);
                  break;
            default:
                  ev->ignore();
                  return;
            }
      EditData ed;
      ed.curGrip = curGrip;
      ed.delta   = delta;
      ed.view    = this;
      ed.hRaster = mscore->hRaster();
      ed.vRaster = mscore->vRaster();
      if (curGrip >= 0)
            ed.pos = grip[curGrip].center() + delta;
      editObject->editDrag(ed);
      updateGrips();
      _score->update();
      mscore->endCmd();
      ev->accept();
      }
Esempio n. 2
0
void QEmitterNode::addRepresentation()
{	
    m_matResource = h3dAddResource(H3DResTypes::Material, qPrintable(m_xmlNode.attribute("material")), 0);

    // Load resource immediately since a later call to loadResourceFromDisk results in a bad behaviour of the Horde3D engine
    QString resourceName = h3dutGetResourcePath(H3DResTypes::Material);
    if( !resourceName.isEmpty() && !resourceName.endsWith('/') && !resourceName.endsWith('\\') )
        resourceName += '/';
    resourceName += m_xmlNode.attribute("material");

    QFile matFile(QFileInfo(resourceName).absoluteFilePath());
    if (!matFile.open(QIODevice::ReadOnly))
        qWarning("Error opening resource %s", qPrintable(m_xmlNode.attribute("material")));

    // Stupid return value, if false it can also be the case that the resource was loaded before instead of that their was an error



    h3dLoadResource(m_matResource, matFile.readAll().append('\0').constData(), matFile.size() + 1);
    matFile.close();

    m_effectResource = h3dAddResource(H3DResTypes::ParticleEffect, qPrintable(m_xmlNode.attribute("effect")), 0);

    // Load resource immediately since a later call to loadResourceFromDisk results in a bad behaviour of the Horde3D engine
    resourceName = h3dutGetResourcePath(H3DResTypes::ParticleEffect);
    if (!resourceName.isEmpty() && !resourceName.endsWith('/') && !resourceName.endsWith('\\'))
        resourceName += '/';
    resourceName += m_xmlNode.attribute("effect");

    QFile effectFile(QFileInfo(resourceName).absoluteFilePath());
    if (!effectFile.open(QIODevice::ReadOnly))
        qWarning("Error opening resource %s", qPrintable(m_xmlNode.attribute("effect")));

    // Stupid return value, if false it can also be the case that the resource was loaded before instead of that their was an error
    h3dLoadResource(m_effectResource, effectFile.readAll().append('\0').constData(), effectFile.size()+1);
    effectFile.close();

    QSceneNode* parentNode = static_cast<QSceneNode*>(parent());
    unsigned int rootID = parentNode ? parentNode->hordeId() : H3DRootNode;

    m_hordeID = h3dAddEmitterNode(
                    rootID,
                    qPrintable(m_xmlNode.attribute("name", "ATTENTION No Node Name")),
                    m_matResource,
                    m_effectResource,
                    m_xmlNode.attribute("maxCount").toUInt(),
                    m_xmlNode.attribute("respawnCount").toInt()
                    );
    h3dSetNodeParamStr(m_hordeID, H3DNodeParams::TagStr, qPrintable(m_xmlNode.attribute("tag", tr(""))));
    h3dSetNodeParamF(m_hordeID, H3DEmitter::ForceF3, 0, m_xmlNode.attribute("forceX", "0.0").toFloat());
    h3dSetNodeParamF(m_hordeID, H3DEmitter::ForceF3, 1, m_xmlNode.attribute("forceY", "0.0").toFloat());
    h3dSetNodeParamF(m_hordeID, H3DEmitter::ForceF3, 2, m_xmlNode.attribute("forceZ", "0.0").toFloat());
    h3dSetNodeParamF(m_hordeID, H3DEmitter::DelayF, 0, m_xmlNode.attribute("delay", "0.0").toFloat());
    h3dSetNodeParamF(m_hordeID, H3DEmitter::SpreadAngleF, 0, m_xmlNode.attribute("spreadAngle", "0.0").toFloat());
    h3dSetNodeParamF(m_hordeID, H3DEmitter::EmissionRateF, 0, m_xmlNode.attribute("emissionRate", "0.0").toFloat());

    // load transformation from file...
    float x, y, z, rx, ry, rz, sx, sy, sz;
    getTransformation(x,y,z,rx,ry,rz,sx,sy,sz);
    // ...and update scene representation
    h3dSetNodeTransform(m_hordeID, x, y, z, rx, ry, rz, sx, sy, sz);

    // Attachment
    QDomElement attachment = m_xmlNode.firstChildElement("Attachment");
    SceneTreeModel* model = static_cast<SceneTreeModel*>(m_model);
    AttachmentPlugIn* plugIn = model->nodeFactory()->attachmentPlugIn();
    if (!attachment.isNull() &&  plugIn != 0)
        plugIn->initNodeAttachment(this);

    startTimer(100);
}
Esempio n. 3
0
void ShaderParameterControl<ControlT, ParamT>::setParameterFromControls(
    QSharedPointer< Shader > shaderProgram )
{
  ParamT *values = new ParamT[ m_rows*m_cols ];

  unsigned short int i;
  for(i = 0; i < (m_rows*m_cols); i++)
  {
    values[ i ] = m_controls[ i ]->value();
  }

  // FIXME: change to glUniform[1,2,3,4][i,f][v](..)
  if(m_rows == 1)
  {
    shaderProgram->setUniformValue(qPrintable(m_info.identifier), values[0]);
  }
  else if(m_cols == 1 && m_rows == 2)
  {
    qreal valuesAsFloat[m_rows];
    for(unsigned int i = 0; i < m_rows; ++i)
    {
      valuesAsFloat[i] = values[i];
    }

    QVector2D vec2(valuesAsFloat[0], valuesAsFloat[1]);
    shaderProgram->setUniformValue(qPrintable(m_info.identifier), vec2);
  }
  else if(m_cols == 1 && m_rows == 3)
  {
    qreal valuesAsFloat[m_rows];
    for(unsigned int i = 0; i < m_rows; ++i)
    {
      valuesAsFloat[i] = values[i];
    }

    QVector3D vec3(valuesAsFloat[0], valuesAsFloat[1], valuesAsFloat[2]);
    shaderProgram->setUniformValue(qPrintable(m_info.identifier), vec3);
  }
  else if(m_cols == 1 && m_rows == 4)
  {
    qreal valuesAsFloat[m_rows];
    for(unsigned int i = 0; i < m_rows; ++i)
    {
      valuesAsFloat[i] = values[i];
    }

    QVector4D vec4(valuesAsFloat[0], valuesAsFloat[1], valuesAsFloat[2],
        valuesAsFloat[3]);
    shaderProgram->setUniformValue(qPrintable(m_info.identifier), vec4);
  }
  // FIXME: QGenericMatrix is row-major, isn't OpenGL column-major
  // FIXME: This case shall also handle vector-types, so look for conversion
  //        in annotatedglshaderprogram.*!
  else ifMatchesMatDimSetUniform(2,2)
  else ifMatchesMatDimSetUniform(2,3)
  else ifMatchesMatDimSetUniform(2,4)
  else ifMatchesMatDimSetUniform(3,2)
  else ifMatchesMatDimSetUniform(3,3)
  else ifMatchesMatDimSetUniform(3,4)
  else ifMatchesMatDimSetUniform(4,2)
  else ifMatchesMatDimSetUniform(4,3)
  else ifMatchesMatDimSetUniform(4,4)
  else
  {
    throw std::logic_error("This uniform-type is not supported yet!");
  }
}
Esempio n. 4
0
/// \brief initiate the ultracopier event dispatcher and check if no other session is running
DebugEngine::DebugEngine()
{
    quit=false;
    QStringList ultracopierArguments=QCoreApplication::arguments();
    if(ultracopierArguments.size()==2)
        if(ultracopierArguments.last()=="quit")
            quit=true;
    addDebugInformationCallNumber=0;
    //Load the first content
    debugHtmlContent+="<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">";
    debugHtmlContent+="<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\">";
    debugHtmlContent+="<head>";
    debugHtmlContent+="<meta name=\"Language\" content=\"en\" />";
    debugHtmlContent+="<meta http-equiv=\"content-language\" content=\"english\" />";
    debugHtmlContent+="<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />";
    debugHtmlContent+="<style type=\"text/css\">";
    debugHtmlContent+="body{font-family:\"DejaVu Sans Mono\";font-size:9pt;}";
    debugHtmlContent+=".Information td{color:#7485df;}";
    debugHtmlContent+=".Critical td{color:#ff0c00;background-color:#FFFE8C;}";
    debugHtmlContent+=".Warning td{color:#efa200;}";
    debugHtmlContent+=".Notice td{color:#999;}";
    debugHtmlContent+=".time{font-weight:bold;}";
    debugHtmlContent+=".Note{font-weight:bold;font-size:1.5em}";
    debugHtmlContent+=".function{font-style:italic;text-decoration:underline}";
    debugHtmlContent+=".location{padding-right:15px;}";
    debugHtmlContent+="td {white-space:nowrap;}";
    debugHtmlContent+="</style>";
    debugHtmlContent+="<title>";
    #ifdef ULTRACOPIER_MODE_SUPERCOPIER
    debugHtmlContent+="Supercopier";
    #else
    debugHtmlContent+="Ultracopier";
    #endif
    debugHtmlContent+=" "+QString(ULTRACOPIER_VERSION)+" "+QString(ULTRACOPIER_PLATFORM_NAME)+", debug report</title>";
    debugHtmlContent+="</head>";
    debugHtmlContent+="<body>";
    debugHtmlContent+="<table>";
    //Load the start time at now
    startTime.start();
    //Load the log file end
    endOfLogFile="</table></body></html>";
    //check if other instance is running, then switch to memory backend
    if(tryConnect())
    {
        ULTRACOPIER_DEBUGCONSOLE(DebugLevel_custom_Notice,"currentBackend: File because other session is runing");
        currentBackend=Memory;
        return;
    }
    //The lock and log file path is not defined
    bool fileNameIsLoaded=false;
    #ifdef ULTRACOPIER_VERSION_PORTABLE
        #ifdef ULTRACOPIER_VERSION_PORTABLEAPPS
            //Load the data folder path
            QDir dir(QCoreApplication::applicationDirPath());
            dir.cdUp();
            dir.cdUp();
            dir.cd("Data");
            logFile.setFileName(dir.absolutePath()+QDir::separator()+"log.html");
            lockFile.setFileName(dir.absolutePath()+QDir::separator()+"ultracopier.lock");
            fileNameIsLoaded=true;
        #else
            //Load the ultracopier path
            QDir dir(QCoreApplication::applicationDirPath());
            logFile.setFileName(dir.absolutePath()+QDir::separator()+"log.html");
            lockFile.setFileName(dir.absolutePath()+QDir::separator()+"ultracopier.lock");
            fileNameIsLoaded=true;
        #endif
    #else
        #ifdef Q_OS_WIN32
            #define EXTRA_HOME_PATH "\\ultracopier\\"
        #else
            #define EXTRA_HOME_PATH "/.config/Ultracopier/"
        #endif
        //Load the user path only if exists and writable
        QDir dir(QDir::homePath()+EXTRA_HOME_PATH);
        bool errorFound=false;
        //If user's directory not exists create it
        if(!dir.exists())
        {
            //If failed not load the file
            if(!dir.mkpath(dir.absolutePath()))
            {
                errorFound=true;
                puts(qPrintable("Unable to make path: "+dir.absolutePath()+", disable file log"));
            }
        }
        //If no error found set the file name
        if(errorFound==false)
        {
            fileNameIsLoaded=true;
            logFile.setFileName(dir.absolutePath()+QDir::separator()+"log.html");
            lockFile.setFileName(dir.absolutePath()+QDir::separator()+"ultracopier.lock");
        }
        errorFound=false;
    #endif
    //If the file name is loaded
    if(fileNameIsLoaded)
    {
        //If the previous file is here, then crash previous, ask if the user want to save
        if(lockFile.exists() && logFile.exists() && !quit)
        {
            //Try open the file as read only to propose save it as the user
            //Don't ask it if unable to write, because unable to remove, then alert at all start
            if(removeTheLockFile())
            {
                //Ask to the user
                QMessageBox::StandardButton reply = QMessageBox::question(NULL,"Save the previous report",
                                                                              #ifdef ULTRACOPIER_MODE_SUPERCOPIER
                                                                              QString("Supercopier")+
                                                                              #else
                                                                              QString("Ultracopier")+
                                                                              #endif
                        " seam have crashed, do you want save the previous report for report it to the forum?",QMessageBox::Yes|QMessageBox::No,QMessageBox::No);
                if(reply==QMessageBox::Yes)
                    saveBugReport();
            }
            else
                puts(qPrintable(logFile.fileName()+" unable to open it as read"));
        }
        //Now try to create and open the log file and lock file
        if(!lockFile.open(QIODevice::WriteOnly|QIODevice::Truncate|QIODevice::Unbuffered))
        {
            currentBackend=Memory;
            puts(qPrintable(lockFile.fileName()+" unable to open it as write, log into file disabled"));
        }
        else
        {
            if(!logFile.open(QIODevice::ReadWrite|QIODevice::Truncate|QIODevice::Unbuffered))
            {
                currentBackend=Memory;
                puts(qPrintable(logFile.fileName()+" unable to open it as write, log into file disabled"));
                removeTheLockFile();
            }
            else
            {
                logFile.resize(0);
                currentBackend=File;
                logFile.write(debugHtmlContent.toUtf8());
            }
        }
    }
}
Esempio n. 5
0
// the value of pkgitem_name differs from the version in createdbobj.cpp
int CreateFunction::upsertPkgItem(const int pkgheadid,
                                  const QMap<QString, int> oldoids,
                                  const QString argtypes, const int itemid,
                                  QString &errMsg)
{
  if (DEBUG)
    qDebug("CreateFunction::upsertPkgItem(%d, QMap, %s, %d, &errMsg)",
           pkgheadid, qPrintable(argtypes), itemid);

  if (pkgheadid < 0)
    return 0;

  int pkgitemid = -1;

  QSqlQuery select;
  select.prepare("SELECT pkgitem_id "
                 "FROM pkgitem "
                 "WHERE ((pkgitem_pkghead_id=:headid)"
                 "  AND  (pkgitem_type=:type)"
                 "  AND  (pkgitem_item_id=:id));");
  select.bindValue(":headid", pkgheadid);
  select.bindValue(":type",  _pkgitemtype);
  select.bindValue(":id",    oldoids.value(argtypes));
  select.exec();
  if (select.first())
    pkgitemid = select.value(0).toInt();
  if (select.lastError().type() != QSqlError::NoError)
  {
    errMsg = _sqlerrtxt.arg(_filename)
                      .arg(select.lastError().databaseText())
                      .arg(select.lastError().driverText());
    return -20;
  }

  QSqlQuery upsert;

  if (pkgitemid >= 0)
    upsert.prepare("UPDATE pkgitem SET pkgitem_descrip=:descrip,"
                   "       pkgitem_item_id=:itemid "
                   "WHERE (pkgitem_id=:id);");
  else
  {
    upsert.exec("SELECT NEXTVAL('pkgitem_pkgitem_id_seq');");
    if (upsert.first())
      pkgitemid = upsert.value(0).toInt();
    else if (upsert.lastError().type() != QSqlError::NoError)
    {
      QSqlError err = upsert.lastError();
      errMsg = _sqlerrtxt.arg(_name).arg(err.driverText()).arg(err.databaseText());
      return -21;
    }
    upsert.prepare("INSERT INTO pkgitem ("
                   "    pkgitem_id, pkgitem_pkghead_id, pkgitem_type,"
                   "    pkgitem_item_id, pkgitem_name, pkgitem_descrip"
                   ") VALUES ("
                   "    :id, :headid, :type,"
                   "    :itemid, :name, :descrip);");
  }

  upsert.bindValue(":id",      pkgitemid);
  upsert.bindValue(":headid",  pkgheadid);
  upsert.bindValue(":type",    _pkgitemtype);
  upsert.bindValue(":itemid",  itemid);
  upsert.bindValue(":name",    _name + "(" + argtypes + ")");
  upsert.bindValue(":descrip", _comment);

  if (!upsert.exec())
  {
    QSqlError err = upsert.lastError();
    errMsg = _sqlerrtxt.arg(_name).arg(err.driverText()).arg(err.databaseText());
    return -22;
  }

  return pkgitemid;
}
Esempio n. 6
0
void TextBase::paste(EditData& ed)
      {
      QString txt = QApplication::clipboard()->text(QClipboard::Clipboard);
      if (MScore::debugMode)
            qDebug("<%s>", qPrintable(txt));

      int state = 0;
      QString token;
      QString sym;
      bool symState = false;

      score()->startCmd();
      for (int i = 0; i < txt.length(); i++ ) {
            QChar c = txt[i];
            if (state == 0) {
                  if (c == '<') {
                        state = 1;
                        token.clear();
                        }
                  else if (c == '&') {
                        state = 2;
                        token.clear();
                        }
                  else {
                        if (symState)
                              sym += c;
                        else {
                              deleteSelectedText(ed);
                              if (c.isHighSurrogate()) {
                                    QChar highSurrogate = c;
                                    Q_ASSERT(i + 1 < txt.length());
                                    i++;
                                    QChar lowSurrogate = txt[i];
                                    insertText(ed, QString(QChar::surrogateToUcs4(highSurrogate, lowSurrogate)));
                                    }
                              else {
                                    insertText(ed, QString(QChar(c.unicode())));
                                    }
                              }
                        }
                  }
            else if (state == 1) {
                  if (c == '>') {
                        state = 0;
                        if (token == "sym") {
                              symState = true;
                              sym.clear();
                              }
                        else if (token == "/sym") {
                              symState = false;
                              insertSym(ed, Sym::name2id(sym));
                              }
                        }
                  else
                        token += c;
                  }
            else if (state == 2) {
                  if (c == ';') {
                        state = 0;
                        if (token == "lt")
                              insertText(ed, "<");
                        else if (token == "gt")
                              insertText(ed, ">");
                        else if (token == "amp")
                              insertText(ed, "&");
                        else if (token == "quot")
                              insertText(ed, "\"");
                        else
                              insertSym(ed, Sym::name2id(token));
                        }
                  else if (!c.isLetter()) {
                        state = 0;
                        insertText(ed, "&");
                        insertText(ed, token);
                        insertText(ed, c);
                        }
                  else
                        token += c;
                  }
            }
      if (state == 2) {
            insertText(ed, "&");
            insertText(ed, token);
            }
      score()->endCmd();
      }
Esempio n. 7
0
/*!
	\brief Reset the subcontrols to reflect the data of the format scheme being edited

	The name can be a bit misleading at first, it has been chosen
	because it directly maps to the effect a "cancel" button would
	have on the widget
*/
void QFormatConfig::cancel()
{
	m_table->clearContents();

	QTime T; T.start();
	QFontDatabase database;
	QStringList fonts = database.families();
	fonts.insert(0, tr("<default>"));
	
	if ( m_currentScheme )
	{
		if (m_categories.isEmpty()) {
			QList<QString> &temp=addCategory("");
			for ( int i = 0; i < m_currentScheme->formatCount(); i++ )
				temp.append(m_currentScheme->id(i));
		}


		int n = 0;
		foreach ( const QList<QString> c, m_categories)
			n+=c.size();
		n+=m_categories.size()-1;
		m_table->setRowCount(n);

		int r = 0;
		for ( int c = 0; c < m_categories.size(); c++ ) {
			if (c!=0) {
				m_table->setItem(r, 0, new QTableWidgetItem());
				m_table->setSpan(r++, 0, 1, 13);
			}
			QTableWidgetItem *item = new QTableWidgetItem(m_categories[c][0]);
			QFont f = item->font(); f.setBold(true); item->setFont(f); item->setBackground(QApplication::palette().mid());
			m_table->setItem(r, 0, item);
			m_table->setSpan(r++, 0, 1, 13);

			for ( int f = 1; f < m_categories[c].size(); f++ ) {
				QString fid = m_categories[c][f];
				const QFormat& fmt = m_currentScheme->format(fid);

				QTableWidgetItem *item;

				item = new QTableWidgetItem(tr(qPrintable(fid)));
				item->setData(Qt::UserRole, fid);
				item->setFlags(Qt::ItemIsEnabled);
				m_table->setItem(r, 0, item);

				item = new QTableWidgetItem;
				item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsUserCheckable);
				item->setCheckState(fmt.weight == QFont::Bold ? Qt::Checked : Qt::Unchecked);
				item->setToolTip(m_table->horizontalHeaderItem(1)->toolTip());
				m_table->setItem(r, 1, item);

				item = new QTableWidgetItem;
				item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsUserCheckable);
				item->setCheckState(fmt.italic ? Qt::Checked : Qt::Unchecked);
				item->setToolTip(m_table->horizontalHeaderItem(2)->toolTip());
				m_table->setItem(r, 2, item);

				item = new QTableWidgetItem;
				item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsUserCheckable);
				item->setCheckState(fmt.underline ? Qt::Checked : Qt::Unchecked);
				item->setToolTip(m_table->horizontalHeaderItem(3)->toolTip());
				m_table->setItem(r, 3, item);

				item = new QTableWidgetItem;
				item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsUserCheckable);
				item->setCheckState(fmt.overline ? Qt::Checked : Qt::Unchecked);
				item->setToolTip(m_table->horizontalHeaderItem(4)->toolTip());
				m_table->setItem(r, 4, item);

				item = new QTableWidgetItem;
				item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsUserCheckable);
				item->setCheckState(fmt.strikeout ? Qt::Checked : Qt::Unchecked);
				item->setToolTip(m_table->horizontalHeaderItem(5)->toolTip());
				m_table->setItem(r, 5, item);

				item = new QTableWidgetItem;
				item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsUserCheckable);
				item->setCheckState(fmt.waveUnderline ? Qt::Checked : Qt::Unchecked);
				item->setToolTip(m_table->horizontalHeaderItem(6)->toolTip());
				m_table->setItem(r, 6, item);

				m_table->setCellWidget(r, 7, new QSimpleColorPicker(fmt.foreground));
				m_table->cellWidget(r, 7)->setToolTip(m_table->horizontalHeaderItem(7)->toolTip());
				//m_table->cellWidget(i, 7)->setMaximumSize(22, 22);

				m_table->setCellWidget(r, 8, new QSimpleColorPicker(fmt.background));
				m_table->cellWidget(r, 8)->setToolTip(m_table->horizontalHeaderItem(8)->toolTip());
				//m_table->cellWidget(i, 8)->setMaximumSize(22, 22);

				m_table->setCellWidget(r, 9, new QSimpleColorPicker(fmt.linescolor));
				m_table->cellWidget(r, 9)->setToolTip(m_table->horizontalHeaderItem(9)->toolTip());
				//m_table->cellWidget(i, 9)->setMaximumSize(22, 22);

				//item = new QTableWidgetItem;
				QFontComboBox *fcmb=new QFontComboBox();
				fcmb->insertItem(0, "<default>");
				int ind=fcmb->findText(fmt.fontFamily);
				if(ind>-1) fcmb->setCurrentIndex(ind);
				else fcmb->setCurrentIndex(0);
				//int ind=fcmb->findText(fmt.fontFamily);
				//if(ind>-1) fcmb->setCurrentIndex(ind);
				//else fcmb->setCurrentIndex(0);
				//QComboBox *fcmb=new QComboBox();
				//fcmb->addItems(fonts);
				//int ind=fcmb->findText(fmt.fontFamily);
				//if(ind>-1) fcmb->setCurrentIndex(ind);
				//else fcmb->setCurrentIndex(0);
				m_table->setCellWidget(r, 10, fcmb);
				fcmb->setToolTip(m_table->horizontalHeaderItem(10)->toolTip());

				QDoubleSpinBox* sb = new QDoubleSpinBox();
				sb->setMaximum(100000);
				sb->setMinimum(1);
				sb->setDecimals(0);
				sb->setSuffix("%");
				sb->setAlignment(Qt::AlignRight);
				sb->setFrame(false);
				double v = fmt.pointSize?100.0*fmt.pointSize/basePointSize:100;
				sb->setValue(v);
				sb->setToolTip(m_table->horizontalHeaderItem(11)->toolTip());
				m_table->setCellWidget(r, 11, sb);

				QSpinBox *psb = new QSpinBox();
				psb->setMaximum(100);
				psb->setMinimum(-1);
				psb->setAlignment(Qt::AlignRight);
				psb->setFrame(false);
				psb->setValue(fmt.priority);
				psb->setToolTip(m_table->horizontalHeaderItem(12)->toolTip());
				m_table->setCellWidget(r, 12, psb);
				r++;
			}
		}
	}

	m_table->resizeColumnsToContents();
	
	qDebug () << T.elapsed();
}
Esempio n. 8
0
MainWindow::MainWindow() : QMainWindow(0)
{
    readSettings();

    QString lang = getSettingsGeneralLanguage();
    qDebug("language: %s", qPrintable(lang));
    if(lang == "system")
        lang = QLocale::system().languageToString(QLocale::system().language()).toLower();

    //Load translations for the Embroidermodder 2 GUI
    QTranslator translatorEmb;
    translatorEmb.load("translations/" + lang + "/embroidermodder2_" + lang);
    qApp->installTranslator(&translatorEmb);

    //Load translations for the commands
    QTranslator translatorCmd;
    translatorCmd.load("translations/" + lang + "/commands_" + lang);
    qApp->installTranslator(&translatorCmd);

    //Load translations provided by Qt - this covers dialog buttons and other common things.
    QTranslator translatorQt;
    translatorQt.load("qt_" + QLocale::system().name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
    qApp->installTranslator(&translatorQt);

    //Init
    mainWin = this;
    //Menus
    fileMenu     = new QMenu(tr("&File"),     this);
    editMenu     = new QMenu(tr("&Edit"),     this);
    viewMenu     = new QMenu(tr("&View"),     this);
    settingsMenu = new QMenu(tr("&Settings"), this);
    windowMenu   = new QMenu(tr("&Window"),   this);
    helpMenu     = new QMenu(tr("&Help"),     this);
    //SubMenus
    recentMenu   = new QMenu(tr("Open &Recent"), this);
    zoomMenu     = new QMenu(tr("&Zoom"),        this);
    panMenu      = new QMenu(tr("&Pan"),         this);
    //Toolbars
    toolbarFile       = addToolBar(tr("File"));
    toolbarEdit       = addToolBar(tr("Edit"));
    toolbarView       = addToolBar(tr("View"));
    toolbarZoom       = addToolBar(tr("Zoom"));
    toolbarPan        = addToolBar(tr("Pan"));
    toolbarIcon       = addToolBar(tr("Icon"));
    toolbarHelp       = addToolBar(tr("Help"));
    toolbarLayer      = addToolBar(tr("Layer"));
    toolbarProperties = addToolBar(tr("Properties"));
    toolbarText       = addToolBar(tr("Text"));
    toolbarPrompt     = addToolBar(tr("Command Prompt"));
    //Selectors
    layerSelector      = new QComboBox(this);
    colorSelector      = new QComboBox(this);
    linetypeSelector   = new QComboBox(this);
    lineweightSelector = new QComboBox(this);
    textFontSelector   = new QFontComboBox(this);
    textSizeSelector   = new QComboBox(this);

    numOfDocs = 0;
    docIndex = 0;

    shiftKeyPressedState = false;

    setWindowIcon(QIcon("icons/" + getSettingsGeneralIconTheme() + "/" + "app" + ".png"));

    //create the mdiArea
    QFrame* vbox = new QFrame(this);
    QVBoxLayout* layout = new QVBoxLayout(vbox);
    layout->setMargin(0);
    vbox->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken);
    mdiArea = new MdiArea(this, vbox);
    mdiArea->useBackgroundLogo(getSettingsGeneralMdiBGUseLogo());
    mdiArea->useBackgroundTexture(getSettingsGeneralMdiBGUseTexture());
    mdiArea->useBackgroundColor(getSettingsGeneralMdiBGUseColor());
    mdiArea->setBackgroundLogo(getSettingsGeneralMdiBGLogo());
    mdiArea->setBackgroundTexture(getSettingsGeneralMdiBGTexture());
    mdiArea->setBackgroundColor(QColor(getSettingsGeneralMdiBGColor()));
    mdiArea->setViewMode(QMdiArea::TabbedView);
    mdiArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    mdiArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    mdiArea->setActivationOrder(QMdiArea::ActivationHistoryOrder);
    layout->addWidget(mdiArea);
    setCentralWidget(vbox);

    //create the Command Prompt
    prompt = new CmdPrompt(this);
    prompt->setFocus(Qt::OtherFocusReason);
    this->setFocusProxy(prompt);
    mdiArea->setFocusProxy(prompt);

    prompt->setPromptTextColor(QColor(getSettingsPromptTextColor()));
    prompt->setPromptBackgroundColor(QColor(getSettingsPromptBGColor()));

    connect(prompt, SIGNAL(startCommand(const QString&)), this, SLOT(runCommandMain(const QString&)));
    connect(prompt, SIGNAL(runCommand(const QString&, const QString&)), this, SLOT(runCommandPrompt(const QString&, const QString&)));

            connect(prompt, SIGNAL(deletePressed()),    this, SLOT(deletePressed()));
    //TODO: connect(prompt, SIGNAL(tabPressed()),       this, SLOT(someUnknownSlot()));
            connect(prompt, SIGNAL(escapePressed()),    this, SLOT(escapePressed()));
            connect(prompt, SIGNAL(F1Pressed()),        this, SLOT(help()));
    //TODO: connect(prompt, SIGNAL(F2Pressed()),        this, SLOT(floatHistory()));
    //TODO: connect(prompt, SIGNAL(F3Pressed()),        this, SLOT(toggleQSNAP()));
            connect(prompt, SIGNAL(F4Pressed()),        this, SLOT(toggleLwt())); //TODO: typically this is toggleTablet(), make F-Keys customizable thru settings
    //TODO: connect(prompt, SIGNAL(F5Pressed()),        this, SLOT(toggleISO()));
    //TODO: connect(prompt, SIGNAL(F6Pressed()),        this, SLOT(toggleCoords()));
            connect(prompt, SIGNAL(F7Pressed()),        this, SLOT(toggleGrid()));
    //TODO: connect(prompt, SIGNAL(F8Pressed()),        this, SLOT(toggleORTHO()));
    //TODO: connect(prompt, SIGNAL(F9Pressed()),        this, SLOT(toggleSNAP()));
    //TODO: connect(prompt, SIGNAL(F10Pressed()),       this, SLOT(togglePOLAR()));
    //TODO: connect(prompt, SIGNAL(F11Pressed()),       this, SLOT(toggleQTRACK()));
            connect(prompt, SIGNAL(F12Pressed()),       this, SLOT(toggleRuler()));
            connect(prompt, SIGNAL(cutPressed()),       this, SLOT(cut()));
            connect(prompt, SIGNAL(copyPressed()),      this, SLOT(copy()));
            connect(prompt, SIGNAL(pastePressed()),     this, SLOT(paste()));
            connect(prompt, SIGNAL(selectAllPressed()), this, SLOT(selectAll()));
            connect(prompt, SIGNAL(undoPressed()),      this, SLOT(undo()));
            connect(prompt, SIGNAL(redoPressed()),      this, SLOT(redo()));

            connect(prompt, SIGNAL(shiftPressed()),     this, SLOT(setShiftPressed()));
            connect(prompt, SIGNAL(shiftReleased()),    this, SLOT(setShiftReleased()));

    //create the Object Property Editor
    dockPropEdit = new PropertyEditor("icons/" + getSettingsGeneralIconTheme(), getSettingsSelectionModePickAdd(), prompt, this);
    addDockWidget(Qt::LeftDockWidgetArea, dockPropEdit);
    connect(dockPropEdit, SIGNAL(pickAddModeToggled()), this, SLOT(pickAddModeToggled()));

    //create the Command History Undo Editor
    dockUndoEdit = new UndoEditor("icons/" + getSettingsGeneralIconTheme(), prompt, this);
    addDockWidget(Qt::LeftDockWidgetArea, dockUndoEdit);

    //setDockOptions(QMainWindow::AnimatedDocks | QMainWindow::AllowTabbedDocks | QMainWindow::VerticalTabs); //TODO: Load these from settings
    //tabifyDockWidget(dockPropEdit, dockUndoEdit); //TODO: load this from settings

    //Javascript
    initMainWinPointer(this);

    engine = new QScriptEngine(this);
    engine->installTranslatorFunctions();
    debugger = new QScriptEngineDebugger(this);
    debugger->attachTo(engine);
    javaInitNatives(engine);

    //Load all commands in a loop
    QDir commandDir("commands");
    QStringList cmdList = commandDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
    foreach(QString cmdName, cmdList)
    {
        javaLoadCommand(cmdName);
    }
Esempio n. 9
0
void QQuickOpenGLShaderEffectCommon::updateShader(QQuickItem *item,
                                                  const QMetaObject *itemMetaObject,
                                                  Key::ShaderType shaderType)
{
    disconnectPropertySignals(item, shaderType);
    uniformData[shaderType].clear();
    clearSignalMappers(shaderType);
    if (shaderType == Key::VertexShader)
        attributes.clear();

    // A qrc or file URL means the shader source is to be read from the specified file.
    QUrl srcUrl(QString::fromUtf8(source.sourceCode[shaderType]));
    if (!srcUrl.scheme().compare(QLatin1String("qrc"), Qt::CaseInsensitive) || srcUrl.isLocalFile()) {
        if (!fileSelector) {
            fileSelector = new QFileSelector(item);
            // There may not be an OpenGL context accessible here. So rely on
            // the window's requestedFormat().
            if (item->window()
                    && item->window()->requestedFormat().profile() == QSurfaceFormat::CoreProfile) {
                fileSelector->setExtraSelectors(QStringList() << QStringLiteral("glslcore"));
            }
        }
        const QString fn = fileSelector->select(QQmlFile::urlToLocalFileOrQrc(srcUrl));
        QFile f(fn);
        if (f.open(QIODevice::ReadOnly | QIODevice::Text)) {
            source.sourceCode[shaderType] = f.readAll();
            f.close();
        } else {
            qWarning("ShaderEffect: Failed to read %s", qPrintable(fn));
            source.sourceCode[shaderType] = QByteArray();
        }
    }

    const QByteArray &code = source.sourceCode[shaderType];
    if (code.isEmpty()) {
        // Optimize for default code.
        if (shaderType == Key::VertexShader) {
            attributes.append(QByteArray(qtPositionAttributeName()));
            attributes.append(QByteArray(qtTexCoordAttributeName()));
            UniformData d;
            d.name = "qt_Matrix";
            d.specialType = UniformData::Matrix;
            uniformData[Key::VertexShader].append(d);
            signalMappers[Key::VertexShader].append(0);
        } else if (shaderType == Key::FragmentShader) {
            UniformData d;
            d.name = "qt_Opacity";
            d.specialType = UniformData::Opacity;
            uniformData[Key::FragmentShader].append(d);
            signalMappers[Key::FragmentShader].append(0);
            const int mappedId = 1 | (Key::FragmentShader << 16);
            auto mapper = new QtPrivate::MappedSlotObject([this, mappedId](){mappedPropertyChanged(mappedId);});
            const char *sourceName = "source";
            d.name = sourceName;
            d.setValueFromProperty(item, itemMetaObject);
            d.specialType = UniformData::Sampler;
            uniformData[Key::FragmentShader].append(d);
            signalMappers[Key::FragmentShader].append(mapper);
        }
    } else {
        lookThroughShaderCode(item, itemMetaObject, shaderType, code);
    }

    connectPropertySignals(item, itemMetaObject, shaderType);
}
Esempio n. 10
0
void TrkDevice::emitError(const QString &s)
{
    d->errorString = s;
    qWarning("%s\n", qPrintable(s));
    emit error(s);
}
void HttpRequestHandler::error(const QString &text, HttpResponse &response) const
{
    response.setHeader("Content-Type", qPrintable("text/plain"));
    response.write(text.toLocal8Bit());
}
Esempio n. 12
0
//see http://opencv.willowgarage.com/documentation/cpp/camera_calibration_and_3d_reconstruction.html
bool ccCalibratedImage::undistort()
{
	if (m_image.isNull())
		return false;

	//nothing to do
	if (m_k1==0 && m_k2==0)
		return true;

	float f2 = m_focal_pix*m_focal_pix;
	float cx = 0.5f*(float)m_width;
	float cy = 0.5f*(float)m_height;

	//look for optimal enlargement coeff
	float enlargeCoef = 1.0f;
	//{
	//	float lastrp = 0;
	//	const float c_stepSize = 0.01f;
	//	unsigned step=0;
	//	while (step<50)
	//	{
	//		enlargeCoef = 1.0f+c_stepSize*(float)step;
	//		float maxcx = 0.5f*enlargeCoef*(float)m_width;
	//		float maxcy = 0.5f*enlargeCoef*(float)m_height;
	//		float maxp2 = (maxcx*maxcx+maxcy*maxcy)/f2;
	//		float maxrp = 1.0f+maxp2*(m_k1+m_k2*maxp2);
	//		float eqx = maxrp * maxcx;
	//		float eqy = maxrp * maxcy;
	//		if ((int)eqx>=cx && (int)eqy>=cy)
	//			break;
	//		//something wrong!
	//		if (maxrp<lastrp)
	//		{
	//			if (step<2)
	//				return false;
	//			else
	//			{
	//				//step back
	//				enlargeCoef = 1.0f+c_stepSize*(float)(step-1);
	//				break;
	//			}
	//		}
	//		lastrp=maxrp;
	//		++step;
	//	}
	//}

	unsigned newWidth = (unsigned)(enlargeCoef*(float)m_width);
	unsigned newHeight = (unsigned)(enlargeCoef*(float)m_height);
	float newCx = 0.5f*(float)newWidth;
	float newCy = 0.5f*(float)newHeight;
	QImage image(QSize(newWidth,newHeight),m_image.format());
	image.fill(0);

	//image undistortion
	{
		for (unsigned i=0;i<newWidth;++i)
		{
			float x = (float)(i-newCx);
			float x2 = x*x;
			for (unsigned j=0;j<newHeight;++j)
			{
				float y = (float)(j-newCy);
				float y2 = y*y;

				float p2 = (x2+y2)/f2; //p = pix/f
				float rp = 1.0f+p2*(m_k1+p2*m_k2); //r(p) = 1.0 + k1 * ||p||^2 + k2 * ||p||^4
				float eqx = rp * x + cx;
				float eqy = rp * y + cy;

				int pixx=(int)eqx;
				int pixy=(int)eqy;
				if (pixx>=0 && pixx<(int)m_width && pixy>=0 && pixy<(int)m_height)
					image.setPixel(i,j,m_image.pixel(pixx,pixy));
			}
		}
	}

	//update image parameters
	m_image = image;
	m_width = newWidth;
	m_height = newHeight;
	//m_aspectRatio = (aspect ratio is not changed)
	m_k1 = m_k2 = 0;

	setName(qPrintable(QString(getName())+QString("_undistort")));

	return true;
}
Esempio n. 13
0
ccPointCloud* ccCalibratedImage::orthoRectifyAsCloud(CCLib::GenericIndexedCloud* keypoints3D, std::vector<KeyPoint>& keypointsImage) const
{
	double a[3],b[3],c[3];

	if (!computeOrthoRectificationParams(keypoints3D,keypointsImage,a,b,c))
		return 0;

	const double& a0 = a[0];
	const double& a1 = a[1];
	const double& a2 = a[2];
	const double& b0 = b[0];
	const double& b1 = b[1];
	const double& b2 = b[2];
	//const double& c0 = c[0];
	const double& c1 = c[1];
	const double& c2 = c[2];

	PointCoordinateType defaultZ = 0.0;

	ccPointCloud* proj = new ccPointCloud(qPrintable(QString("%1.ortho-rectified").arg(getName())));
	if (!proj->reserve(m_width*m_height))
	{
		delete proj;
		return 0;
	}

	if (!proj->reserveTheRGBTable())
	{
		delete proj;
		return 0;
	}
	proj->showColors(true);
	colorType C[3];

	unsigned realCount=0;

	//ortho rectification
	{
		for (unsigned pi = 0; pi<(unsigned)m_width; ++pi)
		{
			double xi = (double)pi-0.5*(double)m_width;
			for (unsigned pj = 0; pj<(unsigned)m_height; ++pj)
			{
				double yi = (double)pj-0.5*(double)m_height;
				double qi = (1.0+c1*xi+c2*yi);
				CCVector3 P((a0+a1*xi+a2*yi)/qi,
							(b0+b1*xi+b2*yi)/qi,
							defaultZ);

				//and color?
				QRgb rgb = m_image.pixel(pi,pj);
				C[0]=qRed(rgb);
				C[1]=qGreen(rgb);
				C[2]=qBlue(rgb);
				if ((int)C[0]+(int)C[1]+(int)C[2]>0)
				{
					//add point
					proj->addPoint(P);
					//and color
					proj->addRGBColor(C);
					++realCount;
				}
			}
		}
	}

	if (realCount==0)
	{
		delete proj;
		proj=0;
	}
	else
	{
		proj->resize(realCount);
	}

	return proj;
}
Esempio n. 14
0
bool KisExifIO::saveTo(KisMetaData::Store* store, QIODevice* ioDevice, HeaderType headerType) const
{
    ioDevice->open(QIODevice::WriteOnly);
    Exiv2::ExifData exifData;
    if (headerType == KisMetaData::IOBackend::JpegHeader) {
        QByteArray header(6, 0);
        header[0] = 0x45;
        header[1] = 0x78;
        header[2] = 0x69;
        header[3] = 0x66;
        header[4] = 0x00;
        header[5] = 0x00;
        ioDevice->write(header);
    }

    for (QHash<QString, KisMetaData::Entry>::const_iterator it = store->begin();
            it != store->end(); ++it) {
        try {
            const KisMetaData::Entry& entry = *it;
            dbgFile << "Trying to save: " << entry.name() << " of " << entry.schema()->prefix() << ":" << entry.schema()->uri();
            QString exivKey;
            if (entry.schema()->uri() == KisMetaData::Schema::TIFFSchemaUri) {
                exivKey = "Exif.Image." + entry.name();
            } else if (entry.schema()->uri() == KisMetaData::Schema::EXIFSchemaUri) { // Distinguish between exif and gps
                if (entry.name().left(3) == "GPS") {
                    exivKey = "Exif.GPS." + entry.name();
                } else {
                    exivKey = "Exif.Photo." + entry.name();
                }
            } else if (entry.schema()->uri() == KisMetaData::Schema::DublinCoreSchemaUri) {
                if (entry.name() == "description") {
                    exivKey = "Exif.Image.ImageDescription";
                } else if (entry.name() == "creator") {
                    exivKey = "Exif.Image.Artist";
                } else if (entry.name() == "rights") {
                    exivKey = "Exif.Image.Copyright";
                }
            } else if (entry.schema()->uri() == KisMetaData::Schema::XMPSchemaUri) {
                if (entry.name() == "ModifyDate") {
                    exivKey = "Exif.Image.DateTime";
                } else if (entry.name() == "CreatorTool") {
                    exivKey = "Exif.Image.Software";
                }
            } else if (entry.schema()->uri() == KisMetaData::Schema::MakerNoteSchemaUri) {
                if (entry.name() == "RawData") {
                    exivKey = "Exif.Photo.MakerNote";
                }
            }
            dbgFile << "Saving " << entry.name() << " to " << exivKey;
            if (exivKey.isEmpty()) {
                dbgFile << entry.qualifiedName() << " is unsavable to EXIF";
            } else {
                Exiv2::ExifKey exifKey(qPrintable(exivKey));
                Exiv2::Value* v = 0;
                if (exivKey == "Exif.Photo.ExifVersion" || exivKey == "Exif.Photo.FlashpixVersion") {
                    v = kmdValueToExifVersion(entry.value());
                } else if (exivKey == "Exif.Photo.FileSource") {
                    char s[] = { 0x03 };
                    v = new Exiv2::DataValue((const Exiv2::byte*)s, 1);
                } else if (exivKey == "Exif.Photo.SceneType") {
                    char s[] = { 0x01 };
                    v = new Exiv2::DataValue((const Exiv2::byte*)s, 1);
                } else if (exivKey == "Exif.Photo.ComponentsConfiguration") {
                    v = kmdIntOrderedArrayToExifArray(entry.value());
                } else if (exivKey == "Exif.Image.Artist") { // load as dc:creator
                    KisMetaData::Value creator = entry.value().asArray()[0];
#if EXIV2_MAJOR_VERSION == 0 && EXIV2_MINOR_VERSION <= 20
                    v = kmdValueToExivValue(creator, Exiv2::ExifTags::tagType(exifKey.tag(), exifKey.ifdId()));
#else
                    v = kmdValueToExivValue(creator, exifKey.defaultTypeId());
#endif
                } else if (exivKey == "Exif.Photo.OECF") {
                    v = kmdOECFStructureToExifOECF(entry.value());
                } else if (exivKey == "Exif.Photo.DeviceSettingDescription") {
                    v = deviceSettingDescriptionKMDToExif(entry.value());
                } else if (exivKey == "Exif.Photo.CFAPattern") {
                    v = cfaPatternKMDToExif(entry.value());
                } else if (exivKey == "Exif.Photo.Flash") {
                    v = flashKMDToExif(entry.value());
                } else if (exivKey == "Exif.Photo.UserComment") {
                    Q_ASSERT(entry.value().type() == KisMetaData::Value::LangArray);
                    QMap<QString, KisMetaData::Value> langArr = entry.value().asLangArray();
                    if (langArr.contains("x-default")) {
#if EXIV2_MAJOR_VERSION == 0 && EXIV2_MINOR_VERSION <= 20
                        v = kmdValueToExivValue(langArr.value("x-default"), Exiv2::ExifTags::tagType(exifKey.tag(), exifKey.ifdId()));
#else
                        v = kmdValueToExivValue(langArr.value("x-default"), exifKey.defaultTypeId());
#endif
                    } else if (langArr.size() > 0) {
#if EXIV2_MAJOR_VERSION == 0 && EXIV2_MINOR_VERSION <= 20
                        v = kmdValueToExivValue(langArr.begin().value(), Exiv2::ExifTags::tagType(exifKey.tag(), exifKey.ifdId()));
#else
                        v = kmdValueToExivValue(langArr.begin().value(), exifKey.defaultTypeId());
#endif
                    }
                } else {
                    dbgFile << exifKey.tag();
#if EXIV2_MAJOR_VERSION == 0 && EXIV2_MINOR_VERSION <= 20
                    v = kmdValueToExivValue(entry.value(), Exiv2::ExifTags::tagType(exifKey.tag(), exifKey.ifdId()));
#else
                    v = kmdValueToExivValue(entry.value(), exifKey.defaultTypeId());
#endif
                }
                if (v && v->typeId() != Exiv2::invalidTypeId) {
                    dbgFile << "Saving key" << exivKey << " of KMD value" << entry.value();
                    exifData.add(exifKey, v);
                } else {
                    dbgFile << "No exif value was created for" << entry.qualifiedName() << " as" << exivKey;// << " of KMD value" << entry.value();
                }
            }
        } catch (Exiv2::AnyError& e) {
            dbgFile << "exiv error " << e.what();
        }
    }
#if EXIV2_MAJOR_VERSION == 0 && EXIV2_MINOR_VERSION <= 17
    Exiv2::DataBuf rawData = exifData.copy();
    ioDevice->write((const char*) rawData.pData_, rawData.size_);
#else
    Exiv2::Blob rawData;
    Exiv2::ExifParser::encode(rawData, Exiv2::littleEndian, exifData);
    ioDevice->write((const char*) &*rawData.begin(), rawData.size());
#endif
    ioDevice->close();
    return true;
}
Esempio n. 15
0
bool CeTcpSyncConnection::deleteDirectory(const QString &directory, bool recursive, bool failIfContentExists)
{
    QString cmd = ceTcpSyncProgram + " deleteDirectory \"" + directory + "\" " + boolToString(recursive) + " " + boolToString(failIfContentExists);
    return system(qPrintable(cmd)) == 0;
}
Esempio n. 16
0
bool SmtpClient::connectToHost()
{
    switch (connectionType)
    {
    case TlsConnection:
    case TcpConnection:
        socket->connectToHost(host, port);
        break;
    case SslConnection:
        ((QSslSocket*) socket)->connectToHostEncrypted(host, port);
        break;

    }

    // Tries to connect to server
    if (!socket->waitForConnected(connectionTimeout))
    {
        emit smtpError(ConnectionTimeoutError);
        return false;
    }

    try
    {
        // Wait for the server's response
        waitForResponse();

        // If the response code is not 220 (Service ready)
        // means that is something wrong with the server
        if (responseCode != 220)
        {
            emit smtpError(ServerError);
            return false;
        }

        // Send a EHLO/HELO message to the server
        // The client's first command must be EHLO/HELO
        sendMessage("EHLO " + name);

        // Wait for the server's response
        waitForResponse();

        // The response code needs to be 250.
        if (responseCode != 250) {
            emit smtpError(ServerError);
            return false;
        }

        if (connectionType == TlsConnection) {
            // send a request to start TLS handshake
            sendMessage("STARTTLS");

            // Wait for the server's response
            waitForResponse();

            // The response code needs to be 220.
            if (responseCode != 220) {
                emit smtpError(ServerError);
                return false;
            };

            ((QSslSocket*) socket)->startClientEncryption();

            if (!((QSslSocket*) socket)->waitForEncrypted(connectionTimeout)) {
                qDebug("%s", qPrintable( ((QSslSocket*) socket)->errorString()));
                emit SmtpError(ConnectionTimeoutError);
                return false;
            }

            // Send ELHO one more time
            sendMessage("EHLO " + name);

            // Wait for the server's response
            waitForResponse();

            // The response code needs to be 250.
            if (responseCode != 250) {
                emit smtpError(ServerError);
                return false;
            }
        }
    }
    catch (ResponseTimeoutException)
    {
        return false;
    }

    // If no errors occured the function returns true.
    return true;
}
Esempio n. 17
0
bool CeTcpSyncConnection::createDirectory(const QString &path, bool deleteBefore)
{
    QString cmd = ceTcpSyncProgram + " createDirectory \"" + path + "\" " + boolToString(deleteBefore);
    return system(qPrintable(cmd)) == 0;
}
int SplitStreamFileFormatReader::openFile(const QString& filename)
{
    // close existing files;
    closeFile();
    QFileInfo fileInfo(filename);
    QDir openDir;
    openDir.setPath(fileInfo.path());

    if(m_directory.exists())
    {
        if(!fileInfo.fileName().isEmpty() && m_knownDataTypes.contains(fileInfo.baseName(),Qt::CaseInsensitive))
        {
            m_primaryData = fileInfo.baseName().toLower();
            m_fileInformation = fileInfo;
        }

        std::vector<QFileInfo> fileLocations = FindValidFiles(openDir);
        std::vector<QFileInfo>::const_iterator fileIt;
        QString temp;
        bool successIndicator = false;
        int index = 0;
        unsigned int totalFrames = 0;
        QString success_msg;
        for (fileIt = fileLocations.begin(); fileIt != fileLocations.end(); ++fileIt)
        {
            temp = (*fileIt).baseName();
            index = m_knownDataTypes.indexOf(temp);
            successIndicator = m_fileReaders[index]->OpenFile((*fileIt).filePath().toStdString());

            if(successIndicator)
            {
                success_msg = QString("Successful! %1 Frames Found.").arg(m_fileReaders[index]->TotalFrames());
                m_available_data << m_knownDataTypes[index];
                m_open_files.push_back(*fileIt);
            }
            else success_msg = "Failed!";

            qDebug("Opening %s - %s", qPrintable((*fileIt).filePath()), qPrintable(success_msg));

            if((totalFrames == 0) || (totalFrames > m_fileReaders[index]->TotalFrames()))
            {
                totalFrames = m_fileReaders[index]->TotalFrames();
            }
        }
        m_totalFrames = totalFrames;
        m_directory = openDir;
    }
    if(m_totalFrames > 0)
    {
        m_fileGood = true;
        qDebug("Loading complete %d frames available.", m_totalFrames);
    }
    else
    {
        m_fileGood = false;
        qDebug("Loading Failed.");
        m_totalFrames = 0;
        m_available_data.clear();
        m_open_files.clear();
    }
    return m_totalFrames;
}
Esempio n. 19
0
MaraUpdaterApplication::MaraUpdaterApplication(int &argc, char **argv) : QApplication(argc, argv),
		_window(new MaraUpdaterWindow())
{
	//MaraTrace trace(__FUNCSIG__, this, __FILE__, __LINE__);

	_app = this;
	qInstallMsgHandler(qtMessageHandler);

	_executeCancelled = false;

	_autoRestart = false;
	_launchedFromTemp = false;

	QStringList args = arguments();

	for(QStringList::iterator ii = args.begin(); ii != args.end(); ++ii)
	{
		if((*ii).toLower() == "autorestart")
		{
			_autoRestart = true;
		}

		if((*ii) == "__TEMP_LAUNCHED__")
		{
			_launchedFromTemp = true;
		}
	}

	if(_launchedFromTemp)
	{
		//MaraTrace trace(__FUNCSIG__ ":TempLaunched", this, __FILE__, __LINE__);
		executeUpdate();
	}
	else
	{
		//MaraTrace trace(__FUNCSIG__ ":NotTempLaunched", this, __FILE__, __LINE__);
		QFileInfo exeFileInfo(QCoreApplication::applicationFilePath());
		QString tempPath = QDir::temp().filePath(exeFileInfo.fileName());
		QFile temp(tempPath);

		if(temp.exists() && !temp.remove())
		{
			QMessageBox::warning(0, "Error", QString("Error removing temp executable %1:\n%2\n\nUpdater will not be able to update itself.").arg(tempPath).arg(temp.errorString()));
			executeUpdate();
		}

		QFile exeFile(QCoreApplication::applicationFilePath());

		std::cout << "Copying self to " << qPrintable(tempPath) << "..." << std::flush;

		if(exeFile.copy(tempPath))
		{
			std::cout << "Success!" << std::flush;
			if(!QProcess::startDetached(tempPath, args << "__TEMP_LAUNCHED__"))
			{
				QMessageBox::critical(0, "Error", QString("Failed launching temp updater."));
			}
			_executeCancelled = true;
		}
		else
		{
			QMessageBox::warning(0, "Error", QString("Error copying to temp location %1:\n%2\n\nUpdater will not be able to update itself.").arg(tempPath).arg(exeFile.errorString()));
			executeUpdate();
		}
	}
}
Esempio n. 20
0
bool CeTcpSyncConnection::copyFileFromDevice(const QString &deviceSource, const QString &localDest, bool failIfExists)
{
    QString cmd = ceTcpSyncProgram + " copyFileFromDevice \"" + deviceSource + "\" \"" + localDest + "\" " + boolToString(failIfExists);
    return system(qPrintable(cmd)) == 0;
}
Esempio n. 21
0
/// \brief For add message info, this function is thread safe
void DebugEngine::addDebugInformation(const DebugLevel_custom &level,const QString& function,const QString& text,QString file,const int& ligne,const QString& location)
{
    if(DebugEngine::debugEngine==NULL)
    {
        qWarning() << "After close: " << function << file << ligne;
        return;
    }
    //Remove the compiler extra patch generated
    file=file.remove(QRegularExpression("\\.\\.?[/\\\\]([^/]+[/\\\\])?"));
    QString addDebugInformation_lignestring=QString::number(ligne);
    QString addDebugInformation_fileString=file;
    if(ligne!=-1)
        addDebugInformation_fileString+=":"+addDebugInformation_lignestring;
    //Load the time from start
    QString addDebugInformation_time = QString::number(startTime.elapsed());
    QString addDebugInformation_htmlFormat;
    bool important=true;
    switch(level)
    {
        case DebugLevel_custom_Information:
            addDebugInformation_htmlFormat="<tr class=\"Information\"><td class=\"time\">"+addDebugInformation_time+"</span></td><td>"+addDebugInformation_fileString+"</td><td class=\"function\">"+function+"()</td><td class=\"location\">"+location+"</td><td>"+htmlEntities(text)+"</td></tr>\n";
        break;
        case DebugLevel_custom_Critical:
            addDebugInformation_htmlFormat="<tr class=\"Critical\"><td class=\"time\">"+addDebugInformation_time+"</span></td><td>"+addDebugInformation_fileString+"</td><td class=\"function\">"+function+"()</td><td class=\"location\">"+location+"</td><td>"+htmlEntities(text)+"</td></tr>\n";
        break;
        case DebugLevel_custom_Warning:
            addDebugInformation_htmlFormat="<tr class=\"Warning\"><td class=\"time\">"+addDebugInformation_time+"</span></td><td>"+addDebugInformation_fileString+"</td><td class=\"function\">"+function+"()</td><td class=\"location\">"+location+"</td><td>"+htmlEntities(text)+"</td></tr>\n";
        break;
        case DebugLevel_custom_Notice:
        {
            addDebugInformation_htmlFormat="<tr class=\"Notice\"><td class=\"time\">"+addDebugInformation_time+"</span></td><td>"+addDebugInformation_fileString+"</td><td class=\"function\">"+function+"()</td><td class=\"location\">"+location+"</td><td>"+htmlEntities(text)+"</td></tr>\n";
            important=false;
        }
        break;
        case DebugLevel_custom_UserNote:
            addDebugInformation_htmlFormat="<tr class=\"Note\"><td class=\"time\">"+addDebugInformation_time+"</span></td><td>"+addDebugInformation_fileString+"</td><td class=\"function\">"+function+"()</td><td class=\"location\">"+location+"</td><td>"+htmlEntities(text)+"</td></tr>\n";
        break;
    }
    //To prevent access of string in multi-thread
    {
        //Show the text in console
        QString addDebugInformation_textFormat;
        addDebugInformation_textFormat = "("+addDebugInformation_time.rightJustified(8,' ')+") ";
        if(file!="" && ligne!=-1)
            addDebugInformation_textFormat += file+":"+addDebugInformation_lignestring+":";
        addDebugInformation_textFormat += function+"(), (location: "+location+"): "+text;
        QMutexLocker lock_mutex(&mutex);
        if(currentBackend==File)
        {
            if(logFile.size()<ULTRACOPIER_DEBUG_MAX_ALL_SIZE*1024*1024 || (important && logFile.size()<ULTRACOPIER_DEBUG_MAX_IMPORTANT_SIZE*1024*1024))
            {
                puts(qPrintable(addDebugInformation_textFormat));
                logFile.write(addDebugInformation_htmlFormat.toUtf8());
            }
        }
        else
        {
            if(debugHtmlContent.size()<ULTRACOPIER_DEBUG_MAX_ALL_SIZE*1024*1024 || (important && debugHtmlContent.size()<ULTRACOPIER_DEBUG_MAX_IMPORTANT_SIZE*1024*1024))
            {
                puts(qPrintable(addDebugInformation_textFormat));
                debugHtmlContent+=addDebugInformation_htmlFormat;
            }
        }
        //Send the new line
        if(addDebugInformationCallNumber<ULTRACOPIER_DEBUG_MAX_GUI_LINE)
        {
            addDebugInformationCallNumber++;
            DebugModel::debugModel->addDebugInformation(startTime.elapsed(),level,function,text,file,ligne,location);
        }
    }
}
Esempio n. 22
0
bool CeTcpSyncConnection::copyDirectoryFromDevice(const QString &deviceSource, const QString &localDest, bool recursive)
{
    QString cmd = ceTcpSyncProgram + " copyDirectoryFromDevice \"" + deviceSource + "\" \"" + localDest + "\" " + boolToString(recursive);
    return system(qPrintable(cmd)) == 0;
}
Esempio n. 23
0
EditStyle::EditStyle(Score* s, QWidget* parent)
   : QDialog(parent)
      {
      setupUi(this);
      setWindowFlags(this->windowFlags() & ~Qt::WindowContextHelpButtonHint);
      cs     = s;
      lstyle = *s->style();
      setModal(true);

      chordDescriptionFileButton->setIcon(*icons[fileOpen_ICON]);

      stemGroups[0] = new QButtonGroup(this);
      stemGroups[0]->addButton(voice1Up);
      stemGroups[0]->addButton(voice1Down);

      stemGroups[1] = new QButtonGroup(this);
      stemGroups[1]->addButton(voice2Up);
      stemGroups[1]->addButton(voice2Down);

      stemGroups[2] = new QButtonGroup(this);
      stemGroups[2]->addButton(voice3Up);
      stemGroups[2]->addButton(voice3Down);

      stemGroups[3] = new QButtonGroup(this);
      stemGroups[3]->addButton(voice4Up);
      stemGroups[3]->addButton(voice4Down);

      pageList->setCurrentRow(0);

      articulationTable->verticalHeader()->setVisible(false);
      articulationTable->setSelectionBehavior(QAbstractItemView::SelectRows);
      QStringList headers;
      headers << tr("Symbol") << tr("Anchor");
      articulationTable->setHorizontalHeaderLabels(headers);
      articulationTable->setColumnWidth(0, 200);
      articulationTable->setColumnWidth(1, 180);
      articulationTable->setRowCount(ARTICULATIONS);

      for (int i = 0; i < ARTICULATIONS; ++i) {
            ArticulationInfo* ai = &Articulation::articulationList[i];

            QPixmap ct = sym2pixmap(&symbols[0][ai->upSym], 3.0);
            QIcon icon(ct);
            QTableWidgetItem* item = new QTableWidgetItem(icon, qApp->translate("articulation", qPrintable(ai->name)));

            item->setFlags(item->flags() & ~Qt::ItemIsEditable);
            articulationTable->setItem(i, 0, item);

            QComboBox* cb = new QComboBox();
            cb->addItem(tr("TopStaff"), A_TOP_STAFF);
            cb->addItem(tr("BottomStaff"), A_BOTTOM_STAFF);
            cb->addItem(tr("Chord"), A_CHORD);
            articulationTable->setCellWidget(i, 1, cb);
            }
      QButtonGroup* bg = new QButtonGroup(this);
      bg->addButton(editEvenHeaderL, 0);
      bg->addButton(editEvenHeaderC, 1);
      bg->addButton(editEvenHeaderR, 2);
      bg->addButton(editOddHeaderL,  3);
      bg->addButton(editOddHeaderC,  4);
      bg->addButton(editOddHeaderR,  5);

      bg->addButton(editEvenFooterL, 6);
      bg->addButton(editEvenFooterC, 7);
      bg->addButton(editEvenFooterR, 8);
      bg->addButton(editOddFooterL,  9);
      bg->addButton(editOddFooterC, 10);
      bg->addButton(editOddFooterR, 11);

      // figured bass init
      QList<QString> fbFontNames = FiguredBass::fontNames();
      foreach(const QString& family, fbFontNames)
            comboFBFont->addItem(family);
      comboFBFont->setCurrentIndex(0);
      connect(comboFBFont, SIGNAL(currentIndexChanged(int)), SLOT(on_comboFBFont_currentIndexChanged(int)));

      setValues();
      connect(buttonBox, SIGNAL(clicked(QAbstractButton*)), SLOT(buttonClicked(QAbstractButton*)));
      connect(chordDescriptionFileButton, SIGNAL(clicked()), SLOT(selectChordDescriptionFile()));
      connect(chordsStandard, SIGNAL(toggled(bool)), SLOT(setChordStyle(bool)));
      connect(chordsJazz, SIGNAL(toggled(bool)), SLOT(setChordStyle(bool)));
      connect(chordsCustom, SIGNAL(toggled(bool)), SLOT(setChordStyle(bool)));

      connect(hideEmptyStaves, SIGNAL(clicked(bool)), dontHideStavesInFirstSystem, SLOT(setEnabled(bool)));

      connect(bg, SIGNAL(buttonClicked(int)), SLOT(editTextClicked(int)));
      }
Esempio n. 24
0
bool CeTcpSyncConnection::copyFile(const QString &srcFile, const QString &destFile, bool failIfExists)
{
    QString cmd = ceTcpSyncProgram + " copyFile \"" + srcFile + "\" \"" + destFile + "\" " + boolToString(failIfExists);
    return system(qPrintable(cmd)) == 0;
}
Esempio n. 25
0
int CreateFunction::writeToDB(const QByteArray &pdata, const QString pkgname, QString &errMsg)
{
  if (DEBUG)
    qDebug("CreateFunction::writeToDb(%s, %s, &errMsg)",
           pdata.data(), qPrintable(pkgname));

  QSqlQuery oidq;
  QMap<QString,int> oldoids;

  if (! pkgname.isEmpty())
  {
    oidq.prepare("SELECT pg_proc.oid, oidvectortypes(proargtypes) "
                 "FROM pg_proc, pg_namespace "
                 "WHERE ((pg_namespace.oid=pronamespace)"
                 "  AND  (proname=:name)"
                 "  AND  (nspname=:schema));");
    oidq.bindValue(":name",   _name);
    oidq.bindValue(":schema", pkgname);

    oidq.exec();
    while (oidq.next())
    {
      oldoids.insert(oidq.value(1).toString(), oidq.value(0).toInt());
    }
    if (oidq.lastError().type() != QSqlError::NoError)
    {
      errMsg = _sqlerrtxt.arg(_filename)
                        .arg(oidq.lastError().databaseText())
                        .arg(oidq.lastError().driverText());
      return -1;
    }
    if (DEBUG)
    {
      QMap<QString, int>::const_iterator i = oldoids.constBegin();
      while (i != oldoids.constEnd())
      {
        qDebug("CreateFunction::writeToDB() %s(%s) -> %d",
               qPrintable(_name), qPrintable(i.key()), i.value());
        i++;
      }
    }
  }

  int returnVal = Script::writeToDB(pdata, pkgname, errMsg);
  if (returnVal < 0)
    return returnVal;

  if (! pkgname.isEmpty())
  {
    QSqlQuery select;
    int pkgheadid = -1;
    select.prepare("SELECT pkghead_id FROM pkghead WHERE (pkghead_name=:name);");
    select.bindValue(":name", pkgname);
    select.exec();
    if (select.first())
      pkgheadid = select.value(0).toInt();
    else if (select.lastError().type() != QSqlError::NoError)
    {
      errMsg = _sqlerrtxt.arg(_filename)
                        .arg(select.lastError().databaseText())
                        .arg(select.lastError().driverText());
      return -4;
    }

    oidq.exec();        // reuse the query
    int count = 0;
    while (oidq.next())
    {
      if (DEBUG)
        qDebug("CreateFunction::writeToDB() oid = %d, argtypes = %s",
               oidq.value(0).toInt(), qPrintable(oidq.value(1).toString()));
      int tmp = upsertPkgItem(pkgheadid, oldoids,
                              oidq.value(1).toString(), oidq.value(0).toInt(),
                              errMsg);
      if (tmp < 0)
        return tmp;
      count++;
    }
    if (oidq.lastError().type() != QSqlError::NoError)
    {
      errMsg = _sqlerrtxt.arg(_filename)
                        .arg(oidq.lastError().databaseText())
                        .arg(oidq.lastError().driverText());
      return -5;
    }
    if (count == 0)
    {
      errMsg = TR("Could not find function %1 in the database for package %2. "
                  "The script %3 does not match the contents.xml description.")
                .arg(_name).arg(pkgname).arg(_filename);
      return -6;
    }
  }

  return 0;
}
Esempio n. 26
0
bool CeTcpSyncConnection::copyDirectory(const QString &srcDirectory, const QString &destDirectory,
                                        bool recursive)
{
    QString cmd = ceTcpSyncProgram + " copyDirectory \"" + srcDirectory + "\" \"" + destDirectory + "\" " + boolToString(recursive);
    return system(qPrintable(cmd)) == 0;
}
Esempio n. 27
0
/*!
    Fills model with some test data at least twenty rows and if possible twenty or more columns.
    Return the parent of a row/column that can be tested.

    NOTE: If readOnly is true tests will try to remove and add rows and columns.
    If you have a tree model returning not the root index will help catch more errors.
 */
QModelIndex ModelsToTest::populateTestArea(QAbstractItemModel *model)
{
    if (QStringListModel *stringListModel = qobject_cast<QStringListModel *>(model)) {
        QString alphabet = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
        stringListModel->setStringList( alphabet.split(",") );
        return QModelIndex();
    }

    if (qobject_cast<QStandardItemModel *>(model)) {
        // Basic tree StandardItemModel
        QModelIndex parent;
        QVariant blue = QVariant(QColor(Qt::blue));
#ifndef Q_OS_WINCE
        for (int i = 0; i < 4; ++i) {
#else
        for (int i = 0; i < 2; ++i) {
#endif
            parent = model->index(0, 0, parent);
            model->insertRows(0, 26 + i, parent);
#ifndef Q_OS_WINCE
            model->insertColumns(0, 26 + i, parent);
#else
            model->insertColumns(0, 4 + i, parent);
#endif
            // Fill in some values to make it easier to debug
            /*
            for (int x = 0; x < 26 + i; ++x) {
                QString xval = QString::number(x);
                for (int y = 0; y < 26 + i; ++y) {
                    QString val = xval + QString::number(y) + QString::number(i);
                    QModelIndex index = model->index(x, y, parent);
                    model->setData(index, val);
                    model->setData(index, blue, Qt::TextColorRole);
                }
            }
            */
        }
        return model->index(0,0);
    }

    if (qobject_cast<QSortFilterProxyModel *>(model)) {
        QAbstractItemModel *realModel = (qobject_cast<QSortFilterProxyModel *>(model))->sourceModel();
        // Basic tree StandardItemModel
        QModelIndex parent;
        QVariant blue = QVariant(QColor(Qt::blue));
#ifndef Q_OS_WINCE
        for (int i = 0; i < 4; ++i) {
#else
        for (int i = 0; i < 2; ++i) {
#endif
            parent = realModel->index(0, 0, parent);
            realModel->insertRows(0, 26+i, parent);
#ifndef Q_OS_WINCE
            realModel->insertColumns(0, 26+i, parent);
#else
            realModel->insertColumns(0, 4, parent);
#endif
            // Fill in some values to make it easier to debug
            /*
            for (int x = 0; x < 26+i; ++x) {
                QString xval = QString::number(x);
                for (int y = 0; y < 26 + i; ++y) {
                    QString val = xval + QString::number(y) + QString::number(i);
                    QModelIndex index = realModel->index(x, y, parent);
                    realModel->setData(index, val);
                    realModel->setData(index, blue, Qt::TextColorRole);
                }
            }
            */
        }
        QModelIndex returnIndex = model->index(0,0);
        if (!returnIndex.isValid())
            qFatal("%s: model index to be returned is invalid", Q_FUNC_INFO);
        return returnIndex;
    }

    if (QDirModel *dirModel = qobject_cast<QDirModel *>(model)) {
        if (!QDir::current().mkdir("test"))
            qFatal("%s: cannot create directory %s",
                   Q_FUNC_INFO,
                   qPrintable(QDir::toNativeSeparators(QDir::currentPath()+"/test")));
        for (int i = 0; i < 26; ++i) {
            QString subdir = QString("test/foo_%1").arg(i);
            if (!QDir::current().mkdir(subdir))
                qFatal("%s: cannot create directory %s",
                       Q_FUNC_INFO,
                       qPrintable(QDir::toNativeSeparators(QDir::currentPath()+"/"+subdir)));
        }
        return dirModel->index(QDir::currentPath()+"/test");
    }

    if (QSqlQueryModel *queryModel = qobject_cast<QSqlQueryModel *>(model)) {
        QSqlQuery q;
        q.exec("CREATE TABLE test(id int primary key, name varchar(30))");
        q.prepare("INSERT INTO test(id, name) values (?, ?)");
#ifndef Q_OS_WINCE
        for (int i = 0; i < 1024; ++i) {
#else
        for (int i = 0; i < 512; ++i) {
#endif
            q.addBindValue(i);
            q.addBindValue("Mr. Smith" + QString::number(i));
            q.exec();
        }
        if (QSqlTableModel *tableModel = qobject_cast<QSqlTableModel *>(model)) {
            tableModel->setTable("test");
            tableModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
            tableModel->select();
        } else {
            queryModel->setQuery("select * from test");
        }
        return QModelIndex();
    }

    if (QListWidget *listWidget = qobject_cast<QListWidget *>(model->parent())) {
#ifndef Q_OS_WINCE
        int items = 100;
#else
        int items = 50;
#endif
        while (items--)
            listWidget->addItem(QString("item %1").arg(items));
        return QModelIndex();
    }

    if (QTableWidget *tableWidget = qobject_cast<QTableWidget *>(model->parent())) {
        tableWidget->setColumnCount(20);
        tableWidget->setRowCount(20);
        return QModelIndex();
    }

    if (QTreeWidget *treeWidget = qobject_cast<QTreeWidget *>(model->parent())) {
        int topItems = 20;
        treeWidget->setColumnCount(1);
        QTreeWidgetItem *parent;
        while (topItems--){
            parent = new QTreeWidgetItem(treeWidget, QStringList(QString("top %1").arg(topItems)));
            for (int i = 0; i < 20; ++i)
                new QTreeWidgetItem(parent, QStringList(QString("child %1").arg(topItems)));
        }
        return QModelIndex();
    }

    qFatal("%s: unknown type of model", Q_FUNC_INFO);
    return QModelIndex();
}

/*!
    If you need to cleanup from populateTest() do it here.
    Note that this is called after every test even if populateTestArea isn't called.
 */
void ModelsToTest::cleanupTestArea(QAbstractItemModel *model)
{
    if (qobject_cast<QDirModel *>(model))
    {
        if (QDir(QDir::currentPath()+"/test").exists())
        {
            for (int i = 0; i < 26; ++i) {
                QString subdir(QString("test/foo_%1").arg(i));
                if (!QDir::current().rmdir(subdir))
                    qFatal("%s: cannot remove directory %s",
                           Q_FUNC_INFO,
                           qPrintable(QDir::toNativeSeparators(QDir::currentPath()+"/"+subdir)));
            }
            if (!QDir::current().rmdir("test"))
                qFatal("%s: cannot remove directory %s",
                       Q_FUNC_INFO,
                       qPrintable(QDir::toNativeSeparators(QDir::currentPath()+"/test")));
        }
    } else if (qobject_cast<QSqlQueryModel *>(model)) {
        QSqlQuery q("DROP TABLE test");
    }
}

void ModelsToTest::setupDatabase()
{
    if (!QSqlDatabase::database().isValid()) {
        QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
        db.setDatabaseName(":memory:");
        if (!db.open()) {
            qWarning() << "Unable to open database" << db.lastError();
            return;
        }
    }
}
Esempio n. 28
0
bool CeTcpSyncConnection::deleteFile(const QString &fileName)
{
    QString cmd = ceTcpSyncProgram + " deleteFile \"" + fileName + "\"";
    return system(qPrintable(cmd)) == 0;
}
Esempio n. 29
0
void NativeInit(int argc, const char *argv[], const char *savegame_directory, const char *external_directory, const char *installID)
{
	std::string config_filename;
	Common::EnableCrashingOnCrashes();
	isMessagePending = false;

	std::string user_data_path = savegame_directory;

	VFSRegister("", new DirectoryAssetReader("assets/"));
	VFSRegister("", new DirectoryAssetReader(user_data_path.c_str()));

	config_filename = user_data_path + "ppsspp.ini";

	g_Config.Load(config_filename.c_str());

	const char *fileToLog = 0;

	bool hideLog = true;
#ifdef _DEBUG
	hideLog = false;
#endif

	bool gfxLog = false;
	// Parse command line
	LogTypes::LOG_LEVELS logLevel = LogTypes::LINFO;
	for (int i = 1; i < argc; i++) {
		if (argv[i][0] == '-') {
			switch (argv[i][1]) {
			case 'd':
				// Enable debug logging
				logLevel = LogTypes::LDEBUG;
				break;
			case 'g':
				gfxLog = true;
				break;
			case 'j':
				g_Config.bJit = true;
				g_Config.bSaveSettings = false;
				break;
			case 'i':
				g_Config.bJit = false;
				g_Config.bSaveSettings = false;
				break;
			case 'l':
				hideLog = false;
				break;
			case 's':
				g_Config.bAutoRun = false;
				g_Config.bSaveSettings = false;
				break;
			case '-':
				if (!strcmp(argv[i], "--log") && i < argc - 1)
					fileToLog = argv[++i];
				if (!strncmp(argv[i], "--log=", strlen("--log=")) && strlen(argv[i]) > strlen("--log="))
					fileToLog = argv[i] + strlen("--log=");
				if (!strcmp(argv[i], "--state") && i < argc - 1)
					stateToLoad = argv[++i];
				if (!strncmp(argv[i], "--state=", strlen("--state=")) && strlen(argv[i]) > strlen("--state="))
					stateToLoad = argv[i] + strlen("--state=");
				break;
			}
		}
		else if (fileToStart.isNull())
		{
			fileToStart = QString(argv[i]);
			if (!QFile::exists(fileToStart))
			{
				qCritical("File '%s' does not exist!", qPrintable(fileToStart));
				exit(1);
			}
		}
		else
		{
			qCritical("Can only boot one file. Ignoring file '%s'", qPrintable(fileToStart));
		}
	}

	if (g_Config.currentDirectory == "")
	{
		g_Config.currentDirectory = QDir::homePath().toStdString();
	}

	g_Config.memCardDirectory = QDir::homePath().toStdString()+"/.ppsspp/";
	g_Config.flashDirectory = g_Config.memCardDirectory+"/flash0/";

	LogManager::Init();
	if (fileToLog != NULL)
		LogManager::GetInstance()->ChangeFileLog(fileToLog);

	LogManager::GetInstance()->SetLogLevel(LogTypes::G3D, LogTypes::LERROR);

	g_gameInfoCache.Init();

#if !defined(USING_GLES2)
	// Start Desktop UI
	MainWindow* mainWindow = new MainWindow();
	mainWindow->show();
#endif
}
int main(int argc, char *argv[])
{
	if(argc<=1)
	{
		printHelp();
		return 0;
	}

	//------------------------------------------------------------------------------------------------------------------------------------
	QString qs_filename_img_tar			=NULL;
	QString qs_filename_img_sub			=NULL;
	QString qs_filename_swc_inigrid		=NULL;
	QString qs_filename_img_sub2tar		=NULL;
	QString qs_filename_swc_grid		=NULL;
	long 	l_refchannel=0;
	double 	d_downsample_ratio=3;

	int c;
	static char optstring[]="ht:s:i:o:r:d:g:";
	opterr=0;
	while((c=getopt(argc,argv,optstring))!=-1)
    {
		switch (c)
        {
			case 'h':
				printHelp ();
				return 0;
				break;
			case 't':
				if (strcmp (optarg, "(null)") == 0 || optarg[0] == '-')
				{
					fprintf (stderr, "Found illegal or NULL parameter for the option -t.\n");
					return 1;
				}
				qs_filename_img_tar.append(optarg);
				break;
			case 's':
				if (strcmp (optarg, "(null)") == 0 || optarg[0] == '-')
				{
					fprintf (stderr, "Found illegal or NULL parameter for the option -s.\n");
					return 1;
				}
				qs_filename_img_sub.append(optarg);
				break;
			case 'i':
				if (strcmp (optarg, "(null)") == 0 || optarg[0] == '-')
				{
					fprintf (stderr, "Found illegal or NULL parameter for the option -i.\n");
					return 1;
				}
				qs_filename_swc_inigrid.append(optarg);
				break;
			case 'o':
				if (strcmp (optarg, "(null)") == 0 || optarg[0] == '-')
				{
					fprintf (stderr, "Found illegal or NULL parameter for the option -o.\n");
					return 1;
				}
				qs_filename_img_sub2tar.append(optarg);
				break;
			case 'r':
				if (strcmp (optarg, "(null)") == 0 || optarg[0] == '-')
				{
					fprintf (stderr, "Found illegal or NULL parameter for the option -r.\n");
					return 1;
				}
				l_refchannel=atoi(optarg);
				break;
			case 'd':
				if (strcmp (optarg, "(null)") == 0 || optarg[0] == '-')
				{
					fprintf (stderr, "Found illegal or NULL parameter for the option -d.\n");
					return 1;
				}
				d_downsample_ratio=QString(optarg).toDouble();
				break;
			case 'g':
				if (strcmp (optarg, "(null)") == 0 || optarg[0] == '-')
				{
					fprintf (stderr, "Found illegal or NULL parameter for the option -g.\n");
					return 1;
				}
				qs_filename_swc_grid.append(optarg);
				break;
			case '?':
				fprintf (stderr, "Unknown option `-%c' or incomplete argument lists.\n", optopt);
				return 1;
				break;
		}
    }

	printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
	printf(">>SSD based affine registration\n");
	printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
	printf(">>input parameters:\n");
	printf(">>  input target  image:          %s\n",qPrintable(qs_filename_img_tar));
	printf(">>  input subject image:          %s\n",qPrintable(qs_filename_img_sub));
	printf(">>  input initial grid:           %s\n",qPrintable(qs_filename_swc_inigrid));
	printf(">>  input reference channel:      %ld\n",l_refchannel);
	printf(">>  input image down sample ratio:%.2f\n",d_downsample_ratio);
	printf(">>-------------------------\n");
	printf(">>output parameters:\n");
	printf(">>  output sub2tar image:         %s\n",qPrintable(qs_filename_img_sub2tar));
	printf(">>  output meshgrid apo:          %s\n",qPrintable(qs_filename_swc_grid));
	printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");

	clock_t start;

	//------------------------------------------------------------------------------------------------------------------------------------
	//pointers definition (needed to be released)
	long *sz_img_tar=0,*sz_img_sub=0;						//input image size. [0]:width, [1]:height, [2]:z, [3]:nchannel
	unsigned char *p_img_tar_input=0,*p_img_sub_input=0;	//input images pointer
	double *p_img64f_tar=0,*p_img64f_sub=0;					//input images pointer (double type)
	double *p_img64f_sub_bk=0;								//backed nonsmoothed subject image pointer
	double *p_img64f_tar_1c=0,*p_img64f_sub_1c=0;			//image pointers with only reference channel
	double *p_img64f_output_sub=0;							//output warped subject image pointer

	//------------------------------------------------------------------------------------------------------------------------------------
	printf("1. Read target and subject image. \n");
	//read target image
	if(SHOWTIME) start=clock();
	int datatype_tar=0;
	if(!loadImage((char *)qPrintable(qs_filename_img_tar),p_img_tar_input,sz_img_tar,datatype_tar))
	{
		printf("ERROR: loadImage() return false in loading [%s].\n", qPrintable(qs_filename_img_tar));
		return false;
	}
	printf("\t>>read image file [%s] complete.\n",qPrintable(qs_filename_img_tar));
	printf("\t\timage size: [w=%ld, h=%ld, z=%ld, c=%ld]\n",sz_img_tar[0],sz_img_tar[1],sz_img_tar[2],sz_img_tar[3]);
	printf("\t\tdatatype: %d\n",datatype_tar);
	if(SHOWTIME) printf("\t>>time consume: %.2f s\n",(clock()-start)/100.0);

	//read subject image
	if(SHOWTIME) start=clock();
	int datatype_sub=0;
	if(!loadImage((char *)qPrintable(qs_filename_img_sub),p_img_sub_input,sz_img_sub,datatype_sub))
	{
		printf("ERROR: loadImage() return false in loading [%s].\n", qPrintable(qs_filename_img_sub));
		return false;
	}
	printf("\t>>read image file [%s] complete.\n",qPrintable(qs_filename_img_sub));
	printf("\t\timage size: [w=%ld, h=%ld, z=%ld, c=%ld]\n",sz_img_sub[0],sz_img_sub[1],sz_img_sub[2],sz_img_sub[3]);
	printf("\t\tdatatype: %d\n",datatype_sub);
	if(SHOWTIME) printf("\t>>time consume: %.2f s\n",(clock()-start)/100.0);

	//check image size
	if(sz_img_tar[0]!=sz_img_sub[0] || sz_img_tar[1]!=sz_img_sub[1] || sz_img_tar[2]!=sz_img_sub[2] || sz_img_tar[3]!=sz_img_sub[3] ||
	   datatype_tar!=datatype_sub)
	{
		printf("ERROR: input target and subject image have different size or datatype!\n");
		releasememory(sz_img_tar,sz_img_sub,p_img_tar_input,p_img_sub_input,p_img64f_tar,p_img64f_sub,p_img64f_sub_bk,p_img64f_tar_1c,p_img64f_sub_1c,p_img64f_output_sub);
		return false;
	}

	long l_npixels=sz_img_tar[0]*sz_img_tar[1]*sz_img_tar[2]*sz_img_tar[3];

	//------------------------------------------------------------------------------------------------------------------------------------
	//read intial grid data (affine)
	bool b_hasinigrid=0;
	vector< vector< vector< vector<double> > > > vec4D_grid_ori,vec4D_grid_ini;
	if(qs_filename_swc_inigrid!=NULL)
	{
		b_hasinigrid=1;

		NeuronTree nt;
		nt=readSWC_file(qs_filename_swc_inigrid);

		//read grid data
		long sz_grid[3]={2,2,2}; //w,h,z
		vec4D_grid_ori.assign(sz_grid[1],vector< vector< vector<double> > >(sz_grid[0],vector< vector<double> >(sz_grid[2],vector<double>(3,0))));
		vec4D_grid_ini=vec4D_grid_ori;
		for(long i=0;i<nt.listNeuron.size();i++)
		{
			long x,y,z;
			if(nt.listNeuron[i].pn!=-1)
			{
				x=nt.listNeuron[i].x/sz_img_tar[0];
				y=nt.listNeuron[i].y/sz_img_tar[1];
				z=nt.listNeuron[i].z/sz_img_tar[2];

				vec4D_grid_ori[y][x][z][0]=nt.listNeuron[i].x;
				vec4D_grid_ori[y][x][z][1]=nt.listNeuron[i].y;
				vec4D_grid_ori[y][x][z][2]=nt.listNeuron[i].z;

				i++;

				vec4D_grid_ini[y][x][z][0]=nt.listNeuron[i].x;
				vec4D_grid_ini[y][x][z][1]=nt.listNeuron[i].y;
				vec4D_grid_ini[y][x][z][2]=nt.listNeuron[i].z;
			}
		}

		printf("\t>>read initial grid file [%s] complete.\n",qPrintable(qs_filename_swc_inigrid));
		printf("\t\tsz_inigrid: %ld,%ld,%ld\n",sz_grid[0],sz_grid[1],sz_grid[2]);

	}

	//------------------------------------------------------------------------------------------------------------------------------------
	//convert image data type to double and rescale to [0~1]
	printf("2. Convert image data from uint16/8 to double and scale to [0~1]. \n");
	if(SHOWTIME) start=clock();
	{
	p_img64f_tar=new double[l_npixels]();
	p_img64f_sub=new double[l_npixels]();
	if(!p_img64f_tar || !p_img64f_sub)
	{
		printf("ERROR: Fail to allocate memory for p_img64f_tar or p_img64f_sub!\n");
		releasememory(sz_img_tar,sz_img_sub,p_img_tar_input,p_img_sub_input,p_img64f_tar,p_img64f_sub,p_img64f_sub_bk,p_img64f_tar_1c,p_img64f_sub_1c,p_img64f_output_sub);
		return false;
	}

	//scale to [0~1]
	long l_maxintensity_tar=0,l_maxintensity_sub=0;
	if(datatype_tar==1)
	{
		l_maxintensity_tar=l_maxintensity_sub=255;
		for(long i=0;i<l_npixels;i++)
		{
			p_img64f_tar[i]=p_img_tar_input[i]/(double)l_maxintensity_tar;
			p_img64f_sub[i]=p_img_sub_input[i]/(double)l_maxintensity_sub;
		}
		printf("\t>>convert from 8-bit to double and scale to [0~1]\n");
	}
	else if(datatype_tar==2)
	{
		unsigned short int * p_data16u_tar=(unsigned short int *)p_img_tar_input;
		unsigned short int * p_data16u_sub=(unsigned short int *)p_img_sub_input;

		//find the maiximal intensity value
		for(long i=0;i<l_npixels;i++)
		{
			if(p_data16u_tar[i]>l_maxintensity_tar)
				l_maxintensity_tar=p_data16u_tar[i];
			if(p_data16u_sub[i]>l_maxintensity_sub)
				l_maxintensity_sub=p_data16u_sub[i];
		}
		//rescale to [0~1]
		for(long i=0;i<l_npixels;i++)
		{
			p_img64f_tar[i]=p_data16u_tar[i]/(double)l_maxintensity_tar;
			p_img64f_sub[i]=p_data16u_sub[i]/(double)l_maxintensity_sub;
		}
		printf("\t>>convert from 16-bit to double and scale to [0~1]\n");
	}
	if(p_img_tar_input) 	{delete []p_img_tar_input;		p_img_tar_input=0;}
	if(p_img_sub_input) 	{delete []p_img_sub_input;		p_img_sub_input=0;}
	printf("\t\t>>l_maxintensity_tar=%ld; l_maxintensity_sub=%ld\n",l_maxintensity_tar,l_maxintensity_sub);
	}
	if(SHOWTIME) printf("\t>>time consume %.2f s\n",(clock()-start)/100.0);

//	q_save64f01_image(p_img64f_tar,sz_img_tar,"tar.tif");
//	q_save64f01_image(p_img64f_sub,sz_img_sub,"sub.tif");

	//------------------------------------------------------------------------------------------------------------------------------------
	//backup the subject image
	printf("3. Backup the subject image before smoothing.\n");
	if(SHOWTIME) start=clock();
	//allocate memory
	p_img64f_sub_bk=new double[l_npixels]();
	if(!p_img64f_sub_bk)
	{
		printf("ERROR: Fail to allocate memory for p_img64f_sub_bk!\n");
		releasememory(sz_img_tar,sz_img_sub,p_img_tar_input,p_img_sub_input,p_img64f_tar,p_img64f_sub,p_img64f_sub_bk,p_img64f_tar_1c,p_img64f_sub_1c,p_img64f_output_sub);
		return false;
	}
	//backup subject image before smoothing
	for(long i=0;i<l_npixels;i++)
		p_img64f_sub_bk[i]=p_img64f_sub[i];
	if(SHOWTIME) printf("\t>>time consume %.2f s\n",(clock()-start)/100.0);

	//------------------------------------------------------------------------------------------------------------------------------------
	//extract or generate the reference channel
	printf("4. Extract or generate reference channel:[%ld].\n",l_refchannel);
	if(SHOWTIME) start=clock();
	long sz_img_1c[4];
	sz_img_1c[0]=sz_img_tar[0];	sz_img_1c[1]=sz_img_tar[1];	sz_img_1c[2]=sz_img_tar[2];	sz_img_1c[3]=1;
	long l_npixels_1c=sz_img_1c[0]*sz_img_1c[1]*sz_img_1c[2];

	//allocate memeory
	p_img64f_tar_1c=new double[l_npixels_1c]();
	p_img64f_sub_1c=new double[l_npixels_1c]();
	if(!p_img64f_tar_1c || !p_img64f_sub_1c)
	{
		printf("ERROR: Fail to allocate memory for p_img64f_tar_1c or p_img64f_sub_1c!\n");
		releasememory(sz_img_tar,sz_img_sub,p_img_tar_input,p_img_sub_input,p_img64f_tar,p_img64f_sub,p_img64f_sub_bk,p_img64f_tar_1c,p_img64f_sub_1c,p_img64f_output_sub);
		return false;
	}
	//extract referece channel (l_refchannel<3) or do some special operation (e.g. l_refchannel=9, for Rex's 2 channels data, we average all channels)
	long pgsz_y=sz_img_tar[0];
	long pgsz_xy=sz_img_tar[0]*sz_img_tar[1];
	long pgsz_xyz=sz_img_tar[0]*sz_img_tar[1]*sz_img_tar[2];
	if(l_refchannel<3 && l_refchannel<sz_img_tar[3])
	{
		printf("\t>>extract channel:[%ld]\n",l_refchannel);
		for(long x=0;x<sz_img_tar[0];x++)
			for(long y=0;y<sz_img_tar[1];y++)
				for(long z=0;z<sz_img_tar[2];z++)
				{
					long ind_1c=pgsz_xy*z+pgsz_y*y+x;
					long ind_ref=pgsz_xyz*l_refchannel+ind_1c;
					p_img64f_tar_1c[ind_1c]=p_img64f_tar[ind_ref];
					p_img64f_sub_1c[ind_1c]=p_img64f_sub[ind_ref];
				}
	}
	else if(l_refchannel==9 && sz_img_tar[3]>1)//for Rex's 2 channels data, we average all channels
	{
		printf("\t>>average all channels --> for Rex's AQ1336 and XL138 data\n");
		for(long x=0;x<sz_img_tar[0];x++)
			for(long y=0;y<sz_img_tar[1];y++)
				for(long z=0;z<sz_img_tar[2];z++)
				{
					long ind_1c=pgsz_xy*z+pgsz_y*y+x;
					for(long c=0;c<sz_img_tar[3];c++)
					{
						long ind_ref=pgsz_xyz*c+ind_1c;
						//initialize
						if(c==0)
						{
							p_img64f_tar_1c[ind_1c]=0;
							p_img64f_sub_1c[ind_1c]=0;
						}
						//average
						p_img64f_tar_1c[ind_1c]+=p_img64f_tar[ind_ref];
						p_img64f_sub_1c[ind_1c]+=p_img64f_sub[ind_ref];
					}
					p_img64f_tar_1c[ind_1c]/=sz_img_tar[3];
					p_img64f_sub_1c[ind_1c]/=sz_img_tar[3];
				}
	}
	else
	{
		printf("ERROR: l_refchannel invalid! \n");
		releasememory(sz_img_tar,sz_img_sub,p_img_tar_input,p_img_sub_input,p_img64f_tar,p_img64f_sub,p_img64f_sub_bk,p_img64f_tar_1c,p_img64f_sub_1c,p_img64f_output_sub);
		return false;
	}

	if(p_img64f_tar) 		{delete []p_img64f_tar;			p_img64f_tar=0;}
	if(p_img64f_sub) 		{delete []p_img64f_sub;			p_img64f_sub=0;}

	if(SHOWTIME) printf("\t>>time consume %.2f s\n",(clock()-start)/100.0);

//	q_save64f01_image(p_img64f_tar_1c,sz_img_1c,"tar_1c.tif");
//	q_save64f01_image(p_img64f_sub_1c,sz_img_1c,"sub_1c.tif");

	//------------------------------------------------------------------------------------------------------------------------------------
	printf("5. Do histogram matching. \n");
	{
	//convert images from 64f to 8u
	unsigned char *p_img8u1c_tar=new unsigned char[l_npixels_1c]();
	unsigned char *p_img8u1c_sub=new unsigned char[l_npixels_1c]();
	if(!p_img8u1c_tar || !p_img8u1c_sub)
	{
		printf("ERROR: Fail to allocate memory for p_img8u1c_tar or p_img8u1c_sub!\n");
		releasememory(sz_img_tar,sz_img_sub,p_img_tar_input,p_img_sub_input,p_img64f_tar,p_img64f_sub,p_img64f_sub_bk,p_img64f_tar_1c,p_img64f_sub_1c,p_img64f_output_sub);
		return false;
	}
	for(long i=0;i<l_npixels_1c;i++)
	{
		p_img8u1c_tar[i]=p_img64f_tar_1c[i]*255+0.5;
		p_img8u1c_sub[i]=p_img64f_sub_1c[i]*255+0.5;
	}
	//do histogram matching
	unsigned char *p_img8u1c_sub2tar=0;
	if(!q_histogram_matching_1c(p_img8u1c_tar,sz_img_1c,
								p_img8u1c_sub,sz_img_1c,
							    p_img8u1c_sub2tar))
	{
		printf("ERROR: q_histogram_matching_1c() return false!\n");
		releasememory(sz_img_tar,sz_img_sub,p_img_tar_input,p_img_sub_input,p_img64f_tar,p_img64f_sub,p_img64f_sub_bk,p_img64f_tar_1c,p_img64f_sub_1c,p_img64f_output_sub);
		return false;
	}
	//write matched subject image to 64f image
	for(long i=0;i<l_npixels_1c;i++)
		p_img64f_sub_1c[i]=p_img8u1c_sub2tar[i]/255.0;
	//free memory
	if(p_img8u1c_tar) 		{delete []p_img8u1c_tar;		p_img8u1c_tar=0;}
	if(p_img8u1c_sub) 		{delete []p_img8u1c_sub;		p_img8u1c_sub=0;}
	if(p_img8u1c_sub2tar) 	{delete []p_img8u1c_sub2tar;	p_img8u1c_sub2tar=0;}
	}

	//------------------------------------------------------------------------------------------------------------------------------------
	printf("6. Pre-warpping subject image based on the initial grid (if provided):\n");
	{
	double *p_img64f_prewarped_sub=0;
	if(b_hasinigrid)
	{
		printf("\t>>use input initial grid to pre-warp subject image\n");
		//warp image based on deformed grid
		if(!q_affine_warpimage_baseongrid(p_img64f_sub_1c,sz_img_1c,vec4D_grid_ini,p_img64f_prewarped_sub))
		{
			printf("ERROR: q_affine_warpimage_baseongrid() return false!\n");
			return false;
		}
		if(p_img64f_sub_1c) 	{delete []p_img64f_sub_1c;		p_img64f_sub_1c=0;}
		p_img64f_sub_1c=p_img64f_prewarped_sub;
		p_img64f_prewarped_sub=0;
	}
	else
		printf("\t>>input initial grid is invalid or not provided, pre-warping is not applied\n");

//	q_save64f01_image(p_img64f_sub_1c,sz_img_1c,"sub_prewarped.tif");
	}


	//------------------------------------------------------------------------------------------------------------------------------------
	//downsample target and subject image
	printf("6. downsample target and subject image. \n");
	if(fabs(d_downsample_ratio-1.0)>1e-7)
	{
		long sz_img_s[4]={1,1,1,1};//w,h,z,c
		for(long i=0;i<3;i++)
			sz_img_s[i]=sz_img_1c[i]/d_downsample_ratio+0.5;

		double *p_img64f_tar_1c_s=0,*p_img64f_sub_1c_s=0;
		if(!q_imresize64f_3D(p_img64f_tar_1c,sz_img_1c,sz_img_s,p_img64f_tar_1c_s) ||
		   !q_imresize64f_3D(p_img64f_sub_1c,sz_img_1c,sz_img_s,p_img64f_sub_1c_s))
		{
			printf("ERROR: q_imresize64f_3D() return false!\n");
			releasememory(sz_img_tar,sz_img_sub,p_img_tar_input,p_img_sub_input,p_img64f_tar,p_img64f_sub,p_img64f_sub_bk,p_img64f_tar_1c,p_img64f_sub_1c,p_img64f_output_sub);
			return false;
		}
		printf("\t>>sz_img_s:[%ld,%ld,%ld,%ld]\n",sz_img_s[0],sz_img_s[1],sz_img_s[2],sz_img_s[3]);

		if(p_img64f_tar_1c) 	{delete []p_img64f_tar_1c;		p_img64f_tar_1c=0;}
		if(p_img64f_sub_1c) 	{delete []p_img64f_sub_1c;		p_img64f_sub_1c=0;}
		p_img64f_tar_1c=p_img64f_tar_1c_s;		p_img64f_tar_1c_s=0;
		p_img64f_sub_1c=p_img64f_sub_1c_s;		p_img64f_sub_1c_s=0;
		for(long i=0;i<3;i++)	sz_img_1c[i]=sz_img_s[i];
		l_npixels_1c=sz_img_1c[0]*sz_img_1c[1]*sz_img_1c[2];

	//	q_save64f01_image(p_img64f_tar_1c,sz_img_1c,"tar_resize.tif");
	//	q_save64f01_image(p_img64f_sub_1c,sz_img_1c,"sub_resize.tif");
	}

	//------------------------------------------------------------------------------------------------------------------------------------
	//make the 0 edge result from the affine registration invalid
	for(long i=0;i<l_npixels_1c;i++)
		if(p_img64f_sub_1c[i]==0) p_img64f_sub_1c[i]=-1e+10;

	//------------------------------------------------------------------------------------------------------------------------------------
	//Gaussian smooth (optional) - inplace operation
	printf("4. Gaussian smooth input target and subject images [optional]. \n");
	{
	long l_kenelradius=3;
	double d_sigma=1.0;
	vector<double> vec1D_kernel;
	if(!q_kernel_gaussian_1D(l_kenelradius,d_sigma,vec1D_kernel))
	{
		printf("ERROR: q_kernel_gaussian_1D() return false!\n");
		releasememory(sz_img_tar,sz_img_sub,p_img_tar_input,p_img_sub_input,p_img64f_tar,p_img64f_sub,p_img64f_sub_bk,p_img64f_tar_1c,p_img64f_sub_1c,p_img64f_output_sub);
		return false;
	}
	printf("\tsmoothing target image.\n");
	if(SHOWTIME) start=clock();
	if(!q_convolve_img64f_3D_fast(p_img64f_tar_1c,sz_img_1c,vec1D_kernel))
	{
		printf("ERROR: q_convolve64f_3D_fast() return false!\n");
		releasememory(sz_img_tar,sz_img_sub,p_img_tar_input,p_img_sub_input,p_img64f_tar,p_img64f_sub,p_img64f_sub_bk,p_img64f_tar_1c,p_img64f_sub_1c,p_img64f_output_sub);
		return false;
	}
	if(SHOWTIME) printf("\t\t>>time consume %.2f s\n",(clock()-start)/100.0);
	printf("\tsmoothing subject image.\n");
	if(SHOWTIME) start=clock();
	if(!q_convolve_img64f_3D_fast(p_img64f_sub_1c,sz_img_1c,vec1D_kernel))
	{
		printf("ERROR: q_convolve64f_3D_fast() return false!\n");
		releasememory(sz_img_tar,sz_img_sub,p_img_tar_input,p_img_sub_input,p_img64f_tar,p_img64f_sub,p_img64f_sub_bk,p_img64f_tar_1c,p_img64f_sub_1c,p_img64f_output_sub);
		return false;
	}
	if(SHOWTIME) printf("\t\t>>time consume %.2f s\n",(clock()-start)/100.0);

//	q_save64f01_image(p_img64f_tar_1c,sz_img_1c,"tar_smooth_affine.tif");
//	q_save64f01_image(p_img64f_sub_1c,sz_img_1c,"sub_smooth_affine.tif");
	}


	//------------------------------------------------------------------------------------------------------------------------------------
	//SSD based affine registration
	printf("############################################################################################################################\n");
	printf("6. Enter affine registration. \n");
	printf("############################################################################################################################\n");
	bool b_alignmasscenter;
	if(b_hasinigrid) b_alignmasscenter=0; else b_alignmasscenter=1;

	vector< vector< vector< vector<double> > > > vec4D_grid;
	if(!q_affine_registration_SSD(p_img64f_tar_1c,p_img64f_sub_1c,sz_img_1c,b_alignmasscenter,vec4D_grid))
	{
		printf("ERROR: q_affine_registration_SSD() return false!\n");
		releasememory(sz_img_tar,sz_img_sub,p_img_tar_input,p_img_sub_input,p_img64f_tar,p_img64f_sub,p_img64f_sub_bk,p_img64f_tar_1c,p_img64f_sub_1c,p_img64f_output_sub);
		return false;
	}

	//rescale the grid according to the real image downsample ratio
	for(long x=0;x<2;x++)
		for(long y=0;y<2;y++)
			for(long z=0;z<2;z++)
			{
				vec4D_grid[y][x][z][0]=vec4D_grid[y][x][z][0]*d_downsample_ratio;
				vec4D_grid[y][x][z][1]=vec4D_grid[y][x][z][1]*d_downsample_ratio;
				vec4D_grid[y][x][z][2]=vec4D_grid[y][x][z][2]*d_downsample_ratio;
			}

	//------------------------------------------------------------------------------------------------------------------------------------
	//prepare the final output (warp and trim the input subject image base on the deformed grid)
	printf("7. Prepare the final output (warp and trim the subject image base on the deformed grid). \n");
	if(SHOWTIME) start=clock();
	//combine current deformed grid with the initial grid (if provided)
	if(b_hasinigrid)
	{
//		for(long x=0;x<vec4D_grid[0].size();x++)
//			for(long y=0;y<vec4D_grid.size();y++)
//				for(long z=0;z<vec4D_grid[0][0].size();z++)
//				{
//					vec4D_grid[y][x][z][0]+=vec4D_grid_ini[y][x][z][0]-vec4D_grid_ori[y][x][z][0];
//					vec4D_grid[y][x][z][1]+=vec4D_grid_ini[y][x][z][1]-vec4D_grid_ori[y][x][z][1];
//					vec4D_grid[y][x][z][2]+=vec4D_grid_ini[y][x][z][2]-vec4D_grid_ori[y][x][z][2];
//				}

		vector<Coord3D_PCM> vec_ori(8,Coord3D_PCM()),vec_cur(8,Coord3D_PCM());
		//compute ori2pre affine matrix Tsub2pre*Xsub=Xpre
		for(long x=0;x<2;x++)
			for(long y=0;y<2;y++)
				for(long z=0;z<2;z++)
				{
					long ind=4*z+2*y+x;
					vec_ori[ind].x=vec4D_grid_ori[y][x][z][0];
					vec_ori[ind].y=vec4D_grid_ori[y][x][z][1];
					vec_ori[ind].z=vec4D_grid_ori[y][x][z][2];

					vec_cur[ind].x=vec4D_grid_ini[y][x][z][0];
					vec_cur[ind].y=vec4D_grid_ini[y][x][z][1];
					vec_cur[ind].z=vec4D_grid_ini[y][x][z][2];
				}
		//compute affine transformation matrix: X_cur=T*X_ori
		Matrix x4x4_affinematrix_sub2pre(4,4);
		q_affine_compute_affinmatrix_3D(vec_ori,vec_cur,x4x4_affinematrix_sub2pre);//	B=T*A

		//compute pre2tar affine matrix Tpre2tar*Xpre=Xtar
		for(long x=0;x<2;x++)
			for(long y=0;y<2;y++)
				for(long z=0;z<2;z++)
				{
					long ind=4*z+2*y+x;
					vec_ori[ind].x=vec4D_grid_ori[y][x][z][0];
					vec_ori[ind].y=vec4D_grid_ori[y][x][z][1];
					vec_ori[ind].z=vec4D_grid_ori[y][x][z][2];

					vec_cur[ind].x=vec4D_grid[y][x][z][0];
					vec_cur[ind].y=vec4D_grid[y][x][z][1];
					vec_cur[ind].z=vec4D_grid[y][x][z][2];
				}
		//compute affine transformation matrix: X_cur=T*X_ori
		Matrix x4x4_affinematrix_pre2tar(4,4);
		q_affine_compute_affinmatrix_3D(vec_ori,vec_cur,x4x4_affinematrix_pre2tar);//	B=T*A

		//compute sub2tar affine matrix Tsub2tar*Xpre=Xtar
		Matrix x4x4_affinematrix_sub2tar(4,4);
		x4x4_affinematrix_sub2tar=x4x4_affinematrix_pre2tar*x4x4_affinematrix_sub2pre;

		//affine transform the original grid
		Matrix x_aff(4,1),x_ori(4,1);
		for(long x=0;x<2;x++)
			for(long y=0;y<2;y++)
				for(long z=0;z<2;z++)
				{
					x_ori(1,1)=vec4D_grid_ori[y][x][z][0];
					x_ori(2,1)=vec4D_grid_ori[y][x][z][1];
					x_ori(3,1)=vec4D_grid_ori[y][x][z][2];
					x_ori(4,1)=1.0;

					x_aff=x4x4_affinematrix_sub2tar*x_ori;

					vec4D_grid[y][x][z][0]=x_aff(1,1)/x_aff(4,1);
					vec4D_grid[y][x][z][1]=x_aff(2,1)/x_aff(4,1);
					vec4D_grid[y][x][z][2]=x_aff(3,1)/x_aff(4,1);
				}
	}
	if(!q_affine_warpimage_baseongrid(p_img64f_sub_bk,sz_img_sub,vec4D_grid,p_img64f_output_sub))
	{
		printf("ERROR: q_warpimage_baseongrid() return false!\n");
		releasememory(sz_img_tar,sz_img_sub,p_img_tar_input,p_img_sub_input,p_img64f_tar,p_img64f_sub,p_img64f_sub_bk,p_img64f_tar_1c,p_img64f_sub_1c,p_img64f_output_sub);
		return false;
	}
	if(SHOWTIME) printf("\t>>q_warpimage_baseongrid_affine() time consume: %.2f s\n",(clock()-start)/100.0);

//	q_save64f01_image(p_img64f_output_sub,sz_img_sub,"sub2tar.tif");

	//------------------------------------------------------------------------------------------------------------------------------------
	//save warped image
	printf("8. Save results to file: \n");
	if(qs_filename_img_sub2tar!=NULL)
	{
		printf("\t>>save affine warped subject image to:[%s]. \n",qPrintable(qs_filename_img_sub2tar));
		if(!q_affine_save64f01_image(p_img64f_output_sub,sz_img_sub,qPrintable(qs_filename_img_sub2tar)))
		{
			printf("ERROR: q_save64f01_image() return false!\n");
			releasememory(sz_img_tar,sz_img_sub,p_img_tar_input,p_img_sub_input,p_img64f_tar,p_img64f_sub,p_img64f_sub_bk,p_img64f_tar_1c,p_img64f_sub_1c,p_img64f_output_sub);
			return false;
		}
	}
	//save deformed grid
	if(qs_filename_swc_grid!=NULL)
	{
		printf("\t>>save deformed grid to swc file:[%s]. \n",qPrintable(qs_filename_swc_grid));
		if(!q_affine_savegrid_swc(vec4D_grid,sz_img_sub,qPrintable(qs_filename_swc_grid)))
		{
			printf("ERROR: q_savegrid_swc() return false!\n");
			releasememory(sz_img_tar,sz_img_sub,p_img_tar_input,p_img_sub_input,p_img64f_tar,p_img64f_sub,p_img64f_sub_bk,p_img64f_tar_1c,p_img64f_sub_1c,p_img64f_output_sub);
			return false;
		}
	}

	//------------------------------------------------------------------------------------------------------------------------------------
	//free memory
	printf(">>Free memory\n");
	releasememory(sz_img_tar,sz_img_sub,p_img_tar_input,p_img_sub_input,p_img64f_tar,p_img64f_sub,p_img64f_sub_bk,p_img64f_tar_1c,p_img64f_sub_1c,p_img64f_output_sub);

	printf(">>Program exit success!\n");
	return 0;
}