Example #1
0
void NewFilterDialog::createFiles()
{
  QString class_name     = m_Ui.class_edit->text();
  QString h_file_name    = "new_filters/" + class_name.lower() + ".h";
  QString cpp_file_name  = "new_filters/" + class_name.lower() + ".cpp";
  QFile h_file(h_file_name);
  QFile cpp_file(cpp_file_name);
  h_file.open(QIODevice::WriteOnly);
  cpp_file.open(QIODevice::WriteOnly);
  {
    QTextStream h(&h_file);
    QTextStream cpp(&cpp_file);
    h << "//                                                                         \n";
    h << "// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n";
    h << "// +                                                                      +\n";
    h << "// + This file is part of enVisu.                                         +\n";
    h << "// +                                                                      +\n";
    h << "// + Copyright 2013 O. Gloth, enGits GmbH                                 +\n";
    h << "// +                                                                      +\n";
    h << "// + enGrid is free software: you can redistribute it and/or modify       +\n";
    h << "// + it under the terms of the GNU General Public License as published by +\n";
    h << "// + the Free Software Foundation, either version 3 of the License, or    +\n";
    h << "// + (at your option) any later version.                                  +\n";
    h << "// +                                                                      +\n";
    h << "// + enGrid is distributed in the hope that it will be useful,            +\n";
    h << "// + but WITHOUT ANY WARRANTY; without even the implied warranty of       +\n";
    h << "// + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        +\n";
    h << "// + GNU General Public License for more details.                         +\n";
    h << "// +                                                                      +\n";
    h << "// + You should have received a copy of the GNU General Public License    +\n";
    h << "// + along with enVisu. If not, see <http://www.gnu.org/licenses/>.       +\n";
    h << "// +                                                                      +\n";
    h << "// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n";
    h << "//                                                                         \n";

    h << "#ifndef " << m_Ui.class_edit->text().lower() << "_H\n";
    h << "#define " << m_Ui.class_edit->text().lower() << "_H\n";
    h << "\n";
    h << "class " << class_name << ";\n";
    h << "\n";
    h << "#include \"mpwsitem.h\"\n";
    h << "#include \"" << class_name.lower() << "config.h\"\n";
    h << "\n";
    h << "#include <" << m_Ui.vtk_edit->text() << ".h>\n";
    h << "\n";
    h << "class " << class_name << " : public MpWsItem\n";
    h << "{\n";
    h << "\n";
    h << "    Q_OBJECT\n";
    h << "\n";
    h << "private:\n";
    h << "\n";
    h << "    " << class_name << "Config dlg;\n";
    h << "    " << m_Ui.vtk_edit->text() << " *vtk;\n";
    h << "\n";
    h << "public:\n";
    h << "\n";
    h << "    " << class_name << " (MpWorkSpace *mws);\n";
    h << "    ~" << class_name << "();\n";
    h << "\n";
    if (m_Ui.polydata_rb->isChecked()) {
      h << "    virtual vtkPolyData* getPolyData();\n";
    } else if (m_Ui.dataset_rb->isChecked()) {
      h << "    virtual vtkDataSet* getDataSet();\n";
    } else if (m_Ui.function_rb->isChecked()) {
      h << "    virtual vtkImplicitFunction* getImplicitFunction();\n";
    };
    h << "\n";
    h << "    virtual void setPolyData        (int i, vtkPolyData         *poly_data);\n";
    h << "    virtual void setDataSet         (int i, vtkDataSet          *data_set);\n";
    h << "    virtual void setImplicitFunction(int i, vtkImplicitFunction *implicit_function);\n";
    h << "    virtual void connectInput       (int i);\n";
    h << "    virtual void disconnectInput    (int i);\n";
    h << "    virtual void connectOutput      (int i);\n";
    h << "    virtual void disconnectOutput   (int i);\n";
    h << "\n";
    h << "public slots:\n";
    h << "\n";
    h << "    virtual void apply ();\n";
    h << "    virtual void config();\n";
    h << "    virtual void help  ();\n";
    h << "    virtual void load  (istream &s);\n";
    h << "    virtual void save  (ostream &s);\n";
    h << "\n";
    h << "};\n";
    h << "\n";
    h << "#endif\n";
    cpp << "#include \"" << m_Ui.class_edit->text().lower() << ".h\"\n";
    cpp << "\n";
    cpp << class_name << "::" << class_name << "(MpWorkSpace *mws) :\n";
    cpp << "        MpWsItem(mws)\n";
    cpp << "{\n";
    cpp << "    loadIcon(\"" << class_name.lower() << ".png\");\n";
    cpp << "    ws->addItem(this);\n";
    cpp << "    setName(\"" << class_name << "\");\n";
    cpp << "    vtk = " << m_Ui.vtk_edit->text() << "::New();\n";
    for (int i = 0; i < m_Ui.inputs_lb->count(); ++i) {
      QString text = m_Ui.inputs_lb->text(i);
      QString type = text.left(19).stripWhiteSpace();
      QString name = text.right(text.length()-22).stripWhiteSpace();
      cpp << "    addInput(\"" << name << "\",\"" << type << "\");\n";
    }
    cpp << "    connect(dlg.apply_pb,SIGNAL(clicked()),this,SLOT(apply()));\n";
    cpp << "    connect(dlg.help_pb,SIGNAL(clicked()),this,SLOT(help()));\n";
    cpp << "    dlg.name_edit->setText(name());\n";
    if (m_Ui.polydata_rb->isChecked()) {
      cpp << "    has_output = true;\n";
      cpp << "    output_type = \"vtkPolyData\";\n";
    } else if (m_Ui.dataset_rb->isChecked()) {
      cpp << "    has_output = true;\n";
      cpp << "    output_type = \"vtkDataSet\";\n";
    } else if (m_Ui.function_rb->isChecked()) {
      cpp << "    has_output = true;\n";
      cpp << "    output_type = \"vtkImplicitFunction\";\n";
    } else {
      cpp << "    has_output = false;\n";
    };
    cpp << "    apply();\n";
    cpp << "};\n";
    cpp << "\n";
    cpp << class_name << "::~" << class_name << "()\n";
    cpp << "{\n";
    cpp << "    vtk->Delete();\n";
    cpp << "};\n";
    cpp << "\n";
    cpp << "void " << class_name << "::apply()\n";
    cpp << "{\n";
    cpp << "    changeName(dlg.name_edit->text());\n";
    cpp << "    ws->render();\n";
    cpp << "};\n";
    cpp << "\n";
    cpp << "void " << class_name << "::config()\n";
    cpp << "{\n";
    cpp << "    if (dlg.exec()) apply();\n";
    cpp << "};\n";
    cpp << "\n";
    cpp << "void " << class_name << "::save(ostream &s)\n";
    cpp << "{\n";
    cpp << "    MpWsItem::save(s);\n";
    cpp << "};\n";
    cpp << "\n";
    cpp << "void " << class_name << "::load(istream &s)\n";
    cpp << "{\n";
    cpp << "    MpWsItem::load(s);\n";
    cpp << "    apply();\n";
    cpp << "};\n";
    cpp << "\n";

    if (m_Ui.polydata_rb->isChecked()) {
      cpp << "vtkPolyData* " << class_name;
      cpp << "::getPolyData()\n";
      cpp << "{\n";
      cpp << "    return vtk->GetOutput();\n";
      cpp << "};\n";
    } else if (m_Ui.dataset_rb->isChecked()) {
      cpp << "vtkDataSet* " << class_name;
      cpp << "::getDataSet()\n";
      cpp << "{\n";
      cpp << "    return vtk->GetOutput();\n";
      cpp << "};\n";
    } else if (m_Ui.function_rb->isChecked()) {
      cpp << "vtkImplicitFunction* " << class_name;
      cpp << "::getImplicitFunction()\n";
      cpp << "{\n";
      cpp << "    return vtk;\n";
      cpp << "};\n";
    };
    cpp << "\n";
    cpp << "void " << class_name << "::setPolyData(int i, vtkPolyData *poly_data)\n";
    cpp << "{\n";
    cpp << "};\n";
    cpp << "\n";
    cpp << "void " << class_name << "::setDataSet(int i, vtkDataSet *data_set)\n";
    cpp << "{\n";
    cpp << "};\n";
    cpp << "\n";
    cpp << "void " << class_name << "::setImplicitFunction(int i, vtkImplicitFunction *function)\n";
    cpp << "{\n";
    cpp << "};\n";
    cpp << "\n";
    cpp << "void " << class_name << "::connectInput(int i)\n";
    cpp << "{\n";
    cpp << "};\n";
    cpp << "\n";
    cpp << "void " << class_name << "::disconnectInput(int i)\n";
    cpp << "{\n";
    cpp << "};\n";
    cpp << "\n";
    cpp << "void " << class_name << "::connectOutput(int i)\n";
    cpp << "{\n";
    cpp << "};\n";
    cpp << "\n";
    cpp << "void " << class_name << "::disconnectOutput(int i)\n";
    cpp << "{\n";
    cpp << "};\n";
    cpp << "\n";
    cpp << "void " << class_name << "::help()\n";
    cpp << "{\n";
    cpp << "};\n";
    cpp << "\n";
  }
}
Example #2
0
// -------------------------------------------------------
QString VHDL_File_Info::parsePorts(QString s, int j)
{
  QRegExp Expr;
  Expr.setCaseSensitivity(Qt::CaseInsensitive);
  int i, p, l, k;

  Expr.setPattern("\\bport\\b");  // start of interface definition
  i = s.indexOf(Expr, j+1);
  if(i < 0)
    return QString("");
  // find opening (
  i = s.indexOf('(', i+4) + 1;
  if(i <= 0)
    return QString("");

  // find closing (
  p = i;
  j = i-1;
  do {
    j = s.indexOf(')', j+1);
    if(j < 0)
      return QString("");
    p = s.indexOf('(', p+1);
    if(p >= 0 && p > j) p = -1;
  } while (p >= 0);

  s = s.mid(i, j-i);
  s.remove('\n');
  s.remove('\t');

  // find port names and types in parameter specification
  l = i = 0;    // remove all VHDL identifiers (e.g. ": out bit;")
  QString types = "", t;
  while((i=s.indexOf(':', i)) >= 0) {
    j = s.indexOf(';', i+2);
    if(j < 0) {
      t = s.mid(i+1);
      t.remove(';');
      t = t.simplified();
      s = s.left(i);
    } else {
      t = s.mid(i+1, j-i);
      t.remove(';');
      t = t.simplified();
      s.remove(i, j-i);
    }
    if ((k = t.indexOf(' ')) >= 0)
      t = t.mid(k+1);
    t = t.simplified();
    k = s.indexOf(';',l+2);
    k = (s.mid(l,k-l).count(',')) + 1;
    while (k-->0) types = types + t + ",";
    i--;
    l = i;
  }

  s.remove(' ');
  s.replace(';', ',');
  TypeNames=types=types.left(types.length()-1);
  return s;
}
void QDeclarativePropertyCache::append(QDeclarativeEngine *engine, const QMetaObject *metaObject, 
                                       int revision, 
                                       Data::Flag propertyFlags, Data::Flag methodFlags, Data::Flag signalFlags)
{
    Q_UNUSED(revision);

    allowedRevisionCache.append(0);

    QDeclarativeEnginePrivate *enginePriv = QDeclarativeEnginePrivate::get(engine);
    int methodCount = metaObject->methodCount();
    // 3 to block the destroyed signal and the deleteLater() slot
    int methodOffset = qMax(3, metaObject->methodOffset()); 

    methodIndexCache.resize(methodCount);
    for (int ii = methodOffset; ii < methodCount; ++ii) {
        QMetaMethod m = metaObject->method(ii);
        if (m.access() == QMetaMethod::Private) 
            continue;
        QString methodName = QString::fromUtf8(m.signature());

        int parenIdx = methodName.indexOf(QLatin1Char('('));
        Q_ASSERT(parenIdx != -1);
        methodName = methodName.left(parenIdx);

        RData *data = new RData;
        data->identifier = enginePriv->objectClass->createPersistentIdentifier(methodName);
        methodIndexCache[ii] = data;  

        data->load(m);
        if (m.methodType() == QMetaMethod::Slot || m.methodType() == QMetaMethod::Method) 
            data->flags |= methodFlags;
        else if (m.methodType() == QMetaMethod::Signal)
            data->flags |= signalFlags;

        data->metaObjectOffset = allowedRevisionCache.count() - 1;

        if (stringCache.contains(methodName)) {
            RData *old = stringCache[methodName];
            // We only overload methods in the same class, exactly like C++
            if (old->flags & Data::IsFunction && old->coreIndex >= methodOffset)
                data->relatedIndex = old->coreIndex;
            data->overrideIndexIsProperty = !bool(old->flags & Data::IsFunction);
            data->overrideIndex = old->coreIndex;
            stringCache[methodName]->release();
            identifierCache[data->identifier.identifier]->release();
        }

        stringCache.insert(methodName, data);
        identifierCache.insert(data->identifier.identifier, data);
        data->addref();
        data->addref();
    }

    int propCount = metaObject->propertyCount();
    int propOffset = metaObject->propertyOffset();

    indexCache.resize(propCount);
    for (int ii = propOffset; ii < propCount; ++ii) {
        QMetaProperty p = metaObject->property(ii);
        if (!p.isScriptable())
            continue;

        QString propName = QString::fromUtf8(p.name());

        RData *data = new RData;
        data->identifier = enginePriv->objectClass->createPersistentIdentifier(propName);
        indexCache[ii] = data;

        data->load(p, engine);
        data->flags |= propertyFlags;

        data->metaObjectOffset = allowedRevisionCache.count() - 1;

        if (stringCache.contains(propName)) {
            RData *old = stringCache[propName];
            data->overrideIndexIsProperty = !bool(old->flags & Data::IsFunction);
            data->overrideIndex = old->coreIndex;
            stringCache[propName]->release();
            identifierCache[data->identifier.identifier]->release();
        }

        stringCache.insert(propName, data);
        identifierCache.insert(data->identifier.identifier, data);
        data->addref();
        data->addref();
    }
}
Example #4
0
QString UPnpDevice::toString(uint padding) const
{
    QString ret =
        QString("UPnP Device\n"
                "===========\n"
                "deviceType:       %1\n"
                "friendlyName:     %2\n"
                "manufacturer:     %3\n"
                "manufacturerURL:  %4\n"
                "modelDescription: %5\n"
                "modelName:        %6\n"
                "modelNumber:      %7\n"
                "modelURL:         %8\n")
        .arg(m_sDeviceType      )
        .arg(m_sFriendlyName    )
        .arg(m_sManufacturer    )
        .arg(m_sManufacturerURL )
        .arg(m_sModelDescription)
        .arg(m_sModelName       )
        .arg(m_sModelNumber     )
        .arg(m_sModelURL        ) +
        QString("serialNumber:     %1\n"
                "UPC:              %2\n"
                "presentationURL:  %3\n"
                "UDN:              %4\n")
        .arg(m_sSerialNumber    )
        .arg(m_sUPC             )
        .arg(m_sPresentationURL )
        .arg(m_sUDN             );

    if (!m_lstExtra.empty())
    {
        NameValues::const_iterator it = m_lstExtra.begin();
        ret += "Extra key value pairs\n";
        for (; it != m_lstExtra.end(); ++it)
        {
            ret += (*it).sName;
            ret += ":";
            int int_padding = 18 - ((*it).sName.length() + 1);
            for (int i = 0; i < int_padding; i++)
                ret += " ";
            ret += QString("%1\n").arg((*it).sValue);
        }
    }

    if (!m_listIcons.empty())
    {
        ret += "Icon List:\n";
        UPnpIconList::const_iterator it = m_listIcons.begin();
        for (; it != m_listIcons.end(); ++it)
            ret += (*it)->toString(padding+2) + "\n";
    }

    if (!m_listServices.empty())
    {
        ret += "Service List:\n";
        UPnpServiceList::const_iterator it = m_listServices.begin();
        for (; it != m_listServices.end(); ++it)
            ret += (*it)->toString(padding+2) + "\n";
    }

    if (!m_listDevices.empty())
    {
        ret += "Device List:\n";
        UPnpDeviceList::const_iterator it = m_listDevices.begin();
        for (; it != m_listDevices.end(); ++it)
            ret += (*it)->toString(padding+2) + "\n";
        ret += "\n";
    }

    // remove trailing newline
    if (ret.endsWith("\n"))
        ret = ret.left(ret.length()-1);

    // add any padding as necessary
    if (padding)
    {
        QString pad;
        for (uint i = 0; i < padding; i++)
            pad += " ";
        ret = pad + ret.replace("\n", QString("\n%1").arg(pad));
    }

    return ret;
}
Example #5
0
AuthenticationResult Server::loginUser(Server_ProtocolHandler *session, QString &name, const QString &password, QString &reasonStr, int &secondsLeft)
{
    if (name.size() > 35)
        name = name.left(35);
    
    Server_DatabaseInterface *databaseInterface = getDatabaseInterface();
    
    QWriteLocker locker(&clientsLock);
    
    AuthenticationResult authState = databaseInterface->checkUserPassword(session, name, password, reasonStr, secondsLeft);
    if ((authState == NotLoggedIn) || (authState == UserIsBanned || authState == UsernameInvalid))
        return authState;
    
    ServerInfo_User data = databaseInterface->getUserData(name, true);
    data.set_address(session->getAddress().toStdString());
    name = QString::fromStdString(data.name()); // Compensate for case indifference
    
    databaseInterface->lockSessionTables();
    
    if (authState == PasswordRight) {
        if (users.contains(name) || databaseInterface->userSessionExists(name)) {
            qDebug("Login denied: would overwrite old session");
            databaseInterface->unlockSessionTables();
            return WouldOverwriteOldSession;
        }
    } else if (authState == UnknownUser) {
        // Change user name so that no two users have the same names,
        // don't interfere with registered user names though.
        QSettings settings("servatrice.ini", QSettings::IniFormat);
        bool requireReg = settings.value("authentication/regonly", 0).toBool();
        if (requireReg) {
            qDebug("Login denied: registration required");
            databaseInterface->unlockSessionTables();
            return RegistrationRequired;
        }

        QString tempName = name;
        int i = 0;
        while (users.contains(tempName) || databaseInterface->userExists(tempName) || databaseInterface->userSessionExists(tempName))
            tempName = name + "_" + QString::number(++i);
        name = tempName;
        data.set_name(name.toStdString());
    }
    
    users.insert(name, session);
    qDebug() << "Server::loginUser:"******"name=" << name;
    
    data.set_session_id(databaseInterface->startSession(name, session->getAddress()));  
    databaseInterface->unlockSessionTables();
    
    usersBySessionId.insert(data.session_id(), session);
    
    qDebug() << "session id:" << data.session_id();
    session->setUserInfo(data);
    
    Event_UserJoined event;
    event.mutable_user_info()->CopyFrom(session->copyUserInfo(false));
    SessionEvent *se = Server_ProtocolHandler::prepareSessionEvent(event);
    for (int i = 0; i < clients.size(); ++i)
        if (clients[i]->getAcceptsUserListChanges())
            clients[i]->sendProtocolItem(*se);
    delete se;
    
    event.mutable_user_info()->CopyFrom(session->copyUserInfo(true, true, true));
    locker.unlock();
    
    se = Server_ProtocolHandler::prepareSessionEvent(event);
    sendIsl_SessionEvent(*se);
    delete se;
    
    return authState;
}
Example #6
0
QwtArray<int> LegendWidget::itemsHeight(int y, int symbolLineLength, int &width, int &height)
{
  // RJT (22/09/09): For most of method, copied in code from current 
  // QtiPlot (rev. 1373) to fix infinite loop if closing bracket missing
  QString text = d_text->text();
  QStringList titles = text.split("\n", QString::KeepEmptyParts);
  int n = (int)titles.count();
  QwtArray<int> heights(n);

  width = 0;
  height = 0;
  int maxL = 0;
  int h = top_margin; // In QtiPlot rev 1373: + d_frame_pen.width();
  for (int i=0; i<n; i++){
    QString s = titles[i];
    int textL = 0;
    //bool curveSymbol = false;
    while (s.contains("\\l(",Qt::CaseInsensitive) || s.contains("\\p{",Qt::CaseInsensitive)){
      int pos = s.indexOf("\\l(", 0,Qt::CaseInsensitive);
      int pos2 = s.indexOf(",",pos); // two arguments in case if pie chart
      int pos3 = s.indexOf(")",pos);
      //curveSymbol = true;
      if (pos >= 0 && (pos2==-1 || pos2>pos3)){
        QwtText aux(parse(s.left(pos))); //not a pie chart
        aux.setFont(d_text->font());
        QSize size = aux.textSize(); // In QtiPlot rev 1373: textSize(p, aux);
        textL += size.width();

        int pos1 = s.indexOf("(", pos);
        int pos2 = s.indexOf(")", pos1);
        if (pos2 == -1){
          s = s.right(s.length() - pos1 - 1);
          continue;
        }
        int point = -1;
        PlotCurve *curve = getCurve(s.mid(pos1+1, pos2-pos1-1), point);
        if (!curve){
          s = s.right(s.length() - pos2 - 1);
          continue;
        }

        textL += symbolLineLength + h_space;
        s = s.right(s.length() - s.indexOf(")", pos) - 1);
      } else { //Pie chart?
        pos = s.indexOf("\\p{", 0,Qt::CaseInsensitive); //look for old syntax
        if (pos >= 0){
          QwtText aux(parse(s.left(pos)));
          aux.setFont(d_text->font());
          QSize size = aux.textSize(); // In QtiPlot rev 1373: textSize(p, aux);
          textL += size.width();
          textL += symbolLineLength;
          int pos2=s.indexOf("}", pos);
          if (pos2==-1) pos2=pos+3;
          s = s.right(s.length() - pos2 - 1);
        } else {
          pos = s.indexOf("\\l(", 0,Qt::CaseInsensitive); // new syntax
          if (pos >= 0){
            QwtText aux(parse(s.left(pos)));
            aux.setFont(d_text->font());
            QSize size = aux.textSize(); // In QtiPlot rev 1373: textSize(p, aux);
            textL += size.width();
            textL += symbolLineLength;
            int pos2=s.indexOf(")", pos);
            if (pos2==-1) pos2=pos+3;
            s = s.right(s.length() - pos2 - 1);
          }
        }
      }
    }
    // RJT (22/09/09): End copied in code from rev. 1373

    QwtText aux(parse(s));
    aux.setFont(d_text->font());
    QSize size = aux.textSize();
    textL += size.width();

    if (textL > maxL)
      maxL = textL;

    int textH = size.height();
    height += textH;

    heights[i] = y + h + textH/2;
    h += textH;
  }

  height += 2*top_margin;
  width = 2*left_margin + maxL + h_space;

  return heights;
}
Example #7
0
void IndexDialog::create()
{
    if(!create_flag){
        close();
        return;
    }
    QString unique;
    if(ckUnique->isChecked())
    {
        unique = QString("unique");
    }
    else
    {
        unique = QString();
    }
    QString iname = txtName->text();
    QString collist;

    int row_count = tbColumnList->rowCount();
    int selected_count=0;
    for(int i=0;i<row_count;i++){
        QTableWidgetItem *item = tbColumnList->item(i,0);
        bool isSelected = item->data(Qt::EditRole).toBool();
        if(isSelected){
            QString col;
            if(tbColumnList->item(i,2)->text().isEmpty()){
                col = QString("%1 %3")
                        .arg(tbColumnList->item(i,1)->text())
                        .arg(tbColumnList->item(i,3)->text());
            }else{
                col = QString("%1 Collate%2 %3")
                    .arg(tbColumnList->item(i,1)->text())
                    .arg(tbColumnList->item(i,2)->text())
                    .arg(tbColumnList->item(i,3)->text());
            }
            collist.append(col.trimmed());
            collist.append(",");
            selected_count ++;
        }
    }
    if(selected_count>0){
        collist = collist.left(collist.length()-1);
    }

    QString sql = QString("create %1 index if not exists %2 on %3(%4)")
            .arg(unique).arg(iname).arg(tbname).arg(collist);

    qDebug()<<sql;
    QSqlDatabase db = QSqlDatabase::database(conname);
    QSqlQuery q(db);
    if(q.exec(sql)){
        MainWindow *mw = qobject_cast<MainWindow*>(qApp->activeWindow());
        if(mw!=0)mw->refresh(conname);
    }else{
        QSqlError se = q.lastError();
        QString err = QString(
           "database:%1\ndriver:%2\nerror number:%3"
           "\nerror type:%4\nerror text:%5")
                .arg(se.databaseText())
                .arg(se.driverText())
                .arg(se.number())
                .arg(se.type()).arg(se.text());
        QMessageBox::warning(this,QString("创建错误"),err);
    }
    close();
}
Example #8
0
// ---------------------------------------------------------------------
int SymbolWidget::analyseLine(const QString& Row)
{
  QPen Pen;
  QBrush Brush;
  QColor Color;
  QString s;
  int i1, i2, i3, i4, i5, i6;

  s = Row.section(' ',0,0);    // component type
  if(s == ".PortSym") {  // here: ports are open nodes
    if(!getCompLineIntegers(Row, &i1, &i2, &i3))  return -1;
    Arcs.append(new struct Arc(i1-4, i2-4, 8, 8, 0, 16*360,
                               QPen(Qt::red,1)));

    if((i1-4) < x1)  x1 = i1-4;  // keep track of component boundings
    if((i1+4) > x2)  x2 = i1+4;
    if((i2-4) < y1)  y1 = i2-4;
    if((i2+4) > y2)  y2 = i2+4;
    return 0;   // do not count Ports
  }
  else if(s == "Line") {
    if(!getCompLineIntegers(Row, &i1, &i2, &i3, &i4))  return -1;
    if(!getPen(Row, Pen, 5))  return -1;
    i3 += i1;
    i4 += i2;
    Lines.append(new Line(i1, i2, i3, i4, Pen));

    if(i1 < x1)  x1 = i1;  // keep track of component boundings
    if(i1 > x2)  x2 = i1;
    if(i2 < y1)  y1 = i2;
    if(i2 > y2)  y2 = i2;
    if(i3 < x1)  x1 = i3;
    if(i3 > x2)  x2 = i3;
    if(i4 < y1)  y1 = i4;
    if(i4 > y2)  y2 = i4;
    return 1;
  }
  else if(s == "EArc") {
    if(!getCompLineIntegers(Row, &i1, &i2, &i3, &i4, &i5, &i6))  return -1;
    if(!getPen(Row, Pen, 7))  return -1;
    Arcs.append(new struct Arc(i1, i2, i3, i4, i5, i6, Pen));

    if(i1 < x1)  x1 = i1;  // keep track of component boundings
    if(i1+i3 > x2)  x2 = i1+i3;
    if(i2 < y1)  y1 = i2;
    if(i2+i4 > y2)  y2 = i2+i4;
    return 1;
  }
  else if(s == ".ID") {
    if(!getCompLineIntegers(Row, &i1, &i2))  return -1;
    Text_x = i1;
    Text_y = i2;
    Prefix = Row.section(' ',3,3);
    if(Prefix.isEmpty())  Prefix = "X";
    return 0;   // do not count IDs
  }
  else if(s == "Arrow") {
    if(!getCompLineIntegers(Row, &i1, &i2, &i3, &i4, &i5, &i6))  return -1;
    if(!getPen(Row, Pen, 7))  return -1;

    double beta   = atan2(double(i6), double(i5));
    double phi    = atan2(double(i4), double(i3));
    double Length = sqrt(double(i6*i6 + i5*i5));

    i3 += i1;
    i4 += i2;
    if(i1 < x1)  x1 = i1;  // keep track of component boundings
    if(i1 > x2)  x2 = i1;
    if(i3 < x1)  x1 = i3;
    if(i3 > x2)  x2 = i3;
    if(i2 < y1)  y1 = i2;
    if(i2 > y2)  y2 = i2;
    if(i4 < y1)  y1 = i4;
    if(i4 > y2)  y2 = i4;

    Lines.append(new Line(i1, i2, i3, i4, Pen));   // base line

    double w = beta+phi;
    i5 = i3-int(Length*cos(w));
    i6 = i4-int(Length*sin(w));
    Lines.append(new Line(i3, i4, i5, i6, Pen)); // arrow head
    if(i5 < x1)  x1 = i5;  // keep track of component boundings
    if(i5 > x2)  x2 = i5;
    if(i6 < y1)  y1 = i6;
    if(i6 > y2)  y2 = i6;

    w = phi-beta;
    i5 = i3-int(Length*cos(w));
    i6 = i4-int(Length*sin(w));
    Lines.append(new Line(i3, i4, i5, i6, Pen));
    if(i5 < x1)  x1 = i5;  // keep track of component boundings
    if(i5 > x2)  x2 = i5;
    if(i6 < y1)  y1 = i6;
    if(i6 > y2)  y2 = i6;

    return 1;
  }
  else if(s == "Ellipse") {
    if(!getCompLineIntegers(Row, &i1, &i2, &i3, &i4))  return -1;
    if(!getPen(Row, Pen, 5))  return -1;
    if(!getBrush(Row, Brush, 8))  return -1;
    Ellips.append(new Area(i1, i2, i3, i4, Pen, Brush));

    if(i1 < x1)  x1 = i1;  // keep track of component boundings
    if(i1 > x2)  x2 = i1;
    if(i2 < y1)  y1 = i2;
    if(i2 > y2)  y2 = i2;
    if(i1+i3 < x1)  x1 = i1+i3;
    if(i1+i3 > x2)  x2 = i1+i3;
    if(i2+i4 < y1)  y1 = i2+i4;
    if(i2+i4 > y2)  y2 = i2+i4;
    return 1;
  }
  else if(s == "Rectangle") {
    if(!getCompLineIntegers(Row, &i1, &i2, &i3, &i4))  return -1;
    if(!getPen(Row, Pen, 5))  return -1;
    if(!getBrush(Row, Brush, 8))  return -1;
    Rects.append(new Area(i1, i2, i3, i4, Pen, Brush));

    if(i1 < x1)  x1 = i1;  // keep track of component boundings
    if(i1 > x2)  x2 = i1;
    if(i2 < y1)  y1 = i2;
    if(i2 > y2)  y2 = i2;
    if(i1+i3 < x1)  x1 = i1+i3;
    if(i1+i3 > x2)  x2 = i1+i3;
    if(i2+i4 < y1)  y1 = i2+i4;
    if(i2+i4 > y2)  y2 = i2+i4;
    return 1;
  }
  else if(s == "Text") {  // must be last in order to reuse "s" *********
    if(!getCompLineIntegers(Row, &i1, &i2, &i3))  return -1;
    Color.setNamedColor(Row.section(' ',4,4));
    if(!Color.isValid()) return -1;

    s = Row.mid(Row.indexOf('"')+1);    // Text (can contain " !!!)
    s = s.left(s.length()-1);
    if(s.isEmpty()) return -1;
    s.replace("\\n", "\n");
    s.replace("\\\\", "\\");

    Texts.append(new Text(i1, i2, s, Color, float(i3)));

    QFont Font(QucsSettings.font);
    Font.setPointSizeF(float(i3));
    QFontMetrics  metrics(Font, 0);  // use the the screen-compatible metric
    QSize r = metrics.size(0, s);  // get size of text
    i3 = i1 + r.width();
    i4 = i2 + r.height();

    if(i1 < x1)  x1 = i1;  // keep track of component boundings
    if(i3 > x2)  x2 = i3;
    if(i2 < y1)  y1 = i2;
    if(i4 > y2)  y2 = i4;
  }

  return 0;
}
Example #9
0
ProgInfo *XMLTVParser::parseProgram(QDomElement &element)
{
    QString uniqueid, season, episode, totalepisodes;
    int dd_progid_done = 0;
    ProgInfo *pginfo = new ProgInfo();

    QString text = element.attribute("start", "");
    fromXMLTVDate(text, pginfo->starttime);
    pginfo->startts = text;

    text = element.attribute("stop", "");
    fromXMLTVDate(text, pginfo->endtime);
    pginfo->endts = text;

    text = element.attribute("channel", "");
    QStringList split = text.split(" ");

    pginfo->channel = split[0];

    text = element.attribute("clumpidx", "");
    if (!text.isEmpty())
    {
        split = text.split('/');
        pginfo->clumpidx = split[0];
        pginfo->clumpmax = split[1];
    }

    for (QDomNode child = element.firstChild(); !child.isNull();
         child = child.nextSibling())
    {
        QDomElement info = child.toElement();
        if (!info.isNull())
        {
            if (info.tagName() == "title")
            {
                if (info.attribute("lang") == "ja_JP")
                {
                    pginfo->title = getFirstText(info);
                }
                else if (info.attribute("lang") == "ja_JP@kana")
                {
                    pginfo->title_pronounce = getFirstText(info);
                }
                else if (pginfo->title.isEmpty())
                {
                    pginfo->title = getFirstText(info);
                }
            }
            else if (info.tagName() == "sub-title" &&
                     pginfo->subtitle.isEmpty())
            {
                pginfo->subtitle = getFirstText(info);
            }
            else if (info.tagName() == "desc" && pginfo->description.isEmpty())
            {
                pginfo->description = getFirstText(info);
            }
            else if (info.tagName() == "category")
            {
                const QString cat = getFirstText(info).toLower();

                if (ProgramInfo::kCategoryNone == pginfo->categoryType &&
                    string_to_myth_category_type(cat) != ProgramInfo::kCategoryNone)
                {
                    pginfo->categoryType = string_to_myth_category_type(cat);
                }
                else if (pginfo->category.isEmpty())
                {
                    pginfo->category = cat;
                }

                if (cat == QObject::tr("movie") || cat == QObject::tr("film"))
                {
                    // Hack for tv_grab_uk_rt
                    pginfo->categoryType = ProgramInfo::kCategoryMovie;
                }
            }
            else if (info.tagName() == "date" && !pginfo->airdate)
            {
                // Movie production year
                QString date = getFirstText(info);
                pginfo->airdate = date.left(4).toUInt();
            }
            else if (info.tagName() == "star-rating" && pginfo->stars.isEmpty())
            {
                QDomNodeList values = info.elementsByTagName("value");
                QDomElement item;
                QString stars, num, den;
                float rating = 0.0;

                // Use the first rating to appear in the xml, this should be
                // the most important one.
                //
                // Averaging is not a good idea here, any subsequent ratings
                // are likely to represent that days recommended programmes
                // which on a bad night could given to an average programme.
                // In the case of uk_rt it's not unknown for a recommendation
                // to be given to programmes which are 'so bad, you have to
                // watch!'
                item = values.item(0).toElement();
                if (!item.isNull())
                {
                    stars = getFirstText(item);
                    num = stars.section('/', 0, 0);
                    den = stars.section('/', 1, 1);
                    if (0.0 < den.toFloat())
                        rating = num.toFloat()/den.toFloat();
                }

                pginfo->stars.setNum(rating);
            }
            else if (info.tagName() == "rating")
            {
                // again, the structure of ratings seems poorly represented
                // in the XML.  no idea what we'd do with multiple values.
                QDomNodeList values = info.elementsByTagName("value");
                QDomElement item = values.item(0).toElement();
                if (item.isNull())
                    continue;
                EventRating rating;
                rating.system = info.attribute("system", "");
                rating.rating = getFirstText(item);
                pginfo->ratings.append(rating);
            }
            else if (info.tagName() == "previously-shown")
            {
                pginfo->previouslyshown = true;

                QString prevdate = info.attribute("start");
                if (!prevdate.isEmpty())
                {
                    QDateTime date;
                    fromXMLTVDate(prevdate, date);
                    pginfo->originalairdate = date.date();
                }
            }
            else if (info.tagName() == "credits")
            {
                parseCredits(info, pginfo);
            }
            else if (info.tagName() == "subtitles")
            {
                if (info.attribute("type") == "teletext")
                    pginfo->subtitleType |= SUB_NORMAL;
                else if (info.attribute("type") == "onscreen")
                    pginfo->subtitleType |= SUB_ONSCREEN;
                else if (info.attribute("type") == "deaf-signed")
                    pginfo->subtitleType |= SUB_SIGNED;
            }
            else if (info.tagName() == "audio")
            {
                parseAudio(info, pginfo);
            }
            else if (info.tagName() == "video")
            {
                parseVideo(info, pginfo);
            }
            else if (info.tagName() == "episode-num")
            {
                if (info.attribute("system") == "dd_progid")
                {
                    QString episodenum(getFirstText(info));
                    // if this field includes a dot, strip it out
                    int idx = episodenum.indexOf('.');
                    if (idx != -1)
                        episodenum.remove(idx, 1);
                    pginfo->programId = episodenum;
                    dd_progid_done = 1;
                }
                else if (info.attribute("system") == "xmltv_ns")
                {
                    int tmp;
                    QString episodenum(getFirstText(info));
                    episode = episodenum.section('.',1,1);
                    totalepisodes = episode.section('/',1,1).trimmed();
                    episode = episode.section('/',0,0).trimmed();
                    season = episodenum.section('.',0,0).trimmed();
                    QString part(episodenum.section('.',2,2));
                    QString partnumber(part.section('/',0,0).trimmed());
                    QString parttotal(part.section('/',1,1).trimmed());

                    pginfo->categoryType = ProgramInfo::kCategorySeries;

                    if (!season.isEmpty())
                    {
                        tmp = season.toUInt() + 1;
                        pginfo->season = tmp;
                        season = QString::number(tmp);
                        pginfo->syndicatedepisodenumber = QString('S' + season);
                    }

                    if (!episode.isEmpty())
                    {
                        tmp = episode.toUInt() + 1;
                        pginfo->episode = tmp;
                        episode = QString::number(tmp);
                        pginfo->syndicatedepisodenumber.append(QString('E' + episode));
                    }

                    if (!totalepisodes.isEmpty())
                    {
                        pginfo->totalepisodes = totalepisodes.toUInt();
                    }

                    uint partno = 0;
                    if (!partnumber.isEmpty())
                    {
                        bool ok;
                        partno = partnumber.toUInt(&ok) + 1;
                        partno = (ok) ? partno : 0;
                    }

                    if (!parttotal.isEmpty() && partno > 0)
                    {
                        bool ok;
                        uint partto = parttotal.toUInt(&ok);
                        if (ok && partnumber <= parttotal)
                        {
                            pginfo->parttotal  = partto;
                            pginfo->partnumber = partno;
                        }
                    }
                }
                else if (info.attribute("system") == "onscreen")
                {
                    pginfo->categoryType = ProgramInfo::kCategorySeries;
                    if (pginfo->subtitle.isEmpty())
                    {
                        pginfo->subtitle = getFirstText(info);
                    }
                }
                else if ((info.attribute("system") == "themoviedb.org") &&
                    (MetadataDownload::GetMovieGrabber().endsWith(QString("/tmdb3.py"))))
                {
                    /* text is movie/<inetref> */
                    QString inetrefRaw(getFirstText(info));
                    if (inetrefRaw.startsWith(QString("movie/"))) {
                        QString inetref(QString ("tmdb3.py_") + inetrefRaw.section('/',1,1).trimmed());
                        pginfo->inetref = inetref;
                    }
                }
                else if ((info.attribute("system") == "thetvdb.com") &&
                    (MetadataDownload::GetTelevisionGrabber().endsWith(QString("/ttvdb.py"))))
                {
                    /* text is series/<inetref> */
                    QString inetrefRaw(getFirstText(info));
                    if (inetrefRaw.startsWith(QString("series/"))) {
                        QString inetref(QString ("ttvdb.py_") + inetrefRaw.section('/',1,1).trimmed());
                        pginfo->inetref = inetref;
                        /* ProgInfo does not have a collectionref, so we don't set any */
                    }
                }
            }
        }
    }

    if (pginfo->category.isEmpty() &&
        pginfo->categoryType != ProgramInfo::kCategoryNone)
        pginfo->category = myth_category_type_to_string(pginfo->categoryType);

    if (!pginfo->airdate)
        pginfo->airdate = current_year;

    /* Let's build ourself a programid */
    QString programid;

    if (ProgramInfo::kCategoryMovie == pginfo->categoryType)
        programid = "MV";
    else if (ProgramInfo::kCategorySeries == pginfo->categoryType)
        programid = "EP";
    else if (ProgramInfo::kCategorySports == pginfo->categoryType)
        programid = "SP";
    else
        programid = "SH";

    if (!uniqueid.isEmpty()) // we already have a unique id ready for use
        programid.append(uniqueid);
    else
    {
        QString seriesid = QString::number(ELFHash(pginfo->title.toUtf8()));
        pginfo->seriesId = seriesid;
        programid.append(seriesid);

        if (!episode.isEmpty() && !season.isEmpty())
        {
            /* Append unpadded episode and season number to the seriesid (to
               maintain consistency with historical encoding), but limit the
               season number representation to a single base-36 character to
               ensure unique programid generation. */
            int season_int = season.toInt();
            if (season_int > 35)
            {
                // Cannot represent season as a single base-36 character, so
                // remove the programid and fall back to normal dup matching.
                if (ProgramInfo::kCategoryMovie != pginfo->categoryType)
                    programid.clear();
            }
            else
            {
                programid.append(episode);
                programid.append(QString::number(season_int, 36));
                if (pginfo->partnumber && pginfo->parttotal)
                {
                    programid += QString::number(pginfo->partnumber);
                    programid += QString::number(pginfo->parttotal);
                }
            }
        }
        else
        {
            /* No ep/season info? Well then remove the programid and rely on
               normal dupchecking methods instead. */
            if (ProgramInfo::kCategoryMovie != pginfo->categoryType)
                programid.clear();
        }
    }
    if (dd_progid_done == 0)
        pginfo->programId = programid;

    return pginfo;
}
Example #10
0
void Widget::udpProcessPendingDatagrams()
{
    while (udpSocket->hasPendingDatagrams())
    {
        QHostAddress rAddr;
        quint16 rPort;
        QByteArray datagram;
        qint64 dataRead = 0;
        int datagramSize = udpSocket->pendingDatagramSize();
        datagram.resize(datagramSize);

        while(dataRead < datagram.size())
        {
            qint64 readNow = udpSocket->readDatagram(datagram.data()+dataRead, datagramSize, &rAddr, &rPort); // le +dataRead sur un tableau, ça décale le pointeur d'un offset de taille dataRead !
            if(readNow != -1)
            {
                dataRead += readNow; // Counts the number of bytes read in total, stop when DataRead reached pendingDatagramSize
                if (datagramSize > (datagram.size() - dataRead)) // Evite de lire après la fin du tableau en mode fragmenté, evite donc que dataSent dépasse datagramSize, sinon Overflow et envoi de données inutiles et aléatoires !!
                    datagramSize = (datagram.size() - dataRead);
                //QMessageBox::information(NULL,"SenderInfo",QString("DatagramSize : %1  sentNow : %2  dataSent : %3 Sizeof(datagram->data()) : %4").arg(QString().setNum(datagramSize),QString().setNum(sentNow),QString().setNum(dataSent),QString().setNum(datagram->size())));
            }
            else
            {
                // Here, we add a message to the udpMessages for filtering later.
                logStatusMessage(QString("Socket error: ").arg(udpSocket->errorString()), udpTag);
                return;
            }
        }

        // Add player on connection
        if ((unsigned char)datagram[0]==MsgConnect && (unsigned char)datagram[1]==0
                && (unsigned char)datagram[2]==0 && datagram.size()>=22)
        {
            QString name = dataToString(datagram.right(datagram.size()-22));
            int nameFullSize = getVUint32Size(datagram.right(datagram.size()-22))+name.size();
            QString sesskey = dataToString(datagram.right(datagram.size()-22-nameFullSize));
            //logMessage(QString("UDP: Connect detected with name : ")+name, udpTag);
            //logMessage(QString("UDP: Connect detected with sesskey : ")+sesskey, udpTag);
            //logMessage(QString("UDP: Datagram was : ")+datagram.toHex(), udpTag);

            bool is_sesskey_valid = true;

            if (enableSessKeyValidation) {
                is_sesskey_valid = QCryptographicHash::hash(QString(sesskey.right(40) + saltPassword).toLatin1(), QCryptographicHash::Md5).toHex() == sesskey.left(32);
            }

            if (is_sesskey_valid)
            {
                //logMessage("Sesskey token accepted", udpTag);

                // Create new player if needed, else just update player
                Player* newPlayer = Player::findPlayer(udpPlayers, rAddr.toString(),rPort);
                if (newPlayer->IP != rAddr.toString()) // IP:Port not found in player list
                {
                    newPlayer->resetNetwork();
                    //newPlayer->connected = true; // Not really connected until we finish the handshake
                    newPlayer->name = name;
                    newPlayer->IP = rAddr.toString();
                    newPlayer->port = rPort;

                    // Check if we have too many players connected
                    int n=0;
                    for (int i=0;i<udpPlayers.size();i++)
                        if (udpPlayers[i]->connected)
                            n++;
                    if (n>=maxConnected)
                    {
                        sendMessage(newPlayer, MsgDisconnect, "Error: Too many players connected. Try again later.");
                    }
                    else
                        // If not add the player
                        udpPlayers << newPlayer;
                }
                else  // IP:Port found in player list
                {
                    if (newPlayer->connected) // TODO: Error, player already connected
                    {
                        sendMessage(newPlayer, MsgDisconnect, "Error: Player already connected.");
                        return;
                    }

                    // Check if we have too many players connected
                    int n=0;
                    for (int i=0;i<udpPlayers.size();i++)
                        if (udpPlayers[i]->connected)
                            n++;
                    if (n>=maxConnected)
                    {
                        sendMessage(newPlayer, MsgDisconnect, "Error: Too many players connected. Try again later.");
                    }

                    newPlayer->resetNetwork();
                    newPlayer->name = name;
                    newPlayer->IP = rAddr.toString();
                    newPlayer->port = rPort;
                    //newPlayer->connected = true; // We're not really connected until we finish the handshake
                }
            }
            else
            {
                QString badHash = QCryptographicHash::hash((QString(sesskey.right(40))
                                +saltPassword).toLatin1(), QCryptographicHash::Md5).toHex();
                logMessage("UDP: Sesskey rejected: got '"+badHash+"' instead of '"+sesskey.left(32)+"', passhash was '"+QString(sesskey.right(40)), udpTag);
                Player* newPlayer = new Player;
                newPlayer->IP = rAddr.toString();
                newPlayer->port = rPort;
                sendMessage(newPlayer, MsgDisconnect, "Error : Wrong sesskey hash.");
                return;
            }
        }

        Player* player = Player::findPlayer(udpPlayers, rAddr.toString(), rPort);
        if (player->IP == rAddr.toString() && player->port == rPort)
        {
            // Acquire data
            player->receivedDatas->append(datagram);

            // Process data
            receiveMessage(player);
        }
        else // You need to connect with TCP first
        {
            logMessage("UDP: Request from unknown peer rejected : "+rAddr.toString()+":"+QString().setNum(rPort), udpTag);
            // Send disconnect message manually, with an appropriate message.
            QString data("BITCH, YOU ARE EITHER A HACKER OR THE SERVER JUST HATES THE F**K OUT OF YOU. RELOG OR YOU AINT GETTIN ON THIS SERVER, K?");
            QByteArray msg(6,0);
            msg[0] = MsgDisconnect;
            msg[3] = (quint8)(((data.size()+1)*8)&0xFF);
            msg[4] = (quint8)((((data.size()+1)*8)>>8)&0xFF);
            msg[5] = (quint8)data.size();
            msg += data;
            win.udpSocket->writeDatagram(msg,rAddr,rPort);
        }
    }
}
Example #11
0
void gtAction::write(const QString& text, gtStyle *style, bool isNote)
{
	if (m_isFirstWrite)
	{
		if (!m_doAppend)
		{
			if (m_it->nextInChain() != 0)
			{
				PageItem *nextItem = m_it->nextInChain();
				while (nextItem != 0)
				{
					nextItem->itemText.clear();
					nextItem = nextItem->nextInChain();
				}
			}
			m_it->itemText.clear();
		}
	}
	int paragraphStyle = -1;
	if (style->target() == "paragraph")
	{
		gtParagraphStyle* pstyle = dynamic_cast<gtParagraphStyle*>(style);
		assert(pstyle != NULL);
		paragraphStyle = applyParagraphStyle(pstyle);
		if (m_isFirstWrite)
			m_inPara = true;
	}
	else if (style->target() == "frame")
	{
		gtFrameStyle* fstyle = dynamic_cast<gtFrameStyle*>(style);
		assert(fstyle != NULL);
		applyFrameStyle(fstyle);
	}

	if ((m_inPara) && (!m_lastCharWasLineChange) && (text.left(1) != "\n") && (m_lastParagraphStyle != -1))
		paragraphStyle = m_lastParagraphStyle;

	if (paragraphStyle == -1)
		paragraphStyle = 0; //::findParagraphStyle(textFrame->doc(), textFrame->doc()->currentStyle);

	const ParagraphStyle& paraStyle = m_textFrame->doc()->paragraphStyles()[paragraphStyle];

	gtFont* font = style->getFont();
//	QString fontName = validateFont(font).scName();
	CharStyle lastStyle, newStyle;
	int lastStyleStart = 0;
	
	if ((m_inPara) && (!m_overridePStyleFont))
	{
		if (paraStyle.charStyle().font().isNone())
		{
			gtFont font2(*font);
			font2.setName(paraStyle.charStyle().font().scName());
			QString fontName2 = validateFont(&font2).scName();
			newStyle.setFont((*m_textFrame->doc()->AllFonts)[fontName2]);
		}
	}
	else
	{
		setCharStyleAttributes(font, newStyle);
	}
	/*newStyle.eraseCharStyle(paraStyle.charStyle());*/

	lastStyle = newStyle;
	lastStyleStart = m_it->itemText.length();
	StoryText* story = NULL;
	if (isNote)
	{
		if (m_noteStory == NULL)
		{
			m_note = m_it->m_Doc->newNote(m_it->m_Doc->m_docNotesStylesList.at(0));
			m_noteStory = new StoryText(m_it->m_Doc);
		}
		story = m_noteStory;
	}
	else
		story = &m_it->itemText;

	QChar ch0(0), ch5(5), ch10(10), ch13(13); 
	for (int a = 0; a < text.length(); ++a)
	{
		if ((text.at(a) == ch0) || (text.at(a) == ch13))
			continue;
		QChar ch = text.at(a);
		if ((ch == ch10) || (ch == ch5))
			ch = ch13;
		
		int pos = story->length();
		if (isNote && ch == SpecialChars::OBJECT)
		{
			NotesStyle* nStyle = m_note->notesStyle();
			QString label = "NoteMark_" + nStyle->name();
			if (nStyle->range() == NSRsection)
				label += " in section " + m_it->m_Doc->getSectionNameForPageIndex(m_it->OwnPage) + " page " + QString::number(m_it->OwnPage +1);
			else if (nStyle->range() == NSRpage)
				label += " on page " + QString::number(m_it->OwnPage +1);
			else if (nStyle->range() == NSRstory)
				label += " in " + m_it->firstInChain()->itemName();
			else if (nStyle->range() == NSRframe)
				label += " in frame" + m_it->itemName();
			if (m_it->m_Doc->getMark(label + "_1", MARKNoteMasterType) != NULL)
				getUniqueName(label,m_it->m_Doc->marksLabelsList(MARKNoteMasterType), "_"); //FIX ME here user should be warned that inserted mark`s label was changed
			else
				label = label + "_1";
			Mark* mrk = m_it->m_Doc->newMark();
			mrk->label = label;
			mrk->setType(MARKNoteMasterType);
			mrk->setNotePtr(m_note);
			m_note->setMasterMark(mrk);
			mrk->setString("");
			mrk->OwnPage = m_it->OwnPage;
			m_it->itemText.insertMark(mrk);
			story->applyCharStyle(lastStyleStart, story->length()-lastStyleStart, lastStyle);
			if (paraStyle.hasName())
			{
				ParagraphStyle pStyle;
				pStyle.setParent(paraStyle.name());
				story->applyStyle(qMax(0,story->length()-1), pStyle);
			}
			else
				story->applyStyle(qMax(0,story->length()-1), paraStyle);
			
			m_lastCharWasLineChange = text.right(1) == "\n";
			m_inPara = style->target() == "paragraph";
			m_lastParagraphStyle = paragraphStyle;
			if (m_isFirstWrite)
				m_isFirstWrite = false;
			if (story->text(pos -1) == SpecialChars::PARSEP)
				story->removeChars(pos-1, 1);
			m_note->setSaxedText(saxedText(story));
			m_note = NULL;
			delete m_noteStory;
			m_noteStory = NULL;
			return;
		}
		else
			story->insertChars(pos, QString(ch));
		if (ch == SpecialChars::PARSEP) 
		{
			if (paraStyle.hasName())
			{
				ParagraphStyle pstyle;
				pstyle.setParent(paraStyle.name());
				story->applyStyle(pos, pstyle);
			}
			else
				story->applyStyle(pos, paraStyle);
		}
	}
	story->applyCharStyle(lastStyleStart, story->length()-lastStyleStart, lastStyle);
	if (paraStyle.hasName())
	{
		ParagraphStyle pStyle;
		pStyle.setParent(paraStyle.name());
		story->applyStyle(qMax(0,story->length()-1), pStyle);
	}
	else
		story->applyStyle(qMax(0,story->length()-1), paraStyle);
	
	m_lastCharWasLineChange = text.right(1) == "\n";
	m_inPara = style->target() == "paragraph";
	m_lastParagraphStyle = paragraphStyle;
	if (m_isFirstWrite)
		m_isFirstWrite = false;
}
Example #12
0
void MainWindow::openFile()
{
    QFileDialog dialog(this, tr("Open File"),
                       directory,
                       tr("NC (*.nc);;All Files (*.*)"));

    dialog.setFileMode(QFileDialog::ExistingFile);

    if (nameFilter.size() > 0)
        dialog.selectNameFilter(nameFilter);

    if (fileOpenDialogState.size() > 0)
        dialog.restoreState(fileOpenDialogState);

    QString fileName;
    QStringList fileNames;
    if (dialog.exec())
    {
        fileOpenDialogState = dialog.saveState();

        fileNames = dialog.selectedFiles();
        if (fileNames.length() > 0)
            fileName = fileNames.at(0);

        nameFilter = dialog.selectedNameFilter();

        resetProgress();
    }

    int slash = fileName.lastIndexOf('/');
    if (slash == -1)
    {
        slash = fileName.lastIndexOf('\\');
    }

    directory = "";
    if (slash != -1)
    {
        directory = fileName.left(slash);
    }

    ui->filePath->setText(fileName);
    if(ui->filePath->text().length() > 0 && ui->btnOpenPort->text() == close_button_text)
    {
        ui->Begin->setEnabled(true);
        ui->Stop->setEnabled(false);
        ui->progressFileSend->setEnabled(false);
        ui->outputRuntime->setEnabled(false);
        ui->labelRuntime->setEnabled(false);
    }
    else
    {
        ui->Begin->setEnabled(false);
        ui->Stop->setEnabled(false);
        ui->progressFileSend->setEnabled(false);
        ui->outputRuntime->setEnabled(false);
        ui->labelRuntime->setEnabled(false);
    }

    if (ui->filePath->text().length() > 0)
    {
        // read in the file to process it
        preProcessFile(ui->filePath->text());

        if (ui->tabAxisVisualizer->currentIndex() != TAB_VISUALIZER_INDEX)
        {
            emit ui->tabAxisVisualizer->setCurrentIndex(TAB_VISUALIZER_INDEX);
        }
    }
}
Example #13
0
void KoskoNetwork::makePath(QString path, QVector<int> &nowImg) {
	int lenOfNum;
	QVector<int> intPath;
	int leftBorder = 10000, upperBorder = -1000, rightBorder = -1000, bottomBorder = 10000, tmp;
	QVector<bool> isInc;
	while (path != "") {
		if (path[1] == '|') {
			isInc << 0;
			path = path.right(path.size() - 3);
			if (path == "")
				break;
		}
		else
			isInc << 1;
		lenOfNum = path.indexOf(",", 0);
		tmp = path.left(lenOfNum).toInt();
		intPath << tmp;
		if (tmp < leftBorder) {
			leftBorder = tmp;
		}
		if (tmp > rightBorder) {
			rightBorder = tmp;
		}
		path = path.right(path.size() - lenOfNum - 2);
		lenOfNum = path.indexOf(" ", 0);
		tmp = path.left(lenOfNum).toInt();
		intPath << tmp;
		if (tmp < bottomBorder) {
			bottomBorder = tmp;
		}
		if (tmp > upperBorder) {
			upperBorder = tmp;
		}
		path = path.right(path.size() - lenOfNum - 3);
	}
	int i;
	for (i = 0; i < intPath.size(); i += 2) {
		intPath[i] -= leftBorder;
		intPath[i + 1] -= bottomBorder;
	}
	nowImg.fill(0);
	int width = rightBorder - leftBorder + 1;
	int height = upperBorder - bottomBorder + 1;
	QVector<int> img (width * height, 0);
	for (i = 0; i < intPath.size() - 2; i += 2) {
		if (isInc[1 + i / 2]) {
			makeLine(intPath.at(i)
					 , intPath.at(i + 1)
					 , intPath.at(i + 2)
					 , intPath.at(i + 3)
					 , width
					 , height
					 , img
					 );
		}
	}
	int leftCM, rightCM, upperCM, bottomCM;
	makeMassCentres(img, width, height, leftCM, rightCM, upperCM, bottomCM);
	fitToSize(intPath, isInc, nowImg, leftCM, rightCM, upperCM, bottomCM);
	outp(nowImg);
}
void BoundTextBox::finalise()
{
	QString value = text();

	while (value.endsWith(","))
		value = value.left(value.length() - 1);

	if (_integerArray != NULL)
	{
		_integerArray->setValue(QIntArrayValidator::parse(value));
	}
	else if (_integer != NULL)
	{
		//_integer->setValue(value.toInt());

		double v = value.toInt();
		double min = _integer->min();
		double max = _integer->max();

		bool pc = _integer->format() == "%";

		if (pc)
		{
			v /= 100;
			min *= 100;
			max *= 100;
		}

		if (v > _integer->max() || v < _integer->min())
		{
			if (pc)
			{
				setIllegal(QString("%1 must be between %2% and %3%").arg(_label).arg(min).arg(max));
			}
			else
			{
				setIllegal(QString("%1 must be between %2 and %3").arg(_label).arg(min).arg(max));
			}
		}
		else
		{
			_integer->setValue(v);
			setLegal();
		}
	}
	else if (_number != NULL)
	{
		double v = value.toDouble();
		double min = _number->min();
		double max = _number->max();

		bool pc = _number->format() == "%";

		if (pc)
		{
			v /= 100;
			min *= 100;
			max *= 100;
		}

		if (v > _number->max() || v < _number->min())
		{
			if (pc)
			{
				setIllegal(QString("%1 must be between %2% and %3%").arg(_label).arg(min).arg(max));
			}
			else
			{
				setIllegal(QString("%1 must be between %2 and %3").arg(_label).arg(min).arg(max));
			}
		}
		else
		{
			_number->setValue(v);
			setLegal();
		}
	}
}
Example #15
0
bool ScriptDebuggerPrivate::executeCommand(const QString &command, const QStringList &args)
{
    if (command == QLatin1String("c")
        || command == QLatin1String("continue")) {
        setMode(Run);
        return true;
    } else if (command == QLatin1String("s")
               || command == QLatin1String("step")) {
        setMode(StepInto);
        return true;
    } else if (command == QLatin1String("n")
               || command == QLatin1String("next")) {
        setMode(StepOver);
        m_stepDepth = 0;
        return true;
    } else if (command == QLatin1String("f")
               || command == QLatin1String("frame")) {
        bool ok = false;
        int index = args.value(0).toInt(&ok);
        if (ok) {
            if (index < 0 || index >= frameCount()) {
                errorMessage("No such frame.");
            } else {
                setCurrentFrameIndex(index);
                QScriptContext *ctx = currentFrameContext();
                message(QString::fromLatin1("#%0  %1").arg(index).arg(ctx->toString()));
            }
        }
    } else if (command == QLatin1String("bt")
               || command == QLatin1String("backtrace")) {
        QScriptContext *ctx = engine()->currentContext();
        int index = -1;
        while (ctx) {
            ++index;
            QString line = ctx->toString();
            message(QString::fromLatin1("#%0  %1").arg(index).arg(line));
            ctx = ctx->parentContext();
        }
    } else if (command == QLatin1String("up")) {
        int index = currentFrameIndex() + 1;
        if (index == frameCount()) {
            errorMessage(QString::fromLatin1("Initial frame selected; you cannot go up."));
        } else {
            setCurrentFrameIndex(index);
            QScriptContext *ctx = currentFrameContext();
            message(QString::fromLatin1("#%0  %1").arg(index).arg(ctx->toString()));
        }
    } else if (command == QLatin1String("down")) {
        int index = currentFrameIndex() - 1;
        if (index < 0) {
            errorMessage(QString::fromLatin1("Bottom (innermost) frame selected; you cannot go down."));
        } else {
            setCurrentFrameIndex(index);
            QScriptContext *ctx = currentFrameContext();
            message(QString::fromLatin1("#%0  %1").arg(index).arg(ctx->toString()));
        }
    } else if (command == QLatin1String("b")
               || command == QLatin1String("break")) {
        QString str = args.value(0);
        int colonIndex = str.indexOf(QLatin1Char(':'));
        if (colonIndex != -1) {
            // filename:line form
            QString fileName = str.left(colonIndex);
            int lineNumber = str.mid(colonIndex+1).toInt();
            int id = m_bpManager->setBreakpoint(fileName, lineNumber);
            message(QString::fromLatin1("Breakpoint %0 at %1, line %2.").arg(id+1).arg(fileName).arg(lineNumber));
        } else {
            // function
            QScriptValue fun = engine()->globalObject().property(str);
            if (fun.isFunction()) {
                int id = m_bpManager->setBreakpoint(fun);
                message(QString::fromLatin1("Breakpoint %0 at %1().").arg(id+1).arg(str));
            }
        }
    } else if (command == QLatin1String("d")
               || command == QLatin1String("delete")) {
        int id = args.value(0).toInt() - 1;
        m_bpManager->removeBreakpoint(id);
    } else if (command == QLatin1String("disable")) {
        int id = args.value(0).toInt() - 1;
        m_bpManager->setBreakpointEnabled(id, false);
    } else if (command == QLatin1String("enable")) {
        int id = args.value(0).toInt() - 1;
        m_bpManager->setBreakpointEnabled(id, true);
    } else if (command == QLatin1String("list")) {
        QScriptContext *ctx = currentFrameContext();
        ScriptInfo *progInfo = scriptInfo(ctx);
        if (!progInfo) {
            errorMessage("No source text available for this frame.");
        } else {
            QScriptContextInfo ctxInfo(ctx);
            bool ok;
            int line = args.value(0).toInt(&ok);
            if (ok) {
                line = qMax(1, line - 5);
            } else {
                line = listLineNumber();
                if (line == -1)
                    line = qMax(progInfo->lineNumber(), ctxInfo.lineNumber() - 5);
            }
            for (int i = line; i < line + 10; ++i) {
                message(QString::fromLatin1("%0\t%1").arg(i).arg(progInfo->lineText(i)));
            }
            setListLineNumber(line + 10);
        }
    } else if (command == QLatin1String("info")) {
        if (args.size() < 1) {
        } else {
            QString what = args.value(0);
            if (what == QLatin1String("locals")) {
                QScriptValueIterator it(currentFrameContext()->activationObject());
                while (it.hasNext()) {
                    it.next();
                    QString line;
                    line.append(it.name());
                    line.append(QLatin1String(" = "));
                    line.append(safeValueToString(it.value()));
                    message(line);
                }
            }
        }
    } else if (command == QLatin1String("help")) {
        message("continue - continue execution\n"
                "step     - step into statement\n"
                "next     - step over statement\n"
                "list     - show where you are\n"
                "\n"
                "break    - set breakpoint\n"
                "delete   - remove breakpoint\n"
                "disable  - disable breakpoint\n"
                "enable   - enable breakpoint\n"
                "\n"
                "backtrace - show backtrace\n"
                "up       - one frame up\n"
                "down     - one frame down\n"
                "frame    - set frame\n"
                "\n"
                "info locals - show local variables");
    } else {
        errorMessage(QString::fromLatin1("Undefined command \"%0\". Try \"help\".")
                     .arg(command));
    }

    return false;
}
/*!
    Searches all files in the \a path for certificates encoded in the
    specified \a format and returns them in a list. \e must be a file or a
    pattern matching one or more files, as specified by \a syntax.

    Example:

    \snippet code/src_network_ssl_qsslcertificate.cpp 0

    \sa fromData()
*/
QList<QSslCertificate> QSslCertificate::fromPath(const QString &path,
                                                 QSsl::EncodingFormat format,
                                                 QRegExp::PatternSyntax syntax)
{
    // $, (,), *, +, ., ?, [, ,], ^, {, | and }.

    // make sure to use the same path separators on Windows and Unix like systems.
    QString sourcePath = QDir::fromNativeSeparators(path);

    // Find the path without the filename
    QString pathPrefix = sourcePath.left(sourcePath.lastIndexOf(QLatin1Char('/')));

    // Check if the path contains any special chars
    int pos = -1;
    if (syntax == QRegExp::Wildcard)
        pos = pathPrefix.indexOf(QRegExp(QLatin1String("[*?[]")));
    else if (syntax != QRegExp::FixedString)
        pos = sourcePath.indexOf(QRegExp(QLatin1String("[\\$\\(\\)\\*\\+\\.\\?\\[\\]\\^\\{\\}\\|]")));
    if (pos != -1) {
        // there was a special char in the path so cut of the part containing that char.
        pathPrefix = pathPrefix.left(pos);
        if (pathPrefix.contains(QLatin1Char('/')))
            pathPrefix = pathPrefix.left(pathPrefix.lastIndexOf(QLatin1Char('/')));
        else
            pathPrefix.clear();
    } else {
        // Check if the path is a file.
        if (QFileInfo(sourcePath).isFile()) {
            QFile file(sourcePath);
            QIODevice::OpenMode openMode = QIODevice::ReadOnly;
            if (format == QSsl::Pem)
                openMode |= QIODevice::Text;
            if (file.open(openMode))
                return QSslCertificate::fromData(file.readAll(), format);
            return QList<QSslCertificate>();
        }
    }

    // Special case - if the prefix ends up being nothing, use "." instead.
    int startIndex = 0;
    if (pathPrefix.isEmpty()) {
        pathPrefix = QLatin1String(".");
        startIndex = 2;
    }

    // The path can be a file or directory.
    QList<QSslCertificate> certs;
    QRegExp pattern(sourcePath, Qt::CaseSensitive, syntax);
    QDirIterator it(pathPrefix, QDir::Files, QDirIterator::FollowSymlinks | QDirIterator::Subdirectories);
    while (it.hasNext()) {
        QString filePath = startIndex == 0 ? it.next() : it.next().mid(startIndex);
        if (!pattern.exactMatch(filePath))
            continue;

        QFile file(filePath);
        QIODevice::OpenMode openMode = QIODevice::ReadOnly;
        if (format == QSsl::Pem)
            openMode |= QIODevice::Text;
        if (file.open(openMode))
            certs += QSslCertificate::fromData(file.readAll(), format);
    }
    return certs;
}
Example #17
0
void LegendWidget::drawText(QPainter *p, const QRect& rect,
		QwtArray<int> height, int symbolLineLength)
{
  p->save();
  if ((dynamic_cast<Graph *>(d_plot->parent()))->antialiasing())
    p->setRenderHints(QPainter::Antialiasing);

  // RJT (22/09/09): For remainder of method, copied in code from current 
  // QtiPlot (rev. 1373) to fix infinite loop if closing bracket missing
  int l = symbolLineLength;
  QString text = d_text->text();
  QStringList titles = text.split("\n", QString::KeepEmptyParts);

  for (int i=0; i<(int)titles.count(); i++){
    int w = left_margin + rect.x(); // QtiPlot Rev 1373 has this as 2nd arg: d_frame_pen.width();
    bool  curveSymbol = false;
    QString s = titles[i];
    while (s.contains("\\l(",Qt::CaseInsensitive) || s.contains("\\p{",Qt::CaseInsensitive)){
      curveSymbol = true;
      int pos = s.indexOf("\\l(", 0,Qt::CaseInsensitive);
      int pos2 = s.indexOf(",",pos); // two arguments in case if pie chart
      int pos3 = s.indexOf(")",pos);
      if (pos >= 0 && (pos2 == -1 || pos2 > pos3)){
        QwtText aux(parse(s.left(pos))); //not a pie chart
        aux.setFont(d_text->font());
        aux.setColor(d_text->color());
        aux.setRenderFlags (Qt::AlignLeft | Qt::AlignVCenter);

        QSize size = aux.textSize(); // In QtiPlot rev 1373: textSize(p, aux);
        QRect tr = QRect(QPoint(w, height[i] - size.height()/2), size);
        aux.draw(p, tr);
        w += size.width();

        int pos1 = s.indexOf("(", pos);
        int pos2 = s.indexOf(")", pos1);
        if (pos2 == -1){
          s = s.right(s.length() - pos1 - 1);
          continue;
        }
        int point = -1;
        PlotCurve *curve = getCurve(s.mid(pos1+1, pos2-pos1-1), point);
        if (!curve){
          s = s.right(s.length() - pos2 - 1);
          continue;
        }

        drawSymbol(curve, point, p, w, height[i], l);
        w += l + h_space;
        s = s.right(s.length() - pos2 - 1);
      } else { // pie chart?
        pos = s.indexOf("\\p{", 0);
        if (pos >= 0){  // old syntax
          QwtText aux(parse(s.left(pos)));
          aux.setFont(d_text->font());
          aux.setColor(d_text->color());
          aux.setRenderFlags (Qt::AlignLeft | Qt::AlignVCenter);

          QSize size = aux.textSize(); // In QtiPlot rev 1373: textSize(p, aux);
          QRect tr = QRect(QPoint(w, height[i] - size.height()/2), size);
          aux.draw(p, tr);
          w += size.width();

          int pos1 = s.indexOf("{", pos);
          int pos2 = s.indexOf("}", pos1);
          if (pos2 == -1){
          s = s.right(s.length() - pos1 - 1);
          continue;
          }
          int point = s.mid(pos1 + 1, pos2 - pos1 - 1).toInt() - 1;
          drawSymbol(dynamic_cast<PlotCurve*>(d_plot->curve(0)), point, p, w, height[i], l);
          w += l;
          s = s.right(s.length() - pos2 - 1);
        } else {
          pos = s.indexOf("\\l(", 0,Qt::CaseInsensitive);
          if (pos >= 0 && pos2 != -1){ //new syntax
            QwtText aux(parse(s.left(pos)));
            aux.setFont(d_text->font());
            aux.setColor(d_text->color());
            aux.setRenderFlags (Qt::AlignLeft | Qt::AlignVCenter);

            QSize size = aux.textSize(); // In QtiPlot rev 1373: textSize(p, aux);
            QRect tr = QRect(QPoint(w, height[i] - size.height()/2), size);
            aux.draw(p, tr);
            w += size.width();

            int pos1 = s.indexOf(",", pos);
            int pos3 = s.indexOf(")", pos1);
            if (pos3 == -1){
              s = s.right(s.length() - pos1 - 1);
              continue;
            }
            int point = s.mid(pos1 + 1, pos3 - pos1 - 1).toInt() - 1;
            drawSymbol(dynamic_cast<PlotCurve*>(d_plot->curve(0)), point, p, w, height[i], l);
            w += l;
            s = s.right(s.length() - pos3 - 1);
          }
        }
      }
    }

    if (!s.isEmpty()){
      if (curveSymbol)
        w += h_space;
      QwtText aux(parse(s));
      aux.setFont(d_text->font());
      aux.setColor(d_text->color());
      aux.setRenderFlags (Qt::AlignLeft | Qt::AlignVCenter);

      QSize size = aux.textSize(); // In QtiPlot rev 1373: textSize(p, aux);
      QRect tr = QRect(QPoint(w, height[i] - size.height()/2), size);
      aux.draw(p, tr);
    }
  }
  p->restore();
}
Ilwis::OperationImplementation::State AggregateRaster::prepare(ExecutionContext *, const SymbolTable & )
{
    QString raster = _expression.parm(0).value();
    QString outputName = _expression.parm(0,false).value();
    int copylist = itDOMAIN | itCOORDSYSTEM;

    if (!_inputObj.prepare(raster, itRASTER)) {
        ERROR2(ERR_COULD_NOT_LOAD_2,raster,"");
        return sPREPAREFAILED;
    }
    _method = toMethod(_expression.parm(1).value());
    if ( _method == NumericStatistics::pLAST) {
        ERROR2(ERR_ILLEGAL_VALUE_2, "parameter value", " aggregation method");
        return sPREPAREFAILED;
    }
    bool ok;
    quint32 groupSz = _expression.parm(2).value().toInt(&ok);
    if (!ok) {
        QString blist = _expression.parm(2).value();
        blist.remove("{");
        blist.remove("}");
        QStringList dims = blist.split(" ");
        if ( dims.size() > 0) {
            for(int i=0; i < dims.size(); ++i)     {
                quint32 val = dims[i].toInt(&ok);
                if ( ok) {
                    _groupSize[i] = val;
                }else
                    break;
            }
        }

    }else {
        _groupSize[0] = groupSz;
        _groupSize[1] = groupSz;

    }
    if ( !ok || groupSize() < 2) {
        ERROR2(ERR_ILLEGAL_VALUE_2, "aggregation group size", QString::number(groupSize()));
        return sPREPAREFAILED;
    }

    _grouped = _expression.parm(3).value().toLower() == "true";
    if ( !_grouped)
        copylist |= itGEOREF;

    _outputObj = OperationHelperRaster::initialize(_inputObj,itRASTER, copylist);
    if ( !_outputObj.isValid()) {
        ERROR1(ERR_NO_INITIALIZED_1, "output rastercoverage");
        return sPREPAREFAILED;
    }
    QString outputBaseName = outputName;
    int index = 0;
    if ( (index = outputName.lastIndexOf(".")) != -1) {
        outputBaseName = outputName.left(index);
    }
    IRasterCoverage inputRaster = _inputObj.as<RasterCoverage>();
    IRasterCoverage outputRaster = _outputObj.as<RasterCoverage>();
    if ( outputName != sUNDEF)
        _outputObj->name(outputName);
    outputRaster->coordinateSystem(inputRaster->coordinateSystem());

    BoundingBox box(inputRaster->size());
    if ( _grouped) {
        int xs = box.xlength();
        int ys = box.ylength();
        int zs = box.zlength();
        int newxs = xs / groupSize(0);
        int newys = ys / groupSize(1);
        int newzs = zs / groupSize(2);
        box = BoundingBox(Size<>(newxs, newys, newzs));

    }
    if ( _expression.parameterCount() == 5 || _grouped) {
        Envelope envlope = inputRaster->envelope();
        Resource resource(QUrl("ilwis://internalcatalog/georeference"),itGEOREF);
        resource.addProperty("size", IVARIANT(box.size()));
        resource.addProperty("envelope", IVARIANT(envlope));
        resource.addProperty("coordinatesystem", inputRaster->coordinateSystem()->id());
        resource.addProperty("name", outputBaseName);
        resource.addProperty("centerofpixel",inputRaster->georeference()->centerOfPixel());
        IGeoReference  grf;
        if (grf.prepare(resource)) {
            mastercatalog()->addItems({resource});
            outputRaster->georeference(grf);
        }
        outputRaster->envelope(envlope);
        outputRaster->size(box.size());
    }

    initialize(outputRaster->size().linearSize());

    return sPREPARED;
}
Example #19
0
/* FilterItem Class - allows easy creation / deletion of regex types */
FilterItem::FilterItem(const QString& filterPattern, int cflags)
{
  m_valid = false;

  m_minLevel = 0;
  m_maxLevel = 0;
  
  QString workString = filterPattern;
  
  QString regexString = workString;

  // find the semi-colon that seperates the regex from the level info
  int breakPoint = workString.find(';');

  // if no semi-colon, then it's all a regex
  if (breakPoint == -1)
    regexString = workString;
  else
  {
    // regex is the left most part of the string up to breakPoint characters
    regexString = workString.left(breakPoint);

    // the level string is everything else
    QString levelString = workString.mid(breakPoint + 1);

#ifdef DEBUG_FILTER 
    printf("regexString=%s\n", (const char*)regexString);
    printf("breakPoint=%d mid()=%s\n",
	   breakPoint, (const char*)levelString);
#endif

    // see if the level string is a range
    breakPoint = levelString.find('-');

    bool ok;
    int level;
    if (breakPoint == -1)
    {
      // no, level string is just a single level
      level = levelString.toInt(&ok);

      // only use the number if it's ok
      if (ok)
	m_minLevel = level;

#ifdef DEBUG_FILTER
      printf("filter min level decode levelStr='%s' level=%d ok=%1d minLevel=%d\n",
	     (const char*)levelString, level, ok, m_minLevel);
#endif
    }
    else
    {
      // it's a range.  The left most stuff before the hyphen is the minimum
      // level
      level = levelString.left(breakPoint).toInt(&ok);

      // only use the number if it's ok
      if (ok)
	m_minLevel = level;

#ifdef DEBUG_FILTER
      printf("filter min level decode levelStr='%s' level=%d ok=%1d minLevel=%d\n",
	     (const char*)levelString.left(breakPoint), level, ok, m_minLevel);
#endif

      // the rest of the string after the hyphen is the max
      levelString = levelString.mid(breakPoint + 1);

      // if a hyphen was specified, but no max value after it, it means
      // all values above min
      if (levelString.isEmpty())
	m_maxLevel = INT_MAX;
      else
      {
	// get the max level
	level = levelString.toInt(&ok);

	// only use the number if it's ok
	if (ok)
	  m_maxLevel = level;

#ifdef DEBUG_FILTER
      printf("filter max level decode levelStr='%s' level=%d ok=%1d maxLevel=%d\n",
	     (const char*)levelString, level, ok, m_maxLevel);
#endif
      }
    }
    
    // if no max level specified, or some dope set it below min, make it 
    // equal the min
    if(m_maxLevel < m_minLevel)
      m_maxLevel = m_minLevel;
  }

  // save the string as the name
  m_name = filterPattern;

#ifdef DEBUG_FILTER
  printf("regexString=%s minLevel=%d maxLevel=%d\n", 
	 (const char*)regexString, m_minLevel, m_maxLevel);
#endif

  // compile the regular expression
  switch (regcomp(&m_regexp, (const char*)regexString, cflags))
  {
    case 0:	// no error
      m_valid = true;
      break;
    case REG_BADRPT:
      fprintf(stderr, "Filter Error: '%s' - ", (const char*)filterPattern);
      fprintf(stderr, "Invalid use of repetition operators such as using '*' as the first character.\n");
      break;
    case REG_BADBR:
      fprintf(stderr, "Filter Error: '%s' - ", (const char*)filterPattern);
      fprintf(stderr, "Invalid use of back reference operator\n");
      break;
    case REG_EBRACE:
      fprintf(stderr, "Filter Error: '%s' - ", (const char*)filterPattern);
      fprintf(stderr, "Un-matched bracket list operators\n");
      break;
    case REG_EBRACK:
      fprintf(stderr, "Filter Error: '%s' - ", (const char*)filterPattern);
      fprintf(stderr, "Un-matched bracket list operators.\n");
      break;
    case REG_ERANGE:
      fprintf(stderr, "Filter Error: '%s' - ", (const char*)filterPattern);
      fprintf(stderr, "Invalid use of the range operator, eg. the ending point of the range occurs prior to the starting point.\n");
      break;
    case REG_ECTYPE:
      fprintf(stderr, "Filter Error: '%s' - ", (const char*)filterPattern);
      fprintf(stderr, "Unknown character class name.\n");
      break;
    case REG_ECOLLATE:
      fprintf(stderr, "Filter Error: '%s' - ", (const char*)filterPattern);
      fprintf(stderr, "Invalid collating element.\n");
      break;
    case REG_EPAREN:
      fprintf(stderr, "Filter Error: '%s' - ", (const char*)filterPattern);
      fprintf(stderr, "Un-matched parenthesis group operators.\n");
      break;
    case REG_ESUBREG:
      fprintf(stderr, "Filter Error: '%s' - ", (const char*)filterPattern);
      fprintf(stderr, "Invalid back reference to a subexpression\n");
      break;
#ifndef __FreeBSD__
    case REG_EEND:
      fprintf(stderr, "Filter Error: '%s' - ", (const char*)filterPattern);
      fprintf(stderr, "Non specific error.\n");
      break;
#endif
    case REG_EESCAPE:
      fprintf(stderr, "Filter Error: '%s' - ", (const char*)filterPattern);
      fprintf(stderr, "Trailing backslash.\n");
      break;
    case REG_BADPAT:
      fprintf(stderr, "Filter Error: '%s' - ", (const char*)filterPattern);
      fprintf(stderr, "Invalid use of pattern operators such as group or list.\n");
      break;
#ifndef __FreeBSD__
    case REG_ESIZE:
      fprintf(stderr, "Filter Error: '%s' - ", (const char*)filterPattern);
      fprintf(stderr, "Compiled regular expression requires a pattern buffer larger than 64 Kb.\n");
      break;
#endif
    case REG_ESPACE:
      fprintf(stderr, "Filter Error: '%s' - ", (const char*)filterPattern);
      fprintf(stderr, "The regex routines ran out of memory\n");
      break;
  } // end of error
}
Example #20
0
void cleanupXML(QTextStream &input, QTextStream &output) {
	QRegExp
		filenameRegExp("filename=\"[^\"]*\""),
		nameRegExp("name=\"[^\"]*\""),
		tagRegExp("^\\s*<([a-zA-Z]+) "),
		leadingSpaces("^ *"),
		closeTag("^\\s*</");
	bool inComment = false, hasContents = false;

	while (!input.atEnd()) {
		QString line = input.readLine();
		bool startComment = line.contains("<!--");
		bool endComment = line.contains("-->");

		if (startComment)
			inComment = true;
		if (endComment)
			inComment = false;

		if (inComment || endComment) {
			if (startComment) {
				/* Turn leading spaces into tabs */
				if (leadingSpaces.indexIn(line) == 0)
					line = QString('\t').repeated(leadingSpaces.matchedLength()) +
						line.mid(leadingSpaces.matchedLength());
			}
			output << line << endl;
			continue;
		}

		/* Make sure that the name attribute is always the first one */
		int tagMatch = tagRegExp.indexIn(line),
			tagLength = tagRegExp.matchedLength();
		int nameMatch = nameRegExp.indexIn(line),
			filenameMatch = filenameRegExp.indexIn(line),
			nameLength = nameRegExp.matchedLength();

		if (tagMatch != -1 && nameMatch != -1 && filenameMatch == -1) {
			QString a = line.mid(tagLength, nameMatch-tagLength).trimmed(),
				b = line.mid(nameMatch+nameLength).trimmed();
			line = line.left(tagLength) + line.mid(nameMatch, nameLength);
			if (a.length() > 0)
				line += " " + a;
			if (b.length() > 0)
				line += " " + b;
		}

		/* Add an extra newline if this is an object tag, and if there
		   have been siblings before it */
		if (tagMatch != -1) {
			const QString &el = tagRegExp.cap(1);
			bool isObject = true;

			isObject &= (el != "string");
			isObject &= (el != "integer");
			isObject &= (el != "float");
			isObject &= (el != "boolean");
			isObject &= (el != "vector");
			isObject &= (el != "point");
			isObject &= (el != "transform");
			isObject &= (el != "spectrum");
			isObject &= (el != "rgb");
			isObject &= (el != "scale");
			isObject &= (el != "translate");
			isObject &= (el != "rotate");
			isObject &= (el != "lookAt");
			isObject &= (el != "matrix");

			if (isObject && hasContents) {
				output << endl;
				hasContents = false;
			}

			if (!isObject)
				hasContents = true;
		}

		/* Turn leading spaces into tabs */
		if (leadingSpaces.indexIn(line) == 0)
			line = QString('\t').repeated(leadingSpaces.matchedLength()) +
				line.mid(leadingSpaces.matchedLength());

		/* Remove ugly spaces */
		if (line.endsWith("  />")) {
			line = line.left(line.size()-4) + QString("/>");
			hasContents = true;
		} else if (line.endsWith(" />")) {
			line = line.left(line.size()-3) + QString("/>");
			hasContents = true;
		} else if (line.endsWith("/>")) {
			hasContents = true;
		} else if (line.endsWith(" >")) {
			line = line.left(line.size()-2) + QString(">");
		} else if (line.endsWith("?>")) {
			hasContents = true;
		}

		if (closeTag.indexIn(line) == 0)
			hasContents = true;

		output << line << endl;
	}
}
void FindApiThread::run()
{
    QFile f(m_fileName);
    if (!f.open(QFile::ReadOnly)) {
        return;
    }
    QTextStream *stream = new QTextStream(&f);
    QRegExp reg("^pkg\\s([\\w\\-\\.\\/]+)(\\s\\(([\\w\\-]+)\\))?,\\s(\\w+)");
    QRegExp regm("\\(\\*?([\\w\\-]+)\\)\\s*(\\w+)");
    while (!stream->atEnd()) {
        QString line = stream->readLine();
        int pos = reg.indexIn(line);
        if (pos < 0) {
            continue;
        }
        // 1 pkgname
        // 2 ? (system)
        // 3 ? system
        // 4 const|func|method|var|type
        QString pkgName = reg.cap(1);
//        if (!reg.cap(3).isEmpty()) {
//            pkg = reg.cap(2)+"."+pkg;
//        }
//        if (!lastPkg || lastPkg->name != pkgName) {
//            lastPkg = m_pkgs.findPackage(pkgName);
//            if (!lastPkg) {
//                lastPkg = new Package(pkgName);
//                m_pkgs.pkgList.append(lastPkg);
//                lastType = 0;
//            }
//        }
        QString right = line.mid(reg.cap().length()).trimmed();
        QString findText;
        QStringList findUrl;
        QString flag = reg.cap(4);
        if (flag == "var") {
            ///pkg archive/tar, var ErrFieldTooLong error
            int pos = right.indexOf(" ");
            QString name = right.left(pos);
            if (pos != -1) {
                findText = pkgName+"."+name+" "+right.mid(pos+1);
                findUrl << pkgName+"#variables"<< name;
            }
            //if (pos != -1 && lastPkg->findValue(name) == 0) {
            //    lastPkg->valueList.append(new Value(VarApi,name,right.mid(pos+1)));
            //}
        } else if (flag == "const") {
            //pkg syscall (windows-amd64), const ECOMM Errno
            int pos = right.indexOf(" ");
            QString name = right.left(pos);
            if (pos != -1) {
                QString exp = right.mid(pos+1);
                findText = pkgName+"."+name+" "+exp;
                //if (exp.startsWith("ideal-") || exp == "uint16") {
                findUrl << pkgName+"#constants" << name;
//                } else {
//                    findUrl << pkgName+"."+name;
//                }
            }
//            if (pos != -1 && lastPkg->findValue(name) == 0) {
//                lastPkg->valueList.append(new Value(ConstApi,name,right.mid(pos+1)));
//            }
        } else if (flag == "func") {
            //pkg bytes, func FieldsFunc([]byte, func(rune) bool) [][]byte
            int pos = right.indexOf("(");
            QString name = right.left(pos);
            if (pos != -1) {
                findText = pkgName+"."+name+" "+right.mid(pos);
                findUrl << pkgName+"#"+name;
            }
//            if (pos != -1 && lastPkg->findValue(name) == 0) {
//                lastPkg->valueList.append(new Value(FuncApi,name,right.mid(pos)));
//            }
        } else if (flag == "method") {
            //pkg archive/tar, method (*Reader) Next() (*Header, error)
            //pkg archive/zip, method (*File) Open() (io.ReadCloser, error)
            //pkg bufio, method (ReadWriter) Available() int
            int pos = regm.indexIn(right);
            if (pos != -1) {
                QString typeName = regm.cap(1);
                QString name = regm.cap(2);
                QString exp = right.mid(regm.cap().length()).trimmed();
                findText = pkgName+"."+typeName+"."+name+" "+exp;
                findUrl << pkgName+"#"+typeName+"."+name;
//                if (lastType == 0 || lastType->name != typeName || lastType->typ == StructApi) {
//                    lastType = lastPkg->findType(typeName);
//                    if (!lastType) {
//                        lastType = new Type(StructApi,typeName,"struct");
//                        lastPkg->typeList.append(lastType);
//                    }
//                }
//                if (lastType->findValue(name) == 0) {
//                    lastType->valueList.append(new Value(TypeMethodApi,name,exp));
//                }
            }
        } else if (flag == "type") {
            //pkg go/ast, type ObjKind int
            //pkg archive/tar, type Header struct
            //pkg archive/tar, type Header struct, AccessTime time.Time
            //pkg container/heap, type Interface interface { Len, Less, Pop, Push, Swap }
            //pkg container/heap, type Interface interface, Len() int
            int pos = right.indexOf(" ");
            if (pos != -1) {
                QString typeName = right.left(pos);
                QString exp = right.mid(pos+1);
                if (exp == "struct") {
                    findText = pkgName+"."+typeName+" "+exp;
                    findUrl << pkgName+"#"+typeName;
//                    lastType = lastPkg->findType(typeName);
//                    if (!lastType) {
//                        lastType = new Type(StructApi,typeName,exp);
//                        lastPkg->typeList.append(lastType);
//                    }
                } else if (exp.startsWith("struct,")) {
                    QString last = exp.mid(7).trimmed();
                    int pos2 = last.indexOf(" ");
                    if (pos2 != -1) {
                        findText = pkgName+"."+typeName;
//                        if (lastType == 0 || lastType->name != typeName || lastType->typ == StructApi) {
//                            lastType = lastPkg->findType(typeName);
//                            if (!lastType) {
//                                lastType = new Type(StructApi,typeName,"struct");
//                                lastPkg->typeList.append(lastType);
//                            }
//                        }
                        QString name = last.left(pos2);
                        if (name == "embedded") {
                            QString emName = last.mid(pos2+1);
                            findText = pkgName+"."+typeName+"."+emName;
                            findUrl << pkgName+"#"+typeName << emName;
//                            if (!lastType->embeddedList.contains(emName)) {
//                                lastType->embeddedList.append(emName);
//                            }
                        } else {
                            findText = pkgName+"."+typeName+"."+name+" "+last.mid(pos2+1);
                            findUrl << pkgName+"#"+typeName << name;
                        }
                        /*else if (lastType->findValue(name) == 0){
                            lastType->valueList.append(new Value(TypeVarApi,name,last.mid(pos2+1)));
                        }*/
                    }
                } else if (exp.startsWith("interface {")) {
                    findText = pkgName+"."+typeName+" "+exp;
                    findUrl << pkgName+"#"+typeName;
//                    lastType = lastPkg->findType(typeName);
//                    if (!lastType) {
//                        lastType = new Type(InterfaceApi,typeName,exp);
//                        lastPkg->typeList.append(lastType);
//                    }
                } else if (exp.startsWith("interface,")) {
                    QString last = exp.mid(10).trimmed();
                    int pos2 = last.indexOf("(");
                    if (pos2 != -1) {

//                        if (lastType == 0 || lastType->name != typeName || lastType->typ == StructApi) {
//                            lastType = lastPkg->findType(typeName);
//                            if (!lastType) {
//                                lastType = new Type(InterfaceApi,typeName,"struct");
//                                lastPkg->typeList.append(lastType);
//                            }
//                        }
                        QString name = last.left(pos2);
                        //if (lastType->findValue(name) == 0) {
                             findText = pkgName+"."+typeName+"."+name+" "+last.mid(pos2);
                             findUrl << pkgName+"#"+typeName+"."+name;
                             //lastType->valueList.append(new Value(TypeMethodApi,name,last.mid(pos2)));
                        //}
                    }
                } else {
                    findText = pkgName+"."+typeName+" "+exp;
                    findUrl << pkgName+"#"+typeName;
//                    lastType = lastPkg->findType(typeName);
//                    if (!lastType) {
//                        lastType = new Type(TypeApi,typeName,exp);
//                        lastPkg->typeList.append(lastType);
//                    }
                }
            }
        }
        if (findText.indexOf(m_text,0,m_bMatchCase?Qt::CaseSensitive:Qt::CaseInsensitive) >= 0) {
            emit findApiOut(findText,line,findUrl);
        }
    }
}
Example #22
0
QFont KConfigBase::readFontEntry(const char *pKey, const QFont *pDefault) const
{
    QFont aRetFont;

    QString aValue = readEntry(pKey);
    if(!aValue.isNull())
    {
        if(aValue.contains(',') > 5)
        {
            // KDE3 and upwards entry
            if(!aRetFont.fromString(aValue) && pDefault)
                aRetFont = *pDefault;
        }
        else
        {
            // backward compatibility with older font formats
            // ### remove KDE 3.1 ?
            // find first part (font family)
            int nIndex = aValue.find(',');
            if(nIndex == -1)
            {
                if(pDefault)
                    aRetFont = *pDefault;
                return aRetFont;
            }
            aRetFont.setFamily(aValue.left(nIndex));

            // find second part (point size)
            int nOldIndex = nIndex;
            nIndex = aValue.find(',', nOldIndex + 1);
            if(nIndex == -1)
            {
                if(pDefault)
                    aRetFont = *pDefault;
                return aRetFont;
            }

            aRetFont.setPointSize(aValue.mid(nOldIndex + 1, nIndex - nOldIndex - 1).toInt());

            // find third part (style hint)
            nOldIndex = nIndex;
            nIndex = aValue.find(',', nOldIndex + 1);

            if(nIndex == -1)
            {
                if(pDefault)
                    aRetFont = *pDefault;
                return aRetFont;
            }

            aRetFont.setStyleHint((QFont::StyleHint)aValue.mid(nOldIndex + 1, nIndex - nOldIndex - 1).toUInt());

            // find fourth part (char set)
            nOldIndex = nIndex;
            nIndex = aValue.find(',', nOldIndex + 1);

            if(nIndex == -1)
            {
                if(pDefault)
                    aRetFont = *pDefault;
                return aRetFont;
            }

            QString chStr = aValue.mid(nOldIndex + 1, nIndex - nOldIndex - 1);
            // find fifth part (weight)
            nOldIndex = nIndex;
            nIndex = aValue.find(',', nOldIndex + 1);

            if(nIndex == -1)
            {
                if(pDefault)
                    aRetFont = *pDefault;
                return aRetFont;
            }

            aRetFont.setWeight(aValue.mid(nOldIndex + 1, nIndex - nOldIndex - 1).toUInt());

            // find sixth part (font bits)
            uint nFontBits = aValue.right(aValue.length() - nIndex - 1).toUInt();

            aRetFont.setItalic(nFontBits & 0x01);
            aRetFont.setUnderline(nFontBits & 0x02);
            aRetFont.setStrikeOut(nFontBits & 0x04);
            aRetFont.setFixedPitch(nFontBits & 0x08);
            aRetFont.setRawMode(nFontBits & 0x20);
        }
    }
    else
    {
        if(pDefault)
            aRetFont = *pDefault;
    }

    return aRetFont;
}
QString EmoticonFactory::convertEmoticons(const QString &html){
    if (html.isEmpty() || list.isEmpty() || map.isEmpty())
        return html;

    QString emoTheme = WSGET(WS_APP_EMOTICON_THEME);
    QString out = "";
    QString buf = html;

    auto it = map.end();
    auto begin = map.begin();

    bool force_emot = WBGET(WB_APP_FORCE_EMOTICONS);

    if (!force_emot){
        buf.prepend(" ");
        buf.append(" ");
    }

    while (!buf.isEmpty()){
        if (buf.startsWith("<a href=") && buf.indexOf("</a>") > 0){
            QString add = buf.left(buf.indexOf("</a>")) + "</a>";

            out += add;
            buf.remove(0, add.length());

            continue;
        }

        bool found = false;

        for (it = map.end()-1; it != begin-1; --it){
            if (force_emot){
                if (buf.startsWith(it.key())){
                    EmoticonObject *obj = it.value();

                    QString img = QString("<img alt=\"%1\" title=\"%1\" align=\"center\" source=\"%2/emoticon%3\" />")
                                  .arg(it.key())
                                  .arg(emoTheme)
                                  .arg(obj->id);

                    out += img + " ";
                    buf.remove(0, it.key().length());

                    found = true;

                    break;
                }
            }
            else{
                if (buf.startsWith(" "+it.key()+" ")){
                    EmoticonObject *obj = it.value();

                    QString img = QString(" <img alt=\"%1\" title=\"%1\" align=\"center\" source=\"%2/emoticon%3\" /> ")
                                  .arg(it.key())
                                  .arg(emoTheme)
                                  .arg(obj->id);

                    out += img;
                    buf.remove(0, it.key().length()+1);

                    found = true;

                    break;
                }
                else if (buf.startsWith(" "+it.key()+"\n")){
                    EmoticonObject *obj = it.value();

                    QString img = QString(" <img alt=\"%1\" title=\"%1\" align=\"center\" source=\"%2/emoticon%3\" />\n")
                                  .arg(it.key())
                                  .arg(emoTheme)
                                  .arg(obj->id);

                    out += img;
                    buf.remove(0, it.key().length()+2);

                    found = true;

                    break;
                }
            }
        }

        if (!found){
            out += buf.at(0);

            buf.remove(0, 1);
        }
    }

    if (!force_emot){
        if (out.startsWith(" "))
            out.remove(0, 1);
        if (out.endsWith(" "))
            out.remove(out.length()-1, 1);
    }

    return out;
}
QgsProviderRegistry::QgsProviderRegistry( const QString& pluginPath )
{
    // At startup, examine the libs in the qgis/lib dir and store those that
    // are a provider shared lib
    // check all libs in the current plugin directory and get name and descriptions
    //TODO figure out how to register and identify data source plugin for a specific
    //TODO layer type
#if 0
    char **argv = qApp->argv();
    QString appDir = argv[0];
    int bin = appDir.findRev( "/bin", -1, false );
    QString baseDir = appDir.left( bin );
    QString mLibraryDirectory = baseDir + "/lib";
#endif
    mLibraryDirectory = pluginPath;
    mLibraryDirectory.setSorting( QDir::Name | QDir::IgnoreCase );
    mLibraryDirectory.setFilter( QDir::Files | QDir::NoSymLinks );

#if defined(Q_OS_WIN) || defined(__CYGWIN__)
    mLibraryDirectory.setNameFilters( QStringList( "*.dll" ) );
#elif ANDROID
    mLibraryDirectory.setNameFilters( QStringList( "*provider.so" ) );
#else
    mLibraryDirectory.setNameFilters( QStringList( "*.so" ) );
#endif

    QgsDebugMsg( QString( "Checking %1 for provider plugins" ).arg( mLibraryDirectory.path() ) );

    if ( mLibraryDirectory.count() == 0 )
    {
        QString msg = QObject::tr( "No QGIS data provider plugins found in:\n%1\n" ).arg( mLibraryDirectory.path() );
        msg += QObject::tr( "No vector layers can be loaded. Check your QGIS installation" );

        QgsMessageOutput* output = QgsMessageOutput::createMessageOutput();
        output->setTitle( QObject::tr( "No Data Providers" ) );
        output->setMessage( msg, QgsMessageOutput::MessageText );
        output->showMessage();
        return;
    }

    // provider file regex pattern, only files matching the pattern are loaded if the variable is defined
    QString filePattern = getenv( "QGIS_PROVIDER_FILE" );
    QRegExp fileRegexp;
    if ( !filePattern.isEmpty() )
    {
        fileRegexp.setPattern( filePattern );
    }

    QListIterator<QFileInfo> it( mLibraryDirectory.entryInfoList() );
    while ( it.hasNext() )
    {
        QFileInfo fi( it.next() );

        if ( !fileRegexp.isEmpty() )
        {
            if ( fileRegexp.indexIn( fi.fileName() ) == -1 )
            {
                QgsDebugMsg( "provider " + fi.fileName() + " skipped because doesn't match pattern " + filePattern );
                continue;
            }
        }

        QLibrary myLib( fi.filePath() );
        if ( !myLib.load() )
        {
            QgsDebugMsg( QString( "Checking %1: ...invalid (lib not loadable): %2" ).arg( myLib.fileName() ).arg( myLib.errorString() ) );
            continue;
        }

        //MH: Added a further test to detect non-provider plugins linked to provider plugins.
        //Only pure provider plugins have 'type' not defined
        isprovider_t *hasType = ( isprovider_t * ) cast_to_fptr( myLib.resolve( "type" ) );
        if ( hasType )
        {
            QgsDebugMsg( QString( "Checking %1: ...invalid (has type method)" ).arg( myLib.fileName() ) );
            continue;
        }

        // get the description and the key for the provider plugin
        isprovider_t *isProvider = ( isprovider_t * ) cast_to_fptr( myLib.resolve( "isProvider" ) );
        if ( !isProvider )
        {
            QgsDebugMsg( QString( "Checking %1: ...invalid (no isProvider method)" ).arg( myLib.fileName() ) );
            continue;
        }

        // check to see if this is a provider plugin
        if ( !isProvider() )
        {
            QgsDebugMsg( QString( "Checking %1: ...invalid (not a provider)" ).arg( myLib.fileName() ) );
            continue;
        }

        // looks like a provider. get the key and description
        description_t *pDesc = ( description_t * ) cast_to_fptr( myLib.resolve( "description" ) );
        if ( !pDesc )
        {
            QgsDebugMsg( QString( "Checking %1: ...invalid (no description method)" ).arg( myLib.fileName() ) );
            continue;
        }

        providerkey_t *pKey = ( providerkey_t * ) cast_to_fptr( myLib.resolve( "providerKey" ) );
        if ( !pKey )
        {
            QgsDebugMsg( QString( "Checking %1: ...invalid (no providerKey method)" ).arg( myLib.fileName() ) );
            continue;
        }

        // add this provider to the provider map
        mProviders[pKey()] = new QgsProviderMetadata( pKey(), pDesc(), myLib.fileName() );

        // load database drivers
        databaseDrivers_t *pDatabaseDrivers = ( databaseDrivers_t * ) cast_to_fptr( myLib.resolve( "databaseDrivers" ) );
        if ( pDatabaseDrivers )
        {
            mDatabaseDrivers = pDatabaseDrivers();
        }

        // load directory drivers
        directoryDrivers_t *pDirectoryDrivers = ( directoryDrivers_t * ) cast_to_fptr( myLib.resolve( "directoryDrivers" ) );
        if ( pDirectoryDrivers )
        {
            mDirectoryDrivers = pDirectoryDrivers();
        }

        // load protocol drivers
        protocolDrivers_t *pProtocolDrivers = ( protocolDrivers_t * ) cast_to_fptr( myLib.resolve( "protocolDrivers" ) );
        if ( pProtocolDrivers )
        {
            mProtocolDrivers = pProtocolDrivers();
        }

        // now get vector file filters, if any
        fileVectorFilters_t *pFileVectorFilters = ( fileVectorFilters_t * ) cast_to_fptr( myLib.resolve( "fileVectorFilters" ) );
        if ( pFileVectorFilters )
        {
            QString fileVectorFilters = pFileVectorFilters();

            if ( !fileVectorFilters.isEmpty() )
                mVectorFileFilters += fileVectorFilters;

            QgsDebugMsg( QString( "Checking %1: ...loaded ok (%2 file filters)" ).arg( myLib.fileName() ).arg( fileVectorFilters.split( ";;" ).count() ) );
        }

        // now get raster file filters, if any
        // this replaces deprecated QgsRasterLayer::buildSupportedRasterFileFilter
        buildsupportedrasterfilefilter_t *pBuild =
            ( buildsupportedrasterfilefilter_t * ) cast_to_fptr( myLib.resolve( "buildSupportedRasterFileFilter" ) );
        if ( pBuild )
        {
            QString fileRasterFilters;
            pBuild( fileRasterFilters );

            QgsDebugMsg( "raster filters: " + fileRasterFilters );
            if ( !fileRasterFilters.isEmpty() )
                mRasterFileFilters += fileRasterFilters;

            QgsDebugMsg( QString( "Checking %1: ...loaded ok (%2 file filters)" ).arg( myLib.fileName() ).arg( fileRasterFilters.split( ";;" ).count() ) );
        }
    }
} // QgsProviderRegistry ctor
Example #25
0
// -------------------------------------------------------
VHDL_File_Info::VHDL_File_Info(QString File, bool isfile)
{
  if (isfile) {
    QFile f(File);
    if(!f.open(QIODevice::ReadOnly))
      File = "";
    else {
      QByteArray FileContent = f.readAll();
      File = QString(FileContent);
    }
    f.close();
  }
  
  QString s;
  PortNames = "";
  int i=0, j, k=0;
  while((i=File.indexOf("--", i)) >= 0) { // remove all VHDL comments
    j = File.indexOf('\n', i+2);          // This also finds "--" within a ...
    if(j < 0)                          // string, but as no strings are ...
      File = File.left(i);             // allowed in entity headers, it ...
    else                               // does not matter.
      File.remove(i, j-i);
  }

  QRegExp Expr;
  Expr.setCaseSensitivity(Qt::CaseInsensitive); 
  for(;;) {
    k--;
    Expr.setPattern("\\bentity\\b");  // start of last entity
    k = File.lastIndexOf(Expr, k);
    if(k < 0)
      return;

    Expr.setPattern("\\bend\\b");    // end of last entity
    i = File.indexOf(Expr, k+7);
    if(i < 0)
      return;
    s = File.mid(k+7, i-k-7);  // cut out entity declaration

    Expr.setPattern("\\b");
    i = s.indexOf(Expr);
    if(i < 0)
      return;
    j = s.indexOf(Expr, i+1);
    if(j < 0)
      return;
    EntityName = s.mid(i, j-i);  // save entity name

    i = s.indexOf(Expr, j+1);
    if(i < 0)
      return;
    j = s.indexOf(Expr, i+1);
    if(j < 0)
      return;
    if(s.mid(i, j-i).toLower() == "is")   // really found start of entity ?
      break;

    if(k < 1)    // already searched the whole text
      return;
  }

  // parse ports, i.e. network connections; and generics, i.e. parameters
  GenNames = parseGenerics(s,j);
  PortNames = parsePorts(s,j);
}
Example #26
0
//-----------------------------------------------------------------------------
void MessSyntax::highlightBlock(const QString &text)
{
	if(text.left(7) == ("In line"))
		setFormat(0, text.length(), QColor(255,0,0));
}
Example #27
0
// -------------------------------------------------------
QString VHDL_File_Info::parseGenerics(QString s, int j)
{
  QRegExp Expr;
  Expr.setCaseSensitivity(Qt::CaseInsensitive);
  int i, p, l, k, n;

  Expr.setPattern("\\bgeneric\\b");
  i = s.indexOf(Expr, j+1);
  if(i < 0)
    return QString("");
  // find opening (
  i = s.indexOf('(', i+4) + 1;
  if(i <= 0)
    return QString("");

  // find closing (
  p = i;
  j = i-1;
  do {
    j = s.indexOf(')', j+1);
    if(j < 0)
      return QString("");
    p = s.indexOf('(', p+1);
    if(p >= 0 && p > j) p = -1;
  } while (p >= 0);

  s = s.mid(i, j-i);
  s.remove('\n');
  s.remove('\t');

  // find generic names, types and defaults in parameter specification
  l = i = 0;
  QString types = "", t, defs = "", d;
  while((i=s.indexOf(':', i)) >= 0) {
    j = s.indexOf(';', i+2);
    n = s.indexOf(":=", i+2);
    d = "";
    if(n >= 0 && (n < j || j < 0) ) {
      j = s.indexOf(';', n+2);
      if(j < 0) {
	d = s.mid(n+2);
	d = d.simplified();
	s = s.left(n);
      } else {
	d = s.mid(n+2, j-n-1);
	d.remove(';');
	d = d.simplified();
	s.remove(n, j-n);
      }
      j = s.indexOf(';', n);
    }
    if(j < 0) {
      t = s.mid(i+1);
      t.remove(';');
      t = t.simplified();
      s = s.left(i);
    } else {
      t = s.mid(i+1, j-i);
      t.remove(';');
      t = t.simplified();
      s.remove(i, j-i);
    }
    if ((k = t.indexOf(' ')) >= 0)
      t = t.mid(k+1);
    t = t.simplified();
    k = s.indexOf(';',l+2);
    k = (s.mid(l,k-l).count(',')) + 1;
    while (k-->0) {
      types = types + t + ",";
      defs = defs + d + ",";
    }
    i--;
    l = i;
  }

  s.remove(' ');
  s.replace(';', ',');
  GenTypes=types=types.left(types.length()-1);
  GenDefs=defs=defs.left(defs.length()-1);
  return s;
}
Example #28
0
void ChannelEditor::customEvent(QEvent *event)
{
    if (event->type() == DialogCompletionEvent::kEventType)
    {
        DialogCompletionEvent *dce = (DialogCompletionEvent*)(event);

        QString resultid= dce->GetId();
        int buttonnum  = dce->GetResult();

        if (resultid == "channelopts")
        {
            switch (buttonnum)
            {
                case 0 :
                    edit(m_channelList->GetItemCurrent());
                    break;
                case 1 :
                    del();
                    break;
            }
        }
        else if (resultid == "delsingle" && buttonnum == 1)
        {
            MythUIButtonListItem *item =
                    qVariantValue<MythUIButtonListItem *>(dce->GetData());
            if (!item)
                return;
            uint chanid = item->GetData().toUInt();
            if (chanid && ChannelUtil::DeleteChannel(chanid))
                m_channelList->RemoveItem(item);
        }
        else if (resultid == "delall" && buttonnum == 1)
        {
            bool del_all = m_sourceFilter == FILTER_ALL;
            bool del_nul = m_sourceFilter == FILTER_UNASSIGNED;

            MSqlQuery query(MSqlQuery::InitCon());
            if (del_all)
            {
                query.prepare("TRUNCATE TABLE channel");
            }
            else if (del_nul)
            {
                query.prepare("SELECT sourceid "
                "FROM videosource "
                "GROUP BY sourceid");

                if (!query.exec() || !query.isActive())
                {
                    MythDB::DBError("ChannelEditor Delete Channels", query);
                    return;
                }

                QString tmp = "";
                while (query.next())
                    tmp += "'" + query.value(0).toString() + "',";

                if (tmp.isEmpty())
                {
                    query.prepare("TRUNCATE TABLE channel");
                }
                else
                {
                    tmp = tmp.left(tmp.length() - 1);
                    query.prepare(QString("DELETE FROM channel "
                    "WHERE sourceid NOT IN (%1)").arg(tmp));
                }
            }
            else
            {
                query.prepare("DELETE FROM channel "
                "WHERE sourceid = :SOURCEID");
                query.bindValue(":SOURCEID", m_sourceFilter);
            }

            if (!query.exec())
                MythDB::DBError("ChannelEditor Delete Channels", query);

            fillList();
        }
        else if (resultid == "iconimportopt")
        {
            MythScreenStack *mainStack = GetMythMainWindow()->GetMainStack();

            ImportIconsWizard *iconwizard;

            QString channelname = dce->GetData().toString();

            switch (buttonnum)
            {
                case 0 : // Import all icons
                    iconwizard = new ImportIconsWizard(mainStack, false);
                    break;
                case 1 : // Rescan for missing
                    iconwizard = new ImportIconsWizard(mainStack, true);
                    break;
                case 2 : // Import a single channel icon
                    iconwizard = new ImportIconsWizard(mainStack, true,
                                                       channelname);
                    break;
                default:
                    return;
            }

            if (iconwizard->Create())
            {
                connect(iconwizard, SIGNAL(Exiting()), SLOT(fillList()));
                mainStack->AddScreen(iconwizard);
            }
            else
                delete iconwizard;
        }
    }
}
Example #29
0
void MsgViewBase::update()
{
    if (m_updated.empty())
        return;
    unsigned i;
    for (i = 0; i < (unsigned)paragraphs(); i++){
        QString s = text(i);
        int n = s.find(MSG_ANCHOR);
        if (n < 0)
            continue;
        s = s.mid(n + strlen(MSG_ANCHOR));
        n = s.find("\"");
        if (n < 0)
            continue;
        string client;
        unsigned id = messageId(s.left(n), client);
        list<Msg_Id>::iterator it;
        for (it = m_updated.begin(); it != m_updated.end(); ++it){
            if (((*it).id == id) && ((*it).client == client))
                break;
        }
        if (it != m_updated.end())
            break;
    }
    m_updated.clear();
    if (i >= (unsigned)paragraphs())
        return;
    int x = contentsX();
    int y = contentsY();
    viewport()->setUpdatesEnabled(false);

    unsigned start = i;
    list<Msg_Id> msgs;
    for (; i < (unsigned)paragraphs(); i++){
        QString s = text(i);
        int n = s.find(MSG_ANCHOR);
        if (n < 0)
            continue;
        s = s.mid(n + strlen(MSG_ANCHOR));
        n = s.find("\"");
        if (n < 0)
            continue;
        string client;
        unsigned id = messageId(s.left(n), client);
        list<Msg_Id>::iterator it;
        for (it = msgs.begin(); it != msgs.end(); ++it){
            if (((*it).id == id) && ((*it).client == client))
                break;
        }
        if (it != msgs.end())
            continue;
        Msg_Id m_id;
        m_id.id     = id;
        m_id.client = client;
        msgs.push_back(m_id);
    }
    int paraFrom, indexFrom;
    int paraTo, indexTo;
    getSelection(&paraFrom, &indexFrom, &paraTo, &indexTo);
    setReadOnly(false);
    setSelection(start, 0, paragraphs() - 1, 0xFFFF, 0);
    removeSelectedText();
    setReadOnly(true);
    QString text;
    for (list<Msg_Id>::iterator it = msgs.begin(); it != msgs.end(); ++it){
        Message *msg = History::load((*it).id, (*it).client.c_str(), m_id);
        if (msg == NULL)
            continue;
        bool bUnread = false;
        for (list<msg_id>::iterator itu = CorePlugin::m_plugin->unread.begin(); itu != CorePlugin::m_plugin->unread.end(); ++itu){
            msg_id &m = (*itu);
            if ((m.contact == msg->contact()) &&
                    (m.id == msg->id()) &&
                    (m.client == msg->client())){
                bUnread = true;
                break;
            }
        }
        text += messageText(msg, bUnread);
    }
    viewport()->setUpdatesEnabled(true);
    append(text);
    if (!CorePlugin::m_plugin->getOwnColors())
        setBackground(i);
    if ((paraFrom != paraTo) || (indexFrom != indexTo))
        setSelection(paraFrom, indexFrom, paraTo, indexTo, 0);
    TextShow::sync();
    setContentsPos(x, y);
    viewport()->repaint();
}
void MainWindow::intern_path(QString t_carId, int t_carPositionX, int t_carPositionY, QString & t_info)
{
    CarPositionInfo t_carPositionInfo = m_carPositionInfo;
    QString temp;
    QString r_temp;
    int len = 0; // 记录共经过多少个车位

    if (t_carPositionX > 0) // 检查后边,左边
    {
        while (t_carPositionX != 0 || t_carPositionY != 0)
        {
            if (t_carPositionInfo.getNorthCar() != "000")//后边有车位
            {
                t_info += t_carPositionInfo.getNorthCar();
                t_carPositionY--;
                m_dataBase->queryCarId_database(t_carPositionInfo.getNorthCar(), t_carPositionInfo); // 根据区域内坐标查车位信息
            }
            else //后边没车,往左走
            {
                t_info += t_carPositionInfo.getEastCar();
                t_carPositionX--;
                m_dataBase->queryCarId_database(t_carPositionInfo.getEastCar(), t_carPositionInfo); // 根据车位ID查询车位信息
            }
            len++;
        }
        qDebug() << "left t_info" << t_info.toLatin1();
        if (len > 0)
        {
            temp = t_info.right(len * 3);
            t_info = t_info.left(t_info.length() - len * 3) + "途经";
        }
        for (int i=1; i<=len; i++)
        {
            r_temp += (temp.right(3 * i)).left(3);
            r_temp += "车位,";
        }
        t_info = t_info + r_temp + "到达" + t_carId + "车位";
    }
    else//t_carPositionX<0,检查后边,右边
    {
        while (t_carPositionX != 0 || t_carPositionY != 0)
        {
            if (t_carPositionInfo.getNorthCar() != "000")//后边有车位
            {
                t_info += t_carPositionInfo.getNorthCar();
                t_carPositionY--;
                m_dataBase->queryCarId_database(t_carPositionInfo.getNorthCar(), t_carPositionInfo); //根据车位ID查询车位信息
            }
            else // 后边没车,往右走
            {
                t_info += t_carPositionInfo.getWestCar();
                t_carPositionX++;
                m_dataBase->queryCarId_database(t_carPositionInfo.getWestCar(), t_carPositionInfo); //根据区域内坐标查车位信息
            }
            len++;
        }
        if (len > 0)
        {
            temp = t_info.right(len * 3);
            t_info = t_info.left(t_info.length() - len * 3) + "途经";
        }
        for (int i=1; i<=len; i++)
        {
            r_temp += (temp.right(3 * i)).left(3);
            r_temp += "车位,";
        }
        t_info = t_info + r_temp + "到达" + t_carId + "车位";
    }
}