QList<ClangCodeCompletionItem> TranslationUnit::completeAt(
    const int line
  , const int column
  , const unsigned completion_flags
  , const clang::unsaved_files_list& unsaved_files
  , const PluginConfiguration::sanitize_rules_list_type& sanitize_rules
  )
{
    auto files = unsaved_files.get();
#ifndef NDEBUG
    for (auto& item : files)
        assert(
            "Sanity check"
          && item.Filename
          && std::strlen(item.Filename)
          && item.Contents
          && item.Length
          );
#endif

    clang::DCXCodeCompleteResults res = {
        clang_codeCompleteAt(
            m_unit
          , m_filename.constData()
          , unsigned(line)
          , unsigned(column)
          , files.data()
          , files.size()
          , completion_flags
          )
      };
    if (!res)
    {
        throw Exception::CompletionFailure(
            i18nc("@item:intext", "Unable to perform code completion").toAscii().constData()
          );
    }

#if 0
    clang_sortCodeCompletionResults(res->Results, res->NumResults);
#endif

    // Collect some diagnostic SPAM
    for (auto i = 0u; i < clang_codeCompleteGetNumDiagnostics(res); ++i)
    {
        clang::DCXDiagnostic diag = {clang_codeCompleteGetDiagnostic(res, i)};
        appendDiagnostic(diag);
    }

    QList<ClangCodeCompletionItem> completions;
    completions.reserve(res->NumResults);                   // Peallocate enough space for completion results

    // Lets look what we've got...
    for (auto i = 0u; i < res->NumResults; ++i)
    {
        const auto str = res->Results[i].CompletionString;
        const auto priority = clang_getCompletionPriority(str);
        const auto cursor_kind = res->Results[i].CursorKind;
        debugShowCompletionResult(i, priority, str, cursor_kind);

        // Skip unusable completions
        // 0) check availability
        const auto availability = clang_getCompletionAvailability(str);
        if (availability != CXAvailability_Available && availability != CXAvailability_Deprecated)
        {
            kDebug(DEBUG_AREA) << "!! Skip result" << i << "as not available";
            continue;
        }
        // 1) check usefulness
        /// \todo Make it configurable
        if (cursor_kind == CXCursor_NotImplemented)
            continue;

        // Collect all completion chunks and from a format string
        QString text_before;
        QString typed_text;
        QString text_after;
        QStringList placeholders;
        int optional_placeholers_start_position = -1;
        // A lambda to append given text to different parts
        // of future completion string, depending on already processed text
        auto appender = [&](const QString& text)
        {
            if (typed_text.isEmpty())
                text_before += text;
            else
                text_after += text;
        };
        auto skip_this_item = false;
        for (
            auto j = 0u
          , chunks = clang_getNumCompletionChunks(str)
          ; j < chunks && !skip_this_item
          ; ++j
          )
        {
            auto kind = clang_getCompletionChunkKind(str, j);
            auto text = toString(clang::DCXString{clang_getCompletionChunkText(str, j)});
            switch (kind)
            {
                // Text that a user would be expected to type to get this code-completion result
                case CXCompletionChunk_TypedText:
                // Text that should be inserted as part of a code-completion result
                case CXCompletionChunk_Text:
                {
                    auto p = sanitize(text, sanitize_rules);// Pipe given piece of text through sanitizer
                    if (p.first)
                        typed_text += p.second;
                    else                                    // Go for next completion item
                        skip_this_item = true;
                    break;
                }
                // Placeholder text that should be replaced by the user
                case CXCompletionChunk_Placeholder:
                {
                    auto p = sanitize(text, sanitize_rules);// Pipe given piece of text through sanitizer
                    if (p.first)
                    {
                        appender(
                            QLatin1String{"%"}
                          + QString::number(placeholders.size() + 1)
                          + QLatin1String{"%"}
                          );
                        placeholders.push_back(p.second);
                    }
                    else                                    // Go for next completion item
                        skip_this_item = true;
                    break;
                }
                // A code-completion string that describes "optional" text that
                // could be a part of the template (but is not required)
                case CXCompletionChunk_Optional:
                {
                    auto ostr = clang_getCompletionChunkCompletionString(str, j);
                    for (
                        auto oci = 0u
                      , ocn = clang_getNumCompletionChunks(ostr)
                      ; oci < ocn
                      ; ++oci
                      )
                    {
                        auto otext = toString(clang::DCXString{clang_getCompletionChunkText(ostr, oci)});
                        // Pipe given piece of text through sanitizer
                        auto p = sanitize(otext, sanitize_rules);
                        if (p.first)
                        {
                            auto okind = clang::kind_of(ostr, oci);
                            if (okind == CXCompletionChunk_Placeholder)
                            {
                                appender(
                                    QLatin1String{"%"}
                                  + QString::number(placeholders.size() + 1)
                                  + QLatin1String{"%"}
                                  );
                                placeholders.push_back(p.second);
                                optional_placeholers_start_position = placeholders.size();
                            }
                            else appender(p.second);
                        }
                        else
                        {
                            skip_this_item = true;
                            break;
                        }
                    }
                    break;
                }
                case CXCompletionChunk_ResultType:
                case CXCompletionChunk_LeftParen:
                case CXCompletionChunk_RightParen:
                case CXCompletionChunk_LeftBracket:
                case CXCompletionChunk_RightBracket:
                case CXCompletionChunk_LeftBrace:
                case CXCompletionChunk_RightBrace:
                case CXCompletionChunk_LeftAngle:
                case CXCompletionChunk_RightAngle:
                case CXCompletionChunk_Comma:
                case CXCompletionChunk_Colon:
                case CXCompletionChunk_SemiColon:
                case CXCompletionChunk_Equal:
                case CXCompletionChunk_CurrentParameter:
                case CXCompletionChunk_HorizontalSpace:
                /// \todo Kate can't handle \c '\n' well in completions list
                case CXCompletionChunk_VerticalSpace:
                {
                    auto p = sanitize(text, sanitize_rules);// Pipe given piece of text through sanitizer
                    if (p.first)
                        appender(p.second);
                    else                                    // Go for next completion item
                        skip_this_item = true;
                    break;
                }
                // Informative text that should be displayed but never inserted
                // as part of the template
                case CXCompletionChunk_Informative:
                    // Informative text before CXCompletionChunk_TypedText usually
                    // just a method scope (i.e. long name of an owner class)
                    // and it's useless for completer cuz it can group items
                    // by parent already...
                    if (!typed_text.isEmpty())
                    {
                        // Pipe given piece of text through sanitizer
                        auto p = sanitize(text, sanitize_rules);
                        if (p.first)
                            appender(p.second);
                        else                                // Go for next completion item
                            skip_this_item = true;
                    }
                    break;
                default:
                    break;
            }
        }
        // Does it pass the completion items sanitizer?
        if (skip_this_item) continue;                       // No! Skip it!

        assert("Priority expected to be less than 100" && priority < 101u);

        const auto comment = toString(clang::DCXString{clang_getCompletionBriefComment(str)});
        //
        completions.push_back({
            makeParentText(str, cursor_kind)
          , text_before
          , typed_text
          , text_after
          , placeholders
          , optional_placeholers_start_position
          , priority
          , cursor_kind
          , comment
          , availability == CXAvailability_Deprecated
          });
    }

    return completions;
}
Esempio n. 2
0
void TunedInputInfo::ToStringList(QStringList &list) const
{
    InputInfo::ToStringList(list);
    list.push_back(QString::number(chanid));
}
Esempio n. 3
0
/**
 * load XML grouping file. It is assumed that tables and combo box cleared before this method is called
 */
void loadGroupingXMLtoTable(Ui::MuonAnalysis& m_uiForm, const std::string& filename)
{
  // Set up the DOM parser and parse xml file
  DOMParser pParser;
  Document* pDoc;
  try
  {
    pDoc = pParser.parse(filename);
  }
  catch(...)
  {
    throw Mantid::Kernel::Exception::FileError("Unable to parse File:" , filename);
  }
  // Get pointer to root element
  Element* pRootElem = pDoc->documentElement();
  if ( !pRootElem->hasChildNodes() )
  {
    throw Mantid::Kernel::Exception::FileError("No root element in XML grouping file:" , filename);
  }  

  NodeList* pNL_group = pRootElem->getElementsByTagName("group");
  if ( pNL_group->length() == 0 )
  {
    throw Mantid::Kernel::Exception::FileError("XML group file contains no group elements:" , filename);
  }


  // add content to group table

  QStringList allGroupNames;  // used to populate combo boxes 
  int numberGroups = static_cast<int>(pNL_group->length());
  for (int iGroup = 0; iGroup < numberGroups; iGroup++)
  {
    Element* pGroupElem = static_cast<Element*>(pNL_group->item(iGroup));

    if ( !pGroupElem->hasAttribute("name") )
      throw Mantid::Kernel::Exception::FileError("Group element without name" , filename);
    std::string gName = pGroupElem->getAttribute("name");


    Element* idlistElement = pGroupElem->getChildElement("ids");
    if (idlistElement)
    {
      std::string ids = idlistElement->getAttribute("val");

      // add info to table
      m_uiForm.groupTable->setItem(iGroup, 0, new QTableWidgetItem(gName.c_str()) );
      m_uiForm.groupTable->setItem(iGroup,1, new QTableWidgetItem(ids.c_str()) );
      allGroupNames.push_back( m_uiForm.groupTable->item(static_cast<int>(iGroup),0)->text() );
    }
    else
    {
      throw Mantid::Kernel::Exception::FileError("XML group file contains no <ids> elements:" , filename);
    }   
  }
  pNL_group->release();
  

  // populate pair table combo boxes

  int rowNum = m_uiForm.pairTable->rowCount();
  for (int i = 0; i < rowNum; i++)
  {
    QComboBox* qw1 = static_cast<QComboBox*>(m_uiForm.pairTable->cellWidget(i,1));
    QComboBox* qw2 = static_cast<QComboBox*>(m_uiForm.pairTable->cellWidget(i,2));

    for (int ii = 0; ii < allGroupNames.size(); ii++)
    {

      qw1->addItem( allGroupNames[ii] );
      qw2->addItem( allGroupNames[ii] );
    }
    
    if ( qw2->count() > 1 )
      qw2->setCurrentIndex(1);
  }




  // add content to pair table

  QStringList allPairNames;  
  NodeList* pNL_pair = pRootElem->getElementsByTagName("pair");
  int nPairs = static_cast<int>(pNL_pair->length());
  if ( pNL_pair->length() > 0 )
  {
    for (int iPair = 0; iPair < nPairs; iPair++)
    {
      Element* pGroupElem = static_cast<Element*>(pNL_pair->item(iPair));

      if ( !pGroupElem->hasAttribute("name") )
        throw Mantid::Kernel::Exception::FileError("pair element without name" , filename);
      std::string gName = pGroupElem->getAttribute("name");
      m_uiForm.pairTable->setItem(iPair,0, new QTableWidgetItem(gName.c_str()) );
      allPairNames.push_back(gName.c_str());

      Element* fwElement = pGroupElem->getChildElement("forward-group");
      if (fwElement)
      {
        std::string ids = fwElement->getAttribute("val");
        QComboBox* qw1 = static_cast<QComboBox*>(m_uiForm.pairTable->cellWidget(iPair,1));
        int comboIndex = qw1->findText(ids.c_str());
        if ( comboIndex < 0 )
          throw Mantid::Kernel::Exception::FileError("XML pair group contains forward-group with unrecognised group name" , filename);
        qw1->setCurrentIndex(comboIndex);
      }
      else
      {
        throw Mantid::Kernel::Exception::FileError("XML pair group contains no <forward-group> elements:" , filename);
      }   

      Element* bwElement = pGroupElem->getChildElement("backward-group");
      if (bwElement)
      {
        std::string ids = bwElement->getAttribute("val");
        QComboBox* qw2 = static_cast<QComboBox*>(m_uiForm.pairTable->cellWidget(iPair,2));
        int comboIndex = qw2->findText(ids.c_str());
        if ( comboIndex < 0 )
          throw Mantid::Kernel::Exception::FileError("XML pair group contains backward-group with unrecognised group name" , filename);
        qw2->setCurrentIndex(comboIndex);
      }
      else
      {
        throw Mantid::Kernel::Exception::FileError("XML pair group contains no <backward-group> elements:" , filename);
      }

      Element* element = pGroupElem->getChildElement("alpha");
      if (element)
      {
        if ( element->hasAttribute("val") )
        {
          m_uiForm.pairTable->setItem(iPair,3, new QTableWidgetItem(element->getAttribute("val").c_str()));
        }
        else
          throw Mantid::Kernel::Exception::FileError("XML pair group contains an <alpha> element with no 'val' attribute:" , filename);
      }
      // if alpha element not there for now just default it to 1.0
      else 
      {
        m_uiForm.pairTable->setItem(iPair,3, new QTableWidgetItem(1.0));
      }

    }
  }
  pNL_pair->release(); 


  // populate front combobox

  //m_uiForm.frontGroupGroupPairComboBox->addItems(allGroupNames);
  //m_uiForm.frontGroupGroupPairComboBox->addItems(allPairNames);


  if ( pRootElem->hasAttribute("description") )
  {
    m_uiForm.groupDescription->setText(pRootElem->getAttribute("description").c_str());
  }
  else
  {
    m_uiForm.groupDescription->setText("");
  }

  // reads default choice 

  Element* element = pRootElem->getChildElement("default");
  if (element)
  {
    if ( element->hasAttribute("name") )
    {
      setGroupGroupPair(m_uiForm, element->getAttribute("name"));
    }
  }


  pDoc->release();
}
Esempio n. 4
0
int main(int argc, char *argv[])
{
    appPath = argv[0];
    printf("\nQt Creator Debugging Helper testing tool\n\n");
    printf("Running query protocol\n");
    qDumpObjectData440(1, 42, 0, 1, 0, 0, 0, 0);
    fputs(qDumpOutBuffer, stdout);
    fputc('\n', stdout);
    fputc('\n', stdout);

    const TypeDumpFunctionMap tdm = registerTypes();
    const TypeDumpFunctionMap::const_iterator cend = tdm.constEnd();

    if (argc < 2) {
        usage(argv[0], tdm);
        return 0;
    }
    // Parse args
    QStringList tests;
    for (int a = 1; a < argc; a++) {
        const char *arg = argv[a];
        if (arg[0] == '-') {
            switch (arg[1]) {
            case 'a':
                optTestAll = true;
                break;
            case 'u':
                optTestUninitialized = true;
                break;
            case 'v':
                optVerbose++;
                break;
            case 'e':
                optEmptyContainers = true;
                break;
            default:
                fprintf(stderr, "Invalid option %s\n", arg);
                usage(argv[0], tdm);
                return -1;
            }
        } else {
            tests.push_back(QLatin1String(arg));
        }
    }
    // Go
    int rc = 0;
    if (optTestAll) {
        for (TypeDumpFunctionMap::const_iterator it = tdm.constBegin(); it != cend; ++it) {
            const QString test = it.key();
            if (tests.contains(test)) {
                printf("\nSkipping: %s\n", qPrintable(test));
            } else {
                printf("\nTesting: %s\n", qPrintable(test));
                rc += (*it.value())();
                if (optTestUninitialized)
                    printf("Survived: %s\n", qPrintable(test));
            }
        }
    } else {
        foreach(const QString &test, tests) {
            printf("\nTesting: %s\n", qPrintable(test));
            const TypeDumpFunctionMap::const_iterator it = tdm.constFind(test);
            if (it == cend) {
                rc = -1;
                fprintf(stderr, "\nUnhandled type: %s\n", qPrintable(test));
            } else {
                rc = (*it.value())();
            }
        }
    }
void DnDEventLoggerWidget::dragLeaveEvent(QDragLeaveEvent *e)
{
    e->accept();
    m_log->push_back(objectName() + QLatin1String("::") + QLatin1String("dragLeaveEvent") + QLatin1String(" QDragLeaveEvent"));
}
Esempio n. 6
0
int main(int argc, char **argv)
{
  QApplication::setOrganizationName("KDAB");
  QApplication::setOrganizationDomain("kdab.com");
  QApplication::setApplicationName("GammaRay");

  QStringList args;
  for (int i = 1; i < argc; ++i) {
    args.push_back(QString::fromLocal8Bit(argv[i]));
  }
  QApplication app(argc, argv);

  QStringList builtInArgs = QStringList() << QLatin1String("-style")
                                          << QLatin1String("-stylesheet")
                                          << QLatin1String("-graphicssystem");

  QString injectorType;
  int pid = -1;
  while (!args.isEmpty() && args.first().startsWith('-')) {
    const QString arg = args.takeFirst();
    if ((arg == QLatin1String("-i") || arg == QLatin1String("--injector")) && !args.isEmpty()) {
      injectorType = args.takeFirst();
      continue;
    }
    if ((arg == QLatin1String("-p") || arg == QLatin1String("--pid")) && !args.isEmpty()) {
      pid = args.takeFirst().toInt();
      continue;
    }
    if (arg == QLatin1String("-h") || arg == QLatin1String("--help")) {
      usage(argv[0]);
      return 0;
    }
    if (arg == QLatin1String("-v") || arg == QLatin1String("--version")) {
      out << PROGRAM_NAME << " version " << GAMMARAY_VERSION_STRING << endl;
      out << "Copyright (C) 2010-2012 Klaralvdalens Datakonsult AB, "
          << "a KDAB Group company, [email protected]" << endl;
      return 0;
    }
    if (arg == QLatin1String("-filtertest")) {
      qputenv("GAMMARAY_TEST_FILTER", "1");
    }
    if (arg == QLatin1String("-unittest")) {
      qputenv("GAMMARAY_UNITTEST", "1");
    }
    if (arg == QLatin1String("-modeltest")) {
      qputenv("GAMMARAY_MODELTEST", "1");
    }
    // built-in arguments of QApp, could be meant for us if we are showing the launcher window
    foreach (const QString &builtInArg, builtInArgs) {
      if (arg == builtInArg && !args.isEmpty()) {
        args.takeFirst();
      }
    }
  }

  if (args.isEmpty() && pid <= 0) {
    LauncherWindow dialog;
    if (dialog.exec() == QDialog::Accepted) {
      args = dialog.launchArguments();
      bool ok;
      pid = dialog.pid().toInt(&ok);
      if (!ok && args.isEmpty()) {
        return 0;
      }
    } else {
      return 0;
    }
  }

  const QString probeDll = ProbeFinder::findProbe(QLatin1String("gammaray_probe"));
  qputenv("GAMMARAY_PROBE_PATH", QFileInfo(probeDll).absolutePath().toLocal8Bit());

  AbstractInjector::Ptr injector;
  if (injectorType.isEmpty()) {
    if (pid > 0) {
      injector = InjectorFactory::defaultInjectorForAttach();
    } else {
      injector = InjectorFactory::defaultInjectorForLaunch();
    }
  } else {
    injector = InjectorFactory::createInjector(injectorType);
  }

  if (injector) {
    if (pid > 0) {
      if (!injector->attach(pid, probeDll, QLatin1String("gammaray_probe_inject"))) {
        err << "Unable to attach injector " << injector->name() << endl;
        err << "Exit code: " << injector->exitCode() << endl;
        if (!injector->errorString().isEmpty()) {
          err << "Error: " << injector->errorString() << endl;
        }
        return 1;
      } else {
        return 0;
      }
    } else {
      if (!injector->launch(args, probeDll, QLatin1String("gammaray_probe_inject"))) {
        err << "Failed to launch injector " << injector->name() << endl;
        err << "Exit code: " << injector->exitCode() << endl;
        if (!injector->errorString().isEmpty()) {
          err << "Error: " << injector->errorString() << endl;
        }
        return 1;
      }
      return injector->exitCode();
    }
    return 1;
  }

  if (injectorType.isEmpty()) {
    if (pid > 0) {
#if defined(Q_OS_WIN)
      err << "Sorry, but at this time there is no attach injector on the Windows platform" << endl;
      err << "Only the launch injector windll is available on Windows" << endl;
#else
      err << "Uh-oh, there is no default attach injector" << endl;
#endif
    } else {
      err << "Uh-oh, there is no default launch injector" << endl;
    }
  } else {
    err << "Injector " << injectorType << " not found." << endl;
  }
  return 1;
}
Esempio n. 7
0
int prepare(QFileInfo f, QStringList paths) {
	if (paths.isEmpty()) {
		cout << "No -path args were passed :(\n";
		return -1;
	}

	int lastVersion = 0;
	QString lastVersionStr;
	QFileInfo last;
	QFileInfoList l = f.absoluteDir().entryInfoList(QDir::Files);
	for (QFileInfoList::iterator i = l.begin(), e = l.end(); i != e; ++i) {
		QRegularExpressionMatch m = QRegularExpression("/tsetup.((\\d+).(\\d+).(\\d+)).exe$").match(i->absoluteFilePath());
		if (!m.hasMatch()) continue;

		int version = m.captured(2).toInt() * 1000000 + m.captured(3).toInt() * 1000 + m.captured(4).toInt();
		if (version > lastVersion) {
			lastVersion = version;
			lastVersionStr = m.captured(1);
			last = *i;
		}
	}

	if (!lastVersion) {
		cout << "No tsetup.X.Y.Z.exe found :(\n";
		return -1;
	}

	cout << "Last version: " << lastVersionStr.toUtf8().constData() << " (" << lastVersion << "), executing packer..\n";

	QDir dir("deploy/" + lastVersionStr);
	if (dir.exists()) {
		cout << "Version " << lastVersionStr.toUtf8().constData() << " already exists in /deploy..\n";
		return -1;
	}

	QString packer = QString("Packer.exe -version %1").arg(lastVersion);
	for (QStringList::iterator i = paths.begin(), e = paths.end(); i != e; ++i) {
		packer += " -path " + *i;
	}

	int res = system(packer.toUtf8().constData());

	if (res) return res;

	dir.mkpath(".");

	paths.push_back("Telegram.pdb");
	paths.push_back("Updater.pdb");
	paths.push_back("tsetup." + lastVersionStr + ".exe");
	paths.push_back(QString("tupdate%1").arg(lastVersion));
	for (QStringList::iterator i = paths.begin(), e = paths.end(); i != e; ++i) {
		if (!QFile::copy(*i, "deploy/" + lastVersionStr + "/" + *i)) {
			cout << "Could not copy " << i->toUtf8().constData() << " to deploy/" << lastVersionStr.toUtf8().constData() << "\n";
			return -1;
		}
		cout << "Copied " << i->toUtf8().constData() << "..\n";
	}
	for (QStringList::iterator i = paths.begin(), e = paths.end(); i != e; ++i) {
		QFile::remove(*i);
	}

	cout << "Update created in deploy/" << lastVersionStr.toUtf8().constData() << "\n";

	return 0;
}
Esempio n. 8
0
FilterChain *FilterManager::LoadFilters(QString Filters,
                                        VideoFrameType &inpixfmt,
                                        VideoFrameType &outpixfmt, int &width,
                                        int &height, int &bufsize,
                                        int max_threads)
{
    if (Filters.toLower() == "none")
        return nullptr;

    vector<const FilterInfo*> FiltInfoChain;
    FilterChain *FiltChain = new FilterChain;
    vector<FmtConv*> FmtList;
    const FilterInfo *FI;
    const FilterInfo *FI2;
    QString Opts;
    const FilterInfo *Convert = GetFilterInfo("convert");
    QStringList OptsList;
    QStringList FilterList = Filters.split(",", QString::SkipEmptyParts);
    VideoFilter *NewFilt = nullptr;
    FmtConv *FC, *FC2, *S1, *S2, *S3;
    VideoFrameType ifmt;
    int nbufsize;
    int cbufsize;
    int postfilt_width = width;
    int postfilt_height = height;

    for (auto i = FilterList.begin(); i != FilterList.end(); ++i)
    {
        QString FiltName = (*i).section('=', 0, 0);
        QString FiltOpts = (*i).section('=', 1);

        if (FiltName.contains("opengl", Qt::CaseInsensitive) ||
            FiltName.contains("vdpau",  Qt::CaseInsensitive))
            continue;

        FI = GetFilterInfo(FiltName);

        if (FI)
        {
            FiltInfoChain.push_back(FI);
            OptsList.push_back(FiltOpts);
        }
        else
        {
            LOG(VB_GENERAL, LOG_ERR, LOC +
                QString("Failed to load filter '%1', "
                        "no such filter exists").arg(FiltName));
            FiltInfoChain.clear();
            break;
        }
    }

    ifmt = inpixfmt;
    for (uint i = 0; i < FiltInfoChain.size(); i++)
    {
        S1 = S2 = S3 = nullptr;
        FI = FiltInfoChain[i];
        if (FiltInfoChain.size() - i == 1)
        {
            for (FC = FI->formats; FC->in != FMT_NONE; FC++)
            {
                if (FC->out == outpixfmt && FC->in == ifmt)
                {
                    S1 = FC;
                    break;
                }
                if (FC->in == ifmt && !S2)
                    S2 = FC;
                if (FC->out == outpixfmt && !S3)
                    S3 = FC;
            }
        }
        else
        {
            FI2 = FiltInfoChain[i+1];
            for (FC = FI->formats; FC->in != FMT_NONE; FC++)
            {
                for (FC2 = FI2->formats; FC2->in != FMT_NONE; FC2++)
                {
                    if (FC->in == ifmt && FC->out == FC2->in)
                    {
                        S1 = FC;
                        break;
                    }
                    if (FC->out == FC2->in && !S3)
                        S3 = FC;
                }
                if (S1)
                    break;
                if (FC->in == ifmt && !S2)
                    S2 = FC;
            }
        }

        if (S1)
            FC = S1;
        else if (S2)
            FC = S2;
        else if (S3)
            FC = S3;
        else
            FC = FI->formats;

        if (FC->in != ifmt && (i > 0 || ifmt != FMT_NONE))
        {
            if (!Convert)
            {
                LOG(VB_GENERAL, LOG_ERR, "FilterManager: format conversion "
                                         "needed but convert filter not found");
                FiltInfoChain.clear();
                break;
            }
            FiltInfoChain.insert(FiltInfoChain.begin() + i, Convert);
            OptsList.insert(i, QString ());
            FmtList.push_back(new FmtConv);
            if (FmtList.back())
            {
                FmtList.back()->in = ifmt;
                FmtList.back()->out = FC->in;
                i++;
            }
            else
            {
                LOG(VB_GENERAL, LOG_ERR,
                    "FilterManager: memory allocation "
                    "failure, returning empty filter chain");
                FiltInfoChain.clear();
                break;
            }
        }
        FmtList.push_back(new FmtConv);
        if (FmtList.back())
        {
            FmtList.back()->in = FC->in;
            FmtList.back()->out = FC->out;
        }
        else
        {
            LOG(VB_GENERAL, LOG_ERR,
                "FilterManager: memory allocation failure, "
                "returning empty filter chain");
            FiltInfoChain.clear();
            break;
        }
        ifmt = FC->out;
    }

    if (ifmt != outpixfmt && outpixfmt != FMT_NONE &&
        (FiltInfoChain.size() || inpixfmt != FMT_NONE))
    {
        if (!Convert)
        {
            LOG(VB_GENERAL, LOG_ERR, "FilterManager: format conversion "
                                     "needed but convert filter not found");
            FiltInfoChain.clear();
        }
        else
        {
            FiltInfoChain.push_back(Convert);
            OptsList.push_back( QString ());
            FmtList.push_back(new FmtConv);
            if (FmtList.back())
            {
                FmtList.back()->in = ifmt;
                FmtList.back()->out = outpixfmt;
            }
            else
            {
                LOG(VB_GENERAL, LOG_ERR,
                    "FilterManager: memory allocation "
                    "failure, returning empty filter chain");
                FiltInfoChain.clear();
            }
        }
    }

    nbufsize = -1;

    if (FiltInfoChain.empty())
    {
        delete FiltChain;
        FiltChain = nullptr;
    }

    for (uint i = 0; i < FiltInfoChain.size(); i++)
    {
        QByteArray tmp = OptsList[i].toLocal8Bit();
        NewFilt = LoadFilter(FiltInfoChain[i], FmtList[i]->in,
                             FmtList[i]->out, postfilt_width,
                             postfilt_height, tmp.constData(),
                             max_threads);

        if (!NewFilt)
        {
            delete FiltChain;
            LOG(VB_GENERAL, LOG_ERR, QString("FilterManager: failed to load "
                                             "filter %1 %2->%3 with args %4")
                    .arg(FiltInfoChain[i]->name)
                    .arg(FmtToString(FmtList[i]->in))
                    .arg(FmtToString(FmtList[i]->out))
                    .arg(OptsList[i]));
            FiltChain = nullptr;
            nbufsize = -1;
            break;
        }

        if (NewFilt->filter && FiltChain)
        {
            FiltChain->Append(NewFilt);
        }
        else
        {
            if (NewFilt->opts)
                free(NewFilt->opts);
            if (NewFilt->cleanup)
                NewFilt->cleanup(NewFilt);
            dlclose(NewFilt->handle);
            free(NewFilt);
        }

        switch (FmtList[i]->out)
        {
            case FMT_YV12:
                cbufsize = postfilt_width * postfilt_height * 3 / 2;
                break;
            case FMT_YUV422P:
                cbufsize = postfilt_width * postfilt_height * 2;
                break;
            case FMT_RGB24:
                cbufsize = postfilt_width * postfilt_height * 3;
                break;
            case FMT_ARGB32:
                cbufsize = postfilt_width * postfilt_height * 4;
                break;
            default:
                cbufsize = 0;
        }

        if (cbufsize > nbufsize)
            nbufsize = cbufsize;
    }

    if (FiltChain)
    {
        if (inpixfmt == FMT_NONE)
            inpixfmt = FmtList.front()->in;
        if (outpixfmt == FMT_NONE)
            outpixfmt = FmtList.back()->out;
        width = postfilt_width;
        height = postfilt_height;
    }
    else
    {
        if (inpixfmt == FMT_NONE && outpixfmt == FMT_NONE)
            inpixfmt = outpixfmt = FMT_YV12;
        else if (inpixfmt == FMT_NONE)
            inpixfmt = outpixfmt;
        else if (outpixfmt == FMT_NONE)
            outpixfmt = inpixfmt;
    }

    switch (inpixfmt)
    {
        case FMT_YV12:
            cbufsize = postfilt_width * postfilt_height * 3 / 2;
            break;
        case FMT_YUV422P:
            cbufsize = postfilt_width * postfilt_height * 2;
            break;
        case FMT_RGB24:
            cbufsize = postfilt_width * postfilt_height * 3;
            break;
        case FMT_ARGB32:
            cbufsize = postfilt_width * postfilt_height * 4;
            break;
        default:
            cbufsize = 0;
    }

    if (cbufsize > nbufsize)
        nbufsize = cbufsize;

    bufsize = nbufsize;

    vector<FmtConv*>::iterator it = FmtList.begin();
    for (; it != FmtList.end(); ++it)
        delete *it;
    FmtList.clear();

    return FiltChain;
}
bool Index::parseDocumentToStringlist(EBook *chmFile, const QUrl& filename, QStringList& tokenlist )
{
	QString parsedbuf, parseentity, text;
	
	if ( !chmFile->getFileContentAsString( text, filename )
	|| text.isEmpty() )
	{
		qWarning( "Search index generator: could not retrieve the document content for %s", qPrintable( filename.toString() ) );
		return false;
	}

	m_charssplit = SPLIT_CHARACTERS;
	m_charsword = WORD_CHARACTERS;
	
	tokenlist.clear();
	
	// State machine states
	enum state_t
	{
		STATE_OUTSIDE_TAGS,		// outside HTML tags; parse text
		STATE_IN_HTML_TAG,		// inside HTML tags; wait for end tag
		STATE_IN_QUOTES,		// inside HTML tags and inside quotes; wait for end quote (in var QuoteChar)
		STATE_IN_HTML_ENTITY	// inside HTML entity; parse the entity
	};
	
	state_t state = STATE_OUTSIDE_TAGS;
	QChar QuoteChar; // used in STATE_IN_QUOTES
	
	for ( int j = 0; j < text.length(); j++ )
	{
		QChar ch = text[j];
		
		if ( (j % 20000) == 0 )
			qApp->processEvents( QEventLoop::ExcludeUserInputEvents );
		
		if ( state == STATE_IN_HTML_TAG )
		{
			// We are inside HTML tag.
			// Ignore everything until we see '>' (end of HTML tag) or quote char (quote start)
			if ( ch == '"' || ch == '\'' )
			{
				state = STATE_IN_QUOTES;
				QuoteChar = ch;
			}
			else if ( ch == '>' )
				state = STATE_OUTSIDE_TAGS;
				
			continue;
		}
		else if ( state == STATE_IN_QUOTES )
		{
			// We are inside quoted text inside HTML tag. 
			// Ignore everything until we see the quote character again
			if ( ch == QuoteChar )
				state = STATE_IN_HTML_TAG;
				
			continue;
		}
		else if ( state == STATE_IN_HTML_ENTITY )
		{
			// We are inside encoded HTML entity (like &nbsp;).
			// Collect to parsedbuf everything until we see ;
			if ( ch.isLetterOrNumber() )
			{
				// get next character of this entity
				parseentity.append( ch );
				continue;
			}
				
			// The entity ended
			state = STATE_OUTSIDE_TAGS;
			
			// Some shitty HTML does not terminate entities correctly. Screw it.			
			if ( ch != ';' && ch != '<' )
			{
				if ( parseentity.isEmpty() )
				{
					// straight '&' symbol. Add and continue.
					parsedbuf += "&";
				}
				else
					qWarning( "Index::parseDocument: incorrectly terminated HTML entity '&%s%c', ignoring", qPrintable( parseentity ), ch.toLatin1() );
				
				j--; // parse this character again, but in different state
				continue;
			}
			
			// Don't we have a space?
			if ( parseentity.toLower() != "nbsp" )
			{
				QString entity = entityDecoder.decode( parseentity );
			
				if ( entity.isNull() )
				{
					// decodeEntity() already printed error message
					//qWarning( "Index::parseDocument: failed to decode entity &%s;", parsedbuf.ascii() );
					continue;
				}
			
				parsedbuf += entity;
				continue;
			}
			else
				ch = ' '; // We got a space, so treat it like it, and not add it to parsebuf
		}
		
		// 
		// Now process STATE_OUTSIDE_TAGS
		//
		
		// Check for start of HTML tag, and switch to STATE_IN_HTML_TAG if it is
		if ( ch == '<' )
		{
			state = STATE_IN_HTML_TAG;
			goto tokenize_buf;
		}
		
		// Check for start of HTML entity
		if ( ch == '&' )
		{
			state = STATE_IN_HTML_ENTITY;
			parseentity = QString::null;
			continue;
		}
		
		// Replace quote by ' - quotes are used in search window to set the phrase
		if ( ch == '"' )
			ch = '\'';
		
		// Ok, we have a valid character outside HTML tags, and probably some in buffer already.
		// If it is char or letter, add it and continue
		if ( ch.isLetterOrNumber() || m_charsword.indexOf( ch ) != -1 )
		{
			parsedbuf.append( ch );
			continue;
		}
		
		// If it is a split char, add the word to the dictionary, and then add the char itself.
		if ( m_charssplit.indexOf( ch ) != -1 )
		{
			if ( !parsedbuf.isEmpty() )
				tokenlist.push_back( parsedbuf.toLower() );
			
			tokenlist.push_back( ch.toLower() );
			parsedbuf = QString::null;
			continue;
		}
		
tokenize_buf:		
		// Just add the word; it is most likely a space or terminated by tokenizer.
		if ( !parsedbuf.isEmpty() )
		{
			tokenlist.push_back( parsedbuf.toLower() );
			parsedbuf = QString::null;
		}
	}
	
	// Add the last word if still here - for broken htmls.
	if ( !parsedbuf.isEmpty() )
		tokenlist.push_back( parsedbuf.toLower() );
	
	return true;
}
int MathInLine::validateMathInLine(NineMLLayout* component, QStringList * errs)
{
    // remove operators

    if (equation.size() == 0) {
        return 1;
    }

    QString test = equation;

    test = equation;
    test.replace('+', ' ');
    test = test.replace('-', ' ');
    test = test.replace('*', ' ');
    test = test.replace('/', ' ');
    test = test.replace('(', ' ');
    test = test.replace(')', ' ');
    test = test.replace('<', ' ');
    test = test.replace('>', ' ');
    test = test.replace('=', ' ');
    test = test.replace(',', ' ');

    QStringList FuncList;
    FuncList.push_back("pow");
    FuncList.push_back("exp");
    FuncList.push_back("sin");
    FuncList.push_back("cos");
    FuncList.push_back("log");
    FuncList.push_back("log10");
    FuncList.push_back("sinh");
    FuncList.push_back("cosh");
    FuncList.push_back("tanh");
    FuncList.push_back("sqrt");
    FuncList.push_back("atan");
    FuncList.push_back("asin");
    FuncList.push_back("acos");
    FuncList.push_back("asinh");
    FuncList.push_back("acosh");
    FuncList.push_back("atanh");
    FuncList.push_back("atan2");
    FuncList.push_back("ceil");
    FuncList.push_back("floor");
    FuncList.push_back("rand");
    FuncList.push_back("mod");


    // not strictly functions...
    FuncList.push_back("t");
    FuncList.push_back("dt");

    // remove double whitespaces
    test = test.simplified();

    // tokenise
    QStringList splitTest;
    splitTest = test.split(' ');

    // check each token...
    for (unsigned int i = 0; i < (uint) splitTest.count(); ++i) {

        bool recognised = false;

        // see if it is in the component
        for (unsigned int j = 0; j<component->ParameterList.size(); j++) {
            if (component->ParameterList[j]->name.compare(splitTest[i]) == 0)
                recognised = true;
        }
        for (unsigned int j = 0; j<component->StateVariableList.size(); j++) {
            if (component->StateVariableList[j]->name.compare(splitTest[i]) == 0)
                recognised = true;
        }
        for (unsigned int j = 0; j<component->AliasList.size(); j++) {
            if (component->AliasList[j]->name.compare(splitTest[i]) == 0)
                recognised = true;
        }
        for (unsigned int j = 0; j<(uint)FuncList.size(); j++) {
            if (FuncList[j].compare(splitTest[i]) == 0)
                recognised = true;
        }
        // see if it is a number...
        if (splitTest[i][0] > 47 && splitTest[i][0] < 58 && splitTest[i][0] != '.') {
            recognised = true;
        }

        // if a token is not recognised, then let the user know - this may be better done elsewhere...
        if (!recognised) {
            errs->push_back("MathString contains unrecognised token " + splitTest[i]);

        }

    }
    if (equation.count("(") != equation.count(")")) {
        errs->push_back("MathString contains mis-matched brackets");
    }

    return 0;
}
Esempio n. 11
0
mass* massDialog::callDialog(modeler *md)
{
	QList<QString> geoList = md->objects().keys();
	QStringList geoStrList;
	for (unsigned int i = 0; i < geoList.size(); i++){
		geoStrList.push_back(geoList[i]);
	}
	QComboBox *CBBase = new QComboBox;
	CBBase->addItems(geoStrList);
	QLabel *LCBBase = new QLabel("Base geometry");
	QLabel *LMass, *LIxx, *LIyy, *LIzz, *LIxy, *LIxz, *LIzy;
	QLineEdit *LEMass, *LEIxx, *LEIyy, *LEIzz, *LEIxy, *LEIxz, *LEIzy;
	
	LMass = new QLabel("Mass"); LEMass = new QLineEdit;
	LIxx = new QLabel("Ixx");	LEIxx = new QLineEdit;
	LIyy = new QLabel("Iyy");   LEIyy = new QLineEdit;
	LIzz = new QLabel("Izz");	LEIzz = new QLineEdit;
	LIxy = new QLabel("Ixy");	LEIxy = new QLineEdit;
	LIxz = new QLabel("Ixz");	LEIxz = new QLineEdit;
	LIzy = new QLabel("Izy");	LEIzy = new QLineEdit;
	
	PBOk = new QPushButton("OK");
	PBCancel = new QPushButton("Cancel");
	connect(PBOk, SIGNAL(clicked()), this, SLOT(Click_ok()));
	connect(PBCancel, SIGNAL(clicked()), this, SLOT(Click_cancel()));
	QGridLayout *massLayout = new QGridLayout;
	massLayout->addWidget(LCBBase, 0, 0);
	massLayout->addWidget(CBBase, 0, 1, 1, 2);
	massLayout->addWidget(LMass, 1, 0);
	massLayout->addWidget(LEMass, 1, 1, 1, 2);
	massLayout->addWidget(LIxx, 2, 0);
	massLayout->addWidget(LEIxx, 2, 1, 1, 1);
	massLayout->addWidget(LIxy, 3, 0);
	massLayout->addWidget(LEIxy, 3, 1, 1, 1);
	massLayout->addWidget(LIyy, 3, 2);
	massLayout->addWidget(LEIyy, 3, 3, 1, 1);
	massLayout->addWidget(LIxz, 4, 0);
	massLayout->addWidget(LEIxz, 4, 1, 1, 1);
	massLayout->addWidget(LIzy, 4, 2);
	massLayout->addWidget(LEIzy, 4, 3, 1, 1);
	massLayout->addWidget(LIzz, 4, 4);
	massLayout->addWidget(LEIzz, 4, 5, 1, 1);
	massLayout->addWidget(PBOk, 5, 4);
	massLayout->addWidget(PBCancel, 5, 5);
	this->setLayout(massLayout);
	this->exec();
	mass* m = NULL;
	if (isDialogOk)
	{
		m = md->makeMass(CBBase->currentText());
		m->setMass(LEMass->text().toFloat());		
		
		VEC3D syminer;							//inertia
		syminer.x = LEIxy->text().toFloat();
		syminer.y = LEIxz->text().toFloat();
		syminer.z = LEIzy->text().toFloat();
		m->setSymIner(syminer);

		VEC3D prininer;
		prininer.x = LEIxx->text().toFloat();
		prininer.y = LEIyy->text().toFloat();
		prininer.z = LEIzz->text().toFloat();
		m->setPrinIner(prininer);
		m->setInertia();//m->define();
	}
	return m;
}
Esempio n. 12
0
int main(int argc, char **argv)
{
    MyScopedSyslogListener syslogListener;

    //did the user specified files on the command line?
    //stash the files so they are loaded into the editor
    //this replaces the currently stored file list
    QStringList files;
    for (int i = 1; i < argc; i++)
    {
        QString file(argv[i]);
        if (file.isEmpty()) continue;
        files.push_back(file);
    }
    if (not files.isEmpty()) getSettings().setValue("GraphEditorTabs/files", files);

    //create the entry point to the GUI
    QApplication app(argc, argv);
    app.setOrganizationName("PothosWare");
    app.setApplicationName("Pothos");

    //create splash screen
    getSplashScreen()->show();

    //setup the application icon
    app.setWindowIcon(QIcon(makeIconPath("PothosGui.png")));

    //perform library initialization with graphical error message on failure
    Pothos::RemoteServer server;
    try
    {
        //try to talk to the server on localhost, if not there, spawn a custom one
        //make a server and node that is temporary with this process
        postStatusMessage("Launching scratch process...");
        try
        {
            Pothos::RemoteClient client("tcp://"+Pothos::Util::getLoopbackAddr());
        }
        catch (const Pothos::RemoteClientError &)
        {
            server = Pothos::RemoteServer("tcp://"+Pothos::Util::getLoopbackAddr(Pothos::RemoteServer::getLocatorPort()));
            //TODO make server background so it does not close with process
            Pothos::RemoteClient client("tcp://"+Pothos::Util::getLoopbackAddr()); //now it should connect to the new server
        }
    }
    catch (const Pothos::Exception &ex)
    {
        QMessageBox msgBox(QMessageBox::Critical, "Pothos Initialization Error", QString::fromStdString(ex.displayText()));
        msgBox.exec();
        return EXIT_FAILURE;
    }

    POTHOS_EXCEPTION_TRY
    {
        postStatusMessage("Initializing Pothos plugins...");
        Pothos::ScopedInit init;

        //create the main window for the GUI
        std::unique_ptr<QWidget> mainWindow(new PothosGuiMainWindow(nullptr));
        mainWindow->show();
        getSplashScreen()->finish(mainWindow.get());
        getSettings().setParent(mainWindow.get());

        //begin application execution
        return app.exec();
    }
    POTHOS_EXCEPTION_CATCH (const Pothos::Exception &ex)
    {
        QMessageBox msgBox(QMessageBox::Critical, "PothosGui Application Error", QString::fromStdString(ex.displayText()));
        msgBox.exec();
        return EXIT_FAILURE;
    }
Esempio n. 13
0
void ContactsInner::updateFilter(QString filter) {
	QStringList f;
	if (!filter.isEmpty()) {
		QStringList filterList = filter.split(cWordSplit(), QString::SkipEmptyParts);
		int l = filterList.size();

		f.reserve(l);
		for (int i = 0; i < l; ++i) {
			QString filterName = filterList[i].trimmed();
			if (filterName.isEmpty()) continue;
			f.push_back(filterName);
		}
		filter = f.join(' ');
	}
	if (_filter != filter) {
		int32 rh = (st::profileListPhotoSize + st::profileListPadding.height() * 2);
		_filter = filter;
		if (_filter.isEmpty()) {
			resize(width(), _contacts->list.count * rh + st::contactsClose.height);
			if (_contacts->list.count) {
				_sel = _contacts->list.begin;
			}
		} else {
			QStringList::const_iterator fb = f.cbegin(), fe = f.cend(), fi;

			_filtered.clear();
			if (!f.isEmpty()) {
				DialogsList *dialogsToFilter = 0;
				if (_contacts->list.count) {
					for (fi = fb; fi != fe; ++fi) {
						DialogsIndexed::DialogsIndex::iterator i = _contacts->index.find(fi->at(0));
						if (i == _contacts->index.cend()) {
							dialogsToFilter = 0;
							break;
						}
						if (!dialogsToFilter || dialogsToFilter->count > i.value()->count) {
							dialogsToFilter = i.value();
						}
					}
				}
				if (dialogsToFilter && dialogsToFilter->count) {
					_filtered.reserve(dialogsToFilter->count);
					for (DialogRow *i = dialogsToFilter->begin, *e = dialogsToFilter->end; i != e; i = i->next) {
						const PeerData::Names &names(i->history->peer->names);
						PeerData::Names::const_iterator nb = names.cbegin(), ne = names.cend(), ni;
						for (fi = fb; fi != fe; ++fi) {
							QString filterName(*fi);
							for (ni = nb; ni != ne; ++ni) {
								if ((*ni).indexOf(*fi) == 0) {
									break;
								}
							}
							if (ni == ne) {
								break;
							}
						}
						if (fi == fe) {
							i->attached = 0;
							_filtered.push_back(i);
						}
					}
				}
			}
			_filteredSel = _filtered.isEmpty() ? -1 : 0;

			resize(width(), _filtered.size() * rh + st::contactsClose.height);
		}
		if (parentWidget()) parentWidget()->update();
		loadProfilePhotos(0);
	}
}
Esempio n. 14
0
template <typename M> void MatchT<M>::split()
{
    if(!ShapeT<M>::isMeshOpen() || parts_.size()==0 || points_.size()==0)
    {
        qCritical() << "Cannot split mesh! Either mesh is not open or parts or points do not exist!" ;
        return;
    }
    
    // Try to find a seg file to use for splitting the mesh
    bool useSegFile = false;
    
    QStringList pathParts = meshFilename_.split("/");
    
    QString segName = pathParts.last().split(".").first().append(".seg");
    
    pathParts.removeLast();
    
    pathParts.push_back(segName);
    
    QString segPath = pathParts.join("/");
    
    QFile file(segPath);
    
    std::vector<int> segLabels;
    
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qCritical() << "Could not open file " << segPath ;
    }
    else
    {
        QTextStream in(&file);
        
        while (!in.atEnd())
        {
            QString line = in.readLine();
            segLabels.push_back(line.toInt());
        }
        
        if (segLabels.size()!= ShapeT<M>::mesh_.n_faces())
        {
            qDebug() << "Mesh has a seg file, but it only contained " << segLabels.size() << " labels for " << ShapeT<M>::mesh_.n_faces() << " faces, so cannot use it!";
        }
        else
        {
            useSegFile = true;
        }
    }
    
    std::map<int, int> partID2partIndex;
    
    std::map<int, std::map<typename M::VertexHandle,typename M::VertexHandle> > partID2vhMap;
    
    typename std::vector<Part>::const_iterator partscIt (parts_.begin()), partscEnd(parts_.end());

    int index =0;
    
    for (; partscIt != partscEnd; ++partscIt)
    {
        partID2partIndex[partscIt->partID_] = index;
        index++;
    }

    
    typename M::ConstFaceIter cfIt(ShapeT<M>::mesh_.faces_begin()), facesEnd(ShapeT<M>::mesh_.faces_end());
    
    int f = 0;
    
    // For every face go over all points of the match and find the nearest point to this face
    for (; cfIt!=facesEnd; ++cfIt)
    {
        int facePartID = -1;
        
        // Get the three vertices of this face (should be 3) so we can get the normal to the face
        typename M::ConstFaceVertexIter cfvIt;
        
        if (useSegFile)
        {
            facePartID = segLabels[ShapeT<M>::indexMap_[f]] + 1; //only works assuming part ids start from 2 and seg ids start from 1
        }
        else
        {
            cfvIt= ShapeT<M>::mesh_.cfv_iter(cfIt);
            
            typename std::vector<MeshPoint>::const_iterator pointsIt(points_.begin()), pointsEnd(points_.end());
            
            double minDistance = std::numeric_limits<double>::max();
          
            typename M::Point p0 = ShapeT<M>::mesh_.point(cfvIt);
            ++cfvIt;
            typename M::Point p1 = ShapeT<M>::mesh_.point(cfvIt);
            ++cfvIt;
            typename M::Point p2 = ShapeT<M>::mesh_.point(cfvIt);
            
            // Go over all points in the match (these have part id labels)
            for( ; pointsIt!=pointsEnd ; ++pointsIt)
            {
                double p2pDistance = sqrDistPoint2Triangle(p0,p1,p2,OpenMesh::vector_cast<typename M::Point>(pointsIt->pos_));
                
                if (p2pDistance < minDistance)
                {
                    minDistance = p2pDistance;
                    facePartID = pointsIt->partID_;
                }
            }
        }
        
        Part& cPart = parts_[partID2partIndex[facePartID]];
        typename ShapeT<M>::Mesh& cMesh = cPart.partShape_.mesh();
        
        std::map< typename M::VertexHandle, typename M::VertexHandle>& cvhMap = partID2vhMap[facePartID];
        
        // reset the face vertex iterator
        cfvIt = ShapeT<M>::mesh_.cfv_iter(cfIt);
        
        std::vector<typename M::VertexHandle> face_vhandles;
        
        int i=0;
        // Go over all vertices of this face (should only be 3 of them), add them to the new mesh if they haven't been added yet, and add their handle to the list of handles for the new face to be added to the new mesh
        for(; cfvIt; ++cfvIt, ++i)
        {
            // check if the vertex has been added to this part
            if(cvhMap.count(cfvIt)<=0)
            {
                typename M::VertexHandle vhandle = cMesh.add_vertex(ShapeT<M>::mesh_.point(cfvIt));
                face_vhandles.push_back(vhandle);
                // add this vertex new handle to the map
                cvhMap[cfvIt] = vhandle;
            }
            else
            {
                face_vhandles.push_back(cvhMap[cfvIt]);
            }
        }
        if( i>3)
        {
            qWarning() << "Warning, found " << i << " vertices for this face instead of 3!!";
        }
        
        cMesh.add_face(face_vhandles);
        
        f++;
    }
    
    // Update normals for all part meshes
    typename std::vector<Part>::iterator partsIt (parts_.begin()), partsEnd(parts_.end());

    for (; partsIt != partsEnd; ++partsIt)
    {
        typename ShapeT<M>::Mesh& cMesh = partsIt->partShape_.mesh();
        
        cMesh.request_face_normals();
        cMesh.request_vertex_normals();
        cMesh.update_face_normals();
        cMesh.update_vertex_normals();
    }
    
    segmented_ = true;
}
Esempio n. 15
0
 static QStringList stringList( const char * headers[], int numHeaders ) {
   QStringList sl;
   for ( int i = 0 ; i < numHeaders ; ++i )
     sl.push_back( headers[i] );
   return sl;
 }
Esempio n. 16
0
LadspaManager::LadspaManager()
{
	// Make sure plugin search paths are set up
	PluginFactory::instance();

	QStringList ladspaDirectories = QString( getenv( "LADSPA_PATH" ) ).
								split( LADSPA_PATH_SEPERATOR );
	ladspaDirectories += ConfigManager::inst()->ladspaDir().split( ',' );

	ladspaDirectories.push_back( "plugins:ladspa" );
#ifndef LMMS_BUILD_WIN32
	ladspaDirectories.push_back( qApp->applicationDirPath() + '/' + LIB_DIR + "ladspa" );
	ladspaDirectories.push_back( "/usr/lib/ladspa" );
	ladspaDirectories.push_back( "/usr/lib64/ladspa" );
	ladspaDirectories.push_back( "/usr/local/lib/ladspa" );
	ladspaDirectories.push_back( "/usr/local/lib64/ladspa" );
	ladspaDirectories.push_back( "/Library/Audio/Plug-Ins/LADSPA" );
#endif

	for( QStringList::iterator it = ladspaDirectories.begin(); 
			 		   it != ladspaDirectories.end(); ++it )
	{
		QDir directory( ( *it ) );
		QFileInfoList list = directory.entryInfoList();
		for( QFileInfoList::iterator file = list.begin();
						file != list.end(); ++file )
		{
			const QFileInfo & f = *file;
			if( !f.isFile() ||
				 f.fileName().right( 3 ).toLower() !=
#ifdef LMMS_BUILD_WIN32
													"dll"
#else
				 									".so"
#endif
								)
			{
				continue;
			}

			QLibrary plugin_lib( f.absoluteFilePath() );

			if( plugin_lib.load() == true )
			{
				LADSPA_Descriptor_Function descriptorFunction =
			( LADSPA_Descriptor_Function ) plugin_lib.resolve(
							"ladspa_descriptor" );
				if( descriptorFunction != NULL )
				{
					addPlugins( descriptorFunction,
							f.fileName() );
				}
			}
			else
			{
				qWarning() << plugin_lib.errorString();
			}
		}
	}
	
	l_ladspa_key_t keys = m_ladspaManagerMap.keys();
	for( l_ladspa_key_t::iterator it = keys.begin();
			it != keys.end(); ++it )
	{
		m_sortedPlugins.append( qMakePair( getName( *it ), *it ) );
	}
	qSort( m_sortedPlugins );
}
Esempio n. 17
0
void QgsObjectCustomProperties::readXml( const QDomNode& parentNode, const QString& keyStartsWith )
{
  QDomNode propsNode = parentNode.namedItem( "customproperties" );
  if ( propsNode.isNull() ) // no properties stored...
    return;

  if ( !keyStartsWith.isEmpty() )
  {
    //remove old keys
    QStringList keysToRemove;
    QMap<QString, QVariant>::const_iterator pIt = mMap.constBegin();
    for ( ; pIt != mMap.constEnd(); ++pIt )
    {
      if ( pIt.key().startsWith( keyStartsWith ) )
      {
        keysToRemove.push_back( pIt.key() );
      }
    }

    QStringList::const_iterator sIt = keysToRemove.constBegin();
    for ( ; sIt != keysToRemove.constEnd(); ++sIt )
    {
      mMap.remove( *sIt );
    }
  }
  else
  {
    mMap.clear();
  }

  QDomNodeList nodes = propsNode.childNodes();

  for ( int i = 0; i < nodes.size(); i++ )
  {
    QDomNode propNode = nodes.at( i );
    if ( propNode.isNull() || propNode.nodeName() != "property" )
      continue;
    QDomElement propElement = propNode.toElement();

    QString key = propElement.attribute( "key" );
    if ( key.isEmpty() || key.startsWith( keyStartsWith ) )
    {
      if ( propElement.hasAttribute( "value" ) )
      {
        QString value = propElement.attribute( "value" );
        mMap[key] = QVariant( value );
      }
      else
      {
        QStringList list;

        for ( QDomElement itemElement = propElement.firstChildElement( "value" );
              !itemElement.isNull();
              itemElement = itemElement.nextSiblingElement( "value" ) )
        {
          list << itemElement.text();
        }

        mMap[key] = QVariant( list );
      }
    }
  }

}
Esempio n. 18
0
QgsComposition* QgsWMSConfigParser::createPrintComposition( const QString& composerTemplate, QgsMapRenderer* mapRenderer, const QMap< QString, QString >& parameterMap ) const
{
  QList<QgsComposerMap*> composerMaps;
  QList<QgsComposerLegend*> composerLegends;
  QList<QgsComposerLabel*> composerLabels;
  QList<const QgsComposerHtml*> composerHtmls;

  QgsComposition* c = initComposition( composerTemplate, mapRenderer, composerMaps, composerLegends, composerLabels, composerHtmls );
  if ( !c )
  {
    return 0;
  }

  QString dpi = parameterMap.value( "DPI" );
  if ( !dpi.isEmpty() )
  {
    c->setPrintResolution( dpi.toInt() );
  }

  //replace composer map parameters
  Q_FOREACH ( QgsComposerMap* currentMap, composerMaps )
  {
    if ( !currentMap )
    {
      continue;
    }

    QString mapId = "MAP" + QString::number( currentMap->id() );

    QString extent = parameterMap.value( mapId + ":EXTENT" );
    if ( extent.isEmpty() ) //map extent is mandatory
    {
      //remove map from composition if not referenced by the request
      c->removeItem( currentMap ); delete currentMap; continue;
    }

    QStringList coordList = extent.split( "," );
    if ( coordList.size() < 4 )
    {
      c->removeItem( currentMap ); delete currentMap; continue; //need at least four coordinates
    }

    bool xMinOk, yMinOk, xMaxOk, yMaxOk;
    double xmin = coordList.at( 0 ).toDouble( &xMinOk );
    double ymin = coordList.at( 1 ).toDouble( &yMinOk );
    double xmax = coordList.at( 2 ).toDouble( &xMaxOk );
    double ymax = coordList.at( 3 ).toDouble( &yMaxOk );
    if ( !xMinOk || !yMinOk || !xMaxOk || !yMaxOk )
    {
      c->removeItem( currentMap ); delete currentMap; continue;
    }

    QgsRectangle r( xmin, ymin, xmax, ymax );

    //Change x- and y- of extent for WMS 1.3.0 if axis inverted
    QString version = parameterMap.value( "VERSION" );
    if ( version == "1.3.0" && mapRenderer && mapRenderer->destinationCrs().axisInverted() )
    {
      r.invert();
    }
    currentMap->setNewExtent( r );

    //scale
    QString scaleString = parameterMap.value( mapId + ":SCALE" );
    if ( !scaleString.isEmpty() )
    {
      bool scaleOk;
      double scale = scaleString.toDouble( &scaleOk );
      if ( scaleOk )
      {
        currentMap->setNewScale( scale );
      }
    }

    //rotation
    QString rotationString = parameterMap.value( mapId + ":ROTATION" );
    if ( !rotationString.isEmpty() )
    {
      bool rotationOk;
      double rotation = rotationString.toDouble( &rotationOk );
      if ( rotationOk )
      {
        currentMap->setMapRotation( rotation );
      }
    }

    //layers / styles
    QString layers = parameterMap.value( mapId + ":LAYERS" );
    QString styles = parameterMap.value( mapId + ":STYLES" );
    if ( !layers.isEmpty() )
    {
      QStringList layerSet;
      QStringList wmsLayerList = layers.split( ",", QString::SkipEmptyParts );
      QStringList wmsStyleList;

      if ( !styles.isEmpty() )
      {
        wmsStyleList = styles.split( ",", QString::SkipEmptyParts );
      }

      for ( int i = 0; i < wmsLayerList.size(); ++i )
      {
        QString wmsLayer = wmsLayerList.at( i );
        QString styleName;
        if ( wmsStyleList.size() > i )
        {
          styleName = wmsStyleList.at( i );
        }
        
        bool allowCaching = true;
        if ( wmsLayerList.count( wmsLayer ) > 1 )
        {
          allowCaching = false;
        }

        QList<QgsMapLayer*> layerList = mapLayerFromStyle( wmsLayer, styleName, allowCaching );
        int listIndex;
        for ( listIndex = layerList.size() - 1; listIndex >= 0; listIndex-- )
        {
          QgsMapLayer* layer = layerList.at( listIndex );
          if ( layer )
          {
            layerSet.push_back( layer->id() );
          }
        }
      }

      currentMap->setLayerSet( layerSet );
      currentMap->setKeepLayerSet( true );
    }

    //grid space x / y
    currentMap->grid()->setIntervalX( parameterMap.value( mapId + ":GRID_INTERVAL_X" ).toDouble() );
    currentMap->grid()->setIntervalY( parameterMap.value( mapId + ":GRID_INTERVAL_Y" ).toDouble() );
  }
  //update legend
  // if it has an auto-update model
  Q_FOREACH ( QgsComposerLegend* currentLegend, composerLegends )
  {
    if ( !currentLegend )
    {
      continue;
    }

    if ( currentLegend->autoUpdateModel() || currentLegend->legendFilterByMapEnabled() )
    {
      // the legend has an auto-update model or
      // has to be filter by map
      // we will update it with map's layers
      const QgsComposerMap* map = currentLegend->composerMap();
      if ( !map )
      {
        continue;
      }

      // get model and layer tree root of the legend
      QgsLegendModelV2* model = currentLegend->modelV2();
      QgsLayerTreeGroup* root = model->rootGroup();


      // get layerIds find in the layer tree root
      QStringList layerIds = root->findLayerIds();
      // get map layerIds
      QStringList layerSet = map->layerSet();

      // get map scale
      double scale = map->scale();

      // Q_FOREACH layer find in the layer tree
      // remove it if the layer id is not in map layerIds
      Q_FOREACH ( const QString& layerId, layerIds )
      {
        QgsLayerTreeLayer* nodeLayer = root->findLayer( layerId );
        if ( !nodeLayer )
        {
          continue;
        }
        if ( !layerSet.contains( layerId ) )
        {
          qobject_cast<QgsLayerTreeGroup*>( nodeLayer->parent() )->removeChildNode( nodeLayer );
        }
        else
        {
          QgsMapLayer* layer = nodeLayer->layer();
          if ( layer->hasScaleBasedVisibility() )
          {
            if ( layer->minimumScale() > scale )
              qobject_cast<QgsLayerTreeGroup*>( nodeLayer->parent() )->removeChildNode( nodeLayer );
            else if ( layer->maximumScale() < scale )
              qobject_cast<QgsLayerTreeGroup*>( nodeLayer->parent() )->removeChildNode( nodeLayer );
          }
        }
      }
      root->removeChildrenGroupWithoutLayers();
    }
  }
Esempio n. 19
0
PickKnobDialog::PickKnobDialog(DockablePanel* panel,
                               QWidget* parent)
    : QDialog(parent)
    , _imp( new PickKnobDialogPrivate(panel) )
{
    NodeSettingsPanel* nodePanel = dynamic_cast<NodeSettingsPanel*>(panel);

    assert(nodePanel);
    if (!nodePanel) {
        throw std::logic_error("PickKnobDialog::PickKnobDialog()");
    }
    NodeGuiPtr nodeGui = nodePanel->getNode();
    NodePtr node = nodeGui->getNode();
    NodeGroup* isGroup = node->isEffectGroup();
    boost::shared_ptr<NodeCollection> collec = node->getGroup();
    NodeGroup* isCollecGroup = dynamic_cast<NodeGroup*>( collec.get() );
    NodesList collectNodes = collec->getNodes();
    for (NodesList::iterator it = collectNodes.begin(); it != collectNodes.end(); ++it) {
        if ( !(*it)->getParentMultiInstance() && (*it)->isActivated() && ( (*it)->getKnobs().size() > 0 ) ) {
            _imp->allNodes.push_back(*it);
        }
    }
    if (isCollecGroup) {
        _imp->allNodes.push_back( isCollecGroup->getNode() );
    }
    if (isGroup) {
        NodesList groupnodes = isGroup->getNodes();
        for (NodesList::iterator it = groupnodes.begin(); it != groupnodes.end(); ++it) {
            if ( !(*it)->getParentMultiInstance() && (*it)->isActivated() && ( (*it)->getKnobs().size() > 0 ) ) {
                _imp->allNodes.push_back(*it);
            }
        }
    }
    QStringList nodeNames;
    for (NodesList::iterator it = _imp->allNodes.begin(); it != _imp->allNodes.end(); ++it) {
        QString name = QString::fromUtf8( (*it)->getLabel().c_str() );
        nodeNames.push_back(name);
    }
    nodeNames.sort();

    _imp->mainLayout = new QGridLayout(this);
    _imp->selectNodeLabel = new Label( tr("Node:") );
    _imp->nodeSelectionCombo = new CompleterLineEdit(nodeNames, nodeNames, false, this);
    _imp->nodeSelectionCombo->setToolTip( GuiUtils::convertFromPlainText(tr("Input the name of a node in the current project."), Qt::WhiteSpaceNormal) );
    _imp->nodeSelectionCombo->setFocus(Qt::PopupFocusReason);

    _imp->knobSelectionCombo = new ComboBox(this);
    QObject::connect( _imp->knobSelectionCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(onKnobComboIndexChanged(int)) );
    QString useAliasTt = GuiUtils::convertFromPlainText(tr("If checked, an alias of the selected parameter will be created, coyping entirely its state. "
                                                           "Only the script-name, label and tooltip will be editable.\n"
                                                           "For choice parameters this will also "
                                                           "dynamically refresh the menu entries when the original parameter's menu is changed.\n"
                                                           "When unchecked, a simple expression will be set linking the two parameters, but things such as dynamic menus "
                                                           "will be disabled."), Qt::WhiteSpaceNormal);
    _imp->useAliasLabel = new Label(tr("Make Alias:"), this);
    _imp->useAliasLabel->setToolTip(useAliasTt);
    _imp->useAliasCheckBox = new QCheckBox(this);
    _imp->useAliasCheckBox->setToolTip(useAliasTt);
    _imp->useAliasCheckBox->setChecked(true);

    QObject::connect( _imp->nodeSelectionCombo, SIGNAL(itemCompletionChosen()), this, SLOT(onNodeComboEditingFinished()) );

    _imp->destPageLabel = new Label(tr("Page:"), this);
    QString pagett = GuiUtils::convertFromPlainText(tr("Select the page into which the parameter will be created."), Qt::WhiteSpaceNormal);
    _imp->destPageLabel->setToolTip(pagett);
    _imp->destPageCombo = new ComboBox(this);
    _imp->destPageCombo->setToolTip(pagett);
    QObject::connect( _imp->destPageCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(onPageComboIndexChanged(int)) );
    const KnobsVec& knobs = node->getKnobs();
    for (std::size_t i = 0; i < knobs.size(); ++i) {
        if ( knobs[i]->isUserKnob() ) {
            boost::shared_ptr<KnobPage> isPage = boost::dynamic_pointer_cast<KnobPage>(knobs[i]);
            if (isPage) {
                _imp->pages.push_back(isPage);
                _imp->destPageCombo->addItem( QString::fromUtf8( isPage->getName().c_str() ) );
            } else {
                boost::shared_ptr<KnobGroup> isGrp = boost::dynamic_pointer_cast<KnobGroup>(knobs[i]);
                if (isGrp) {
                    _imp->groups.push_back(isGrp);
                }
            }
        }
    }
    if (_imp->destPageCombo->count() == 0) {
        _imp->destPageLabel->hide();
        _imp->destPageCombo->hide();
    }


    _imp->groupLabel = new Label(tr("Group:"), this);
    QString grouptt = GuiUtils::convertFromPlainText(tr("Select the group into which the parameter will be created."), Qt::WhiteSpaceNormal);
    _imp->groupCombo = new ComboBox(this);
    _imp->groupLabel->setToolTip(grouptt);
    _imp->groupCombo->setToolTip(grouptt);
    onPageComboIndexChanged(0);

    _imp->buttons = new QDialogButtonBox(QDialogButtonBox::StandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel),
                                         Qt::Horizontal, this);
    QObject::connect( _imp->buttons, SIGNAL(accepted()), this, SLOT(accept()) );
    QObject::connect( _imp->buttons, SIGNAL(rejected()), this, SLOT(reject()) );

    _imp->mainLayout->addWidget(_imp->selectNodeLabel, 0, 0, 1, 1);
    _imp->mainLayout->addWidget(_imp->nodeSelectionCombo, 0, 1, 1, 1);
    _imp->mainLayout->addWidget(_imp->knobSelectionCombo, 0, 2, 1, 1);
    _imp->mainLayout->addWidget(_imp->useAliasLabel, 1, 0, 1, 1);
    _imp->mainLayout->addWidget(_imp->useAliasCheckBox, 1, 1, 1, 1);
    _imp->mainLayout->addWidget(_imp->destPageLabel, 2, 0, 1, 1);
    _imp->mainLayout->addWidget(_imp->destPageCombo, 2, 1, 1, 1);
    _imp->mainLayout->addWidget(_imp->groupLabel, 2, 2, 1, 1);
    _imp->mainLayout->addWidget(_imp->groupCombo, 2, 3, 1, 1);
    _imp->mainLayout->addWidget(_imp->buttons, 3, 0, 1, 3);

    QTimer::singleShot( 25, _imp->nodeSelectionCombo, SLOT(showCompleter()) );
}
Save_grid_dialog::Save_grid_dialog( const GsTL_project* project,
				    QWidget * parent, const char * name) 
  : QFileDialog( parent ) {

  if (name)
    setObjectName(name);
  
  setModal(true);
  setFileMode( QFileDialog::AnyFile );
  setLabelText(QFileDialog::Accept, "Save");

  QGridLayout * lo = dynamic_cast<QGridLayout*>(this->layout());
  
  grid_selector_ = new QComboBox( this);
  QLabel* label = new QLabel( "Grid to save", this );
  lo->addWidget(label, 4,0,Qt::AlignLeft);
  lo->addWidget(grid_selector_,4,1,Qt::AlignLeft);



  //TL modified
  propList_ = new QListWidget( this);
  propList_->setSelectionMode(QAbstractItemView::ExtendedSelection);
  QLabel* plabel = new QLabel( "Properties to save", this );
  lo->addWidget(plabel, 5,0,Qt::AlignLeft);
  lo->addWidget(propList_,5,1,Qt::AlignLeft);


  //TL + AB modified
  masked_as_regular_frame_ = new QFrame(this);
  saveRegular_ = new QCheckBox(masked_as_regular_frame_);
  //saveRegular_->setDisabled(true);
  QLabel* slabel = new QLabel( "Save masked grid as Cartesian", masked_as_regular_frame_ );
  QHBoxLayout* mgrid_to_cgrid_layout = new QHBoxLayout(masked_as_regular_frame_);
  mgrid_to_cgrid_layout->addWidget(slabel);
  mgrid_to_cgrid_layout->addWidget(saveRegular_);
  masked_as_regular_frame_->setLayout(mgrid_to_cgrid_layout);
  lo->addWidget(masked_as_regular_frame_,6,1,Qt::AlignLeft);
  masked_as_regular_frame_->setVisible(false);

 // lo->addWidget(slabel, 6,0,Qt::AlignLeft);
 // lo->addWidget(saveRegular_,6,1,Qt::AlignLeft);
  
  // search for available output filters

  QStringList filters;
  SmartPtr<Named_interface> ni_filter = 
    Root::instance()->interface( outfilters_manager );
  Manager* dir = dynamic_cast<Manager*>( ni_filter.raw_ptr() );
  appli_assert( dir );

  Manager::type_iterator begin = dir->begin();
  Manager::type_iterator end = dir->end();
  for( ; begin != end ; ++begin ) {
    SmartPtr<Output_filter> outf(dynamic_cast<Output_filter*>(dir->new_interface(*begin).raw_ptr() ));
    if( outf->type_data() != "Grid") continue;
    QString filt( begin->c_str() );
    filt += " (*.*)";
    filters.push_back( filt ) ;
  }

  setFilters( filters );

  
  // search for available grids

  const GsTL_project::String_list& grids = project->objects_list();
  typedef GsTL_project::String_list::const_iterator const_iterator;
  for( const_iterator it = grids.begin(); it != grids.end(); ++it ) {
    grid_selector_->addItem( it->c_str() );
  }

  QObject::connect( grid_selector_, SIGNAL( activated(const QString &) ),
	  this, SLOT( gridChanged(const QString &) ) );

  if (!grid_selector_->currentText().isEmpty())
	gridChanged(grid_selector_->currentText());
}
Esempio n. 21
0
void QgsSearchQueryBuilder::loadQuery()
{
  QSettings s;
  QString lastQueryFileDir = s.value( "/UI/lastQueryFileDir", "" ).toString();

  QString queryFileName = QFileDialog::getOpenFileName( 0, tr( "Load query from file" ), lastQueryFileDir, tr( "Query files" ) + "(*.qqf);;" + tr( "All files" ) + "(*)" );
  if ( queryFileName.isNull() )
  {
    return;
  }

  QFile queryFile( queryFileName );
  if ( !queryFile.open( QIODevice::ReadOnly ) )
  {
    QMessageBox::critical( 0, tr( "Error" ), tr( "Could not open file for reading" ) );
    return;
  }
  QDomDocument queryDoc;
  if ( !queryDoc.setContent( &queryFile ) )
  {
    QMessageBox::critical( 0, tr( "Error" ), tr( "File is not a valid xml document" ) );
    return;
  }

  QDomElement queryElem = queryDoc.firstChildElement( "Query" );
  if ( queryElem.isNull() )
  {
    QMessageBox::critical( 0, tr( "Error" ), tr( "File is not a valid query document" ) );
    return;
  }

  QString query = queryElem.text();

  //todo: test if all the attributes are valid
  QgsSearchString search;
  if ( !search.setString( query ) )
  {
    QMessageBox::critical( this, tr( "Search string parsing error" ), search.parserErrorMsg() );
    return;
  }

  QgsSearchTreeNode* searchTree = search.tree();
  if ( !searchTree )
  {
    QMessageBox::critical( this, tr( "Error creating search tree" ), search.parserErrorMsg() );
    return;
  }

  QStringList attributes = searchTree->referencedColumns();
  QMap< QString, QString> attributesToReplace;
  QStringList existingAttributes;

  //get all existing fields
  QMap<QString, int>::const_iterator fieldIt = mFieldMap.constBegin();
  for ( ; fieldIt != mFieldMap.constEnd(); ++fieldIt )
  {
    existingAttributes.push_back( fieldIt.key() );
  }

  //if a field does not exist, ask what field should be used instead
  QStringList::const_iterator attIt = attributes.constBegin();
  for ( ; attIt != attributes.constEnd(); ++attIt )
  {
    //test if attribute is there
    if ( !mFieldMap.contains( *attIt ) )
    {
      bool ok;
      QString replaceAttribute = QInputDialog::getItem( 0, tr( "Select attribute" ), tr( "There is no attribute '%1' in the current vector layer. Please select an existing attribute" ).arg( *attIt ),
                                 existingAttributes, 0, false, &ok );
      if ( !ok || replaceAttribute.isEmpty() )
      {
        return;
      }
      attributesToReplace.insert( *attIt, replaceAttribute );
    }
  }

  //Now replace all the string in the query
  QList<QgsSearchTreeNode*> columnRefList = searchTree->columnRefNodes();
  QList<QgsSearchTreeNode*>::iterator columnIt = columnRefList.begin();
  for ( ; columnIt != columnRefList.end(); ++columnIt )
  {
    QMap< QString, QString>::const_iterator replaceIt = attributesToReplace.find(( *columnIt )->columnRef() );
    if ( replaceIt != attributesToReplace.constEnd() )
    {
      ( *columnIt )->setColumnRef( replaceIt.value() );
    }
  }

  txtSQL->clear();
  QString newQueryText = query;
  if ( attributesToReplace.size() > 0 )
  {
    newQueryText = searchTree->makeSearchString();
  }
  txtSQL->insertPlainText( newQueryText );
}
Esempio n. 22
0
QString Kleo::printableClassification( unsigned int classification ) {
    QStringList parts;
    if ( classification & CMS )
        parts.push_back( "CMS" );
    if ( classification & OpenPGP )
        parts.push_back( "OpenPGP" );
    if ( classification & Binary )
        parts.push_back( "Binary" );
    if ( classification & Ascii )
        parts.push_back( "Ascii" );
    if ( classification & DetachedSignature )
        parts.push_back( "DetachedSignature" );
    if ( classification & OpaqueSignature )
        parts.push_back( "OpaqueSignature" );
    if ( classification & ClearsignedMessage )
        parts.push_back( "ClearsignedMessage" );
    if ( classification & CipherText )
        parts.push_back( "CipherText" );
    if ( classification & Certificate )
        parts.push_back( "Certificate" );
    if ( classification & ExportedPSM )
        parts.push_back( "ExportedPSM" );
    if ( classification & CertificateRequest )
        parts.push_back( "CertificateRequest" );
    return parts.join( ", " );
}
Esempio n. 23
0
void HarmonicsInfoForm::
        harmonicsChanged()
{
    rebuilding = 2;

    QStringList header;
    header.push_back("Time");
    header.push_back("Frequency");
    header.push_back("Value here");
    header.push_back("Mode");
    header.push_back("Fundamental frequency");
    header.push_back("Harmonic number");
    header.push_back("Tone name");
    header.push_back("Compliance");

    ui->tableWidget->clear();
    ui->tableWidget->setRowCount(0);
    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableWidget->setColumnCount(header.size());
    ui->tableWidget->setHorizontalHeaderLabels( header );
    ui->tableWidget->verticalHeader()->hide();

    QTableWidgetItem*prototype = new QTableWidgetItem;
    prototype->setFlags( prototype->flags() & ~Qt::ItemIsEditable);
    ui->tableWidget->setItemPrototype( prototype );

    //Tfr::FreqAxis fa = project->tools().render_model.display_scale();
    foreach( const QPointer<TooltipView>& view, harmonicscontroller->views() )
    {
        if (!view)
            continue;

        TooltipModel *model = view->model();

        unsigned row = ui->tableWidget->rowCount();
        ui->tableWidget->insertRow( row );
        setCellInLastRow(0, QString("%1").arg(model->pos_time));
        setCellInLastRow(1, QString("%1").arg(model->pos_hz));
        setCellInLastRow(2, QString("%1").arg(model->max_so_far));
        setCellInLastRow(3, QString("%1").arg(model->automarkingStr().c_str()));
        setCellInLastRow(4, QString("%1").arg(model->pos_hz/model->markers));
        setCellInLastRow(5, QString("%1").arg(model->markers));
        setCellInLastRow(6, QString("%1").arg(model->toneName().c_str()));
        setCellInLastRow(7, QString("%1").arg(model->compliance));

        ui->tableWidget->setUserData(row, new CurrentViewUserData(view));
    }

    static bool once_per_process = true;
    if (once_per_process)
    {
        dock->setVisible( true );
        dock->raise();

        Ui::SaweMainWindow* MainWindow = project->mainWindow();
        if (Qt::NoDockWidgetArea == MainWindow->dockWidgetArea(dock))
        {
            MainWindow->addDockWidget(Qt::BottomDockWidgetArea, dock);
        }

        once_per_process = false;
    }

    rebuilding = 1;

    // Select current row
    unsigned row = 0;
    foreach( const QPointer<TooltipView>& view, harmonicscontroller->views() )
    {
        if (!view)
            continue;

        if (view.data() == harmonicscontroller->current_view())
            ui->tableWidget->selectRow(row);

        ++row;
    }
    rebuilding = 0;
}
// Returns a list of section-names found
QStringList WPDefManager::getSections( WPDEF_TYPE Type )
{
	QStringList SectionList;
	DefSections *ListPointer;
	DefSections::iterator MyIter;

	switch( Type )
	{
	case WPDT_ITEM:
		ListPointer = &Items;
		break;
	
	case WPDT_SCRIPT:
		ListPointer = &Scripts;
		break;

	case WPDT_NPC:
		ListPointer = &NPCs;
		break;

	case WPDT_MENU:
		ListPointer = &Menus;
		break;

	case WPDT_SPELL:
		ListPointer = &Spells;
		break;

	case WPDT_LIST:
		ListPointer = &StringLists;
		break;

	case WPDT_PRIVLEVEL:
		ListPointer = &PrivLevels;
		break;

	case WPDT_SPAWNREGION:
		ListPointer = &SpawnRegions;
		break;

	case WPDT_REGION:
		ListPointer = &Regions;
		break;

	case WPDT_MULTI:
		ListPointer = &Multis;
		break;

	case WPDT_TEXT:
		ListPointer = &Texts;
		break;

	default:
		// Return an empty list
		return SectionList;
	};

	for( MyIter = ListPointer->begin(); MyIter != ListPointer->end(); ++MyIter )
	{
		SectionList.push_back( MyIter.key() );
	}

	return SectionList;
}
void tst_QWidget_window::tst_dnd()
{
    QStringList log;
    DnDEventLoggerWidget dndTestWidget(&log);

    dndTestWidget.setObjectName(QLatin1String("dndTestWidget"));
    dndTestWidget.setWindowTitle(dndTestWidget.objectName());
    dndTestWidget.resize(200, 300);

    QWidget *dropsRefusingWidget1 = new DnDEventLoggerWidget(&log, &dndTestWidget);
    dropsRefusingWidget1->setObjectName(QLatin1String("dropsRefusingWidget1"));
    dropsRefusingWidget1->resize(180, 80);
    dropsRefusingWidget1->move(10, 10);

    QWidget *dropsAcceptingWidget1 = new DnDEventLoggerWidget(&log, &dndTestWidget);
    dropsAcceptingWidget1->setAcceptDrops(true);
    dropsAcceptingWidget1->setObjectName(QLatin1String("acceptingDropsWidget1"));
    dropsAcceptingWidget1->resize(180, 80);
    dropsAcceptingWidget1->move(10, 110);

    // Create a native widget on top of dropsAcceptingWidget1 to check QTBUG-27336
    QWidget *nativeWidget = new QWidget(dropsAcceptingWidget1);
    nativeWidget->resize(160, 60);
    nativeWidget->move(10, 10);
    nativeWidget->winId();

    QWidget *dropsAcceptingWidget2 = new DnDEventLoggerWidget(&log, &dndTestWidget);
    dropsAcceptingWidget2->setAcceptDrops(true);
    dropsAcceptingWidget2->setObjectName(QLatin1String("acceptingDropsWidget2"));
    dropsAcceptingWidget2->resize(180, 80);
    dropsAcceptingWidget2->move(10, 210);

    QWidget *dropsRefusingWidget2 = new DnDEventLoggerWidget(&log, dropsAcceptingWidget2);
    dropsRefusingWidget2->setObjectName(QLatin1String("dropsRefusingDropsWidget2"));
    dropsRefusingWidget2->resize(160, 60);
    dropsRefusingWidget2->move(10, 10);

    dndTestWidget.show();
    qApp->setActiveWindow(&dndTestWidget);
    QVERIFY(QTest::qWaitForWindowActive(&dndTestWidget));

    QMimeData mimeData;
    mimeData.setText(QLatin1String("testmimetext"));

    // Simulate DnD events on the QWidgetWindow.
    QPoint position = QPoint(11, 1);
    QDragEnterEvent e(position, Qt::CopyAction, &mimeData, Qt::LeftButton, Qt::NoModifier);
    QWindow *window = dndTestWidget.windowHandle();
    qApp->sendEvent(window, &e);
    log.push_back(msgEventAccepted(e));
    while (true) {
        position.ry() += 20;
        if (position.y() >= 250) {
            QDropEvent e(position, Qt::CopyAction, &mimeData, Qt::LeftButton, Qt::NoModifier);
            qApp->sendEvent(window, &e);
            log.push_back(msgEventAccepted(e));
            break;
        } else {
            QDragMoveEvent e(position, Qt::CopyAction, &mimeData, Qt::LeftButton, Qt::NoModifier);
            qApp->sendEvent(window, &e);
            log.push_back(msgEventAccepted(e));
        }
    }

    window = nativeWidget->windowHandle();
    QDragEnterEvent enterEvent(QPoint(0, 0), Qt::CopyAction, &mimeData, Qt::LeftButton, Qt::NoModifier);
    qApp->sendEvent(window, &enterEvent);
    log.push_back(msgEventAccepted(enterEvent));

    QDragMoveEvent moveEvent(QPoint(1, 1), Qt::CopyAction, &mimeData, Qt::LeftButton, Qt::NoModifier);
    qApp->sendEvent(window, &moveEvent);
    log.push_back(msgEventAccepted(moveEvent));

    QDropEvent dropEvent(QPoint(2, 2), Qt::CopyAction, &mimeData, Qt::LeftButton, Qt::NoModifier);
    qApp->sendEvent(window, &dropEvent);
    log.push_back(msgEventAccepted(dropEvent));

    // Compare logs.
    QStringList expectedLog;
    const int expectedLogSize = int(sizeof(expectedLogC) / sizeof(expectedLogC[0]));
    const QString mimeDataAddress = QString::number(quintptr(&mimeData));
    const QString mimeDataAddressPlaceHolder = QLatin1String("MIME_DATA_ADDRESS");
    for (int i= 0; i < expectedLogSize; ++i)
        expectedLog.push_back(QString::fromLatin1(expectedLogC[i]).replace(mimeDataAddressPlaceHolder, mimeDataAddress));

    QCOMPARE(log, expectedLog);
}
Esempio n. 26
0
void
MultiplayerDialog::buildPlayersList()
{
	boost::intrusive_ptr< Core::LandscapeModel::IModelLocker >
		locker = m_environment.lockModel();

	boost::intrusive_ptr< Core::LandscapeModel::ILandscape >
		landscape = locker->getLandscapeModel()->getLandscape();

	// Races

	Core::LandscapeModel::IStaticData::RacesCollection reces;
	m_environment.fetchRaces( reces );

	QStringList races;

	Core::LandscapeModel::IStaticData::RacesCollectionIterator
			beginRaces = reces.begin()
		,	endRaces = reces.end();

	for ( ; beginRaces != endRaces; ++beginRaces )
		races.push_back( beginRaces->first );

	// List

	Core::LandscapeModel::ILandscapeModel::PlayersCollection players;
	locker->getLandscapeModel()->fetchPlayers( players );

	Core::LandscapeModel::ILandscapeModel::PlayersCollectionIterator
			begin = players.begin()
		,	end = players.end();

	for ( ; begin != end; ++begin )
	{
		QHBoxLayout* playerLayout = new QHBoxLayout();

		QString palyerLabelText
			= QString( Resources::Views::PlayerByStartPointLabelFormat )
				.arg( ( *begin )->getStartPointId() )
				.arg( ( *begin )->getName() );

		QLabel* playerLabel = new QLabel( palyerLabelText );

		playerLayout->addWidget( playerLabel );

		QComboBox* playerComboBox = new QComboBox();
		playerComboBox->addItems( m_nonePlayerTypes );

		playerComboBox->setCurrentText( Core::LandscapeModel::PlayerType::toString( ( *begin )->getType() ) );

		QObject::connect( playerComboBox, SIGNAL( currentIndexChanged( int ) ), this, SLOT( onPlayerTypeChanged() ) );

		playerLayout->addWidget( playerComboBox );
		playerLayout->addWidget( new QLabel( Resources::Views::RaceLabel ) );

		QComboBox* raceComboBox = new QComboBox();
		raceComboBox->addItems( races );

		raceComboBox->setCurrentText( ( *begin )->getRace() );

		QObject::connect( raceComboBox, SIGNAL( currentIndexChanged( int ) ), this, SLOT( onPlayerRaceChanged() ) );

		playerLayout->addWidget( raceComboBox );
		playerLayout->addWidget( new QLabel( Resources::Views::ColorLabel ) );

		QComboBox* colorsComboBox = new QComboBox();

		playerLayout->addWidget( colorsComboBox );

		m_playersLayout->addLayout( playerLayout );

		m_playersData.insert(
			std::make_pair(
					( *begin )->getUniqueId()
				,	PlayerData( *playerLabel, *playerComboBox, *raceComboBox, *colorsComboBox, ( *begin )->getUniqueId() ) ) );
	}

	updatePlayersColors();

} // MultiplayerDialog::buildPlayersList
Esempio n. 27
0
void qBicWin::sort()
{
    QList<QStringList>* sortedVals = new QList<QStringList>();
    QStringList list = m_bic.split("|");
    QStringList rows = list[0].split(QRegExp("\\s+"));
    rows.removeAll("");
    QStringList cols = list[1].split(QRegExp("\\s+"));
    cols.removeAll("");
    QVector<int> iRows;
    QVector<int> iCols;
    for(int i=rows.size()-1;i>=0;i--)
    {
        sortedVals->push_front((*m_plValues)[rows.at(i).toInt()]);
        iRows.push_back(rows[i].toInt());
    }
    for(int i=0; i< cols.size(); i++)
    {
        iCols.push_back(cols[i].toInt());
    }
    for(int i=0;i<rowC;i++)
    {
        if(!iRows.contains(i))
            sortedVals->push_back((*m_plValues)[i]);
        QStringList temp;
        for(int j=iCols.size()-1; j>=0; j--)
        {
            temp.push_front((*sortedVals)[i].at(iCols[j]));
        }
        for(int j=0;j<colC;j++)
        {
            if(!iCols.contains(j))
                temp.push_back((*sortedVals)[i].at(j));
        }
        (*sortedVals)[i] = temp;
    }
    for(int nV =0;nV<sortedVals->size();nV++)
    {
        QStringList row = (*sortedVals)[nV];
        for(int nC = 0; nC<row.size();nC++)
        {
            QString value = row.at(nC);
            double val = value.toDouble();
           // qDebug() << val;
            colorMap->data()->setCell(nC, nV, value.toDouble());
        }
    }
    colorMap->rescaleDataRange(true);

    QVector<double> x_1;
    QVector<double> x_2;
    x_1.append(0);
    x_1.append(iRows.size());
    x_1.append(iRows.size());
    x_1.append(0);
    x_1.append(0);

    x_2.append(0);
    x_2.append(0);
    x_2.append(iCols.size());
    x_2.append(iCols.size());
    x_2.append(0);

    curve->setPen(QPen(Qt::white));
  //  curve->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssDisc, 5));

    curve->setData(x_2,x_1);


    plot->replot();
}
//--------------------------------------------------------------------------------------------------
/// 
//--------------------------------------------------------------------------------------------------
QList<caf::PdmOptionItemInfo> RimEclipseResultDefinition::calculateValueOptionsForSpecifiedDerivedListPosition(bool showDerivedResultsFirstInList, const caf::PdmFieldHandle* fieldNeedingOptions, bool * useOptionsOnly)
{
    if (fieldNeedingOptions == &m_resultVariableUiField)
    {
        if (this->currentGridCellResults())
        {
            QList<caf::PdmOptionItemInfo> optionList;
  
            QStringList cellCenterResultNames;
            QStringList cellFaceResultNames;
    
            foreach(QString s, getResultVariableListForCurrentUIFieldSettings())
            {
                if (RimDefines::isPerCellFaceResult(s))
                {
                    cellFaceResultNames.push_back(s);
                }
                else
                {
                    cellCenterResultNames.push_back(s);
                }
            }

            cellCenterResultNames.sort();
            cellFaceResultNames.sort();

            // Cell Center result names
            foreach(QString s, cellCenterResultNames)
            {
                optionList.push_back(caf::PdmOptionItemInfo(s, s));
            }

            // Ternary Result
            bool hasAtLeastOneTernaryComponent = false;
            if (cellCenterResultNames.contains("SOIL")) hasAtLeastOneTernaryComponent = true;
            else if (cellCenterResultNames.contains("SGAS")) hasAtLeastOneTernaryComponent = true;
            else if (cellCenterResultNames.contains("SWAT")) hasAtLeastOneTernaryComponent = true;

            if (m_resultTypeUiField == RimDefines::DYNAMIC_NATIVE && hasAtLeastOneTernaryComponent)
            {
                optionList.push_front(caf::PdmOptionItemInfo(RimDefines::ternarySaturationResultName(), RimDefines::ternarySaturationResultName()));
            }

            // Cell Face result names
            foreach(QString s, cellFaceResultNames)
            {
                if (showDerivedResultsFirstInList)
                {
                    optionList.push_front(caf::PdmOptionItemInfo(s, s));
                }
                else
                {
                    optionList.push_back(caf::PdmOptionItemInfo(s, s));
                }
            }

            optionList.push_front(caf::PdmOptionItemInfo(RimDefines::undefinedResultName(), RimDefines::undefinedResultName()));

            if (useOptionsOnly) *useOptionsOnly = true;

            return optionList;
        }
Esempio n. 29
0
bool ProjectFile::open(const QString &fileName)
{
    QFile file(fileName);
    file.open(QIODevice::ReadWrite | QIODevice::Text);
    if (!file.isOpen())
        return false;
    QStringList list;
    QString line;
    bool bnext = false;
    while (!file.atEnd()) {
        QByteArray ar = file.readLine().trimmed();
        if (!ar.isEmpty() && ar.right(1) == "\\") {
            bnext = true;
            ar[ar.length()-1] = ' ';
        } else {
            bnext = false;
        }
        line.push_back(ar);
        if (!bnext && !line.isEmpty()) {
            list.push_back(line);
            line.clear();
        }
    }
    file.close();

    if (!line.isEmpty()) {
        list.push_back(line);
    }
    _filePath = fileName;
    _isMakefile = QFileInfo(fileName).suffix().toLower() != "pro";

    context.clear();
    foreach (QString line, list) {
        if (line.size() >= 1 && line.at(0) == '#')
            continue;
        QStringList v = line.split(QRegExp("\\+="),QString::SkipEmptyParts);
        if (v.count() == 1) {
            v = line.split(QRegExp("="),QString::SkipEmptyParts);
            if (v.count() == 2) {
                QStringList v2 = v.at(1).split(" ",QString::SkipEmptyParts);
                if (!v2.isEmpty()) {
                    context[v.at(0).trimmed()] = v2;
                }
            }
        } else if (v.count() == 2) {
            QStringList v2 = v.at(1).split(" ",QString::SkipEmptyParts);
            if (!v2.isEmpty())
                context[v.at(0).trimmed()].append(v2);
        }
    }
    return !context.isEmpty();
    /*
    QString all = file.readAll();
    all.replace(QRegExp("\\\\[\\s]*[\n\r]+[\\s]*")," ");
    QStringList list = all.split(QRegExp("[\r\n]"),QString::SkipEmptyParts);
    context.clear();
    foreach(QString line, list) {
         line.replace("\t"," ");
        QStringList v = line.split(QRegExp("\\+="),QString::SkipEmptyParts);
        if (v.count() == 1) {
            v = line.split(QRegExp("="),QString::SkipEmptyParts);
            if (v.count() == 2) {
                QStringList v2 = v.at(1).split(" ",QString::SkipEmptyParts);
                if (!v2.isEmpty()) {
                    context[v.at(0).trimmed()] = v2;
                }
            }
        } else if (v.count() == 2) {
            QStringList v2 = v.at(1).split(" ",QString::SkipEmptyParts);
            if (!v2.isEmpty())
                context[v.at(0).trimmed()].append(v2);
        }
    }
    file.close();
    _filePath = fileName;
    return !context.isEmpty();
    */
}
Esempio n. 30
0
//接受通信软件返回回来的数据.
void comm_param_settings::set_ack_comm_cfg_param(PG_RTUI_Base* data)
{
    switch(data->type)
    {
    case ePG_RTUI_ack_getinterfacenum:  //通信节点参数管理返回得到的结构.
    {
        flagSendGetInterface = false;
        PG_RTUI_Ack_GetInterfaceNum *paraInfo = (PG_RTUI_Ack_GetInterfaceNum*)(data);
        ui->comboBox->clear();
        //向comboBox添加数据.
        int num = paraInfo->interfaceNum;
        QStringList test;
        for(int i=0;i<num;i++)
        {
            test.push_back(QString::number(i, 10));
        }
        flagSendGetInterface = true;
        ui->comboBox->addItems(test);
        ui->comboBox->setCurrentIndex(0);//设置当前的索引.
        delete paraInfo;
        break;
    }

    case ePG_RTUI_ack_getlink:   //通信链路参数管理返回得到的结构.
    {
        PG_RTUI_Ack_GetLink *linkInfo =(PG_RTUI_Ack_GetLink *)(data);
        ui->lineEdit_5->setText(QString::number(linkInfo->nodeSrcId, 10));
        ui->lineEdit_6->setText(QString::number(linkInfo->nodeDstId, 10));
        ui->lineEdit_7->setText(QString::number(linkInfo->switchNum, 10));
        ui->lineEdit_8->setText(QString::number(linkInfo->connectorNum, 10));

        ui->lineEdit_9->setText(QString::number(linkInfo->switchLoss));
        ui->lineEdit_10->setText(QString::number(linkInfo->connectorLoss));
        ui->lineEdit_11->setText(QString::number(linkInfo->lossCoefficient));
        double ber = linkInfo->ber;
        if(-0.0000001<ber && ber<0.0000001)
            ber=0;
        ui->lineEdit_12->setText(QString::number(ber));
        delete linkInfo;
        break;
    }

    case ePG_RTUI_ack_getinterface:   //通信参数管理,端口选择后返回.
    {
        PG_RTUI_Ack_GetInterface *paraInfo = (PG_RTUI_Ack_GetInterface*)(data);
        ui->lineEdit->setText(QString::number(paraInfo->nodeId,10));
        ui->lineEdit_2->setText(QString::number(paraInfo->bandwidth,10));
        double txPower = paraInfo->txPower;
        if(-0.0000001<txPower && txPower<0.0000001)
            txPower=0;
        ui->lineEdit_3->setText(QString::number(txPower));
        double rxSensitivity = paraInfo->rxSensitivity;
        if(-0.0000001<rxSensitivity && rxSensitivity<0.0000001)
            rxSensitivity=0;
        ui->lineEdit_4->setText(QString::number(rxSensitivity));
        ui->lineEdit_21->setText(paraInfo->mode?"1":"0");
        delete paraInfo;
        break;
    }

    }
}