int LAPlatformManager::Load(const QString& aDirectory,
                            const bool&    aKeepPlatforms)
{
  LALogger::TraceBeginMethod(LA_DEBUG_STATIC_ARGS);

  /* Returned value */
  int numberOfPlatforms = 0;

  /* Create singleton if needed */
  LAPlatformManager::checkSingleton();

  /* Factories to insert */
  LAPlatformList insertedPlatforms;

  QDir             platformsDirectory(aDirectory);
  QString          fullPath = "";
 	LAPlatform*      platform = NULL;

  LALogger::Trace(LALogger::DEBUG,
                  LALogger::MAIN,
                  "LAPlatformManager::Load: Path = " + aDirectory,
                  LA_DEBUG_STATIC_ARGS);

  if (!(platformsDirectory.exists()))
    {
      qWarning() << "LAPlatformManager::Load: Failed to load platforms from" << aDirectory << "- Directory does not exist";
      numberOfPlatforms = -1;
    }

  /*! Filter directories and order them */
  platformsDirectory.setFilter(QDir::Dirs);
	platformsDirectory.setSorting(QDir::Name);
  QStringList platformList = platformsDirectory.entryList();

	if (-1 != numberOfPlatforms &&
       0 >= platformList.count())
		{
			qWarning() << "LAPlatformManager::Load: No platform to load from" << aDirectory;
			numberOfPlatforms = -1;
		}
  else
    {

      /* For all directories, load the platform (if no file is in the directory, it will be ignored */
      for (QStringList::Iterator platformDirectory = platformList.begin(); platformList.end() != platformDirectory; platformDirectory++)
        {

          /* Do not consider dot directories */
          if (!(*platformDirectory).startsWith("."))
            {

              LALogger::Trace(LALogger::DEBUG,
                              LALogger::MAIN,
                              "LAPlatformManager::Load: Processing " + *platformDirectory,
                              LA_DEBUG_STATIC_ARGS);

              platform = new LAPlatform(aDirectory + *platformDirectory);
              /* Load factory */
              if (-1 == platform->Load())
                {
                  delete platform;
                  platform = NULL;
                }
              else
                {
                  /* If factory is successfully loaded, add it to list */
                  insertedPlatforms.insert(platform->getName(), platform);
                  numberOfPlatforms++;
                }

            }

        }

    }

  /* If platform list to insert is not empty */
  if (0 < insertedPlatforms.count())
    {
      /* If old platforms are to be erased before */
      if (false == aKeepPlatforms)
        {
          LALogger::Trace(LALogger::DEBUG,
                          LALogger::MAIN,
                          "LAPlatformManager::Load: Erasing old platforms",
                          LA_DEBUG_STATIC_ARGS);

          /* Put them in the old platforms list */
          _M_ManagerSingleton->m_oldPlatforms += _M_ManagerSingleton->m_platforms;

          /* Clear platforms */
          _M_ManagerSingleton->m_platforms.clear();
        }

      LALogger::Trace(LALogger::DEBUG,
                      LALogger::MAIN,
                      QString("LAPlatformManager::Load: Adding %1 platforms").arg(insertedPlatforms.count()),
                      LA_DEBUG_STATIC_ARGS);

      /* Add newly loaded platforms to current list */
      _M_ManagerSingleton->m_platforms += insertedPlatforms;
    }

  LALogger::Trace(LALogger::DEBUG,
                  LALogger::MAIN,
                  QString("LAPlatformManager::Load: %1  platforms read from ").arg(numberOfPlatforms)
                    + aDirectory,
                  LA_DEBUG_STATIC_ARGS);

  LALogger::TraceEndMethod(LA_DEBUG_STATIC_ARGS);
  return numberOfPlatforms;
}
Example #2
0
void MainWindow::fileSave()
{
    if (! modified) {
        statusBar()->showMessage(tr("No changes to be saved."), 2000);
        return;
    }

    statusBar()->showMessage(tr("Saving changes..."));

    {
        QSettings settings(QLatin1String("Trolltech"));
        settings.beginGroup(QLatin1String("Qt"));
        QFontDatabase db;
        QFont font = db.font(familycombo->currentText(),
                             stylecombo->currentText(),
                             psizecombo->currentText().toInt());

        QStringList actcg, inactcg, discg;
        bool overrideDesktopSettings = (gstylecombo->currentText() != desktopThemeName);
        if (overrideDesktopSettings) {
            int i;
            for (i = 0; i < QColorGroup::NColorRoles; i++)
                actcg << editPalette.color(QPalette::Active,
                                           (QColorGroup::ColorRole) i).name();
            for (i = 0; i < QColorGroup::NColorRoles; i++)
                inactcg << editPalette.color(QPalette::Inactive,
                                             (QColorGroup::ColorRole) i).name();
            for (i = 0; i < QColorGroup::NColorRoles; i++)
                discg << editPalette.color(QPalette::Disabled,
                                           (QColorGroup::ColorRole) i).name();
        }

        settings.setValue(QLatin1String("font"), font.toString());
        settings.setValue(QLatin1String("Palette/active"), actcg);
        settings.setValue(QLatin1String("Palette/inactive"), inactcg);
        settings.setValue(QLatin1String("Palette/disabled"), discg);

        settings.setValue(QLatin1String("fontPath"), fontpaths);
        settings.setValue(QLatin1String("embedFonts"), fontembeddingcheckbox->isChecked());
        settings.setValue(QLatin1String("style"), overrideDesktopSettings ? gstylecombo->currentText() : QString());

        settings.setValue(QLatin1String("doubleClickInterval"), dcispin->value());
        settings.setValue(QLatin1String("cursorFlashTime"), cfispin->value() == 9 ? 0 : cfispin->value() );
        settings.setValue(QLatin1String("wheelScrollLines"), wslspin->value());
        settings.setValue(QLatin1String("resolveSymlinks"), resolvelinks->isChecked());

        QSize strut(strutwidth->value(), strutheight->value());
        settings.setValue(QLatin1String("globalStrut/width"), strut.width());
        settings.setValue(QLatin1String("globalStrut/height"), strut.height());

        settings.setValue(QLatin1String("useRtlExtensions"), rtlExtensions->isChecked());

#ifdef Q_WS_X11
        QString style = inputStyle->currentText();
        QString str = QLatin1String("On The Spot");
        if ( style == trUtf8( "Over The Spot" ) )
            str = QLatin1String("Over The Spot");
        else if ( style == trUtf8( "Off The Spot" ) )
            str = QLatin1String("Off The Spot");
        else if ( style == trUtf8( "Root" ) )
            str = QLatin1String("Root");
        settings.setValue( QLatin1String("XIMInputStyle"), str );
#endif
#if defined(Q_WS_X11) && !defined(QT_NO_XIM)
        settings.setValue(QLatin1String("DefaultInputMethod"), inputMethod->currentText());
#endif

        QString audioSink = settings.value(QLatin1String("audiosink"), QLatin1String("Auto")).toString();
        QString videoMode = settings.value(QLatin1String("videomode"), QLatin1String("Auto")).toString();
        settings.setValue(QLatin1String("audiosink"), audiosinkCombo->itemData(audiosinkCombo->currentIndex()));
        settings.setValue(QLatin1String("videomode"), videomodeCombo->itemData(videomodeCombo->currentIndex()));

        QStringList effects;
        if (effectcheckbox->isChecked()) {
            effects << QLatin1String("general");

            switch (menueffect->currentItem()) {
            case 1: effects << QLatin1String("animatemenu"); break;
            case 2: effects << QLatin1String("fademenu"); break;
            }

            switch (comboeffect->currentItem()) {
            case 1: effects << QLatin1String("animatecombo"); break;
            }

            switch (tooltipeffect->currentItem()) {
            case 1: effects << QLatin1String("animatetooltip"); break;
            case 2: effects << QLatin1String("fadetooltip"); break;
            }

            switch ( toolboxeffect->currentItem() ) {
            case 1: effects << QLatin1String("animatetoolbox"); break;
            }
        } else
            effects << QLatin1String("none");
        settings.setValue(QLatin1String("GUIEffects"), effects);

        QStringList familysubs = QFont::substitutions();
        QStringList::Iterator fit = familysubs.begin();
        settings.beginGroup(QLatin1String("Font Substitutions"));
        while (fit != familysubs.end()) {
            QStringList subs = QFont::substitutes(*fit);
            settings.setValue(*fit, subs);
            fit++;
        }
        settings.endGroup(); // Font Substitutions
        settings.endGroup(); // Qt
    }

#if defined(Q_WS_X11)
    qt_x11_apply_settings_in_all_apps();
#endif // Q_WS_X11

    setModified(false);
    statusBar()->showMessage(QLatin1String("Saved changes."));
}
void MakefileHandler::parse( const QString& folder, bool recursive )
{
    //look for either Makefile.am.in, Makefile.am, or Makefile.in, in that order
    AutoTools::ProjectAST* ast;
    int ret = -1;
    QString filePath = folder + "/Makefile.am.in";
    if ( QFile::exists( filePath ) )
        ret = AutoTools::Driver::parseFile( filePath, &ast );
    else
    {
        filePath = folder + "/Makefile.am";
        if ( QFile::exists( filePath ) )
            ret = AutoTools::Driver::parseFile( filePath, &ast );
        else
        {
            filePath = folder + "/Makefile.in";
            if ( QFile::exists( filePath ) )
                ret = AutoTools::Driver::parseFile( filePath, &ast );
            else
                kdDebug(9020) << k_funcinfo << "no appropriate file to parse in "
                              << folder << endl;
        }
    }

    if ( ret != 0 )
    {
        return;
    }

    kdDebug(9020) << k_funcinfo << filePath << " was parsed correctly. Adding information" << endl;
    Q_ASSERT( ast != 0 );
    d->projects[filePath] = ast;
    d->folderToFileMap[folder] = filePath;

    if ( recursive && ast && ast->hasChildren() )
    {
        QValueList<AutoTools::AST*> astChildList = ast->children();
        QValueList<AutoTools::AST*>::iterator it(astChildList.begin()), clEnd(astChildList.end());
        for ( ; it != clEnd; ++it )
        {
            if ( (*it)->nodeType() == AutoTools::AST::AssignmentAST )
            {
                AutoTools::AssignmentAST* assignment = static_cast<AutoTools::AssignmentAST*>( (*it) );
                if ( assignment->scopedID == "SUBDIRS"  )
                {
                    QString list = assignment->values.join( QString::null );
                    list.simplifyWhiteSpace();
                    kdDebug(9020) << k_funcinfo << "subdirs is " << list << endl;
                    QStringList subdirList = QStringList::split( " ",  list );
                    QStringList::iterator vit = subdirList.begin();
                    for ( ; vit != subdirList.end(); ++vit )
                    {
                        QString realDir = ( *vit );
                        if ( realDir.startsWith( "\\" ) )
                            realDir.remove( 0, 1 );

                        realDir = realDir.stripWhiteSpace();
                        if ( realDir != "." && realDir != ".." && !realDir.isEmpty() )
                        {
                            if ( isVariable( realDir ) )
                            {
                                kdDebug(9020) << k_funcinfo << "'" << realDir << "' is a variable" << endl;
                                realDir = resolveVariable( realDir, ast );
                            }

                            kdDebug(9020) << k_funcinfo << "Beginning parsing of '" << realDir << "'" << endl;
                            parse( folder + '/' + realDir, recursive );
                        }
                    }
                }
            }
        }
    }
}
Example #4
0
void SSDP::ProcessData( MSocketDevice *pSocket )
{
    long nBytes = 0;
    long nRead  = 0;

    while ((nBytes = pSocket->bytesAvailable()) > 0)
    {
        QByteArray buffer;
        buffer.resize(nBytes);

        nRead = pSocket->readBlock( buffer.data(), nBytes );

        QHostAddress  peerAddress = pSocket->peerAddress();
        quint16       peerPort    = pSocket->peerPort   ();

        // ------------------------------------------------------------------
        QString     str          = QString(buffer.constData());
        QStringList lines        = str.split("\r\n", QString::SkipEmptyParts);
        QString     sRequestLine = lines.size() ? lines[0] : "";

        lines.pop_front();

        // ------------------------------------------------------------------
        // Parse request Type
        // ------------------------------------------------------------------

        VERBOSE(VB_UPNP+VB_EXTRA,
                QString( "SSDP::ProcessData - requestLine: %1" )
                .arg( sRequestLine ));

        SSDPRequestType eType = ProcessRequestLine( sRequestLine );

        // ------------------------------------------------------------------
        // Read Headers into map
        // ------------------------------------------------------------------

        QStringMap  headers;

        for ( QStringList::Iterator it = lines.begin();
                                    it != lines.end(); ++it ) 
        {
            QString sLine  = *it;
            QString sName  = sLine.section( ':', 0, 0 ).trimmed();
            QString sValue = sLine.section( ':', 1 );

            sValue.truncate( sValue.length() );  //-2

            if ((sName.length() != 0) && (sValue.length() !=0))
                headers.insert( sName.toLower(), sValue.trimmed() );
        }

//        pSocket->SetDestAddress( peerAddress, peerPort );

        // --------------------------------------------------------------
        // See if this is a valid request
        // --------------------------------------------------------------

        switch( eType )
        {
            case SSDP_MSearch    :
                ProcessSearchRequest ( headers, peerAddress, peerPort ); break;
            case SSDP_MSearchResp:
                ProcessSearchResponse( headers                        ); break;
            case SSDP_Notify     :
                ProcessNotify        ( headers                        ); break;
            case SSDP_Unknown:
            default:
                VERBOSE(VB_UPNP, "SSPD::ProcessData - Unknown request Type.");
                break;
        }
    }

}
Example #5
0
OptionsDialog::OptionsDialog(QWidget *parent, const char *name)
  : KDialogBase(IconList, i18n("Configure"), Help|Default|Ok|Apply|Cancel, Ok, parent, name, false, true)
{

  //******** Server ************************************
  serverTab = addPage(i18n("Server"),i18n("DICT Server Configuration"), BarIcon("network", KIcon::SizeMedium ));
  QGridLayout* grid = new QGridLayout(serverTab,10,3,0,spacingHint());

  w_server = new KLineEdit(serverTab);
  w_server->setText(global->server);
  QLabel *l = new QLabel(w_server, i18n("Host&name:"), serverTab);
  grid->addWidget(l,0,0);
  grid->addMultiCellWidget(w_server,0,0,1,2);
  connect( w_server, SIGNAL( textChanged ( const QString & ) ), this, SLOT( slotChanged() ) );

  w_port = new KLineEdit(serverTab);
  w_port->setValidator(new KIntValidator(0,65536,this));
  w_port->setText(QString::number(global->port));
  l = new QLabel(w_port, i18n("&Port:"), serverTab);
  grid->addWidget(l,1,0);
  grid->addWidget(w_port,1,1);
  connect( w_port, SIGNAL( textChanged ( const QString & ) ), this, SLOT( slotChanged() ) );

  w_idleHold = new KIntSpinBox(0,300,5,0,10,serverTab);
  w_idleHold->setSuffix(i18n(" sec"));
  w_idleHold->setValue(global->idleHold);
  l = new QLabel(w_idleHold, i18n("Hold conn&ection for:"), serverTab);
  grid->addWidget(l,2,0);
  grid->addWidget(w_idleHold,2,1);
  connect( w_idleHold, SIGNAL( valueChanged(int) ), this, SLOT( slotChanged() ) );

  w_timeout = new KIntSpinBox(5,600,5,5,10,serverTab);
  w_timeout->setSuffix(i18n(" sec"));
  w_timeout->setValue(global->timeout);
  l = new QLabel(w_timeout, i18n("T&imeout:"), serverTab);
  grid->addWidget(l,3,0);
  grid->addWidget(w_timeout,3,1);
  connect( w_timeout, SIGNAL( valueChanged(int) ), this, SLOT( slotChanged() ) );

  w_pipesize = new KIntSpinBox(100,5000,2,2,10,serverTab);
  w_pipesize->setSuffix(i18n(" bytes"));
  w_pipesize->setValue(global->pipeSize);
  l = new QLabel(w_pipesize, i18n("Command &buffer:"), serverTab);
  grid->addWidget(l,4,0);
  grid->addWidget(w_pipesize,4,1);
  connect( w_pipesize, SIGNAL( valueChanged(int) ), this, SLOT( slotChanged() ) );

  QStringList encodingNames = KGlobal::charsets()->descriptiveEncodingNames();
  int i=0,x=0;
  for ( QStringList::Iterator it = encodingNames.begin(); it != encodingNames.end(); ++it ) {
    if (KGlobal::charsets()->encodingForName(*it)==global->encoding) {
      x = i;
      break;
    }
    i++;
  }
  w_encoding = new QComboBox(serverTab);
  w_encoding->insertStringList(encodingNames);
  w_encoding->setCurrentItem(x);
  l = new QLabel(w_encoding, i18n("Encod&ing:"), serverTab);
  grid->addWidget(l,5,0);
  grid->addMultiCellWidget(w_encoding,5,5,1,2);
  connect( w_encoding, SIGNAL( activated(int) ), this, SLOT( slotChanged() ) );

  w_auth = new QCheckBox(i18n("Server requires a&uthentication"),serverTab);
  w_auth->setChecked(global->authEnabled);
  grid->addMultiCellWidget(w_auth,6,6,0,2);
  connect( w_auth, SIGNAL( toggled(bool) ), this, SLOT( slotChanged() ) );
  connect(w_auth,SIGNAL(toggled(bool)),SLOT(slotAuthRequiredToggled(bool)));

  w_user = new KLineEdit(serverTab);
  w_user->setText(global->user);
  l_user = new QLabel(w_user, i18n("U&ser:"),serverTab);
  grid->addWidget(l_user,7,0);
  grid->addMultiCellWidget(w_user,7,7,1,2);
  connect( w_user, SIGNAL( textChanged ( const QString & ) ), this, SLOT( slotChanged() ) );

  w_secret = new KLineEdit(serverTab);
  w_secret->setEchoMode(QLineEdit::Password);
  w_secret->setText(global->secret);
  l_secret = new QLabel(w_secret, i18n("Pass&word:"), serverTab);
  grid->addWidget(l_secret,8,0);
  grid->addMultiCellWidget(w_secret,8,8,1,2);
  connect( w_secret, SIGNAL( textChanged ( const QString & ) ), this, SLOT( slotChanged() ) );

  slotAuthRequiredToggled( w_auth->isChecked() );

  grid->setColStretch(1,2);
  grid->setColStretch(2,2);

  //************ Appearance ***************************
  appTab = addPage(i18n("Appearance"),i18n("Customize Visual Appearance"), BarIcon("appearance", KIcon::SizeMedium ));

  QGridLayout *topL=new QGridLayout(appTab, 8, 3, 0, spacingHint());

  //color-list
  c_List = new DialogListBox(false, appTab);
  topL->addMultiCellWidget(c_List,1,3,0,1);
  connect(c_List, SIGNAL(selected(QListBoxItem*)),SLOT(slotColItemSelected(QListBoxItem*)));
  connect(c_List, SIGNAL(selectionChanged()), SLOT(slotColSelectionChanged()));

  c_olorCB = new QCheckBox(i18n("&Use custom colors"),appTab);
  topL->addWidget(c_olorCB,0,0);
  connect(c_olorCB, SIGNAL(toggled(bool)), this, SLOT(slotColCheckBoxToggled(bool)));
  connect(c_olorCB, SIGNAL(toggled(bool) ), this, SLOT( slotChanged()));

  c_olChngBtn=new QPushButton(i18n("Cha&nge..."), appTab);
  connect(c_olChngBtn, SIGNAL(clicked()), SLOT(slotColChangeBtnClicked()));
  topL->addWidget(c_olChngBtn,1,2);

  c_olDefBtn=new QPushButton(i18n("Default&s"), appTab);
  connect(c_olDefBtn, SIGNAL(clicked()), SLOT(slotColDefaultBtnClicked()));
  topL->addWidget(c_olDefBtn,2,2);
  connect(c_olDefBtn, SIGNAL(clicked()), SLOT(slotChanged()));

  //font-list
  f_List = new DialogListBox(false, appTab);
  topL->addMultiCellWidget(f_List,5,7,0,1);
  connect(f_List, SIGNAL(selected(QListBoxItem*)),SLOT(slotFontItemSelected(QListBoxItem*)));
  connect(f_List, SIGNAL(selectionChanged()),SLOT(slotFontSelectionChanged()));

  f_ontCB = new QCheckBox(i18n("Use custom &fonts"),appTab);
  topL->addWidget(f_ontCB,4,0);
  connect(f_ontCB, SIGNAL(toggled(bool)), SLOT(slotFontCheckBoxToggled(bool)));
  connect(f_ontCB, SIGNAL(toggled(bool)), SLOT(slotChanged()));

  f_ntChngBtn=new QPushButton(i18n("Chang&e..."), appTab);
  connect(f_ntChngBtn, SIGNAL(clicked()), SLOT(slotFontChangeBtnClicked()));
  topL->addWidget(f_ntChngBtn,5,2);

  f_ntDefBtn=new QPushButton(i18n("Defaul&ts"), appTab);
  connect(f_ntDefBtn, SIGNAL(clicked()), SLOT(slotFontDefaultBtnClicked()));
  topL->addWidget(f_ntDefBtn,6,2);
  connect(f_ntDefBtn, SIGNAL(clicked()), SLOT(slotChanged()));

  topL->setColStretch(1,2);
  topL->setColStretch(2,0);
  topL->setRowStretch(3,1);
  topL->setRowStretch(7,1);
  topL->setResizeMode(QLayout::Minimum);

  //init
  c_olorCB->setChecked(global->useCustomColors);
  slotColCheckBoxToggled(global->useCustomColors);
  for(int i=0; i<global->colorCount(); i++)
    c_List->insertItem(new ColorListItem(global->colorName(i), global->color(i)));

  f_ontCB->setChecked(global->useCustomFonts);
  slotFontCheckBoxToggled(global->useCustomFonts);
  for(int i=0; i<global->fontCount(); i++)
    f_List->insertItem(new FontListItem(global->fontName(i), global->font(i)));

  //************ Layout ***************************
  layoutTab = addPage(i18n("Layout"),i18n("Customize Output Format"), BarIcon("text_left", KIcon::SizeMedium ));

  QVBoxLayout *vbox = new QVBoxLayout(layoutTab, 0, spacingHint());

  QButtonGroup *bGroup = new QButtonGroup(i18n("Headings"),layoutTab);
  QVBoxLayout *bvbox = new QVBoxLayout(bGroup,8,5);

  bvbox->addSpacing(fontMetrics().lineSpacing()-4);
  w_layout[0] = new QRadioButton(i18n("O&ne heading for each database"),bGroup);
  w_layout[0]->setChecked(global->headLayout == 0);
  bvbox->addWidget(w_layout[0],1);
  w_layout[1] = new QRadioButton(i18n("A&s above, with separators between the definitions"),bGroup);
  w_layout[1]->setChecked(global->headLayout == 1);
  bvbox->addWidget(w_layout[1],1);
  w_layout[2] = new QRadioButton(i18n("A separate heading for &each definition"),bGroup);
  w_layout[2]->setChecked(global->headLayout == 2);
  bvbox->addWidget(w_layout[2],1);
  connect(w_layout[0], SIGNAL(toggled(bool)), SLOT(slotChanged()));
  connect(w_layout[1], SIGNAL(toggled(bool)), SLOT(slotChanged()));
  connect(w_layout[2], SIGNAL(toggled(bool)), SLOT(slotChanged()));

  vbox->addWidget(bGroup,0);
  vbox->addStretch(1);

  //************ Other ***************************
  otherTab = addPage(i18n("Miscellaneous"),i18n("Various Settings"), BarIcon("misc", KIcon::SizeMedium ));

  vbox = new QVBoxLayout(otherTab, 0, spacingHint());

  QGroupBox *group = new QGroupBox(i18n("Limits"),otherTab);

  grid = new QGridLayout(group,4,2,8,5);
  grid->addRowSpacing(0, fontMetrics().lineSpacing()-4);

  w_MaxDefinitions = new KIntSpinBox(100,10000,100,100,10,group);
  w_MaxDefinitions->setValue(global->maxDefinitions);
  l = new QLabel(w_MaxDefinitions, i18n("De&finitions:"), group);
  grid->addWidget(l,1,0);
  grid->addWidget(w_MaxDefinitions,1,1);
  connect(w_MaxDefinitions, SIGNAL(valueChanged(int)), SLOT(slotChanged()));

  w_Maxbrowse = new KIntSpinBox(1,100,1,1,10,group);
  w_Maxbrowse->setValue(global->maxBrowseListEntrys);
  l = new QLabel(w_Maxbrowse, i18n("Cached &results:"), group);
  grid->addWidget(l,2,0);
  grid->addWidget(w_Maxbrowse,2,1);
  connect(w_Maxbrowse, SIGNAL(valueChanged(int)), SLOT(slotChanged()));

  w_Maxhist = new KIntSpinBox(10,5000,10,10,10,group);
  w_Maxhist->setValue(global->maxHistEntrys);
  l = new QLabel(w_Maxhist, i18n("Hi&story entries:"), group);
  grid->addWidget(l,3,0);
  grid->addWidget(w_Maxhist,3,1);
  connect(w_Maxhist, SIGNAL(valueChanged(int)), SLOT(slotChanged()));

  grid->setColStretch(1,1);

  vbox->addWidget(group,0);

  group = new QGroupBox(i18n("Other"),otherTab);

  QVBoxLayout *vbox2 = new QVBoxLayout(group, 8, 5);

  vbox2->addSpacing(fontMetrics().lineSpacing()-4);

  w_Savehist = new QCheckBox(i18n("Sa&ve history on exit"),group);
  w_Savehist->setChecked(global->saveHistory);
  vbox2->addWidget(w_Savehist,0);
  connect(w_Savehist, SIGNAL(toggled(bool)), SLOT(slotChanged()));

  w_Clipboard = new QCheckBox(i18n("D&efine selected text on start"),group);
  w_Clipboard->setChecked(global->defineClipboard);
  vbox2->addWidget(w_Clipboard,1);
  connect(w_Clipboard, SIGNAL(toggled(bool)), SLOT(slotChanged()));

  vbox->addWidget(group,0);
  vbox->addStretch(2);

  setHelp("preferences");

  if (global->optSize.isValid())
    resize(global->optSize);
  else
    resize(300,200);
  enableButton( Apply, false );
  configChanged = false;
}
void SpellHighlighter::rehighlight()
{
  /* Higlighting misspelled words. The main idea: we scan the text for words,
     remembering the stile with which each word (or spacer) were written, if we
     need to mark word as misspelled, we hide current word's style into font-family property
     after "sim-im-misspelled" keyword, replacing ';' with '|' and then sets word's color 
     as red. When we needs to remove misspelled highlightin, we just restore original style 
     form font-family stile definition.
     
     These makes misspelled words shown in red color with default font. This is the best thing
     we can do without rewriting QTextEdit.
  */
  if (textEdit()->textFormat()!=RichText) return; // For RichText edit fields only ;-)
  if ((! m_isInRehighlight) && (! static_cast<TextEdit*>(textEdit())->isInDragAndDrop()))
  {
//    SIM::log(SIM::L_DEBUG, "SpellHighlighter::rehighlight()");

    m_isInRehighlight = true;
    removeHighlight(0);
    
    QString txt = textEdit()->text();

    QString new_txt = "";
    QString tag = QString::null;
    QString word = QString::null;
    QString spacer = QString::null;  // both spases and punctuations
    QString amp_seq = QString::null; // we are specialty treating ampersant sequences because otherwice '&amp;' will be treated as
                                     // [punct][word][punt] and thus splitted apart with formatting tags
    
    QString current_style=QString::null;
    QString current_misspelled_style="font-family:sim-im-misspelled|;color:red";


    for(int i=0;i<txt.length();i++)
    {
      bool close_tag = false;
      bool close_word = false;
      bool close_spacer = false;
      bool close_amp_seq = false;
      
      if (tag)
      {
        tag+=txt[i];
        if (txt[i] == '>') close_tag=true;
      }
      
      if (txt[i] == '<')
      {
        if (word) close_word=true;
        if (spacer) close_spacer=true;
        if (amp_seq) close_amp_seq=true;
        tag = txt[i];
      }
      if (amp_seq)
      {
        amp_seq +=txt[i];
        if (txt[i]==';') close_amp_seq =true;
      }
      if (!tag && txt[i] == '&')
      {
        if (word) close_word=true;
        if (spacer) close_spacer=true;
        amp_seq = "&";
      }
      if ((!tag) && (!amp_seq) && (txt[i].isSpace() || txt[i].isPunct()))
      {
        spacer+=txt[i];
        if (word) close_word=true;
      }
      if ((!tag) && (!amp_seq) && !txt[i].isSpace() && !txt[i].isPunct())
      {
        word+=txt[i];
        if (spacer) close_spacer=true;
      }

      if (close_amp_seq)
      {
        if (! current_style.isEmpty())
          new_txt+="<span style=\""+current_style+"\">"+amp_seq+"</span>";
        else
           new_txt+=amp_seq;
        amp_seq = QString::null;
      }
      if (close_spacer)
      {
        if (! current_style.isEmpty())
          new_txt+="<span style=\""+current_style+"\">"+spacer+"</span>";
        else
           new_txt+=spacer;
        spacer =QString::null;
      }
      if (close_word)
      {
        if (! current_misspelled_style.isEmpty())
          if (m_plugin->checkWord(word))
            new_txt+="<span style=\""+current_style+"\">"+word+"</span>";
          else
            new_txt+="<span style=\""+current_misspelled_style+"\">"+word+"</span>";
        else
          new_txt+=word;
        word =QString::null;
      }
      if (close_tag)
      {
        if (tag.find(QRegExp("<span "),0)>-1)
        {
          current_style = tag;
          current_style.replace(QRegExp("^\\<span\\ style=\"(.*)\">"),"\\1");

          current_misspelled_style = current_style;
          current_misspelled_style.replace(";","|");
          current_misspelled_style = "font-family:sim-im-misspelled|"+current_misspelled_style+";color:red";
 
          QStringList items = QStringList::split(";",current_style);
          for ( QStringList::Iterator it = items.begin(); it != items.end(); ++it )
          {
            QString item = *it;
            if ( (item.find(QRegExp("^font\\-family\\:")) ==-1) &&
                 (item.find(QRegExp("^color\\:")) ==-1) )
            {
              current_misspelled_style+=";"+item;
            }
          }
          tag=QString::null;
        }
        if (tag.find(QRegExp("</span>"),0)>-1)
        {
          current_style= QString::null;
          current_misspelled_style="font-family:sim-im-misspelled|;color:red";
          tag=QString::null;
        }
        new_txt+=tag;
        tag=QString::null;
      }
    }

//    SIM::log(SIM::L_DEBUG, "SpellHighlighter::rehighlight: new_text: %s",new_txt.utf8().data());

    // remembering cursor position, changing text, and then returning cursor to it's original position.
    int para;
    int index;
    int sel_paraFrom;
    int sel_indexFrom;
    int sel_paraTo;
    int sel_indexTo;

    textEdit()->getSelection (&sel_paraFrom, &sel_indexFrom, &sel_paraTo, &sel_indexTo);
    textEdit()->getCursorPosition ( &para, &index );
    textEdit()->setText(new_txt);
    textEdit()->setCursorPosition ( para, index );
    textEdit()->setSelection (sel_paraFrom, sel_indexFrom, sel_paraTo, sel_indexTo); 

    m_isInRehighlight = false;
  }
}
Example #7
0
FilterChain *FilterManager::LoadFilters(QString Filters,
                                        VideoFrameType &inpixfmt,
                                        VideoFrameType &outpixfmt, int &width,
                                        int &height, int &bufsize,
                                        int max_threads)
{
    if (Filters.toLower() == "none")
        return NULL;

    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 = NULL;
    FmtConv *FC, *FC2, *S1, *S2, *S3;
    VideoFrameType ifmt;
    unsigned int i;
    int nbufsize;
    int cbufsize;
    int postfilt_width = width;
    int postfilt_height = height;

    for (QStringList::Iterator 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 (i = 0; i < FiltInfoChain.size(); i++)
    {
        S1 = S2 = S3 = NULL;
        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.size())
    {
        delete FiltChain;
        FiltChain = NULL;
    }

    for (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 = NULL;
            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)
            inpixfmt = 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 QgsManageConnectionsDialog::populateConnections()
{
  // Export mode. Populate connections list from settings
  if ( mDialogMode == Export )
  {
    QSettings settings;
    switch ( mConnectionType )
    {
      case WMS:
        settings.beginGroup( "/Qgis/connections-wms" );
        break;
      case WFS:
        settings.beginGroup( "/Qgis/connections-wfs" );
        break;
      case WCS:
        settings.beginGroup( "/Qgis/connections-wcs" );
        break;
      case PostGIS:
        settings.beginGroup( "/PostgreSQL/connections" );
        break;
      case MSSQL:
        settings.beginGroup( "/MSSQL/connections" );
        break;
      case Oracle:
        settings.beginGroup( "/Oracle/connections" );
        break;
    }
    QStringList keys = settings.childGroups();
    QStringList::Iterator it = keys.begin();
    while ( it != keys.end() )
    {
      QListWidgetItem *item = new QListWidgetItem();
      item->setText( *it );
      listConnections->addItem( item );
      ++it;
    }
    settings.endGroup();
  }
  // Import mode. Populate connections list from file
  else
  {
    QFile file( mFileName );
    if ( !file.open( QIODevice::ReadOnly | QIODevice::Text ) )
    {
      QMessageBox::warning( this, tr( "Loading connections" ),
                            tr( "Cannot read file %1:\n%2." )
                            .arg( mFileName )
                            .arg( file.errorString() ) );
      return false;
    }

    QDomDocument doc;
    QString errorStr;
    int errorLine;
    int errorColumn;

    if ( !doc.setContent( &file, true, &errorStr, &errorLine, &errorColumn ) )
    {
      QMessageBox::warning( this, tr( "Loading connections" ),
                            tr( "Parse error at line %1, column %2:\n%3" )
                            .arg( errorLine )
                            .arg( errorColumn )
                            .arg( errorStr ) );
      return false;
    }

    QDomElement root = doc.documentElement();
    switch ( mConnectionType )
    {
      case WMS:
        if ( root.tagName() != "qgsWMSConnections" )
        {
          QMessageBox::information( this, tr( "Loading connections" ),
                                    tr( "The file is not an WMS connections exchange file." ) );
          return false;
        }
        break;

      case WFS:
        if ( root.tagName() != "qgsWFSConnections" )
        {
          QMessageBox::information( this, tr( "Loading connections" ),
                                    tr( "The file is not an WFS connections exchange file." ) );
          return false;
        }
        break;

      case WCS:
        if ( root.tagName() != "qgsWCSConnections" )
        {
          QMessageBox::information( this, tr( "Loading connections" ),
                                    tr( "The file is not an WCS connections exchange file." ) );
          return false;
        }
        break;

      case PostGIS:
        if ( root.tagName() != "qgsPgConnections" )
        {
          QMessageBox::information( this, tr( "Loading connections" ),
                                    tr( "The file is not an PostGIS connections exchange file." ) );
          return false;
        }
        break;

      case MSSQL:
        if ( root.tagName() != "qgsMssqlConnections" )
        {
          QMessageBox::information( this, tr( "Loading connections" ),
                                    tr( "The file is not an MSSQL connections exchange file." ) );
          return false;
        }
        break;
      case Oracle:
        if ( root.tagName() != "qgsOracleConnections" )
        {
          QMessageBox::information( this, tr( "Loading connections" ),
                                    tr( "The file is not an Oracle connections exchange file." ) );
          return false;
        }
        break;
    }

    QDomElement child = root.firstChildElement();
    while ( !child.isNull() )
    {
      QListWidgetItem *item = new QListWidgetItem();
      item->setText( child.attribute( "name" ) );
      listConnections->addItem( item );
      child = child.nextSiblingElement();
    }
  }
  return true;
}
Example #9
0
void SearchManager::search(const QString &pattern, const KABC::Field::List &fields, Type type)
{
    mPattern = pattern;
    mFields = fields;
    mType = type;

    KABC::Addressee::List allContacts;
    mContacts.clear();

#if KDE_VERSION >= 319
    KABC::AddresseeList list(mAddressBook->allAddressees());
    if(!fields.isEmpty())
        list.sortByField(fields.first());

    allContacts = list;
#else
    KABC::AddressBook::ConstIterator abIt(mAddressBook->begin());
    const KABC::AddressBook::ConstIterator abEndIt(mAddressBook->end());
    for(; abIt != abEndIt; ++abIt)
        allContacts.append(*abIt);
#endif

#ifdef KDEPIM_NEW_DISTRLISTS
    // Extract distribution lists from allContacts
    mDistributionLists.clear();
    KABC::Addressee::List::Iterator rmIt(allContacts.begin());
    const KABC::Addressee::List::Iterator rmEndIt(allContacts.end());
    while(rmIt != rmEndIt)
    {
        if(KPIM::DistributionList::isDistributionList(*rmIt))
        {
            mDistributionLists.append(static_cast<KPIM::DistributionList>(*rmIt));
            rmIt = allContacts.remove(rmIt);
        }
        else
            ++rmIt;
    }

    typedef KPIM::DistributionList::Entry Entry;
    if(!mSelectedDistributionList.isNull())
    {
        const KPIM::DistributionList dl = KPIM::DistributionList::findByName(mAddressBook, mSelectedDistributionList);
        if(!dl.isEmpty())
        {
            allContacts.clear();
            const Entry::List entries = dl.entries(mAddressBook);
            const Entry::List::ConstIterator end = entries.end();
            for(Entry::List::ConstIterator it = entries.begin(); it != end; ++it)
            {
                allContacts.append((*it).addressee);
            }
        }
    }

#endif

    if(mPattern.isEmpty())      // no pattern, return all
    {
        mContacts = allContacts;

        emit contactsUpdated();

        return;
    }

    const KABC::Field::List fieldList = !mFields.isEmpty() ? mFields : KABC::Field::allFields();

    KABC::Addressee::List::ConstIterator it(allContacts.begin());
    const KABC::Addressee::List::ConstIterator endIt(allContacts.end());
    for(; it != endIt; ++it)
    {
#ifdef KDEPIM_NEW_DISTRLISTS
        if(KPIM::DistributionList::isDistributionList(*it))
            continue;
#endif

        bool found = false;
        // search over all fields
        KABC::Field::List::ConstIterator fieldIt(fieldList.begin());
        const KABC::Field::List::ConstIterator fieldEndIt(fieldList.end());
        for(; fieldIt != fieldEndIt; ++fieldIt)
        {

            if(type == StartsWith && (*fieldIt)->value(*it).startsWith(pattern, false))
            {
                mContacts.append(*it);
                found = true;
                break;
            }
            else if(type == EndsWith && (*fieldIt)->value(*it).endsWith(pattern, false))
            {
                mContacts.append(*it);
                found = true;
                break;
            }
            else if(type == Contains && (*fieldIt)->value(*it).find(pattern, 0, false) != -1)
            {
                mContacts.append(*it);
                found = true;
                break;
            }
            else if(type == Equals && (*fieldIt)->value(*it).localeAwareCompare(pattern) == 0)
            {
                mContacts.append(*it);
                found = true;
                break;
            }
        }

        if(!found)
        {
            // search over custom fields
            const QStringList customs = (*it).customs();

            QStringList::ConstIterator customIt(customs.begin());
            const QStringList::ConstIterator customEndIt(customs.end());
            for(; customIt != customEndIt; ++customIt)
            {
                int pos = (*customIt).find(':');
                if(pos != -1)
                {
                    const QString value = (*customIt).mid(pos + 1);
                    if(type == StartsWith && value.startsWith(pattern, false))
                    {
                        mContacts.append(*it);
                        break;
                    }
                    else if(type == EndsWith && value.endsWith(pattern, false))
                    {
                        mContacts.append(*it);
                        break;
                    }
                    else if(type == Contains && value.find(pattern, 0, false) != -1)
                    {
                        mContacts.append(*it);
                        break;
                    }
                    else if(type == Equals && value.localeAwareCompare(pattern) == 0)
                    {
                        mContacts.append(*it);
                        break;
                    }
                }
            }
        }
    }

    emit contactsUpdated();
}
Example #10
0
BalloonMsg::BalloonMsg(void *param, const QString &_text, QStringList &btn, QWidget *parent, const QRect *rcParent,
                       bool bModal, bool bAutoHide, unsigned bwidth, const QString &box_msg, bool *bChecked)
        : QDialog(parent, "ballon", bModal,
                  (bAutoHide ? WType_Popup : WType_TopLevel | WStyle_StaysOnTop)
                  | WStyle_Customize | WStyle_NoBorderEx | WStyle_Tool | WDestructiveClose | WX11BypassWM)
{
    m_param = param;
    m_parent = parent;
    m_width = bwidth;
    m_bAutoHide = bAutoHide;
    m_bYes = false;
    m_bChecked = bChecked;
    bool bTailDown = true;
    setPalette(QToolTip::palette());
    text = _text;
    QFrame *frm = new QFrame(this);
    frm->setPalette(palette());
    QVBoxLayout *vlay = new QVBoxLayout(frm);
    vlay->setMargin(0);
    m_check = NULL;
    if (!box_msg.isEmpty()){
        m_check = new QCheckBox(box_msg, frm);
        vlay->addWidget(m_check);
        if (m_bChecked)
            m_check->setChecked(*m_bChecked);
    }
    QHBoxLayout *lay = new QHBoxLayout(vlay);
    lay->setSpacing(5);
    lay->addStretch();
    unsigned id = 0;
    bool bFirst = true;
    for (QStringList::Iterator it = btn.begin(); it != btn.end(); ++it, id++){
        BalloonButton *b = new BalloonButton(*it, frm, id);
        connect(b, SIGNAL(action(int)), this, SLOT(action(int)));
        lay->addWidget(b);
        if (bFirst){
            b->setDefault(true);
            bFirst = false;
        }
    }
    setButtonsPict(this);
    lay->addStretch();
    int wndWidth = frm->minimumSizeHint().width();
    int hButton  = frm->minimumSizeHint().height();

    int txtWidth = bwidth;
    QRect rc;
    if (rcParent){
        rc = *rcParent;
    }else{
        QPoint p = parent->mapToGlobal(parent->rect().topLeft());
        rc = QRect(p.x(), p.y(), parent->width(), parent->height());
    }
    if (rc.width() > txtWidth) txtWidth = rc.width();

    QSimpleRichText richText(_text, font(), "", QStyleSheet::defaultSheet(), QMimeSourceFactory::defaultFactory(), -1, Qt::blue, false);
    richText.setWidth(wndWidth);
    richText.adjustSize();
    QSize s(richText.widthUsed(), richText.height());
    QSize sMin = frm->minimumSizeHint();
    if (s.width() < sMin.width())
        s.setWidth(sMin.width());
    int BALLOON_SHADOW = BALLOON_SHADOW_DEF;
#ifdef WIN32
    /* FIXME */
    /*    if ((GetClassLong(winId(), GCL_STYLE) & CS_DROPSHADOW) && style().inherits("QWindowsXPStyle"))
            BALLOON_SHADOW = 0; */
#endif
    resize(s.width() + BALLOON_R * 2 + BALLOON_SHADOW,
           s.height() + BALLOON_R * 2 + BALLOON_TAIL + BALLOON_SHADOW + hButton + BALLOON_MARGIN);
    mask = QBitmap(width(), height());
    int w = width() - BALLOON_SHADOW;
    int tailX = w / 2;
    int posX = rc.left() + rc.width() / 2 + BALLOON_TAIL_WIDTH - tailX;
    if (posX <= 0) posX = 1;
    QRect rcScreen = screenGeometry();
    if (posX + width() >= rcScreen.width())
        posX = rcScreen.width() - 1 - width();
    int tx = posX + tailX - BALLOON_TAIL_WIDTH;
    if (tx < rc.left()) tx = rc.left();
    if (tx > rc.left() + rc.width()) tx = rc.left() + rc.width();
    tailX = tx + BALLOON_TAIL_WIDTH - posX;
    if (tailX < BALLOON_R) tailX = BALLOON_R;
    if (tailX > width() - BALLOON_R - BALLOON_TAIL_WIDTH) tailX = width() - BALLOON_R - BALLOON_TAIL_WIDTH;
    if (rc.top() <= height() + 2){
        bTailDown = false;
        move(posX, rc.top() + rc.height() + 1);
    }else{
        move(posX, rc.top() - height() - 1);
    }
    int pos = 0;
    int h = height() - BALLOON_SHADOW - BALLOON_TAIL;
    if (!bTailDown) pos += BALLOON_TAIL;
    textRect.setRect(BALLOON_R, pos + BALLOON_R, w - BALLOON_R * 2, h);
    frm->resize(s.width(), hButton);
    frm->move(BALLOON_R, pos + h - BALLOON_R - hButton);
    QPainter p;
    p.begin(&mask);
#ifdef WIN32
    QColor bg(255, 255, 255);
    QColor fg(0, 0, 0);
#else
    QColor bg(0, 0, 0);
    QColor fg(255, 255, 255);
#endif
    p.fillRect(0, 0, width(), height(), bg);
    p.fillRect(0, pos + BALLOON_R, w, h - BALLOON_R * 2, fg);
    p.fillRect(BALLOON_R, pos, w - BALLOON_R * 2, h, fg);
    p.fillRect(BALLOON_SHADOW, pos + BALLOON_R + BALLOON_SHADOW, w, h - BALLOON_R * 2, fg);
    p.fillRect(BALLOON_R + BALLOON_SHADOW, pos + BALLOON_SHADOW, w - BALLOON_R * 2, h, fg);
    p.setBrush(fg);
    p.drawEllipse(0, pos, BALLOON_R * 2, BALLOON_R * 2);
    p.drawEllipse(w - BALLOON_R * 2, pos, BALLOON_R * 2, BALLOON_R * 2);
    p.drawEllipse(w - BALLOON_R * 2, pos + h - BALLOON_R * 2, BALLOON_R * 2, BALLOON_R * 2);
    p.drawEllipse(0, pos + h - BALLOON_R * 2, BALLOON_R * 2, BALLOON_R * 2);
    p.drawEllipse(BALLOON_SHADOW, pos + BALLOON_SHADOW, BALLOON_R * 2, BALLOON_R * 2);
    p.drawEllipse(w - BALLOON_R * 2 + BALLOON_SHADOW, pos + BALLOON_SHADOW, BALLOON_R * 2, BALLOON_R * 2);
    p.drawEllipse(w - BALLOON_R * 2 + BALLOON_SHADOW, pos + h - BALLOON_R * 2 + BALLOON_SHADOW, BALLOON_R * 2, BALLOON_R * 2);
    p.drawEllipse(BALLOON_SHADOW, pos + h - BALLOON_R * 2 + BALLOON_SHADOW, BALLOON_R * 2, BALLOON_R * 2);
    QPointArray arr(3);
    arr.setPoint(0, tailX, bTailDown ? h : pos);
    arr.setPoint(1, tailX + BALLOON_TAIL_WIDTH, bTailDown ? h : pos);
    arr.setPoint(2, tailX - BALLOON_TAIL_WIDTH, bTailDown ? height() - BALLOON_SHADOW : 0);
    p.drawPolygon(arr);
    arr.setPoint(0, tailX + BALLOON_SHADOW, (bTailDown ? h : pos) + BALLOON_SHADOW);
    arr.setPoint(1, tailX + BALLOON_TAIL_WIDTH + BALLOON_SHADOW, (bTailDown ? h : pos) + BALLOON_SHADOW);
    arr.setPoint(2, tailX - BALLOON_TAIL_WIDTH + BALLOON_SHADOW, bTailDown ? height() : BALLOON_SHADOW);
    p.drawPolygon(arr);
    p.end();
    setMask(mask);
    qApp->syncX();
    QPixmap pict = QPixmap::grabWindow(QApplication::desktop()->winId(), x(), y(), width(), height());
    intensity(pict, -0.50f);
    p.begin(&pict);
    p.setBrush(colorGroup().background());
    p.drawEllipse(0, pos, BALLOON_R * 2, BALLOON_R * 2);
    p.drawEllipse(w - BALLOON_R * 2, pos, BALLOON_R * 2, BALLOON_R * 2);
    p.drawEllipse(w - BALLOON_R * 2, pos + h - BALLOON_R * 2, BALLOON_R * 2, BALLOON_R * 2);
    p.drawEllipse(0, pos + h - BALLOON_R * 2, BALLOON_R * 2, BALLOON_R * 2);
    arr.setPoint(0, tailX, bTailDown ? h - 1 : pos + 1);
    arr.setPoint(1, tailX + BALLOON_TAIL_WIDTH, bTailDown ? h - 1 : pos + 1);
    arr.setPoint(2, tailX - BALLOON_TAIL_WIDTH, bTailDown ? height() - BALLOON_SHADOW : 0);
    p.drawPolygon(arr);
    p.fillRect(0, pos + BALLOON_R, w, h - BALLOON_R * 2, colorGroup().background());
    p.fillRect(BALLOON_R, pos, w - BALLOON_R * 2, h, colorGroup().background());
    p.drawLine(0, pos + BALLOON_R, 0, pos + h - BALLOON_R);
    p.drawLine(w - 1, pos + BALLOON_R, w - 1, pos + h - BALLOON_R);
    if (bTailDown){
        p.drawLine(BALLOON_R, 0, w - BALLOON_R, 0);
        p.drawLine(BALLOON_R, h - 1, tailX, h - 1);
        p.drawLine(tailX + BALLOON_TAIL_WIDTH, h - 1, w - BALLOON_R, h - 1);
    }else{
        p.drawLine(BALLOON_R, pos + h - 1, w - BALLOON_R, pos + h - 1);
        p.drawLine(BALLOON_R, pos, tailX, pos);
        p.drawLine(tailX + BALLOON_TAIL_WIDTH, pos, w - BALLOON_R, pos);
    }
    p.end();
    setBackgroundPixmap(pict);
    setAutoMask(true);
    if (!bAutoHide)
        setFocusPolicy(NoFocus);

    QWidget *top = NULL;
    if (parent)
        top = parent->topLevelWidget();
    if (top){
        raiseWindow(top);
        top->installEventFilter(this);
    }
}
Example #11
0
//Add the book's confs, from it's conf file
void BookList::AddBookConfs(Book *book, QList<QString> text)
{
    vector<QString> linesplit;

    for(int i=0; i<text.size() ; i++)
    {
        if (text[i].indexOf("Comments") != -1)
        {
            book->Comments = text[i].mid(9);
        }

        else if (text[i].indexOf("GroupId") != -1)
        {
            book->GroupId = text[i].mid(8);
        }

        else if (text[i].indexOf("DisplayName") != -1)
        {
            book->setNormallDisplayName(text[i].mid(12).replace(QRegExp("^ *"), ""));
        }

        //field for the display name of the directory
        else if (text[i].indexOf("BranchName") != -1)
        {
            linesplit.clear();
            splittotwo(text[i],linesplit ,"=");
            if (linesplit[1]!="")
            {
                book->setTreeDisplayName(linesplit[1]);
            }
        }

        else if (text[i].indexOf("LastLevelIndex") != -1)
        {
            int n;
            if(ToNum(text[i].mid(15),&n))
                book->LastLevelIndex = n;
        }

        else if (text[i].indexOf("PutNewLinesAsIs") != -1)
        {
            if(text[i].mid(16) != "1")
                book->PutNewLinesAsIs=false;
            else
                book->PutNewLinesAsIs=true;
        }

        else if (text[i].indexOf("TextSource") != -1)
        {
            qDebug() << "(C)" + text[i].mid(11);
            book->setCopyrightInfo(text[i].mid(11));
        }

        else if (text[i].indexOf("ForcedBookName") != -1)
        {
            linesplit.clear();
            splittotwo(text[i],linesplit ,"=");
            if (linesplit[1]!="")
                book->setTreeDisplayName(linesplit[1]);
        }

        else if (text[i].indexOf("HiddenFromIndex") != -1)
        {
            int t;
            GetIntValue(text[i], &t);
            if (t==1)
            {
                book->setIsHidden(true);
                book->setIsInSearch(false);
            }
        }

        else if (text[i].indexOf("WeaveLevel") != -1)
        {
            QString wl = text[i].mid(text[i].size()-1);
            book->WeaveLevel = wl;
        }

        else if (text[i].indexOf("AddSource") != -1)
        {
            if ( book->mWeavedSources.size() == 0)
            {
                //Add the book it self as the first source
                weavedSource base;

                base.FilePath = book->getPath();

                base.Zoom = 0;

                base.id = 0;

                base.show = true;

                book->mWeavedSources.append(base);
            }

            QStringList p = text[i].mid(10).split(":");
            if (p.size() > 1)
            {
                weavedSource src;
                src.FilePath = BOOKPATH + (BOOKPATH.endsWith("/") ? "" : "/") + p[0];
                src.Title = p[1];

                src.Zoom = 0;

                src.id = book->mWeavedSources.size();

                src.show = false;

                book->mWeavedSources.append(src);
            }
            else
            {
                qDebug() << "Invalid weaved source in:" << book->getPath();
                qDebug() << "Bad path:" << text[i];
            }
        }

        // code from yoch to add new commentaries by id
        else if (text[i].indexOf("MixedSources") != -1)
        {
            QString srcLst = text[i].mid(12);
            srcLst = srcLst.mid(srcLst.indexOf("(") + 1);
            srcLst = srcLst.mid(0, srcLst.indexOf(")"));
            QList<int> wsrc;
            QStringList srcId = srcLst.split(',', QString::SkipEmptyParts);

            for (QStringList::const_iterator it = srcId.begin(); it != srcId.end(); ++it)
            {
                int id;
                if(ToNum(*it, &id))
                {
                    weavedSource src;
                    src.show = false;
                    src.id = id;
                    //                    mWeavedSources.push_back(src);
                    book->mWeavedSources.append(src);
                }
            }
        }

        else if (text[i].indexOf("CosmeticsType") != -1)
        {
            book->setCosmetics(text[i]);
        }

        else if (text[i].indexOf("UniqueId") != -1)
        {
            int id;
            if(ToNum(text[i].mid(9), &id) == true)
                book->setUniqueId(id);
        }

        else if (text[i].indexOf("Nikud") != -1)
        {
            book->hasNikud=true;
        }

        else if (text[i].indexOf("Teamim") != -1)
        {
            book->hasTeamim=true;
        }
        else if (text[i].indexOf("Kukayta") != -1)
        {
            book->isEncrypted=true;
        }

    }
}
Example #12
0
MythSocket *RemoteFile::openSocket(bool control)
{
    QUrl qurl(path);
    QString dir;

    QString host = qurl.host();
    int port = qurl.port();

    dir = qurl.path();

    if (qurl.hasQuery())
        dir += "?" + QUrl::fromPercentEncoding(qurl.encodedQuery());

    if (qurl.hasFragment())
        dir += "#" + qurl.fragment();

    QString sgroup = qurl.userName();

    MythSocket *lsock = new MythSocket();
    QString stype = (control) ? "control socket" : "file data socket";

    QString loc_err = QString("RemoteFile::openSocket(%1), Error: ").arg(stype);

    if (port <= 0)
    {
        port = GetMythDB()->GetSettingOnHost("BackendServerPort", host).toInt();

        // if we still have no port use the default
        if (port <= 0)
            port = 6543;
    }

    if (!lsock->connect(host, port))
    {
        VERBOSE(VB_IMPORTANT, loc_err +
                QString("\n\t\t\tCould not connect to server %1:%2")
                .arg(host).arg(port));
        lsock->DownRef();
        return NULL;
    }

    QString hostname = GetMythDB()->GetHostName();

    QStringList strlist;

    if (control)
    {
        strlist.append( QString("ANN Playback %1 %2").arg(hostname).arg(false) );
        lsock->writeStringList(strlist);
        if (!lsock->readStringList(strlist, true))
        {
            VERBOSE(VB_IMPORTANT, loc_err +
                    QString("\n\t\t\tCould not read string list from server "
                            "%1:%2").arg(host).arg(port));
            lsock->DownRef();
            return NULL;
        }
    }
    else
    {
        strlist.push_back(QString("ANN FileTransfer %1 %2 %3 %4")
                          .arg(hostname).arg(writemode)
                          .arg(usereadahead).arg(timeout_ms));
        strlist << QString("%1").arg(dir);
        strlist << sgroup;

        QStringList::const_iterator it = possibleauxfiles.begin();
        for (; it != possibleauxfiles.end(); ++it)
            strlist << *it;

        if (!lsock->writeStringList(strlist) ||
            !lsock->readStringList(strlist, true))
        {
            VERBOSE(VB_IMPORTANT, loc_err +
                    QString("Did not get proper response from %1:%2")
                    .arg(host).arg(port));
            strlist.clear();
            strlist.push_back("ERROR");
            strlist.push_back("invalid response");
        }

        if (strlist.size() >= 4)
        {
            it = strlist.begin(); ++it;
            recordernum = (*it).toInt(); ++it;
            filesize = decodeLongLong(strlist, it);
            for (; it != strlist.end(); ++it)
                auxfiles << *it;
        }
        else if (0 < strlist.size() && strlist.size() < 4 &&
                 strlist[0] != "ERROR")
        {
            VERBOSE(VB_IMPORTANT, loc_err +
                    QString("Did not get proper response from %1:%2")
                    .arg(host).arg(port));
            strlist.clear();
            strlist.push_back("ERROR");
            strlist.push_back("invalid response");
        }
    }

    if (strlist.empty() || strlist[0] == "ERROR")
    {
        lsock->DownRef();
        lsock = NULL;
        if (strlist.empty())
        {
            VERBOSE(VB_IMPORTANT, loc_err + "Failed to open socket, timeout");
        }
        else
        {
            VERBOSE(VB_IMPORTANT, loc_err + "Failed to open socket" +
                    ((strlist.size() >= 2) ?
                     QString(", error was %1").arg(strlist[1]) :
                     QString(", remote error")));
        }
    }

    return lsock;
}
void MigrateDialog::process()
{
    unsigned size = 0;
    for (list<QCheckBox*>::iterator it = m_boxes.begin(); it != m_boxes.end(); ++it){
        if (!(*it)->isChecked())
            continue;
        QString path = user_file((*it)->text());
        path += '/';
        icqConf.close();
        clientsConf.close();
        contactsConf.close();
        icqConf.setName(path + "icq.conf");
        clientsConf.setName(path + "clients.conf");
        contactsConf.setName(path + "contacts.conf");
        lblStatus->setText(path + "icq.conf");
        if (!icqConf.open(IO_ReadOnly)){
            error(i18n("Can't open %1") .arg(path + "icq.conf"));
            return;
        }
        if (!clientsConf.open(IO_WriteOnly | IO_Truncate)){
            error(i18n("Can't open %1") .arg(path + "clients.conf"));
            return;
        }
        if (!contactsConf.open(IO_WriteOnly | IO_Truncate)){
            error(i18n("Can't open %1") .arg(path + "contacts.conf"));
            return;
        }
        m_uin    = 0;
        m_passwd = "";
        m_state  = 0;
        m_grpId		= 0;
        m_contactId = 0;
        Buffer cfg;
        cfg.init(icqConf.size());
        icqConf.readBlock(cfg.data(), icqConf.size());
        for (;;){
            QCString section = cfg.getSection();
            if (section.isEmpty())
                break;
            m_state = 3;
            if (section == "Group")
                m_state = 1;
            if (section == "User")
                m_state = 2;
            if (!m_bProcess)
                return;
            for (;;){
                QCString l = cfg.getLine();
                if (l.isEmpty())
                    break;
                QCString line = l;
                QCString name = getToken(line, '=');
                if (name == "UIN")
                    m_uin = line.toUInt();
                if (name == "EncryptPassword")
                    m_passwd = line;
                if (name == "Name")
                    m_name = line;
                if (name == "Alias")
                    m_name = line;
            }
            flush();
            barCnv->setProgress(cfg.readPos());
            qApp->processEvents();
        }
        icqConf.close();
        clientsConf.close();
        contactsConf.close();
        m_state = 3;
        size += icqConf.size();
        if (!m_bProcess)
            return;
        barCnv->setProgress(size);
        qApp->processEvents();
        QString h_path = path;
#ifdef WIN32
        h_path += "history\\";
#else
        h_path += "history/";
#endif
        QDir history(h_path);
        QStringList l = history.entryList("*.history", QDir::Files);
        for (QStringList::Iterator it = l.begin(); it != l.end(); ++it){
            hFrom.close();
            hTo.close();
            hFrom.setName(h_path + (*it));
            lblStatus->setText(h_path + (*it));
            hTo.setName(h_path + QString(m_owner) + '.' + (*it).left((*it).find('.')));
            if (!hFrom.open(IO_ReadOnly)){
                error(i18n("Can't open %1") .arg(hFrom.name()));
                return;
            }
            if (!hTo.open(IO_WriteOnly | IO_Truncate)){
                error(i18n("Can't open %1") .arg(hTo.name()));
                return;
            }
            cfg.init(hFrom.size());
            hFrom.readBlock(cfg.data(), hFrom.size());
            for (;;){
                QCString section = cfg.getSection();
                if (section.isEmpty())
                    break;
                m_state = 3;
                if (section == "Message")
                    m_state = 4;
                if (!m_bProcess)
                    return;
                for (;;){
                    QCString l = cfg.getLine();
                    if (l.isEmpty())
                        break;
                    QCString line = l;
                    QCString name = getToken(line, '=');
                    if (name == "Message")
                        m_message = line;
                    if (name == "Time")
                        m_time = line;
                    if (name == "Direction")
                        m_direction = line;
                    if (name == "Charset")
                        m_charset = line;
                }
                flush();
                barCnv->setProgress(cfg.readPos());
                qApp->processEvents();
            }
            hFrom.close();
            hTo.close();
            m_state = 3;
            size += hFrom.size();
            if (!m_bProcess)
                return;
            barCnv->setProgress(size);
            qApp->processEvents();
        }
        if (chkRemove->isChecked()){
            icqConf.remove();
            icqConf.setName(path + "sim.conf");
            icqConf.remove();
            for (QStringList::Iterator it = l.begin(); it != l.end(); ++it){
                hFrom.setName(h_path + (*it));
                hFrom.remove();
            }
        }
    }
    m_bProcess = false;
    accept();
}
Example #14
0
QVariant KConfigBase::readPropertyEntry(const char *pKey, const QVariant &aDefault) const
{
    if(!hasKey(pKey))
        return aDefault;

    QVariant tmp = aDefault;

    switch(aDefault.type())
    {
        case QVariant::Invalid:
            return QVariant();
        case QVariant::String:
            return QVariant(readEntry(pKey, aDefault.toString()));
        case QVariant::StringList:
            return QVariant(readListEntry(pKey));
        case QVariant::List:
        {
            QStringList strList = readListEntry(pKey);
            QStringList::ConstIterator it = strList.begin();
            QStringList::ConstIterator end = strList.end();
            QValueList< QVariant > list;

            for(; it != end; ++it)
            {
                tmp = *it;
                list.append(tmp);
            }
            return QVariant(list);
        }
        case QVariant::Font:
            return QVariant(readFontEntry(pKey, &tmp.asFont()));
        case QVariant::Point:
            return QVariant(readPointEntry(pKey, &tmp.asPoint()));
        case QVariant::Rect:
            return QVariant(readRectEntry(pKey, &tmp.asRect()));
        case QVariant::Size:
            return QVariant(readSizeEntry(pKey, &tmp.asSize()));
        case QVariant::Color:
            return QVariant(readColorEntry(pKey, &tmp.asColor()));
        case QVariant::Int:
            return QVariant(readNumEntry(pKey, aDefault.toInt()));
        case QVariant::UInt:
            return QVariant(readUnsignedNumEntry(pKey, aDefault.toUInt()));
        case QVariant::LongLong:
            return QVariant(readNum64Entry(pKey, aDefault.toLongLong()));
        case QVariant::ULongLong:
            return QVariant(readUnsignedNum64Entry(pKey, aDefault.toULongLong()));
        case QVariant::Bool:
            return QVariant(readBoolEntry(pKey, aDefault.toBool()), 0);
        case QVariant::Double:
            return QVariant(readDoubleNumEntry(pKey, aDefault.toDouble()));
        case QVariant::DateTime:
            return QVariant(readDateTimeEntry(pKey, &tmp.asDateTime()));
        case QVariant::Date:
            return QVariant(readDateTimeEntry(pKey, &tmp.asDateTime()).date());

        case QVariant::Pixmap:
        case QVariant::Image:
        case QVariant::Brush:
        case QVariant::Palette:
        case QVariant::ColorGroup:
        case QVariant::Map:
        case QVariant::IconSet:
        case QVariant::CString:
        case QVariant::PointArray:
        case QVariant::Region:
        case QVariant::Bitmap:
        case QVariant::Cursor:
        case QVariant::SizePolicy:
        case QVariant::Time:
        case QVariant::ByteArray:
        case QVariant::BitArray:
        case QVariant::KeySequence:
        case QVariant::Pen:
            break;
    }

    Q_ASSERT(0);
    return QVariant();
}
Example #15
0
QStringList ScribusQApp::getLang(QString lang)
{
	QStringList langs;

	// read the locales
	if (!lang.isEmpty())
		langs.push_back(lang);

	//add in user preferences lang, only overridden by lang command line option
	QString Pff = QDir::convertSeparators(ScPaths::getApplicationDataDir());
	QFileInfo Pffi = QFileInfo(Pff);
	if (Pffi.exists())
	{
		QString PrefsPfad;
		if (Pffi.isDir())
			PrefsPfad = Pff;
		else
			PrefsPfad = QDir::homePath();
		QString prefsXMLFile=QDir::convertSeparators(PrefsPfad + "/prefs135.xml");
		QFileInfo infoPrefsFile(prefsXMLFile);
		if (infoPrefsFile.exists())
		{
			PrefsFile* prefsFile = new PrefsFile(prefsXMLFile);
			if (prefsFile) {
				PrefsContext* userprefsContext = prefsFile->getContext("user_preferences");
				if (userprefsContext) {
					QString prefslang = userprefsContext->get("gui_language","");
					if (!prefslang.isEmpty())
						langs.push_back(prefslang);
				}
			}
			delete prefsFile;
		}
	}

	if (!(lang = ::getenv("LC_ALL")).isEmpty())
		langs.push_back(lang);
	if (!(lang = ::getenv("LC_MESSAGES")).isEmpty())
		langs.push_back(lang);
	if (!(lang = ::getenv("LANG")).isEmpty())
		langs.push_back(lang);

#if defined(_WIN32)
	wchar_t out[256];
	QString language, sublanguage;
	LCID lcIdo = GetUserDefaultLCID();
	WORD sortId = SORTIDFROMLCID(lcIdo);
	LANGID langId = GetUserDefaultUILanguage();
	LCID lcIdn = MAKELCID(langId, sortId);
	if ( GetLocaleInfoW(lcIdn, LOCALE_SISO639LANGNAME , out, 255) )
	{
		language = QString::fromUtf16( (ushort*)out );
		if ( GetLocaleInfoW(lcIdn, LOCALE_SISO3166CTRYNAME, out, 255) )
		{
			sublanguage = QString::fromUtf16( (ushort*)out ).toLower();
			lang = language;
			if ( sublanguage != language && !sublanguage.isEmpty() )
				lang += "_" + sublanguage.toUpper();
			langs.push_back(lang);
		}
	}
#endif

	langs.push_back(QString(QLocale::system().name()));

	// remove duplicate entries...
	QStringList::Iterator it = langs.end();
	while (it != langs.begin())
	{
		--it;
		if (langs.count(*it) > 1)
			it = langs.erase(it);
	}

	return langs;
}
Example #16
0
/* Check if file meets the find's requirements*/
void KQuery::processQuery( KFileItem* file)
{
  QRegExp *filename_match;

    if ( file->name() == "." || file->name() == ".." )
      return;

    bool matched=false;

    for ( filename_match = m_regexps.first(); !matched && filename_match; filename_match = m_regexps.next() )
    {
      matched |=  filename_match->isEmpty()  ||
                  (filename_match->exactMatch( file->url().fileName( true ) ) );
    }
    if (!matched)
      return;

    switch( m_sizemode )
    {
        case 1: // "at least"
            if ( file->size() < m_sizeboundary1 ) return;
            break;
        case 2: // "at most"
            if ( file->size() > m_sizeboundary1 ) return;
            break;
        case 3: // "equal"
            if ( file->size() != m_sizeboundary1 ) return;
            break;
        case 4: // "between"
            if ( (file->size() < m_sizeboundary1) || (file->size() > m_sizeboundary2) ) return;
            break;
        case 0: // "none" -> fall to default
        default:
            break;
    }

    // make sure it's in the correct date range
    // what about 0 times?
    if ( m_timeFrom && m_timeFrom > file->time(KIO::UDS_MODIFICATION_TIME) )
      return;
    if ( m_timeTo && m_timeTo < file->time(KIO::UDS_MODIFICATION_TIME) )
      return;

    // username / group match
    if ( (!m_username.isEmpty()) && (m_username != file->user()) )
       return;
    if ( (!m_groupname.isEmpty()) && (m_groupname != file->group()) )
       return;

    // file type
    switch (m_filetype)
    {
      case 0:
        break;
      case 1: // plain file
        if ( !S_ISREG( file->mode() ) )
          return;
        break;
      case 2:
        if ( !file->isDir() )
          return;
        break;
      case 3:
        if ( !file->isLink() )
          return;
        break;
      case 4:
        if ( !S_ISCHR ( file->mode() ) && !S_ISBLK ( file->mode() ) &&
              !S_ISFIFO( file->mode() ) && !S_ISSOCK( file->mode() ) )
              return;
        break;
      case 5: // binary
        if ( (file->permissions() & 0111) != 0111 || file->isDir() )
          return;
        break;
      case 6: // suid
        if ( (file->permissions() & 04000) != 04000 ) // fixme
          return;
        break;
      default:
        if (!m_mimetype.isEmpty() && !m_mimetype.contains(file->mimetype()))
          return;
    }

    // match datas in metainfo...
    if ((!m_metainfo.isEmpty())  && (!m_metainfokey.isEmpty()))
    {
       bool foundmeta=false;
       QString filename = file->url().path();

       if(filename.startsWith("/dev/"))
          return;

       KFileMetaInfo metadatas(filename);
       KFileMetaInfoItem metaitem;
       QStringList metakeys;
       QString strmetakeycontent;

       if(metadatas.isEmpty())
          return;

       metakeys=metadatas.supportedKeys();
       for ( QStringList::Iterator it = metakeys.begin(); it != metakeys.end(); ++it )
       {
          if (!metaKeyRx->exactMatch(*it))
             continue;
          metaitem=metadatas.item(*it);
          strmetakeycontent=metaitem.string();
          if(strmetakeycontent.find(m_metainfo)!=-1)
          {
             foundmeta=true;
             break;
          }
       }
       if (!foundmeta)
          return;
    }

    // match contents...
    QString matchingLine;
    if (!m_context.isEmpty())
    {

       if( !m_search_binary && ignore_mimetypes.findIndex(file->mimetype()) != -1 ) {
         kdDebug() << "ignoring, mime type is in exclusion list: " << file->url() << endl;
         return;
       }

       bool found = false;
       bool isZippedOfficeDocument=false;
       int matchingLineNumber=0;

       // FIXME: doesn't work with non local files

       QString filename;
       QTextStream* stream=0;
       QFile qf;
       QRegExp xmlTags;
       QByteArray zippedXmlFileContent;

       // KWord's and OpenOffice.org's files are zipped...
       if( ooo_mimetypes.findIndex(file->mimetype()) != -1 ||
           koffice_mimetypes.findIndex(file->mimetype()) != -1 )
       {
         KZip zipfile(file->url().path());
         KZipFileEntry *zipfileEntry;

         if(zipfile.open(IO_ReadOnly))
         {
           const KArchiveDirectory *zipfileContent = zipfile.directory();

           if( koffice_mimetypes.findIndex(file->mimetype()) != -1 )
             zipfileEntry = (KZipFileEntry*)zipfileContent->entry("maindoc.xml");
           else
             zipfileEntry = (KZipFileEntry*)zipfileContent->entry("content.xml"); //for OpenOffice.org

           if(!zipfileEntry) {
             kdWarning() << "Expected XML file not found in ZIP archive " << file->url() << endl;
             return;
           }

           zippedXmlFileContent = zipfileEntry->data();
           xmlTags.setPattern("<.*>");
           xmlTags.setMinimal(true);
           stream = new QTextStream(zippedXmlFileContent, IO_ReadOnly);
           stream->setEncoding(QTextStream::UnicodeUTF8);
           isZippedOfficeDocument = true;
         } else {
           kdWarning() << "Cannot open supposed ZIP file " << file->url() << endl;
         }
       } else if( !m_search_binary && !file->mimetype().startsWith("text/") &&
           file->url().isLocalFile() ) {
         KMimeType::Format f = KMimeType::findFormatByFileContent(file->url().path());
         if ( !f.text ) {
           kdDebug() << "ignoring, not a text file: " << file->url() << endl;
           return;
         }
       }

       if(!isZippedOfficeDocument) //any other file or non-compressed KWord
       {
         filename = file->url().path();
         if(filename.startsWith("/dev/"))
            return;
         qf.setName(filename);
         qf.open(IO_ReadOnly);
         stream=new QTextStream(&qf);
         stream->setEncoding(QTextStream::Locale);
       }

       while ( ! stream->atEnd() )
       {
          QString str = stream->readLine();
          matchingLineNumber++;

          if (str.isNull()) break;
          if(isZippedOfficeDocument)
            str.replace(xmlTags, "");

          if (m_regexpForContent)
          {
             if (m_regexp.search(str)>=0)
             {
                matchingLine=QString::number(matchingLineNumber)+": "+str;
                found = true;
                break;
             }
          }
          else
          {
             if (str.find(m_context, 0, m_casesensitive) != -1)
             {
                matchingLine=QString::number(matchingLineNumber)+": "+str;
                found = true;
                break;
             }
          }
          kapp->processEvents();
       }
       delete stream;

       if (!found)
          return;
    }
    emit addFile(file,matchingLine);
}
Example #17
0
bool TWScript::doParseHeader(const QString& beginComment, const QString& endComment,
							 const QString& Comment, bool skipEmpty /* = true */)
{
	QFile file(m_Filename);
	QStringList lines;
	QString line;
	bool codecChanged = true;
	bool success = false;
	QTextCodec* codec;

	if (!file.exists() || !file.open(QIODevice::ReadOnly))
		return false;
	
	m_Codec = QTextCodec::codecForName("UTF-8");
	if (!m_Codec)
		m_Codec = QTextCodec::codecForLocale();

	while (codecChanged) {
		codec = m_Codec;
		file.seek(0);
		lines = codec->toUnicode(file.readAll()).split(QRegExp("\r\n|[\n\r]"));
	
		// skip any empty lines
		if (skipEmpty) {
			while (!lines.isEmpty() && lines.first().isEmpty())
				lines.removeFirst();
		}
		if (lines.isEmpty())
			break;
	
		// is this a valid TW script?
		line = lines.takeFirst();
		if (!beginComment.isEmpty()) {
			if (!line.startsWith(beginComment))
				break;
			line = line.mid(beginComment.size()).trimmed();
		}
		else if (!Comment.isEmpty()) {
			if (!line.startsWith(Comment))
				break;
			line = line.mid(Comment.size()).trimmed();
		}
		if (!line.startsWith("TeXworksScript"))
			break;
	
		// scan to find the extent of the header lines
		QStringList::iterator i;
		for (i = lines.begin(); i != lines.end(); ++i) {
			// have we reached the end?
			if (skipEmpty && i->isEmpty()) {
				i = lines.erase(i);
				--i;
				continue;
			}
			if (!endComment.isEmpty()) {
				if (i->startsWith(endComment))
					break;
			}
			if (!i->startsWith(Comment))
				break;
			*i = i->mid(Comment.size()).trimmed();
		}
		lines.erase(i, lines.end());
		
		codecChanged = false;
		switch (doParseHeader(lines)) {
			case ParseHeader_OK:
				success = true;
				break;
			case ParseHeader_Failed:
				success = false;
				break;
			case ParseHeader_CodecChanged:
				codecChanged = true;
				break;
		}
	}
	
	file.close();
	return success;
}
Example #18
0
bool CachedProvider::storeInCache(const QString &identifier, const QImage &comic, const Settings &info)
{
    const QString path = identifierToPath(identifier);

    int index = identifier.indexOf(QLatin1Char(':'));
    const QString comicName = identifier.mid(0, index);
    const QString pathMain = identifierToPath(comicName);
    const QString dirPath = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1String("/plasma_engine_comic/") ;

    if (!info.isEmpty()) {
        QSettings settings(path + QLatin1String(".conf"), QSettings::IniFormat);
        QSettings settingsMain(pathMain + QLatin1String(".conf"), QSettings::IniFormat);

        for (Settings::const_iterator i = info.constBegin(); i != info.constEnd(); ++i) {
                if ((i.key() == QLatin1String("firstStripIdentifier")) || (i.key() == QLatin1String("title")) ||
                     (i.key() == QLatin1String("lastCachedStripIdentifier")) || (i.key() == QLatin1String("suffixType")) ||
                     (i.key() == QLatin1String("shopUrl")) || (i.key() == QLatin1String("isLeftToRight")) ||
                     (i.key() == QLatin1String("isTopToBottom"))) {
                    settingsMain.setValue(i.key(), i.value());
                } else {
                    settings.setValue(i.key(), i.value());
                }
        }

        QStringList comics;
        if (settingsMain.contains(QLatin1String("comics"))) {
            comics = settingsMain.value(QLatin1String("comics"), QStringList()).toStringList();
        } else {
            //existing strips haven't been stored in the conf-file yet, do that now, oldest first, newest last
            QDir dir(dirPath);
            comics = dir.entryList(QStringList() << QUrl::toPercentEncoding(comicName + ':') + '*', QDir::Files, QDir::Time | QDir::Reversed);
            QStringList::iterator it = comics.begin();
            while (it != comics.end()) {
                //only count images, not the conf files
                if ((*it).endsWith(QLatin1String(".conf"))) {
                    it = comics.erase(it);
                } else {
                    ++it;
                }
            }
        }
        comics.append(QUrl::toPercentEncoding(identifier));

        const int limit = CachedProvider::maxComicLimit();
        //limit is on
        if (limit > 0) {
            qDebug() << QLatin1String("MaxComicLimit on.");
            int comicsToRemove = comics.count() - limit;
            QStringList::iterator it = comics.begin();
            while (comicsToRemove > 0 && it != comics.end()) {
                qDebug() << QLatin1String("Remove file") << (dirPath + (*it));
                QFile::remove(dirPath + (*it));
                QFile::remove(dirPath + (*it) + QLatin1String(".conf"));
                it = comics.erase(it);
                -- comicsToRemove;
            }
        }
        settingsMain.setValue(QLatin1String("comics"), comics);
    }

    return comic.save(path, "PNG");
}
void SpellHighlighter::removeHighlight(int stand_alone)
// removes all misspel highlilighting from text, puts it back to edit field
// QEdit will merge spans with similuar stiles by itself.
// stand_alone == 0 when it is called as a part of rehighlight;
// == 1 when it is called separately, and should avoid onchange infinite loop by itself
{
  if (textEdit()->textFormat()!=RichText) return; // For RichText edit fields only ;-)
  if (!stand_alone || ( stand_alone && ! m_isInRehighlight))
  {
    if (stand_alone) m_isInRehighlight = 1;
    QString txt = textEdit()->text();

//    SIM::log(SIM::L_DEBUG, "SpellHighlighter::removeHlight: src text: %s",txt.utf8().data());

    QString new_txt = "";
    QString tag = QString::null;
    for(int i=0;i<txt.length();i++)
    {
      if (tag) tag+=txt[i];
      if (txt[i] == '<')
      {
        tag = txt[i];
      }
      if (! tag) new_txt += txt[i];
      if (tag && txt[i] == '>')
      {
        if (tag.find(QRegExp("^\\<span\\ style=\""),0)==0)
        {
//          SIM::log(SIM::L_DEBUG, "styletag: %s\n",tag.data());
          QString s = tag;
          s.replace(QRegExp("^\\<span\\ style=\"(.*)\">"),"\\1");
          QStringList items = QStringList::split(";",s);
          for ( QStringList::Iterator it = items.begin(); it != items.end(); ++it )
          {
            QString style_item = *it;
            if (style_item.find(QRegExp("^font\\-family\\:sim-im-misspelled\\|"))>-1)
            {
//              SIM::log(SIM::L_DEBUG, "found: %s\n",style_item.data());
              style_item.replace(QRegExp("^font\\-family\\:sim-im-misspelled\\|(.*)$"),"\\1");
              style_item.replace("|",";");
              tag= "<span style =\""+ style_item+"\">";
            }
          }
        }
        new_txt +=tag;
        tag=QString::null;
      }
    }

//    SIM::log(SIM::L_DEBUG, "SpellHighlighter::removeHlight:  cleaned text: %s",new_txt.utf8().data());

    if (txt != new_txt)
    {
      int para;
      int index;
      int sel_paraFrom;
      int sel_indexFrom;
      int sel_paraTo;
      int sel_indexTo;

      textEdit()->getSelection (&sel_paraFrom, &sel_indexFrom, &sel_paraTo, &sel_indexTo);
      textEdit()->getCursorPosition ( &para, &index );

      textEdit()->setText(new_txt);

      textEdit()->setCursorPosition ( para, index );
      textEdit()->setSelection (sel_paraFrom, sel_indexFrom, sel_paraTo, sel_indexTo); 
    }
    if (stand_alone) m_isInRehighlight = 0;
  }
}
Example #20
0
QString KNMusicQQLyrics::downloadLyrics(const KNMusicDetailInfo &detailInfo)
{
    //Generate the url and get the data from the url.
    QString url="http://qqmusic.qq.com/fcgi-bin/qm_getLyricId.fcg?name="+
            processKeywordsToGBK(detailInfo.textLists[Name])+"&singer="+
            processKeywordsToGBK(detailInfo.textLists[Artist])+"&from=qqplayer";
    QByteArray responseData;
    get(url, responseData);
    //Check the response.
    if(responseData.isEmpty())
    {
        return QString();
    }
    //Tencent use GBK as default codec, translate the data to UTF-8, parse it
    //with DomDocument.
    QDomDocument xmlDoc;
    xmlDoc.setContent(m_gbkCodec->toUnicode(responseData));
    //To find whether it contains song info.
    QDomNodeList songInfoList=xmlDoc.elementsByTagName("songinfo");
    if(songInfoList.isEmpty())
    {
        return QString();
    }
    //Get the song id from the song info.
    QStringList songIDList;
    for(int i=0; i<songInfoList.length(); i++)
    {
        //Ensure the song info is available.
        QDomElement currentSongInfo=songInfoList.at(i).toElement();
        if(currentSongInfo.isNull())
        {
            continue;
        }
        //Ensure the id is not empty.
        QString currentID=currentSongInfo.attribute("id");
        if(!currentID.isEmpty())
        {
            songIDList.append(currentID);
        }
    }
    //Check if the song id is empty.
    if(songIDList.isEmpty())
    {
        return QString();
    }
    //Get the detail data for each song.
    for(QStringList::iterator i=songIDList.begin();
        i!=songIDList.end();
        ++i)
    {
        get(generateRequestString(*i), responseData);
        //Check the response data is empty or not.
        if(responseData.isEmpty())
        {
            continue;
        }
        //Parse the response data.
        QString xml_text=m_gbkCodec->toUnicode(responseData);
        xmlDoc.setContent(xml_text);
        //Find the lyrics.
        QDomNodeList lr=xmlDoc.elementsByTagName("lyric");
        if(lr.isEmpty())
        {
            continue;
        }
        QString lyricsContent=lr.at(0).childNodes().at(0).toText().data();
        if(lyricsContent.isEmpty())
        {
            continue;
        }
        //Write the lyrics and return the file name.
        return writeLyricsFile(detailInfo, lyricsContent);
    }
    return QString();
}
Example #21
0
ExternalTool * ExternalTool::createFromXml(const QByteArray &xml, QString *errorMessage, const QString &locale)
{
    int descriptionLocale = -1;
    int nameLocale = -1;
    int categoryLocale = -1;
    const QStringList &locales = splitLocale(locale);
    auto tool = new ExternalTool;
    QXmlStreamReader reader(xml);

    if (!reader.readNextStartElement() || reader.name() != kExternalTool)
        reader.raiseError("Missing start element <externaltool>");
    tool->m_id = reader.attributes().value(kId).toString();
    if (tool->m_id.isEmpty())
        reader.raiseError("Missing or empty id attribute for <externaltool>");
    while (reader.readNextStartElement()) {
        if (reader.name() == kDescription) {
            localizedText(locales, &reader, &descriptionLocale, &tool->m_description);
        } else if (reader.name() == kDisplayName) {
            localizedText(locales, &reader, &nameLocale, &tool->m_displayName);
        } else if (reader.name() == kCategory) {
            localizedText(locales, &reader, &categoryLocale, &tool->m_displayCategory);
        } else if (reader.name() == kOrder) {
            if (tool->m_order >= 0) {
                reader.raiseError("only one <order> element allowed");
                break;
            }
            bool ok;
            tool->m_order = reader.readElementText().toInt(&ok);
            if (!ok || tool->m_order < 0)
                reader.raiseError("<order> element requires non-negative integer value");
        } else if (reader.name() == kExecutable) {
            if (reader.attributes().hasAttribute(kOutput)) {
                if (!parseOutputAttribute(kOutput, &reader, &tool->m_outputHandling))
                    break;
            }
            if (reader.attributes().hasAttribute(kError)) {
                if (!parseOutputAttribute(kError, &reader, &tool->m_errorHandling))
                    break;
            }
            if (reader.attributes().hasAttribute(kModifiesDocument)) {
                const QStringRef value = reader.attributes().value(kModifiesDocument);
                if (value == kYes || value == kTrue) {
                    tool->m_modifiesCurrentDocument = true;
                } else if (value == kNo || value == kFalse) {
                    tool->m_modifiesCurrentDocument = false;
                } else {
                    reader.raiseError("Allowed values for modifiesdocument attribute are 'yes','true','no','false'");
                    break;
                }
            }
            while (reader.readNextStartElement()) {
                if (reader.name() == kPath) {
                    tool->m_executables.append(reader.readElementText());
                } else if (reader.name() == kArguments) {
                    if (!tool->m_arguments.isEmpty()) {
                        reader.raiseError("only one <arguments> element allowed");
                        break;
                    }
                    tool->m_arguments = reader.readElementText();
                } else if (reader.name() == kInput) {
                    if (!tool->m_input.isEmpty()) {
                        reader.raiseError("only one <input> element allowed");
                        break;
                    }
                    tool->m_input = reader.readElementText();
                } else if (reader.name() == kWorkingDirectory) {
                    if (!tool->m_workingDirectory.isEmpty()) {
                        reader.raiseError("only one <workingdirectory> element allowed");
                        break;
                    }
                    tool->m_workingDirectory = reader.readElementText();
                } else if (reader.name() == kBaseEnvironmentId) {
                    if (tool->m_baseEnvironmentProviderId.isValid()) {
                        reader.raiseError("only one <baseEnvironmentId> element allowed");
                        break;
                    }
                    tool->m_baseEnvironmentProviderId = Id::fromString(reader.readElementText());
                } else if (reader.name() == kEnvironment) {
                    if (!tool->m_environment.isEmpty()) {
                        reader.raiseError("only one <environment> element allowed");
                        break;
                    }
                    QStringList lines = reader.readElementText().split(QLatin1Char(';'));
                    for (auto iter = lines.begin(); iter != lines.end(); ++iter)
                        *iter = QString::fromUtf8(QByteArray::fromPercentEncoding(iter->toUtf8()));
                    tool->m_environment = EnvironmentItem::fromStringList(lines);
                } else {
                    reader.raiseError(QString::fromLatin1("Unknown element <%1> as subelement of <%2>").arg(
                                          reader.qualifiedName().toString(), kExecutable));
                    break;
                }
            }
        } else {
            reader.raiseError(QString::fromLatin1("Unknown element <%1>").arg(reader.qualifiedName().toString()));
        }
    }
    if (reader.hasError()) {
        if (errorMessage)
            *errorMessage = reader.errorString();
        delete tool;
        return nullptr;
    }
    return tool;
}
Example #22
0
QMap<QString, QString> proFileTagMap( const QString& text )
{
    QString t = text;
    QMap<QString, QString> tagMap;
    bool stillProcess = true; // If include() has a $$tag then we need to reprocess
    
    while(stillProcess) {

	/* 
	    Strip any commments before we try to include.  We
	    still need to do it after we include to make sure the
	    included file does not have comments
	*/
	t.replace( QRegExp(QString("#[^\n]*\n")), QString(" ") );

	/*
	    Process include() commands.
	    $$PWD is a special case so we have to change it while 
	    we know where the included file is.
        */
	QRegExp callToInclude("include\\s*\\(\\s*([^()\\s]+)\\s*\\)");
	int i = 0;
	while ( (i = callToInclude.search(t, i)) != -1 ) {
	    bool doneWithVar = false;
	    QString fileName = callToInclude.cap(1);
	    QString after = fileName.replace("$$PWD", QDir::currentDirPath());
	    if (!tagMap.isEmpty() && after.contains("$$")) {
		QRegExp var( "\\$\\$[({]?([a-zA-Z0-9_]+)[)}]?" );
		int ii = 0;
		while ((ii = after.find(var, ii)) != -1) {
		    if (tagMap.contains(var.cap(1))) {
			after.replace(ii, var.cap(0).length(), tagMap[var.cap(1)]);
		    } else { // Couldn't find it
			doneWithVar = true;
			break;
		    }
		}
		
	    }
	    if (doneWithVar || !after.contains("$$")) {
		after = loadFile(after);
		QFileInfo fi(callToInclude.cap(1));
		after.replace("$$PWD", fi.dirPath());
		t.replace( i, callToInclude.matchedLength(), after );
	    }
	    i += after.length();
	}

	/*
	    Strip comments, merge lines ending with backslash, add
	    spaces around '=' and '+=', replace '\n' with ';', and
	    simplify white spaces.
	*/
	t.replace( QRegExp(QString("#[^\n]*\n")), QString(" ") );
	t.replace( QRegExp(QString("\\\\[^\n\\S]*\n")), QString(" ") );
	t.replace( "=", QString(" = ") );
	t.replace( "+ =", QString(" += ") );
	t.replace( "\n", QString(";") );
	t = t.simplifyWhiteSpace();
	
	/*
	    Populate tagMap with 'key = value' entries.
	*/
	QStringList lines = QStringList::split( QChar(';'), t );
	QStringList::Iterator line;
	for ( line = lines.begin(); line != lines.end(); ++line ) {
	    QStringList toks = QStringList::split( QChar(' '), *line );
	    
	    if ( toks.count() >= 3 && 
		(toks[1] == QString("=") || toks[1] == QString("+=")) ) {
		QString tag = toks.first();
		int k = tag.findRev( QChar(':') ); // as in 'unix:'
		if ( k != -1 )
		    tag = tag.mid( k + 1 );
		toks.remove( toks.begin() );
		
		QString action = toks.first();
		toks.remove( toks.begin() );
		
		if ( tagMap.contains(tag) ) {
		    if ( action == QString("=") )
			tagMap.replace( tag, toks.join(QChar(' ')) );
		    else
			tagMap[tag] += QChar( ' ' ) + toks.join( QChar(' ') );
		} else {
		    tagMap[tag] = toks.join( QChar(' ') );
		}
	    }
	}
	
	/*
	    Expand $$variables within the 'value' part of a 'key = value'
	    pair.
	*/
	QRegExp var( "\\$\\$[({]?([a-zA-Z0-9_]+)[)}]?" );
	QMap<QString, QString>::Iterator it;
	for ( it = tagMap.begin(); it != tagMap.end(); ++it ) {
	    int i = 0;
	    while ( (i = var.search((*it), i)) != -1 ) {
		int len = var.matchedLength();
		QString invocation = var.cap(1);
		QString after;
		
		if ( invocation == "system" ) {
		    // skip system(); it will be handled in the next pass
		    ++i;
		} else {
		    if ( tagMap.contains(invocation) )
			after = tagMap[invocation];
		    else if (invocation.lower() == "pwd")
			after = QDir::currentDirPath();
		    (*it).replace( i, len, after );
		    i += after.length();
		}
	    }
	}
    
	/*
	  Execute system() calls.
	*/
	QRegExp callToSystem( "\\$\\$system\\s*\\(([^()]*)\\)" );
	for ( it = tagMap.begin(); it != tagMap.end(); ++it ) {
	    int i = 0;
	    while ( (i = callToSystem.search((*it), i)) != -1 ) {
		/*
		  This code is stolen from qmake's project.cpp file.
		  Ideally we would use the same parser, so we wouldn't
		  have this code duplication.
		*/
		QString after;
		char buff[256];
		FILE *proc = QT_POPEN( callToSystem.cap(1).latin1(), "r" );
		while ( proc && !feof(proc) ) {
		    int read_in = (int)fread( buff, 1, 255, proc );
		    if ( !read_in )
			break;
		    for ( int i = 0; i < read_in; i++ ) {
			if ( buff[i] == '\n' || buff[i] == '\t' )
			    buff[i] = ' ';
		    }
		    buff[read_in] = '\0';
		    after += buff;
		}
		(*it).replace( i, callToSystem.matchedLength(), after );
		i += after.length();
	    }
	}
	stillProcess = callToInclude.search(t) != -1;
    }
    return tagMap;
}
Example #23
0
/******************************************************************************
* Read preference values from the config file.
*/
void Preferences::read()
{
    initialise();

    KConfig *config = KGlobal::config();
    config->setGroup(GENERAL_SECTION);
    QStringList cols = config->readListEntry(MESSAGE_COLOURS);
    if(!cols.count())
        mMessageColours = default_messageColours;
    else
    {
        mMessageColours.clear();
        for(QStringList::Iterator it = cols.begin();  it != cols.end();  ++it)
        {
            QColor c((*it));
            if(c.isValid())
                mMessageColours.insert(c);
        }
    }
    mDefaultBgColour          = config->readColorEntry(MESSAGE_BG_COLOUR, &default_defaultBgColour);
    mMessageFont              = config->readFontEntry(MESSAGE_FONT, &mDefault_messageFont);
    mRunInSystemTray          = config->readBoolEntry(RUN_IN_SYSTEM_TRAY, default_runInSystemTray);
    mDisableAlarmsIfStopped   = config->readBoolEntry(DISABLE_IF_STOPPED, default_disableAlarmsIfStopped);
    mAutostartTrayIcon        = config->readBoolEntry(AUTOSTART_TRAY, default_autostartTrayIcon);
    mModalMessages            = config->readBoolEntry(MODAL_MESSAGES, default_modalMessages);
    mMessageButtonDelay       = config->readNumEntry(MESSAGE_BUTTON_DELAY, default_messageButtonDelay);
    if(mMessageButtonDelay > 10)
        mMessageButtonDelay = 10;    // prevent windows being unusable for a long time
    if(mMessageButtonDelay < -1)
        mMessageButtonDelay = -1;
    mTooltipAlarmCount        = static_cast<int>(config->readUnsignedNumEntry(TOOLTIP_ALARM_COUNT, default_tooltipAlarmCount));
    if(mTooltipAlarmCount < 1)
        mTooltipAlarmCount = 1;
    mShowTooltipAlarmTime     = config->readBoolEntry(TOOLTIP_ALARM_TIME, default_showTooltipAlarmTime);
    mShowTooltipTimeToAlarm   = config->readBoolEntry(TOOLTIP_TIME_TO_ALARM, default_showTooltipTimeToAlarm);
    mTooltipTimeToPrefix      = config->readEntry(TOOLTIP_TIME_TO_PREFIX, default_tooltipTimeToPrefix);
    mDaemonTrayCheckInterval  = static_cast<int>(config->readUnsignedNumEntry(DAEMON_TRAY_INTERVAL, default_daemonTrayCheckInterval));
    if(mDaemonTrayCheckInterval < 1)
        mDaemonTrayCheckInterval = 1;
    QCString client           = config->readEntry(EMAIL_CLIENT,
                                defaultEmailClient).local8Bit();  // don't use readPathEntry() here (values are hard-coded)
    mEmailClient              = (client == "sendmail" ? SENDMAIL : KMAIL);
    mEmailCopyToKMail         = config->readBoolEntry(EMAIL_COPY_TO_KMAIL, default_emailCopyToKMail);
    QString from              = config->readEntry(EMAIL_FROM, emailFrom(default_emailFrom(), false, false));
    mEmailFrom                = emailFrom(from);
    QString bccFrom           = config->readEntry(EMAIL_BCC_ADDRESS, emailFrom(default_emailBccFrom, false, true));
    mEmailBccFrom             = emailFrom(bccFrom);
    if(mEmailFrom == MAIL_FROM_CONTROL_CENTRE  ||  mEmailBccFrom == MAIL_FROM_CONTROL_CENTRE)
        mEmailAddress = mEmailBccAddress = KAMail::controlCentreAddress();
    if(mEmailFrom == MAIL_FROM_ADDR)
        mEmailAddress     = from;
    if(mEmailBccFrom == MAIL_FROM_ADDR)
        mEmailBccAddress  = bccFrom;
    mCmdXTermCommand          = translateXTermPath(config, config->readEntry(CMD_XTERM_COMMAND), false);
    QDateTime defStartOfDay(QDate(1900, 1, 1), default_startOfDay);
    mStartOfDay               = config->readDateTimeEntry(START_OF_DAY, &defStartOfDay).time();
    mOldStartOfDay.setHMS(0, 0, 0);
    int sod = config->readNumEntry(START_OF_DAY_CHECK, 0);
    if(sod)
        mOldStartOfDay    = mOldStartOfDay.addMSecs(sod ^ SODxor);
    mDisabledColour           = config->readColorEntry(DISABLED_COLOUR, &default_disabledColour);
    mExpiredColour            = config->readColorEntry(EXPIRED_COLOUR, &default_expiredColour);
    mExpiredKeepDays          = config->readNumEntry(EXPIRED_KEEP_DAYS, default_expiredKeepDays);

    config->setGroup(DEFAULTS_SECTION);
    mDefaultLateCancel        = static_cast<int>(config->readUnsignedNumEntry(DEF_LATE_CANCEL, default_defaultLateCancel));
    mDefaultAutoClose         = config->readBoolEntry(DEF_AUTO_CLOSE, default_defaultAutoClose);
    mDefaultConfirmAck        = config->readBoolEntry(DEF_CONFIRM_ACK, default_defaultConfirmAck);
    mDefaultCopyToKOrganizer  = config->readBoolEntry(DEF_COPY_TO_KORG, default_defaultCopyToKOrganizer);
    int soundType             = config->readNumEntry(DEF_SOUND_TYPE, default_defaultSoundType);
    mDefaultSoundType         = (soundType < 0 || soundType > SoundPicker::SPEAK)
                                ? default_defaultSoundType : (SoundPicker::Type)soundType;
    mDefaultSoundVolume       = static_cast<float>(config->readDoubleNumEntry(DEF_SOUND_VOLUME, default_defaultSoundVolume));
#ifdef WITHOUT_ARTS
    mDefaultSoundRepeat       = false;
#else
    mDefaultSoundRepeat       = config->readBoolEntry(DEF_SOUND_REPEAT, default_defaultSoundRepeat);
#endif
    mDefaultSoundFile         = config->readPathEntry(DEF_SOUND_FILE);
    mDefaultCmdScript         = config->readBoolEntry(DEF_CMD_SCRIPT, default_defaultCmdScript);
    int logType               = config->readNumEntry(DEF_CMD_LOG_TYPE, default_defaultCmdLogType);
    mDefaultCmdLogType        = (logType < EditAlarmDlg::DISCARD_OUTPUT || logType > EditAlarmDlg::EXEC_IN_TERMINAL)
                                ? default_defaultCmdLogType : (EditAlarmDlg::CmdLogType)logType;
    mDefaultCmdLogFile        = config->readPathEntry(DEF_LOG_FILE);
    mDefaultEmailBcc          = config->readBoolEntry(DEF_EMAIL_BCC, default_defaultEmailBcc);
    int recurPeriod           = config->readNumEntry(DEF_RECUR_PERIOD, default_defaultRecurPeriod);
    mDefaultRecurPeriod       = (recurPeriod < RecurrenceEdit::SUBDAILY || recurPeriod > RecurrenceEdit::ANNUAL)
                                ? default_defaultRecurPeriod : (RecurrenceEdit::RepeatType)recurPeriod;
    QCString feb29            = config->readEntry(FEB29_RECUR_TYPE, defaultFeb29RecurType).local8Bit();
    mDefaultFeb29Type         = (feb29 == "Mar1") ? KARecurrence::FEB29_MAR1 : (feb29 == "Feb28") ? KARecurrence::FEB29_FEB28 : KARecurrence::FEB29_FEB29;
    QString remindUnits       = config->readEntry(DEF_REMIND_UNITS);
    mDefaultReminderUnits     = (remindUnits == QString::fromLatin1("Minutes"))      ? TimePeriod::MINUTES
                                : (remindUnits == QString::fromLatin1("HoursMinutes")) ? TimePeriod::HOURS_MINUTES
                                : (remindUnits == QString::fromLatin1("Days"))         ? TimePeriod::DAYS
                                : (remindUnits == QString::fromLatin1("Weeks"))        ? TimePeriod::WEEKS : default_defaultReminderUnits;
    mDefaultPreAction         = config->readEntry(DEF_PRE_ACTION, default_defaultPreAction);
    mDefaultPostAction        = config->readEntry(DEF_POST_ACTION, default_defaultPostAction);
    mInstance->emitPreferencesChanged();
    mStartOfDayChanged = (mStartOfDay != mOldStartOfDay);
    if(mStartOfDayChanged)
    {
        mInstance->emitStartOfDayChanged();
        mOldStartOfDay = mStartOfDay;
    }
}
Example #24
0
bool LoaderWindow::openFile(QString pfilename)
{
  fileNew();
  
  QFileInfo fi(pfilename);
  if (fi.filePath().isEmpty())
    return false;
    
  QByteArray data = gunzipFile(fi.filePath());
  if(data.isEmpty())
  {
    QMessageBox::warning(this, tr("Error Opening File"),
                         tr("<p>The file %1 appears to be empty or it is not "
                            "compressed in the expected format.")
                         .arg(fi.filePath()));
    return false;
  }

  _files = new TarFile(data);
  if(!_files->isValid())
  {
    QMessageBox::warning(this, tr("Error Opening file"),
                         tr("<p>The file %1 does not appear to contain a valid "
                            "update package (not a valid TAR file?).")
                         .arg(fi.filePath()));
    delete _files;
    _files = 0;
    return false;
  }

  // find the content file
  QStringList list = _files->_list.keys();
  QString contentFile = QString::null;
  QStringList contentsnames;
  contentsnames << "package.xml" << "contents.xml";
  for (int i = 0; i < contentsnames.size() && contentFile.isNull(); i++)
  {
    QRegExp re(".*" + contentsnames.at(i) + "$");
    for(QStringList::Iterator mit = list.begin(); mit != list.end(); ++mit)
    {
      if(re.exactMatch(*mit))
      {
        if(!contentFile.isNull())
        {
          QMessageBox::warning(this, tr("Error Opening file"),
                               tr("<p>Multiple %1 files found in %2. "
                                  "Currently only packages containing a single "
                                  "content.xml file are supported.")
                               .arg(contentsnames.at(i)).arg(fi.filePath()));
          delete _files;
          _files = 0;
          return false;
        }
        contentFile = *mit;
      }
    }
  }

  QStringList msgList;
  QList<bool> fatalList;

  if(contentFile.isNull())
  {
    QMessageBox::warning(this, tr("Error Opening file"),
                         tr("<p>No %1 file was found in package %2.")
                         .arg(contentsnames.join(" or ")).arg(fi.filePath()));
    delete _files;
    _files = 0;
    return false;
  }
  else if (! contentFile.endsWith(contentsnames.at(0)))
  {
    qDebug("Deprecated Package Format: Packages for this version of "
           "the Updater should have their contents described by a file "
           "named %s. The current package being loaded uses an outdated "
           "file name %s.",
           qPrintable(contentsnames.at(0)), qPrintable(contentFile));
  }

  QByteArray docData = _files->_list[contentFile];
  QDomDocument doc;
  QString errMsg;
  int errLine, errCol;
  if(!doc.setContent(docData, &errMsg, &errLine, &errCol))
  {
    QMessageBox::warning(this, tr("Error Opening file"),
                         tr("<p>There was a problem reading the %1 file in "
                            "this package.<br>%2<br>Line %3, Column %4")
                         .arg(contentFile).arg(errMsg)
                         .arg(errLine).arg(errCol));
    delete _files;
    _files = 0;
    return false;
  }

  _text->clear();
  _text->setEnabled(true);

  QString delayedWarning;
  _package = new Package(doc.documentElement(), msgList, fatalList);
  if (msgList.size() > 0)
  {
    bool fatal = false;
    if (DEBUG)
      qDebug("LoaderWindow::fileOpen()  i fatal msg");
    for (int i = 0; i < msgList.size(); i++)
    {
      _text->append(QString("<br><font color=\"%1\">%2</font>")
                    .arg(fatalList.at(i) ? "red" : "orange")
                    .arg(msgList.at(i)));
      fatal = fatal || fatalList.at(i);
      if (DEBUG)
        qDebug("LoaderWindow::fileOpen() %2d %5d %s",
               i, fatalList.at(i), qPrintable(msgList.at(i)));
    }
    if (fatal)
    {
      _text->append(tr("<p><font color=\"red\">The %1 file appears "
                       "to be invalid.</font></p>").arg(contentFile));
      return false;
    }
    else
      delayedWarning = tr("<p><font color=\"orange\">The %1 file "
                          "seems to have problems. You should contact %2 "
                          "before proceeding.</font></p>")
                      .arg(contentFile)
                      .arg(_package->developer().isEmpty() ?
                           tr("the package developer") : _package->developer());
  }

  _pkgname->setText(tr("Package %1 (%2)").arg(_package->id()).arg(fi.filePath()));

  _progress->setValue(0);
  _progress->setMaximum(_files->_list.count() - 1);
  _progress->setEnabled(true);
  if (DEBUG)
    qDebug("LoaderWindow::fileOpen() progress initialized to max %d",
           _progress->maximum());

  _status->setEnabled(true);
  _status->setText(tr("<p><b>Checking Prerequisites!</b></p>"));
  _text->append("<p><b>Prerequisites</b>:<br>");
  bool allOk = true;
  // check prereqs
  QString str;
  QStringList strlist;
  QStringList::Iterator slit;
  XSqlQuery qry;
  for(QList<Prerequisite*>::iterator i = _package->_prerequisites.begin();
      i != _package->_prerequisites.end(); ++i)
  {
    _status->setText(tr("<p><b>Checking Prerequisites!</b></p><p>%1...</p>")
                       .arg((*i)->name()));
    _text->append(tr("%1").arg((*i)->name()));
    if (! (*i)->met(errMsg))
    {
      allOk = false;
      str = QString("<blockquote><font size=\"+1\" color=\"red\"><b>%1</b></font></blockquote>").arg(tr("Failed"));
      if (! errMsg.isEmpty())
       str += tr("<p>%1</p>").arg(errMsg);

      strlist = (*i)->providerList();
      if(strlist.count() > 0)
      {
        str += tr("<b>Requires:</b><br>");
        str += tr("<ul>");
        for(slit = strlist.begin(); slit != strlist.end(); ++slit)
          str += tr("<li>%1: %2</li>").arg((*i)->provider(*slit).package()).arg((*i)->provider(*slit).info());
        str += tr("</ul>");
      }
      
      str += tr("</blockquote>");
      _text->append(str);
      if (DEBUG)
        qDebug("%s", qPrintable(str));
    }
  }

  if(!allOk)
  {
    _status->setText(tr("<p><b>Checking Prerequisites!</b></p><p>One or more prerequisites <b>FAILED</b>. These prerequisites must be satisified before continuing.</p>"));
    return false;
  }

  _status->setText(tr("<p><b>Checking Prerequisites!</b></p><p>Check completed.</p>"));
  if (delayedWarning.isEmpty())
    _text->append(tr("<p><b><font color=\"green\">Ready to Start update!</font></b></p>"));
  else
  {
    _text->append(tr("<p><b>Ready to Start update!</b></p>"));
    _text->append(delayedWarning);
  }
  _text->append(tr("<p><b>NOTE</b>: Have you backed up your database? If not, you should "
                   "backup your database now. It is good practice to backup a database "
                   "before updating it.</p>"));

  /*
  single vs multiple transaction functionality was added at around the same
  time as OpenMFG/PostBooks 2.3.0 was being developed. before 2.3.0, update
  scripts from xTuple (OpenMFG, LLC) assumed multiple transactions (one per
  file within the package). take advantage of the update package naming
  conventions to see if we've been given a pre-2.3.0 file and *need* to use
  multiple transactions.
  */
  _premultitransfile = false;

  _start->setEnabled(true);
  return true;
}
Example #25
0
MainWindow::MainWindow()
    : MainWindowBase(0, "main window"),
      editPalette(palette()), previewPalette(palette()), previewstyle(0)
{
    modified = true;
    desktopThemeName = tr("Desktop Settings (Default)");
    setIcon(QPixmap(":/trolltech/qtconfig/images/appicon.png"));
    QStringList gstyles = QStyleFactory::keys();
    gstyles.sort();
    gstylecombo->addItem(desktopThemeName);
    gstylecombo->setItemData(gstylecombo->findText(desktopThemeName),
                                tr("Choose style and palette based on your desktop settings."), Qt::ToolTipRole);
    gstylecombo->insertStringList(gstyles);

    QSettings settings(QLatin1String("Trolltech"));
    settings.beginGroup(QLatin1String("Qt"));

    QString currentstyle = settings.value(QLatin1String("style")).toString();
    if (currentstyle.isEmpty()) {
        gstylecombo->setCurrentItem(gstylecombo->findText(desktopThemeName));
        currentstyle = QLatin1String(QApplication::style()->name());
    } else {
        int index = gstylecombo->findText(currentstyle, Qt::MatchFixedString);
        if (index != -1) {
            gstylecombo->setCurrentItem(index);
        } else { // we give up
            gstylecombo->insertItem(QLatin1String("Unknown"));
            gstylecombo->setCurrentItem(gstylecombo->count() - 1);
        }
    }
    buttonMainColor->setColor(palette().color(QPalette::Active,
                                              QColorGroup::Button));
    buttonMainColor2->setColor(palette().color(QPalette::Active,
                                               QColorGroup::Window));
    connect(buttonMainColor, SIGNAL(colorChanged(QColor)),
                this, SLOT(buildPalette()));
    connect(buttonMainColor2, SIGNAL(colorChanged(QColor)),
                this, SLOT(buildPalette()));

    if (X11->desktopEnvironment == DE_KDE)
        colorConfig->hide();
    else
        labelKDENote->hide();

    QFontDatabase db;
    QStringList families = db.families();
    familycombo->insertStringList(families);

    QStringList fs = families;
    QStringList fs2 = QFont::substitutions();
    QStringList::Iterator fsit = fs2.begin();
    while (fsit != fs2.end()) {
        if (! fs.contains(*fsit))
            fs += *fsit;
        fsit++;
    }
    fs.sort();
    familysubcombo->insertStringList(fs);

    choosesubcombo->insertStringList(families);
    Q3ValueList<int> sizes = db.standardSizes();
    Q3ValueList<int>::Iterator it = sizes.begin();
    while (it != sizes.end())
        psizecombo->insertItem(QString::number(*it++));

    dcispin->setValue(QApplication::doubleClickInterval());
    cfispin->setValue(QApplication::cursorFlashTime());
    wslspin->setValue(QApplication::wheelScrollLines());
    // #############
//    resolvelinks->setChecked(qt_resolve_symlinks);

    effectcheckbox->setChecked(QApplication::isEffectEnabled(Qt::UI_General));
    effectbase->setEnabled(effectcheckbox->isChecked());

    if (QApplication::isEffectEnabled(Qt::UI_FadeMenu))
        menueffect->setCurrentItem(2);
    else if (QApplication::isEffectEnabled(Qt::UI_AnimateMenu))
        menueffect->setCurrentItem(1);

    if (QApplication::isEffectEnabled(Qt::UI_AnimateCombo))
        comboeffect->setCurrentItem(1);

    if (QApplication::isEffectEnabled(Qt::UI_FadeTooltip))
        tooltipeffect->setCurrentItem(2);
    else if (QApplication::isEffectEnabled(Qt::UI_AnimateTooltip))
        tooltipeffect->setCurrentItem(1);

    if ( QApplication::isEffectEnabled( Qt::UI_AnimateToolBox ) )
        toolboxeffect->setCurrentItem( 1 );

    QSize globalStrut = QApplication::globalStrut();
    strutwidth->setValue(globalStrut.width());
    strutheight->setValue(globalStrut.height());

    // find the default family
    QStringList::Iterator sit = families.begin();
    int i = 0, possible = -1;
    while (sit != families.end()) {
        if (*sit == QApplication::font().family())
            break;
        if ((*sit).contains(QApplication::font().family()))
            possible = i;

        i++;
        sit++;
    }
    if (sit == families.end())
        i = possible;
    if (i == -1) // no clue about the current font
        i = 0;

    familycombo->setCurrentItem(i);

    QStringList styles = db.styles(familycombo->currentText());
    stylecombo->insertStringList(styles);

    QString stylestring = db.styleString(QApplication::font());
    sit = styles.begin();
    i = 0;
    possible = -1;
    while (sit != styles.end()) {
        if (*sit == stylestring)
            break;
        if ((*sit).contains(stylestring))
            possible = i;

        i++;
        sit++;
    }
    if (sit == styles.end())
        i = possible;
    if (i == -1) // no clue about the current font
        i = 0;
    stylecombo->setCurrentItem(i);

    i = 0;
    for (int psize = QApplication::font().pointSize(); i < psizecombo->count(); ++i) {
        const int sz = psizecombo->text(i).toInt();
        if (sz == psize) {
            psizecombo->setCurrentItem(i);
            break;
        } else if(sz > psize) {
            psizecombo->insertItem(i, QString::number(psize));
            psizecombo->setCurrentItem(i);
            break;
        }
    }

    QStringList subs = QFont::substitutes(familysubcombo->currentText());
    sublistbox->clear();
    sublistbox->insertStringList(subs);

    rtlExtensions->setChecked(settings.value(QLatin1String("useRtlExtensions"), false).toBool());

#ifdef Q_WS_X11
    inputStyle->setCurrentText(settings.value(QLatin1String("XIMInputStyle"), trUtf8("On The Spot")).toString());
#else
    inputStyle->hide();
    inputStyleLabel->hide();
#endif

#if defined(Q_WS_X11) && !defined(QT_NO_XIM)
    QStringList inputMethods = QInputContextFactory::keys();
    int inputMethodIndex = -1;
    QString defaultInputMethod = settings.value(QLatin1String("DefaultInputMethod"), QLatin1String("xim")).toString();
    for (int i = inputMethods.size()-1; i >= 0; --i) {
        const QString &im = inputMethods.at(i);
        if (im.contains(QLatin1String("imsw"))) {
            inputMethods.removeAt(i);
            if (inputMethodIndex > i)
                --inputMethodIndex;
        } else if (im == defaultInputMethod) {
            inputMethodIndex = i;
        }
    }
    if (inputMethodIndex == -1 && !inputMethods.isEmpty())
        inputMethodIndex = 0;
    inputMethod->addItems(inputMethods);
    inputMethod->setCurrentIndex(inputMethodIndex);
#else
    inputMethod->hide();
    inputMethodLabel->hide();
#endif

    fontembeddingcheckbox->setChecked(settings.value(QLatin1String("embedFonts"), true).toBool());
    fontpaths = settings.value(QLatin1String("fontPath")).toStringList();
    fontpathlistbox->insertStringList(fontpaths);

    audiosinkCombo->addItem(tr("Auto (default)"), QLatin1String("Auto"));
    audiosinkCombo->setItemData(audiosinkCombo->findText(tr("Auto (default)")),
                                tr("Choose audio output automatically."), Qt::ToolTipRole);
    audiosinkCombo->addItem(tr("aRts"), QLatin1String("artssink"));
    audiosinkCombo->setItemData(audiosinkCombo->findText(tr("aRts")),
                                tr("Experimental aRts support for GStreamer."), Qt::ToolTipRole);
#ifdef HAVE_PHONON
    phononVersionLabel->setText(QLatin1String(Phonon::phononVersion()));
#endif
#ifndef QT_NO_GSTREAMER
    if (gst_init_check(0, 0, 0)) {
        gchar *versionString = gst_version_string();
        gstversionLabel->setText(QLatin1String(versionString));
        g_free(versionString);
        GList* factoryList = gst_registry_get_feature_list(gst_registry_get_default (), GST_TYPE_ELEMENT_FACTORY);
        QString name, klass, description;
        for (GList* iter = g_list_first(factoryList) ; iter != NULL ; iter = g_list_next(iter)) {
            GstPluginFeature *feature = GST_PLUGIN_FEATURE(iter->data);
            klass = QLatin1String(gst_element_factory_get_klass(GST_ELEMENT_FACTORY(feature)));
            if (klass == QLatin1String("Sink/Audio")) {
                name = QLatin1String(GST_PLUGIN_FEATURE_NAME(feature));
                if (name == QLatin1String("sfsink"))
                    continue; //useless to output audio to file when you cannot set the file path
                else if (name == QLatin1String("autoaudiosink"))
                    continue; //This is used implicitly from the auto setting
                GstElement *sink = gst_element_factory_make (qPrintable(name), NULL);
                if (sink) {
                    description = QLatin1String(gst_element_factory_get_description (GST_ELEMENT_FACTORY(feature)));
                    audiosinkCombo->addItem(name, name);
                    audiosinkCombo->setItemData(audiosinkCombo->findText(name), description, Qt::ToolTipRole);
                    gst_object_unref (sink);
                }
            }
        }
        g_list_free(factoryList);
    }
#else
    tab4->setEnabled(false);
    phononLabel->setText(tr("Phonon GStreamer backend not available."));
#endif

    videomodeCombo->addItem(tr("Auto (default)"), QLatin1String("Auto"));
    videomodeCombo->setItemData(videomodeCombo->findText(tr("Auto (default)")), tr("Choose render method automatically"), Qt::ToolTipRole);
#ifdef Q_WS_X11
    videomodeCombo->addItem(tr("X11"), QLatin1String("X11"));
    videomodeCombo->setItemData(videomodeCombo->findText(tr("X11")), tr("Use X11 Overlays"), Qt::ToolTipRole);
#endif
#ifndef QT_NO_OPENGL
    videomodeCombo->addItem(tr("OpenGL"), QLatin1String("OpenGL"));
    videomodeCombo->setItemData(videomodeCombo->findText(tr("OpenGL")), tr("Use OpenGL if available"), Qt::ToolTipRole);
#endif
    videomodeCombo->addItem(tr("Software"), QLatin1String("Software"));
    videomodeCombo->setItemData(videomodeCombo->findText(tr("Software")), tr("Use simple software rendering"), Qt::ToolTipRole);

    QString audioSink = settings.value(QLatin1String("audiosink"), QLatin1String("Auto")).toString();
    QString videoMode = settings.value(QLatin1String("videomode"), QLatin1String("Auto")).toString();
    audiosinkCombo->setCurrentItem(audiosinkCombo->findData(audioSink));
    videomodeCombo->setCurrentItem(videomodeCombo->findData(videoMode));

    settings.endGroup(); // Qt

    helpview->setText(tr(appearance_text));

    setModified(false);
    updateStyleLayout();
}
Example #26
0
void KXNeurApp::refreshLang()
{
    QStringList lngs;
    xnkb->getGroupNames(lngs);
    QString lng;
    uint i;


    for ( i = 0 ; i < langs.count() ; i++ )
	trayicon->menu->removeItem(langs[i]->menuid);
    langs.clear();

    i = 0;
    langs.resize(lngs.count());

    for ( QStringList::Iterator iter = lngs.begin(); iter != lngs.end(); iter++, i++ ) {
	lng = *iter;
	QString code = all_langs->readEntry(lng);
	// printf("%s - %s\n", lng.latin1(), code.latin1());
	if ( code == QString::null ) {
	    langs.insert(i, new XNLang(i18n("* Unknown lang *")));
	    langs[i]->lg = QString::number(i);
	    langs[i]->supp_lg = -1;
	}
	else {
	    langs.insert(i, new XNLang(lng));
	    langs[i]->lg = code;
	    langs[i]->supp_lg = 0;
	}

	QPixmap pix(19, 16);
	QPainter painter(&pix);
	QFont font("helvetica", 9, QFont::Bold);
	font.setPixelSize(10);
	painter.setFont(font);
	if ( langs[i]->supp_lg >= 0 ) {
            painter.setPen(KGlobalSettings::highlightedTextColor());
            pix.fill(KGlobalSettings::highlightColor());
	    painter.drawText(1, 0, pix.width(), pix.height(), Qt::AlignHCenter | Qt::AlignVCenter, langs[i]->lg);
	}
	else {
	    pix.fill();
	    painter.drawText(0, 0, pix.width(), pix.height(), Qt::AlignHCenter | Qt::AlignVCenter, langs[i]->lg);
	}
	langs[i]->pic = pix;

    };

    for ( int j = 0 ; j < xnconf->total_languages ; j++ ) {
	QString code = all_langs->readEntry(xnconf->get_lang_name(xnconf, j));
	if ( code != QString::null ) {
	    QString path;
	    QPixmap pic;
	    for ( i = 0 ; i < langs.count() ; i++ ) {
		if ( code == langs[i]->lg ) {
		    langs[i]->name = xnconf->get_lang_name(xnconf, j);
		    langs[i]->supp_lg = 1;
		    break;
		}
	    }
	    path = locate("pixmap", langs[i]->name+".png");
	    if ( KXNeurSettings::ShowInTray() == SHOW_ICON && !path.isEmpty() ) {
	    // printf("show flag\n");
		pic.load(path);
		langs[i]->pic = pic;
	    }
	}
    }

    for ( i = 0 ; i < langs.count() ; i++ )
	langs[i]->menuid = trayicon->menu->insertItem(langs[i]->pic, langs[i]->name, i, i+1);
}
Example #27
0
bool DTVConfParser::ParseVDR(const QStringList &tokens, int channelNo)
{
    DTVChannelInfo chan;
    DTVMultiplex   mux;

    QStringList::const_iterator it = tokens.begin();

    chan.lcn = channelNo;

// BBC ONE:754166:I999B8C34D34M16T2G32Y0:T:27500:600:601, 602:0:0:4168:0:0:0

    PARSE_SKIP(unknown);

    PARSE_UINT_1000(mux.frequency);

    if (it == tokens.end())
        return false;

    QString params = (*it++);
    while (!params.isEmpty())
    {
        QString ori = params;
        int s = (int) (params.toAscii().constData()[0]);
        params = params.mid(1);
        switch (s)
        {
            case 'I':
                mux.inversion.ParseVDR(params);
                break;
            case 'B':
                mux.bandwidth.ParseVDR(params);
                break;
            case 'C':
                mux.hp_code_rate.ParseVDR(params);
                break;
            case 'D':
                mux.lp_code_rate.ParseVDR(params);
                break;
            case 'M':
                mux.modulation.ParseVDR(params);
                break;
            case 'T':
                mux.trans_mode.ParseVDR(params);
                break;
            case 'G':
                mux.guard_interval.ParseVDR(params);
                break;
            case 'Y':
                mux.hierarchy.ParseVDR(params);
                break;
            case 'V':
            case 'H':
            case 'R':
            case 'L':
                mux.polarity.ParseVDR(ori);
                break;
            case 'S':
                mux.mod_sys.ParseVDR(params);
                break;
            case 'O':
                mux.rolloff.ParseVDR(params);
                break;
            default:
                return false;
        }
    }

    for (uint i = 0; i < 6; i++)
        PARSE_SKIP(unknown);

    PARSE_UINT(chan.serviceid);

    AddChannel(mux, chan);

    return true;
}
Example #28
0
void EditFile::showFiles()
{
    QString s = edtFile->text();
#ifdef WIN32
    s.replace(QRegExp("\\\\"), "/");
#endif
    if (bDirMode){
        s = QFileDialog::getExistingDirectory(s, topLevelWidget(), title);
    }else if (bMultiplyMode){
        QStringList lst = QFileDialog::getOpenFileNames(filter, QString::null, topLevelWidget());
        if ((lst.count() > 1) || ((lst.count() > 0) && (lst[0].find(' ') >= 0))){
            for (QStringList::Iterator it = lst.begin(); it != lst.end(); ++it){
                *it = QString("\"") + *it + QString("\"");
            }
        }
        s = lst.join(" ");
    }else{
        if (s.isEmpty()){
            s = startDir;
            if (!s.isEmpty()){
                string d;
                d = QFile::encodeName(s);
                makedir((char*)d.c_str());
            }
        }
        if (createPreview){
            FileDialog *dlg = new FileDialog( s, filter, topLevelWidget(), title.isEmpty() ? i18n("Open") : title);
            if ( topLevelWidget()->icon() && !topLevelWidget()->icon()->isNull()){
                dlg->setIcon( *topLevelWidget()->icon() );
            }else if (qApp->mainWidget() && qApp->mainWidget()->icon() && !qApp->mainWidget()->icon()->isNull()){
                dlg->setIcon( *qApp->mainWidget()->icon() );
            }
            FilePreview *preview = createPreview(dlg);
#ifdef USE_KDE
            dlg->setOperationMode( KFileDialog::Opening);
            if (preview)
                dlg->setPreviewWidget(preview);
#else
            dlg->setMode( QFileDialog::ExistingFile );
            if (preview){
                dlg->setContentsPreview(preview, preview);
                dlg->setContentsPreviewEnabled(true);
                dlg->setPreviewMode(QFileDialog::Contents);
            }
#endif
            dlg->setFilter(filter);
            QString result;
            s = "";
            if (dlg->exec() == QDialog::Accepted){
                s = dlg->selectedFile();
            }
            // under KDE 3.1x / QT 3.1x sim crashes when preview is deleted...
            //            delete preview;
#ifdef WIN32
            delete preview;
#endif
            delete dlg;
        }else{
#ifdef USE_KDE
            if (bCreate){
                if (title.isEmpty()){
                    s = QFileDialog::getSaveFileName(s, filter, topLevelWidget());
                }else{
                    s = QFileDialog::getSaveFileName(s, filter, topLevelWidget(), title);
                }
            }else{
                if (title.isEmpty()){
                    s = QFileDialog::getOpenFileName(s, filter, topLevelWidget());
                }else{
                    s = QFileDialog::getOpenFileName(s, filter, topLevelWidget(), title);
                }
            }
#else
            if (bCreate){
                s = QFileDialog::getSaveFileName(s, filter, topLevelWidget(), "filedialog", title);
            }else{
                s = QFileDialog::getOpenFileName(s, filter, topLevelWidget(), "filedialog", title);
            }
#endif
        }
    }
#ifdef WIN32
    s.replace(QRegExp("/"), "\\");
#endif
    if (s.length()) edtFile->setText(s);
}
Example #29
0
int Playlist::CreateCDMP3(void)
{
    // Check & get global settings
    if (!gCoreContext->GetNumSetting("CDWriterEnabled"))
    {
        LOG(VB_GENERAL, LOG_ERR, "CD Writer is not enabled.");
        return 1;
    }

    QString scsidev = MediaMonitor::defaultCDWriter();
    if (scsidev.isEmpty())
    {
        LOG(VB_GENERAL, LOG_ERR, "No CD Writer device defined.");
        return 1;
    }

    int disksize = gCoreContext->GetNumSetting("CDDiskSize", 2);
    QString writespeed = gCoreContext->GetSetting("CDWriteSpeed", "2");
    bool MP3_dir_flag = gCoreContext->GetNumSetting("CDCreateDir", 1);

    double size_in_MB = 0.0;

    QStringList reclist;

    SongList::const_iterator it = songs.begin();
    for (; it != songs.end(); ++it)
    {
        if ((*it)->getCDFlag())
            continue;

        if ((*it)->getValue() == 0)
        {
            LOG(VB_GENERAL, LOG_ERR, kID0err);
        }
        else if ((*it)->getValue() > 0)
        {
            // Normal track
            Metadata *tmpdata =
                all_available_music->getMetadata((*it)->getValue());
            if (tmpdata)
            {
                // check filename..
                QFileInfo testit(tmpdata->Filename());
                if (!testit.exists())
                    continue;
                size_in_MB += testit.size() / 1000000.0;
                QString outline;
                if (MP3_dir_flag)
                {
                    if (tmpdata->Artist().length() > 0)
                        outline += tmpdata->Artist() + "/";
                    if (tmpdata->Album().length() > 0)
                        outline += tmpdata->Album() + "/";
                }

                outline += "=";
                outline += tmpdata->Filename();

                reclist += outline;
            }
        }
        else if ((*it)->getValue() < 0)
        {
            // FIXME: handle playlists
        }
    }

    int max_size;
    if (disksize == 0)
        max_size = 650;
    else
        max_size = 700;

    if (size_in_MB >= max_size)
    {
        LOG(VB_GENERAL, LOG_ERR, "MP3 CD creation aborted -- cd size too big.");
        return 1;
    }

    // probably should tie stdout of mkisofs to stdin of cdrecord sometime
    QString tmptemplate("/tmp/mythmusicXXXXXX");

    QString tmprecordlist = createTempFile(tmptemplate);
    if (tmprecordlist == tmptemplate)
    {
        LOG(VB_GENERAL, LOG_ERR, "Unable to open temporary file");
        return 1;
    }

    QString tmprecordisofs = createTempFile(tmptemplate);
    if (tmprecordisofs == tmptemplate)
    {
        LOG(VB_GENERAL, LOG_ERR, "Unable to open temporary file");
        return 1;
    }

    QFile reclistfile(tmprecordlist);

    if (!reclistfile.open(QIODevice::WriteOnly))
    {
        LOG(VB_GENERAL, LOG_ERR, "Unable to open temporary file");
        return 1;
    }

    QTextStream recstream(&reclistfile);

    QStringList::Iterator iter;

    for (iter = reclist.begin(); iter != reclist.end(); ++iter)
    {
        recstream << *iter << "\n";
    }

    reclistfile.close();

    progress = new MythProgressDialog(QObject::tr("Creating CD File System"),
                                      100);
    progress->setProgress(1);

    QStringList args;
    QString command;

    command = "mkisofs";
    args << "-graft-points";
    args << "-path-list";
    args << tmprecordlist;
    args << "-o";
    args << tmprecordisofs;
    args << "-J";
    args << "-R";

    uint flags = kMSRunShell | kMSStdErr | kMSBuffered |
                 kMSDontDisableDrawing | kMSDontBlockInputDevs | 
                 kMSRunBackground;

    proc = new MythSystem(command, args, flags);

    connect(proc, SIGNAL(readDataReady(int)), this, SLOT(mkisofsData(int)), 
            Qt::DirectConnection);
    connect(proc, SIGNAL(finished()),         this, SLOT(processExit()), 
            Qt::DirectConnection);
    connect(proc, SIGNAL(error(uint)),        this, SLOT(processExit(uint)), 
            Qt::DirectConnection);

    procExitVal = GENERIC_EXIT_RUNNING;
    proc->Run();

    while( procExitVal == GENERIC_EXIT_RUNNING )
        usleep( 100000 );

    uint retval = procExitVal;

    progress->Close();
    progress->deleteLater();
    proc->disconnect();
    delete proc;

    if (retval)
    {
        LOG(VB_GENERAL, LOG_ERR, QString("Unable to run mkisofs: returns %1")
                .arg(retval));
    }
    else
    {
        progress = new MythProgressDialog(QObject::tr("Burning CD"), 100);
        progress->setProgress(2);

        command = "cdrecord";
        args = QStringList();
        args << "-v";
        //args << "-dummy";
        args << QString("dev=%1").arg(scsidev);

        if (writespeed.toInt() > 0)
        {
            args << "-speed=";
            args << writespeed;
        }

        args << "-data";
        args << tmprecordisofs;

        flags = kMSRunShell | kMSStdErr | kMSStdOut | kMSBuffered |
                kMSDontDisableDrawing | kMSDontBlockInputDevs |
                kMSRunBackground;

        proc = new MythSystem(command, args, flags);
        connect(proc, SIGNAL(readDataReady(int)), 
                this, SLOT(cdrecordData(int)), Qt::DirectConnection);
        connect(proc, SIGNAL(finished()),
                this, SLOT(processExit()), Qt::DirectConnection);
        connect(proc, SIGNAL(error(uint)),
                this, SLOT(processExit(uint)), Qt::DirectConnection);
        procExitVal = GENERIC_EXIT_RUNNING;
        proc->Run();

        while( procExitVal == GENERIC_EXIT_RUNNING )
            usleep( 100000 );

        retval = procExitVal;

        progress->Close();
        progress->deleteLater();
        proc->disconnect();
        delete proc;

        if (retval)
        {
            LOG(VB_GENERAL, LOG_ERR,
                QString("Unable to run cdrecord: returns %1") .arg(retval));
        }
    }

    QFile::remove(tmprecordlist);
    QFile::remove(tmprecordisofs);

    return retval;
}
Example #30
0
void MultiValuesEdit::setData(const QStringList& data)
{
    d->dataList->clear();
    for (QStringList::const_iterator it = data.begin(); it != data.end(); ++it )
        d->dataList->addSqueezedItem(*it);
}