Example #1
2
void ViewerModel::processParsedData(ParseJobFiles* parser)
{
   Data::Bank& bank(parser->data());
   if (bank.isEmpty()) return;

   QString name(parser->name());

   // Determine if we need to replace an existing Molecule in the Model View.
   bool overwrite(parser->flags()  & ParseJobFiles::Overwrite);
   bool makeActive(parser->flags() & ParseJobFiles::MakeActive);
   bool addStar(parser->flags()    & ParseJobFiles::AddStar);
   bool found(false);

   Layer::Molecule* molecule(newMolecule());
   molecule->setCheckState(Qt::Unchecked);
   molecule->setText(name);
   molecule->appendData(bank);
   if (addStar) molecule->setIcon(QIcon(":/resources/icons/Favourites.png"));

   QStandardItem* child;
   QStandardItem* root(invisibleRootItem());

   void* moleculePointer(parser->moleculePointer());

   if (overwrite && moleculePointer) {
      for (int row = 0; row < root->rowCount(); ++row) {
          child = root->child(row);
          if (child->text() == name) {
             Layer::Base* base = QVariantPointer<Layer::Base>::toPointer(child->data());
             Layer::Molecule* mol = qobject_cast<Layer::Molecule*>(base);

             if (mol && mol == moleculePointer) {
                molecule->setCheckState(mol->checkState());
                // makeActive = makeActive || (mol->checkState() == Qt::Checked);
                // This may result in a memory leak, but we need the Molecule
                // to remain lying around in case of an undo action.
                takeRow(row);
                insertRow(row, molecule);
                found = true;
                qDebug() << "found existing molecule";
                break;
             }
          }
      }
   }

   // If we didn't find an existing Molecule to overwrite, we check the last
   // Molecule on the list and if that is still 'Untitled' and empty, use it.
   if (!found) {
      child = root->child(root->rowCount()-1);
      if (child->text() == DefaultMoleculeName && !child->hasChildren()) {
         Layer::Base* base = QVariantPointer<Layer::Base>::toPointer(child->data());
         Layer::Molecule* mol = qobject_cast<Layer::Molecule*>(base);
         makeActive = makeActive || (mol->checkState() == Qt::Checked);
         // This may result in a memory leak, but we need the Molecule
         // to remain lying around in case of an undo action.
         takeRow(child->row());
      }

      Command::AddMolecule* cmd = new Command::AddMolecule(molecule, root);
      postCommand(cmd);
   }

   if (makeActive) {
      forAllMolecules(boost::bind(&Layer::Molecule::setCheckState, _1, Qt::Unchecked));
      molecule->setCheckState(Qt::Checked);
      sceneRadiusChanged(sceneRadius());
      changeActiveViewerMode(Viewer::Manipulate);
   }

   fileOpened(parser->filePath());
}
Example #2
0
void ClassesDatas::setDefault(QStandardItem *modelSkills,
                              QStandardItem *modelStatistics)
{
    SystemClass* sysClass;
    QStandardItem* item;
    SuperListItem* skill;
    SuperListItem* statistic;
    SystemStatisticProgression* statisticProgression;
    SystemClassSkill* classSkill;
    QList<QStandardItem *> row;
    QStandardItemModel* skills;
    QStandardItemModel* statisticsProgression;
    QString names[] = {"Knight", "Witch", "Mage", "Ninja", "Animal"};
    int initialLevels[] = {1, 1, 1, 1, 1};
    int maxLevels[] = {100, 100, 100, 100, 100};
    int expBases[] = {5, 5, 5, 5, 5};
    int expInflations[] = {20, 20, 20, 20, 20};
    QVector<int> idsStatistics[] = {
        QVector<int>({3, 4, 5, 6, 7, 8, 9, 10, 11, 12}),
        QVector<int>({3, 4, 5, 6, 7, 8, 9, 10, 11, 12}),
        QVector<int>({3, 4, 5, 6, 7, 8, 9, 10, 11, 12}),
        QVector<int>({3, 4, 5, 6, 7, 8, 9, 10, 11, 12}),
        QVector<int>({3, 4, 5, 6, 7, 8, 9, 10, 11, 12})
    };
    QVector<bool> isFix[] = {
        QVector<bool>({true, true, true, false, false, true, true, true, true,
            true}),
        QVector<bool>({true, true, true, false, false, true, true, true, true,
            true}),
        QVector<bool>({true, true, true, false, false, true, true, true, true,
            true}),
        QVector<bool>({true, true, true, false, false, true, true, true, true,
            true}),
        QVector<bool>({true, true, true, false, false, true, true, true, true,
            true})
    };
    QVector<int> initialValue[] = {
        QVector<int>({20, 10, 10, 1, 1, 1, 1, 0, 0, 1}),
        QVector<int>({20, 10, 10, 1, 1, 1, 1, 0, 0, 1}),
        QVector<int>({20, 10, 10, 1, 1, 1, 1, 0, 0, 1}),
        QVector<int>({20, 10, 10, 1, 1, 1, 1, 0, 0, 1}),
        QVector<int>({5, 10, 10, 1, 1, 1, 1, 0, 0, 1})
    };
    QVector<int> finalValue[] = {
        QVector<int>({1000, 500, 100, 999, 999, 200, 200, 50, 50, 200}),
        QVector<int>({1000, 500, 100, 999, 999, 200, 200, 50, 50, 200}),
        QVector<int>({1000, 500, 100, 999, 999, 200, 200, 50, 50, 200}),
        QVector<int>({1000, 500, 100, 999, 999, 200, 200, 50, 50, 200}),
        QVector<int>({1000, 500, 100, 999, 999, 200, 200, 50, 50, 200})
    };
    QVector<QString> formula[] = {
        QVector<QString>({"", "", "", "Math.ceil(u.str * 0.3)",
            "Math.ceil(u.int * 0.3)", "", "", "", "", ""}),
        QVector<QString>({"", "", "", "Math.ceil(u.str * 0.3)",
            "Math.ceil(u.int * 0.3)", "", "", "", "", ""}),
        QVector<QString>({"", "", "", "Math.ceil(u.str * 0.3)",
            "Math.ceil(u.int * 0.3)", "", "", "", "", ""}),
        QVector<QString>({"", "", "", "Math.ceil(u.str * 0.3)",
            "Math.ceil(u.int * 0.3)", "", "", "", "", ""}),
        QVector<QString>({"", "", "", "Math.ceil(u.str * 0.3)",
            "Math.ceil(u.int * 0.3)", "", "", "", "", ""})
    };
    QVector<int> skillIds[] = {
        QVector<int>({6}),
        QVector<int>({7}),
        QVector<int>({8, 9, 10, 11}),
        QVector<int>({12, 13}),
        QVector<int>({})
    };
    QVector<int> skillLevels[] = {
        QVector<int>({1}),
        QVector<int>({1}),
        QVector<int>({1,1,5,10}),
        QVector<int>({1, 5}),
        QVector<int>({})
    };

    int length = (sizeof(names)/sizeof(*names));

    for (int i = 0; i < length; i++){
        // Statistics progression
        statisticsProgression = new QStandardItemModel;
        for (int j = 0; j < idsStatistics[i].size(); j++){
            statistic = SuperListItem::getById(modelStatistics, idsStatistics[i]
                [j]);
            statisticProgression = new SystemStatisticProgression(statistic->id(),
                statistic->name(), new PrimitiveValue(finalValue[i][j]), isFix
                [i][j], new SystemProgressionTable(new PrimitiveValue(
                initialValue[i][j]), new PrimitiveValue(finalValue[i][j]), 0),
                new PrimitiveValue(0), new PrimitiveValue(formula[i][j]));
            row = statisticProgression->getModelRow();
            statisticsProgression->appendRow(row);
        }
        item = new QStandardItem();
        item->setText(SuperListItem::beginningText);
        statisticsProgression->appendRow(item);

        // Skills
        skills = new QStandardItemModel;
        for (int j = 0; j < skillIds[i].size(); j++){
            skill = SuperListItem::getById(modelSkills, skillIds[i][j]);
            classSkill = new SystemClassSkill(skill->id(), skill->name(),
                                              skillLevels[i][j]);
            row = classSkill->getModelRow();
            skills->appendRow(row);
        }
        item = new QStandardItem();
        item->setText(SuperListItem::beginningText);
        skills->appendRow(item);

        sysClass = new SystemClass(i + 1, new LangsTranslation(names[i]),
            initialLevels[i], maxLevels[i], expBases[i], expInflations[i],
            statisticsProgression, skills);
        item = new QStandardItem;
        item->setData(QVariant::fromValue(
                          reinterpret_cast<quintptr>(sysClass)));
        item->setText(sysClass->toString());
        m_model->appendRow(item);
    }
}
Example #3
0
bool AlarmView::updateAlarms()
{
    bool playSound = false;
    QIcon aicon(":icon/audible");
    QIcon sicon(":icon/silent");

    mStandardModel->clear();
    mAlarmCount = 0;

    QString localDT;
    QString tzDT;

    // Filter out occurrences that do not have an alarm
    for (int i=0; i < mModel->rowCount(); i++) {
        QOccurrence o = mModel->occurrence(i);
        QAppointment a = o.appointment();
        if (a.hasAlarm() && (o.startInCurrentTZ() == mStartTime) /* && (o.alarmDelay() == warnDelay)*/) {
            if (!playSound && (a.alarm() == QAppointment::Audible)) {
                playSound = true;
            }
            QStandardItem* item = new QStandardItem();
            if (a.alarm() == QAppointment::Audible)
                item->setData(aicon, Qt::DecorationRole);
            else
                item->setData(sicon, Qt::DecorationRole);

            if (!a.description().isEmpty())
                item->setData(a.description(), Qt::DisplayRole);
            else
                item->setData(tr("No description", "no description for appointment"), Qt::DisplayRole);

            QList< StringPair > subList;
            if (!a.location().isEmpty()) {
                subList.append(qMakePair(QString(), a.location()));
            }

            formatDateTime(o, true, localDT, tzDT);
            if (a.isAllDay()) {
                subList.append(qMakePair(tr("All day: "), localDT));
            } else {
                subList.append(qMakePair(tr("Starts: "), localDT));
                if (!tzDT.isEmpty())
                    subList.append(qMakePair(QString(""), tzDT));
                formatDateTime(o, false, localDT, tzDT);
                subList.append(qMakePair(tr("Ends: "), localDT));
                if (!tzDT.isEmpty())
                    subList.append(qMakePair(QString(""), tzDT));
            }
            item->setData(QVariant::fromValue(subList), TwoLevelDelegate::SubLabelsRole);

            item->setData(i, TwoLevelDelegate::TwoLevelDelegateUserRole);
            mStandardModel->appendRow(item);
        }
    }

    int rowCount = mStandardModel->rowCount();

    // Select the first item
    mAlarmList->setCurrentIndex(mStandardModel->index(0,0));

    // XXX i18n boneheadedness.
    if (rowCount < 2) {
        setWindowTitle(tr("Reminder"));
    } else {
        setWindowTitle(tr("Reminders"));
    }

    mSnoozeButton->setFocus();

    // If we actually got any matching alarms...
    if (rowCount > 0) {
        if (playSound) {
            Qtopia::soundAlarm();
            mAlarmTimer.start(5000,this);
        }

        return true;
    } else {
        emit closeView();
        return false;
    }
}
Example #4
0
QStandardItem* JamendoService::CreateRootItem() {
  QStandardItem* item = new QStandardItem(QIcon(":providers/jamendo.png"), kServiceName);
  item->setData(true, InternetModel::Role_CanLazyLoad);
  return item;
}
TicketListV::TicketListV(QMainWindow *parent) :
    QMainWindow(parent),
    ui(new Ui::TicketListV)
{
    ui->setupUi(this);

    // Make the main screen fixed size
    this->setFixedSize(this->width(), this->height());

 _flag = false; // undo vector has not been initialize at this point

    //
    // CUSTOM CSS AREA
    //

    QPixmap pixmap(":/new/prefix1/refresh2.png");
    QIcon ButtonIcon(pixmap);
    ui->refreshButton->setIcon(ButtonIcon);
    ui->refreshButton->setIconSize(pixmap.rect().size());

    QFile data(":/new/prefix1/greenButton.qss");
    data.open(QFile::ReadOnly);
    QTextStream styleIn(&data);
    this->_greenButton = styleIn.readAll();
    data.close();

    //
    // Instantiate all the QComboboxes with the correct data
    //

    // Custom number combo box
    ui->ticketInput->addItem("10");
    ui->ticketInput->addItem("25");
    ui->ticketInput->addItem("50");
    ui->ticketInput->addItem("100");

    // Set to 25 as default
    ui->ticketInput->setCurrentIndex(1);

    // Filter list combo box
    ui->filterList->addItem("Select filter(s) to apply");
    ui->filterList->addItem("Ticket Number");
    ui->filterList->addItem("Customer First Name");
    ui->filterList->addItem("Customer Last Name");
    ui->filterList->addItem("Category");
    ui->filterList->addItem("Severity");
    ui->filterList->addItem("Status");
    ui->filterList->addItem("Assigned to");
    ui->filterList->addItem("Open date/time range");
    ui->filterList->addItem("Closed date/time range");

    ui->filterBox->setEnabled(false);
    ui->applyButton->setEnabled(false);
    ui->applyButton->setStyleSheet("QPushButton { background: grey; }");

    this->Model = new QStandardItemModel;
    QStandardItem* defaultItem = new QStandardItem;
    defaultItem->setText("Applied Filters");
    this->Model->insertRow(0, defaultItem);

    // Create all the items for the applied filters combo box
    for (int i = 1; i < 10; i++) {
        QStandardItem* tempItem = new QStandardItem;
        tempItem->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);
        tempItem->setData(Qt::Unchecked, Qt::CheckStateRole);
        this->Model->insertRow(i, tempItem);
    }

   // Add the appropriate names for each section of the box
   this->Model->item(1,0)->setText("Ticket Number");
   this->Model->item(2,0)->setText("Customer First Name");
   this->Model->item(3,0)->setText("Customer Last Name");
   this->Model->item(4,0)->setText("Category");
   this->Model->item(5,0)->setText("Severity");
   this->Model->item(6,0)->setText("Status");
   this->Model->item(7,0)->setText("Assigned to");
   this->Model->item(8,0)->setText("Open date/time range");
   this->Model->item(9,0)->setText("Closed date/time range");

   ui->appliedFilters->setModel(this->Model);

   // Show/Hide specific columns combo box
   this->Model2 = new QStandardItemModel;
   QStandardItem* defaultItem2 = new QStandardItem;
   defaultItem2->setText("Select column(s) to hide/show");
   this->Model2->insertRow(0, defaultItem2);

   // Create all the items for the combo box
   for (int i = 1; i < 11; i++) {
       QStandardItem* tempItem2 = new QStandardItem;
       tempItem2->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);
       tempItem2->setData(Qt::Unchecked, Qt::CheckStateRole);
       this->Model2->insertRow(i, tempItem2);
   }

  this->Model2->item(1,0)->setText("Ticket Number");
  this->Model2->item(2,0)->setText("Customer First Name");
  this->Model2->item(3,0)->setText("Customer Last Name");
  this->Model2->item(4,0)->setText("Category");
  this->Model2->item(5,0)->setText("Severity");
  this->Model2->item(6,0)->setText("Status");
  this->Model2->item(7,0)->setText("Agent First Name");
  this->Model2->item(8,0)->setText("Agent Last Name");
  this->Model2->item(9,0)->setText("Open date/time range");
  this->Model2->item(10,0)->setText("Closed date/time range");

  ui->showHideBox->setModel(this->Model2);

   // Create the view's own controller
   this->_controller = TicketListController();

   this->_currentIndex = 0;
   this->_offset = 25;

   // Convert the current index and offset
   QString currentIndex = QString::number(this->_currentIndex);
   QString offset =  QString::number(this->_offset);

    this->_model2 = new QSortFilterProxyModel();

   // Create the menu bar area
   QMenu *fileMenu;
   QMenu *editMenu;

   fileMenu = menuBar()->addMenu(tr("&File"));
   QAction *openAct =  new QAction(tr("&Open a ticket"), this);
   QAction *createAct = new QAction(tr("&Create a ticket"), this);
   QAction *cusAct = new QAction(tr("&Edit a Customer"), this);

   // Add some nice status tips
   createAct->setStatusTip(tr("Create a new Ticket"));
   cusAct->setStatusTip(tr("Edit the customer who opened the currently selected ticket"));
   openAct->setStatusTip(tr("Open selected ticket"));

   // Add options to the filemenu
   fileMenu->addAction(createAct);
   fileMenu->addAction(cusAct);
   fileMenu->addAction(openAct);

   // Edit menu
   editMenu = menuBar()->addMenu(tr("&Edit"));
   QAction *undoAct =  new QAction(tr("&Undo"), this);

   // Add status tip
   undoAct->setStatusTip(tr("Undo changes made to the last modified ticket"));

   // Give functionality to the buttons
   connect(undoAct, SIGNAL(triggered()), this, SLOT(undoClicked()));

   // Add options to the edit menu
   editMenu->addAction(undoAct);

   //
   // SIGNALS AND SLOTS
   //

   // give functionality to the buttons
   connect(ui->nextPageButton,SIGNAL(clicked()), this, SLOT(nextPageButtonClicked()));
   connect(ui->previousPageButton,SIGNAL(clicked()), this, SLOT(previousPageButtonClicked()));
   connect(ui->lastPageButton,SIGNAL(clicked()), this, SLOT(lastPageButtonClicked()));
   connect(ui->firstPageButton,SIGNAL(clicked()), this, SLOT(firstPageButtonClicked()));

   // give functionality to the buttons
   connect(createAct, SIGNAL(triggered()),this, SLOT(newTicketButtonClicked()));
   connect(cusAct, SIGNAL(triggered()), this, SLOT(editCus()));
   connect(openAct, SIGNAL(triggered()), this, SLOT(editTicket()));

   // Identify when the customer combo box is clicked
   connect(ui->ticketInput,SIGNAL(currentIndexChanged(int)), this, SLOT(updateData()));

   // Identify when the filter list combo box is clicked. Show the current filter in the text box.
   connect(ui->filterList,SIGNAL(currentIndexChanged(int)), this, SLOT(showFilter(int)));

   // Identify when they apply a filter
   connect(ui->applyButton,SIGNAL(clicked()), this, SLOT(applyFilter()));

   // Allow double-clicking of the customers to open up an edit window
   connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(editTicket()));

   // Check what filters have been checked and apply those to the table
   connect(this->Model, SIGNAL(dataChanged ( const QModelIndex&, const QModelIndex&)), this, SLOT(appliedFiltersChanged(const QModelIndex&, const QModelIndex&)));

   // Check what columns have hidden or shown
   connect(this->Model2, SIGNAL(dataChanged ( const QModelIndex&, const QModelIndex&)), this, SLOT(showHideBoxChanged(const QModelIndex&)));

   connect(ui->refreshButton, SIGNAL(clicked()), this, SLOT(updateData()));


   // RIGHT CLICK STUFF
   this->ui->tableView->setContextMenuPolicy(Qt::CustomContextMenu);
   connect(this->ui->tableView, SIGNAL (customContextMenuRequested(const QPoint&)), this, SLOT(rightClickMenu(const QPoint&)));

   this->ui->filterList->setCurrentIndex(7);
   this->ui->filterBox->setText(this->_controller.getAgentID());
   applyFilter();
   this->ui->filterList->setCurrentIndex(6);
   this->ui->filterBox->setText("Pending");
   applyFilter();
   this->ui->tableView->setColumnHidden(10, true);
   this->ui->filterList->setCurrentIndex(0);
   this->ui->filterBox->setText("");

   this->ui->tableView->sortByColumn(0, Qt::AscendingOrder);
   this->ui->tableView->setSortingEnabled(true);

   this->ui->dateTimeEdit1->hide();
   this->ui->dateTimeEdit2->hide();

   updateButtonData();
}
Example #6
0
/** Constructor */
BlogsDialog::BlogsDialog(QWidget *parent)
: MainPage (parent)
{
  	/* Invoke the Qt Designer generated object setup routine */
  	setupUi(this);

  	connect(actionCreate_Blog, SIGNAL(triggered()), this, SLOT(createBlog()));
  	connect(postButton, SIGNAL(clicked()), this, SLOT(createMsg()));
  	connect(subscribeButton, SIGNAL( clicked( void ) ), this, SLOT( subscribeBlog ( void ) ) );
  	connect(unsubscribeButton, SIGNAL( clicked( void ) ), this, SLOT( unsubscribeBlog ( void ) ) );
  	
    connect(treeView, SIGNAL(clicked(const QModelIndex &)), this, SLOT(selectBlog(const QModelIndex &)));
    connect(treeView, SIGNAL(activated(const QModelIndex &)), this, SLOT(toggleSelection(const QModelIndex &)));
    connect(treeView, SIGNAL(customContextMenuRequested( QPoint ) ), this, SLOT( blogListCustomPopupMenu( QPoint ) ) );

  	mBlogId = "";
  	mPeerId = rsPeers->getOwnId(); // add your id

    model = new QStandardItemModel(0, 2, this);
    model->setHeaderData(0, Qt::Horizontal, tr("Name"), Qt::DisplayRole);
    model->setHeaderData(1, Qt::Horizontal, tr("ID"), Qt::DisplayRole);

    treeView->setModel(model);
    treeView->setEditTriggers(QAbstractItemView::NoEditTriggers);

    treeView->setItemDelegate(new ChanGroupDelegate());

    // hide header and id column
    treeView->setHeaderHidden(true);
    treeView->hideColumn(1);
    
    itemFont = QFont("ARIAL", 10);
    itemFont.setBold(true);
	
    QStandardItem *OwnBlogs = new QStandardItem(tr("My Blogs"));
    OwnBlogs->setForeground(QBrush(QColor(79, 79, 79)));
    OwnBlogs->setFont(itemFont);
    
    QStandardItem *SubscribedBlogs = new QStandardItem(tr("Subscribed Blogs"));
    SubscribedBlogs->setForeground(QBrush(QColor(79, 79, 79)));
    SubscribedBlogs->setFont(itemFont);

    QStandardItem *PopularBlogs = new QStandardItem(tr("Popular Blogs"));
    PopularBlogs->setForeground(QBrush(QColor(79, 79, 79)));
    PopularBlogs->setFont(itemFont);

    QStandardItem *OtherBlogs = new QStandardItem(tr("Other Blogs"));
    OtherBlogs->setForeground(QBrush(QColor(79, 79, 79)));        
    OtherBlogs->setFont(itemFont);

    model->appendRow(OwnBlogs);
    model->appendRow(SubscribedBlogs);
    model->appendRow(PopularBlogs);
    model->appendRow(OtherBlogs);

    //added from ahead
    updateBlogList();

    mBlogFont = QFont("MS SANS SERIF", 22);
    nameLabel->setFont(mBlogFont);    
    nameLabel->setMinimumWidth(20);
		   
    QMenu *blogmenu = new QMenu();
    blogmenu->addAction(actionCreate_Blog); 
    blogmenu->addSeparator();
    blogpushButton->setMenu(blogmenu);
	
    QTimer *timer = new QTimer(this);
    timer->connect(timer, SIGNAL(timeout()), this, SLOT(checkUpdate()));
    timer->start(1000);
}
Example #7
0
void QgsComposerLegend::drawLayerChildItems( QPainter* p, QStandardItem* layerItem, double& currentYCoord, double& maxXCoord, int layerOpacity )
{
  if ( !layerItem )
  {
    return;
  }

  //Draw all symbols first and the texts after (to find out the x coordinate to have the text aligned)
  QList<double> childYCoords;
  QList<double> realItemHeights;

  double textHeight = fontHeightCharacterMM( mItemFont, QChar( '0' ) );
  double itemHeight = qMax( mSymbolHeight, textHeight );

  double textAlignCoord = 0; //alignment for legend text

  QStandardItem* currentItem;

  int numChildren = layerItem->rowCount();

  for ( int i = 0; i < numChildren; ++i )
  {
    //real symbol height. Can be different from standard height in case of point symbols
    double realSymbolHeight;
    double realItemHeight = itemHeight; //will be adjusted if realSymbolHeight turns out to be larger

    currentYCoord += mSymbolSpace;
    double currentXCoord = mBoxSpace;

    currentItem = layerItem->child( i, 0 );

    if ( !currentItem )
    {
      continue;
    }

    QgsSymbol* symbol = 0;
    QgsComposerSymbolItem* symbolItem = dynamic_cast<QgsComposerSymbolItem*>( currentItem );
    if ( symbolItem )
    {
      symbol = symbolItem->symbol();
    }

    QgsSymbolV2* symbolNg = 0;
    QgsComposerSymbolV2Item* symbolV2Item = dynamic_cast<QgsComposerSymbolV2Item*>( currentItem );
    if ( symbolV2Item )
    {
      symbolNg = symbolV2Item->symbolV2();
    }
    QgsComposerRasterSymbolItem* rasterItem = dynamic_cast<QgsComposerRasterSymbolItem*>( currentItem );

    if ( symbol )  //item with symbol?
    {
      //draw symbol
      drawSymbol( p, symbol, currentYCoord + ( itemHeight - mSymbolHeight ) / 2, currentXCoord, realSymbolHeight, layerOpacity );
      realItemHeight = qMax( realSymbolHeight, itemHeight );
      currentXCoord += mIconLabelSpace;
    }
    else if ( symbolNg ) //item with symbol NG?
    {
      drawSymbolV2( p, symbolNg, currentYCoord + ( itemHeight - mSymbolHeight ) / 2, currentXCoord, realSymbolHeight, layerOpacity );
      realItemHeight = qMax( realSymbolHeight, itemHeight );
      currentXCoord += mIconLabelSpace;
    }
    else if ( rasterItem )
    {
      if ( p )
      {
        p->setBrush( rasterItem->color() );
        p->drawRect( QRectF( currentXCoord, currentYCoord + ( itemHeight - mSymbolHeight ) / 2, mSymbolWidth, mSymbolHeight ) );
      }
      currentXCoord += mSymbolWidth;
      currentXCoord += mIconLabelSpace;
    }
    else //item with icon?
    {
      QIcon symbolIcon = currentItem->icon();
      if ( !symbolIcon.isNull() && p )
      {
        symbolIcon.paint( p, currentXCoord, currentYCoord + ( itemHeight - mSymbolHeight ) / 2, mSymbolWidth, mSymbolHeight );
        currentXCoord += mSymbolWidth;
        currentXCoord += mIconLabelSpace;
      }
    }

    childYCoords.push_back( currentYCoord );
    realItemHeights.push_back( realItemHeight );
    currentYCoord += realItemHeight;
    textAlignCoord = qMax( currentXCoord, textAlignCoord );
  }

  maxXCoord = qMax( maxXCoord, textAlignCoord );
  for ( int i = 0; i < numChildren; ++i )
  {
    if ( p )
    {
      p->setPen( QColor( 0, 0, 0 ) );
      drawText( p, textAlignCoord, childYCoords.at( i ) + textHeight + ( realItemHeights.at( i ) - textHeight ) / 2, layerItem->child( i, 0 )->text(), mItemFont );
      maxXCoord = qMax( maxXCoord, textAlignCoord + mBoxSpace + textWidthMillimeters( mItemFont,  layerItem->child( i, 0 )->text() ) );
    }
  }
}
Example #8
0
void MainWindow::exportAsCSV(QString fileName,const WorkSheet *ws)
{
    QString str;
    bool bstatus;
    int i,j;
    int linecount = 0;
    QStandardItem *item;
    QModelIndex index;
    const ProxyFilter *proxyFilter = 0;
    const WorkSheetModel *model = 0;
    if (!ws || !ws->fixTable) {
        qWarning() << "ws is null or HAS NO FIX TABLE" << __FILE__ << __LINE__;
        GUI::ConsoleMessage msg("Export failed, work sheet is null or has no table",
                                GUI::ConsoleMessage::ErrorMsg);
        displayConsoleMessage(msg);
        return;
    }
    QFileInfo fi(fileName);
    if (fi.suffix().toLower() != "csv")
        fileName.append(".csv");

    QFile file(fileName);
    QTextStream ts(&file);
    if (file.exists()) {
        str = fileName + " already exists.";
        QMessageBox::warning(this,"Export Failed",str);
        GUI::ConsoleMessage msg ("Export failed" + str,
                                 GUI::ConsoleMessage::ErrorMsg);
        displayConsoleMessage(msg);
        return;

    }
    bstatus = file.open(QIODevice::WriteOnly);
    if (!bstatus) {
        str = "Unable to open file: " + fileName;
        QMessageBox::warning(this,"Export Failed",str);
        GUI::ConsoleMessage msg("Export failed" + str,
                                GUI::ConsoleMessage::ErrorMsg);
        displayConsoleMessage(msg);
        return;
    }
    model = ws->fixTable->getWorkSheetModel();
    bool proxyInUse = ws->fixTable->proxyFilterInUse();
    if (proxyInUse) {
        proxyFilter = ws->fixTable->getProxyFilter();
        for (i=0;i<proxyFilter->rowCount(); i++ ) {
            QStringList itemList;
            for(j=0;j< proxyFilter->columnCount();j++) {
                index = proxyFilter->index(i,j);
                index = proxyFilter->mapToSource(index);
                item = model->itemFromIndex(index);
                if (item) {
                    itemList << item->text();
                }
                else {
                    itemList << " ";
                }

            }
            ts << itemList.join(',') << "\n";
        }
    }
    else {
        for (i=0;i<model->rowCount(); i++ ) {
            QStringList itemList;
            for(j=0;j< model->columnCount();j++) {
                index = model->index(i,j);
                item = model->itemFromIndex(index);
                if (item) {
                    itemList << item->text();
                }
                else {
                    itemList << " ";
                }

            }
            ts << itemList.join(',') << "\n";
        }
    }
    GUI::ConsoleMessage msg(QString("Exported to " +  fileName + ", " + QString::number(i) + " lines."));
    displayConsoleMessage(msg);
    file.close();
}
Example #9
0
void QgsPgTableModel::setSql( const QModelIndex &index, const QString &sql )
{
  if ( !index.isValid() || !index.parent().isValid() )
  {
    return;
  }

  //find out schema name and table name
  QModelIndex schemaSibling = index.sibling( index.row(), DbtmSchema );
  QModelIndex tableSibling = index.sibling( index.row(), DbtmTable );
  QModelIndex geomSibling = index.sibling( index.row(), DbtmGeomCol );

  if ( !schemaSibling.isValid() || !tableSibling.isValid() || !geomSibling.isValid() )
  {
    return;
  }

  QString schemaName = itemFromIndex( schemaSibling )->text();
  QString tableName = itemFromIndex( tableSibling )->text();
  QString geomName = itemFromIndex( geomSibling )->text();

  QList<QStandardItem *> schemaItems = findItems( schemaName, Qt::MatchExactly, DbtmSchema );
  if ( schemaItems.empty() )
  {
    return;
  }

  QStandardItem *schemaItem = schemaItems.at( DbtmSchema );

  int n = schemaItem->rowCount();
  for ( int i = 0; i < n; i++ )
  {
    QModelIndex currentChildIndex = indexFromItem( schemaItem->child( i, DbtmSchema ) );
    if ( !currentChildIndex.isValid() )
    {
      continue;
    }

    QModelIndex currentTableIndex = currentChildIndex.sibling( i, DbtmTable );
    if ( !currentTableIndex.isValid() )
    {
      continue;
    }

    QModelIndex currentGeomIndex = currentChildIndex.sibling( i, DbtmGeomCol );
    if ( !currentGeomIndex.isValid() )
    {
      continue;
    }

    if ( itemFromIndex( currentTableIndex )->text() == tableName && itemFromIndex( currentGeomIndex )->text() == geomName )
    {
      QModelIndex sqlIndex = currentChildIndex.sibling( i, DbtmSql );
      if ( sqlIndex.isValid() )
      {
        itemFromIndex( sqlIndex )->setText( sql );
        break;
      }
    }
  }
}
Example #10
0
void ItemsList::generateCSV()
{
    QString separator = ";";
    QList <QStandardItem*> itemsList;
    QTextStream out( csvFile );
    if ( !csvFile->open(QIODevice::WriteOnly | QIODevice::Append) )
        {
            runMsg("Nie można otworzyć pliku pomocniczego schedule.csv.");
            return;
        }

    QBrush brush;
    QFont checkedFont;
    checkedFont.setFamily("Arial");
    checkedFont.setBold(true);
    checkedFont.setWeight(15);
    brush.setColor(Qt::green);

    if (!mainOrderActive)
    {
        out << m_order + separator << m_year + "-" + m_month + "-" + m_day + separator << m_recipient + separator << endl;
        out << "Rodzaj stołu" + separator
            << "Elektryczna regulacja wysokości" + separator
            << "Uchwyty do pasów" + separator
            << "Regulacja kąta odchylenia" + separator
            << "Elektrycznie łamane leżysko" + separator
            << "Układ jezdny z hamulcami"+ separator
            << "Zagłówek 3-elementowy"+ separator
            << "Pozycja fotela"+ separator
            << "Sterowanie nożne"+ separator
            << "Pilot podblatowy"+ separator
            << "Kołki do stabilizacji"+ separator
            << "Uchwyt na prześcieradło"+ separator
            << "Zatyczka"+ separator
            << "Stal nierdzewna"+ separator
            << "Ilość sztuk"+ separator
            << "Kolor blatu"+ separator
            << "Kolor ramy" + separator
            << "Uwagi" << endl;
        mainOrderActive = true;
    }

    out << m_actualTable + separator;
    QStandardItem * item = new QStandardItem(m_actualTable);
    item -> setTextAlignment( Qt::AlignHCenter | Qt::AlignVCenter );
    itemsList.push_back( item );

    /* fill options */
    for( uint row = 0 ; row < m_statesArray.size() ; ++row ) {
        out << QString::number(m_statesArray[row]) + separator;
        item = new QStandardItem(QString::number(m_statesArray[row]));
        item -> setTextAlignment( Qt::AlignHCenter | Qt::AlignVCenter );
        if(item->text() == "1")
        {
            item -> setForeground(brush);
            item -> setFont(checkedFont);
        }
        itemsList.push_back( item );
    }

    out << m_quantity + separator;
    item = new QStandardItem(m_quantity);
    item -> setTextAlignment( Qt::AlignHCenter | Qt::AlignVCenter );
    itemsList.push_back( item );

    out << m_topColor + separator;
    item = new QStandardItem(m_topColor);
    item -> setTextAlignment( Qt::AlignHCenter | Qt::AlignVCenter );
    itemsList.push_back( item );

    out << m_bottomColor + separator ;
    item = new QStandardItem(m_bottomColor);
    item -> setTextAlignment( Qt::AlignHCenter | Qt::AlignVCenter );
    itemsList.push_back( item );

    out << m_notes + separator << endl;
    item = new QStandardItem(m_notes);
    item -> setTextAlignment( Qt::AlignHCenter | Qt::AlignVCenter );
    itemsList.push_back( item );

    csvFile->close();
    tableDialog->model->appendColumn(itemsList);

    runMsg("Dodano do zamówienia.");
}
Example #11
0
QTXLSX_USE_NAMESPACE

void MainWindow::exportAsXLSXA(QString fileName,WorkSheet *ws)
{
    QString str;
    QStringList headerArray;
    //headerArray << "A"<<"B"<<"C"<<"D"<<"E"<<"F"<<"G"<<"H"<<"I"<<"J"<<"K"<<"L"<<"M"<<"N"<<"O"<<"P"<<"Q"<<"R"<<"S"<<"T"<<"U"<<"V"<<"W"<<"X"<<"Y"<<"Z"<<"AA"<<"AB"<<"AC"<<"AD"<<"AE"<<"AF"<<"AG"<<"AH"<<"AI"<<"AJ"<<"AK"<<"AL"<<"AM"<<"AN"<<"AO"<<"AP"<<"AQ"<<"AR"<<"AS"<<"AT"<<"AU"<<"AV"<<"AW"<<"AX"<<"AY"<<"AZ";
    bool bstatus;
    int i,j;
    int linecount = 0;
    QStandardItem *item;
    QModelIndex index;
    const ProxyFilter *proxyFilter = 0;
    const WorkSheetModel *model = 0;
    if (!ws || !ws->fixTable) {
        qWarning() << "ws is null or HAS NO FIX TABLE" << __FILE__ << __LINE__;
        GUI::ConsoleMessage msg("Export failed, work sheet is null or has no table",
                                GUI::ConsoleMessage::ErrorMsg);
        displayConsoleMessage(msg);
        return;
    }
    model = ws->fixTable->getWorkSheetModel();


    QFileInfo fi(fileName);
    if (fi.suffix().toLower() != "xlsx")
        fileName.append(".xlsx");
    Document xlsx;
    QString xmlFileName = ws->getFileName();
    xlsx.addSheet("From:" + xmlFileName);
    Format headerStyle;
    headerStyle.setFontBold(true);
    headerStyle.setHorizontalAlignment(Format::AlignHCenter);
    headerStyle.setVerticalAlignment(Format::AlignVCenter);
    int w;
    QFontMetrics fm(ws->fixTable->font());
    xlsx.setColumnWidth(1,model->columnCount() + 1,20);
    bool proxyInUse = ws->fixTable->proxyFilterInUse();
    for (i=0;i<model->columnCount();i++) {
        item = model->horizontalHeaderItem(i);
        xlsx.setColumnFormat(1,i,headerStyle);
        xlsx.write(1, i+1, item->text());
    }
    if (proxyInUse) {
        proxyFilter = ws->fixTable->getProxyFilter();
        for (i=0;i<proxyFilter->rowCount(); i++ ) {
            QStringList itemList;
            for(j=0;j< proxyFilter->columnCount();j++) {
                index = proxyFilter->index(i,j);
                index = proxyFilter->mapToSource(index);
                item = model->itemFromIndex(index);
                if (item) {
                  xlsx.write(i+2,j+1,item->text());
                }
            }
        }
    }
    else {
        for(i=0;i<model->rowCount();i++) {
            for(j=0;j< model->columnCount();j++) {
                index = model->index(i,j);
                item = model->itemFromIndex(index);
                if (item) {
                    xlsx.write(i+2,j+1,item->text());
                }

            }
        }
    }
    xlsx.saveAs(fileName);
    GUI::ConsoleMessage msg(QString("Exported to " +  fileName + ", " + QString::number(i) + " lines."));
    displayConsoleMessage(msg);
}
Example #12
0
void SpotifyService::PlaylistsUpdated(const pb::spotify::Playlists& response) {
  if (login_task_id_) {
    app_->task_manager()->SetTaskFinished(login_task_id_);
    login_task_id_ = 0;
  }

  // Create starred and inbox playlists if they're not here already
  if (!search_) {
    search_ =
        new QStandardItem(IconLoader::Load("edit-find", IconLoader::Base), 
                          tr("Search results"));
    search_->setToolTip(
        tr("Start typing something on the search box above to "
           "fill this search results list"));
    search_->setData(Type_SearchResults, InternetModel::Role_Type);
    search_->setData(InternetModel::PlayBehaviour_MultipleItems,
                     InternetModel::Role_PlayBehaviour);

    starred_ = new QStandardItem(QIcon(":/star-on.png"), tr("Starred"));
    starred_->setData(Type_StarredPlaylist, InternetModel::Role_Type);
    starred_->setData(true, InternetModel::Role_CanLazyLoad);
    starred_->setData(InternetModel::PlayBehaviour_MultipleItems,
                      InternetModel::Role_PlayBehaviour);
    starred_->setData(true, InternetModel::Role_CanBeModified);

    inbox_ = new QStandardItem(IconLoader::Load("mail-message", 
                               IconLoader::Base), tr("Inbox"));
    inbox_->setData(Type_InboxPlaylist, InternetModel::Role_Type);
    inbox_->setData(true, InternetModel::Role_CanLazyLoad);
    inbox_->setData(InternetModel::PlayBehaviour_MultipleItems,
                    InternetModel::Role_PlayBehaviour);

    toplist_ = new QStandardItem(QIcon(), tr("Top tracks"));
    toplist_->setData(Type_Toplist, InternetModel::Role_Type);
    toplist_->setData(true, InternetModel::Role_CanLazyLoad);
    toplist_->setData(InternetModel::PlayBehaviour_MultipleItems,
                      InternetModel::Role_PlayBehaviour);

    root_->appendRow(search_);
    root_->appendRow(toplist_);
    root_->appendRow(starred_);
    root_->appendRow(inbox_);
  } else {
    // Always reset starred playlist
    // TODO: might be improved by including starred playlist in the response,
    // and reloading it only when needed, like other playlists.
    starred_->removeRows(0, starred_->rowCount());
    LazyPopulate(starred_);
  }

  // Don't do anything if the playlists haven't changed since last time.
  if (!DoPlaylistsDiffer(response)) {
    qLog(Debug) << "Playlists haven't changed - not updating";
    return;
  }
  qLog(Debug) << "Playlist have changed: updating";

  // Remove and recreate the other playlists
  for (QStandardItem* item : playlists_) {
    item->parent()->removeRow(item->row());
  }
  playlists_.clear();

  for (int i = 0; i < response.playlist_size(); ++i) {
    const pb::spotify::Playlists::Playlist& msg = response.playlist(i);

    QString playlist_title = QStringFromStdString(msg.name());
    if (!msg.is_mine()) {
      const std::string& owner = msg.owner();
      playlist_title +=
          tr(", by ") + QString::fromUtf8(owner.c_str(), owner.size());
    }
    QStandardItem* item = new QStandardItem(playlist_title);
    item->setData(InternetModel::Type_UserPlaylist, InternetModel::Role_Type);
    item->setData(true, InternetModel::Role_CanLazyLoad);
    item->setData(msg.index(), Role_UserPlaylistIndex);
    item->setData(msg.is_mine(), InternetModel::Role_CanBeModified);
    item->setData(InternetModel::PlayBehaviour_MultipleItems,
                  InternetModel::Role_PlayBehaviour);
    item->setData(QUrl(QStringFromStdString(msg.uri())),
                  InternetModel::Role_Url);

    root_->appendRow(item);
    playlists_ << item;

    // Preload the playlist items so that drag & drop works immediately.
    LazyPopulate(item);
  }
}
Example #13
0
void
WhatsHotWidget::infoSystemInfo( Tomahawk::InfoSystem::InfoRequestData requestData, QVariant output )
{
    if ( requestData.caller != s_whatsHotIdentifier )
        return;

    if ( output.isNull() )
    {
        tDebug( LOGVERBOSE ) << Q_FUNC_INFO << "Info came back empty";
        return;
    }

    if ( !output.canConvert< QVariantMap >() )
    {
        tDebug( LOGVERBOSE ) << Q_FUNC_INFO << "WhatsHot: Could not parse output into a map";
        return;
    }

    QVariantMap returnedData = output.toMap();
    switch ( requestData.type )
    {
    case InfoSystem::InfoChartCapabilities:
    {
        QStandardItem *rootItem= m_crumbModelLeft->invisibleRootItem();
        QVariantMap defaults;
        if ( returnedData.contains( "defaults" ) )
            defaults = returnedData.take( "defaults" ).toMap();
        QString defaultSource = returnedData.take( "defaultSource" ).toString();

        foreach ( const QString label, returnedData.keys() )
        {
            QStandardItem *childItem = parseNode( rootItem, label, returnedData[label] );
            rootItem->appendRow(childItem);
        }

        // Set the default source
        // Set the default chart for each source
        for ( int i = 0; i < rootItem->rowCount(); i++ )
        {
            QStandardItem* source = rootItem->child( i, 0 );
            if ( defaultSource.toLower() == source->text().toLower() )
            {
                source->setData( true, Breadcrumb::DefaultRole );
            }

            if ( defaults.contains( source->text().toLower() ) )
            {
                QStringList defaultIndices = defaults[ source->text().toLower() ].toStringList();
                QStandardItem* cur = source;

                foreach( const QString& index, defaultIndices )
                {
                    // Go through the children of the current item, marking the default one as default
                    for ( int k = 0; k < cur->rowCount(); k++ )
                    {
                        if ( cur->child( k, 0 )->text() == index )
                        {
                            cur = cur->child( k, 0 ); // this is the default, drill down into the default to pick the next default
                            cur->setData( true, Breadcrumb::DefaultRole );
                            break;
                        }
                    }
                }
            }
        }

        m_sortedProxy->setSourceModel( m_crumbModelLeft );
        m_sortedProxy->sort( 0, Qt::AscendingOrder );
        ui->breadCrumbLeft->setModel( m_sortedProxy );
        break;
    }

    case InfoSystem::InfoChart:
    {
        if( !returnedData.contains("type") )
            break;
        const QString type = returnedData["type"].toString();
        if( !returnedData.contains(type) )
            break;
        const QString side = requestData.customData["whatshot_side"].toString();
        const QString chartId = requestData.input.value< Tomahawk::InfoSystem::InfoStringHash >().value( "chart_id" );

        m_queuedFetches.remove( chartId );

        ChartDataLoader* loader = new ChartDataLoader();
        loader->setProperty( "chartid", chartId );
        loader->moveToThread( m_workerThread );

        if ( type == "artists" )
        {
            loader->setType( ChartDataLoader::Artist );
            loader->setData( returnedData[ "artists" ].value< QStringList >() );

            connect( loader, SIGNAL( artists( Tomahawk::ChartDataLoader*, QList< Tomahawk::artist_ptr > ) ), this, SLOT( chartArtistsLoaded( Tomahawk::ChartDataLoader*, QList< Tomahawk::artist_ptr > ) ) );

            TreeModel* artistsModel = new TreeModel( ui->artistsViewLeft );
            artistsModel->setMode( InfoSystemMode );
            artistsModel->setStyle( PlayableModel::Collection );

            m_artistModels[ chartId ] = artistsModel;

            if ( m_queueItemToShow == chartId )
                setLeftViewArtists( artistsModel );
        }
        else if ( type == "albums" )
void NotifyOptionsWidget::createTreeModel()
{
	static const struct { ushort kind; QString name; } KindsList[] = { 
		{ INotification::PopupWindow, tr("Display a notification in popup window") },
		{ INotification::SoundPlay, tr("Play sound at the notification") },
		{ INotification::ShowMinimized, tr("Show the corresponding window minimized in the taskbar") },
		{ INotification::AlertWidget, tr("Highlight the corresponding window in the taskbar") },
		{ INotification::TabPageNotify, tr("Display a notification in tab") },
		{ INotification::RosterNotify, tr("Display a notification in your roster") },
		{ INotification::TrayNotify, tr("Display a notification in tray") },
		{ INotification::TrayAction, tr("Display a notification in tray context menu") },
		{ INotification::AutoActivate, tr("Immediately activate the notification") },
		{ 0, QString::null }
	};

	FModel.clear();
	FModel.setColumnCount(2);

	INotificationType globalType;
	globalType.order = 0;
	globalType.kindMask = 0xFFFF;
	globalType.title = tr("Allowed types of notifications");
	globalType.icon = IconStorage::staticStorage(RSR_STORAGE_MENUICONS)->getIcon(MNI_NOTIFICATIONS);

	QMap<QString,INotificationType> notifyTypes;
	notifyTypes.insert(QString::null,globalType);
	foreach(const QString &typeId, FNotifications->notificationTypes())
		notifyTypes.insert(typeId,FNotifications->notificationType(typeId));

	for(QMap<QString,INotificationType>::const_iterator it=notifyTypes.constBegin(); it!=notifyTypes.constEnd(); ++it)
	{
		if (!it->title.isEmpty() && it->kindMask>0)
		{
			QStandardItem *typeNameItem = new QStandardItem(it->title);
			typeNameItem->setFlags(Qt::ItemIsEnabled);
			typeNameItem->setData(it.key(),MDR_TYPE);
			typeNameItem->setData(it->order,MDR_SORT);
			typeNameItem->setIcon(it->icon);
			setItemBold(typeNameItem,true);

			QStandardItem *typeEnableItem = new QStandardItem;
			typeEnableItem->setFlags(Qt::ItemIsEnabled);

			FTypeItems.insert(it.key(),typeNameItem);
			FModel.invisibleRootItem()->appendRow(QList<QStandardItem *>() << typeNameItem << typeEnableItem);

			for (int index =0; KindsList[index].kind!=0; index++)
			{
				if ((it->kindMask & KindsList[index].kind)>0)
				{
					QStandardItem *kindNameItem = new QStandardItem(KindsList[index].name);
					kindNameItem->setFlags(Qt::ItemIsEnabled);
					kindNameItem->setData(index,MDR_SORT);

					QStandardItem *kindEnableItem = new QStandardItem();
					kindEnableItem->setFlags(Qt::ItemIsEnabled);
					kindEnableItem->setTextAlignment(Qt::AlignCenter);
					kindEnableItem->setCheckable(true);
					kindEnableItem->setCheckState(Qt::PartiallyChecked);
					kindEnableItem->setData(it.key(),MDR_TYPE);
					kindEnableItem->setData(KindsList[index].kind,MDR_KIND);

					typeNameItem->appendRow(QList<QStandardItem *>() << kindNameItem << kindEnableItem);
				}
			}
		}
	}
}
Example #15
0
//*** class PathEnum ***
PathEnum::PathEnum(const CppReader &reader, CppObjList &objs):
    ok(false), reader(reader)
{
    //recognization?
    if( !reader.header().startsWith("enum"))
        return;
    ok = true;
    //yes!

    //whether exists the enum name?
    QString name;
    QRegExp rn("^enum\\s+([a-zA-Z_]\\w*)\\s*$");
    if(reader.header().contains(rn) &&
            ! objs.indexOf( name = rn.cap(1)) )        //query for the existance of the name.
    {
        QStandardItem *item = new Item::CppItem(Item::Enum);
        item->setForeground(Qt::darkMagenta);
        item->setData(rn.cap(1),Item::NameRole);
        item->setData(reader.header(),Qt::ToolTipRole);
        item->setEditable(false);
        objs.append( item);
    }

    //the content of the enum.
    QStringList list = reader.body().split(',',QString::SkipEmptyParts);
    QRegExp rx("^\\s*([a-zA-Z_]\\w*)\\s*(?:=[^,;]+)?$");
    foreach (const QString &it, list)
    {
        if(! it.contains(rx) )
            continue;
        if( ! objs.indexOf( rx.cap(1)))
        {
            QStandardItem *item = new Item::CppItem(Item::Enumerator);
            item->setForeground(Qt::darkMagenta);
            item->setData(rx.cap(1),Item::NameRole);
            item->setData("enum: " + it,Qt::ToolTipRole);
            item->setData( name.isEmpty() ? "int" : name, Item::PurifiedTypeRole);
            item->setEditable(false);
            objs.append( item);
        }
    }
}
Example #16
0
bool QgsPgTableModel::setData( const QModelIndex &idx, const QVariant &value, int role )
{
  if ( !QStandardItemModel::setData( idx, value, role ) )
    return false;

  if ( idx.column() == DbtmType || idx.column() == DbtmSrid || idx.column() == DbtmPkCol )
  {
    QgsWkbTypes::Type wkbType = ( QgsWkbTypes::Type ) idx.sibling( idx.row(), DbtmType ).data( Qt::UserRole + 2 ).toInt();

    QString tip;
    if ( wkbType == QgsWkbTypes::Unknown )
    {
      tip = tr( "Specify a geometry type in the '%1' column" ).arg( tr( "Data Type" ) );
    }
    else if ( wkbType != QgsWkbTypes::NoGeometry )
    {
      bool ok;
      int srid = idx.sibling( idx.row(), DbtmSrid ).data().toInt( &ok );

      if ( !ok || srid == std::numeric_limits<int>::min() )
        tip = tr( "Enter a SRID into the '%1' column" ).arg( tr( "SRID" ) );
    }

    QStringList pkCols = idx.sibling( idx.row(), DbtmPkCol ).data( Qt::UserRole + 1 ).toStringList();
    if ( tip.isEmpty() && !pkCols.isEmpty() )
    {
      QSet<QString> s0( idx.sibling( idx.row(), DbtmPkCol ).data( Qt::UserRole + 2 ).toStringList().toSet() );
      QSet<QString> s1( pkCols.toSet() );
      if ( !s0.intersects( s1 ) )
        tip = tr( "Select columns in the '%1' column that uniquely identify features of this layer" ).arg( tr( "Feature id" ) );
    }

    for ( int i = 0; i < DbtmColumns; i++ )
    {
      QStandardItem *item = itemFromIndex( idx.sibling( idx.row(), i ) );
      if ( tip.isEmpty() )
      {
        if ( i == DbtmSchema )
        {
          item->setData( QVariant(), Qt::DecorationRole );
        }

        item->setFlags( item->flags() | Qt::ItemIsSelectable );
        item->setToolTip( QString() );
      }
      else
      {
        item->setFlags( item->flags() & ~Qt::ItemIsSelectable );

        if ( i == DbtmSchema )
          item->setData( QgsApplication::getThemeIcon( QStringLiteral( "/mIconWarning.svg" ) ), Qt::DecorationRole );

        if ( i == DbtmSchema || i == DbtmTable || i == DbtmGeomCol )
        {
          item->setFlags( item->flags() );
          item->setToolTip( tip );
        }
      }
    }
  }

  return true;
}
/*************************************************************
* Full list update helper methods
*************************************************************/
void list_handling::update_full_list_packages(){
	vector<package>::iterator old_it = content.begin();
	vector<package>::iterator new_it = new_content.begin();
	vector<download>::iterator dit;

	int line_nr = 0;
	bool expanded;

	QStandardItem *pkg;

	vector<view_info> info = get_current_view();
	deselect_list();
	list->setAnimated(false);

	// loop all packages
	while((old_it != content.end()) && (new_it != new_content.end())){

		// compare package items
		QModelIndex index = compare_one_package(line_nr, pkg, old_it, new_it, info, expanded);

		// compare downloads
		compare_downloads(index, new_it, old_it, info);

		if((old_it->name != new_it->name) || (old_it->password != new_it->password)){
			pkg = list_model->item(line_nr, 1);
			if(new_it->password != "")
				pkg->setIcon(QIcon("img/key.png"));
			else if(old_it->password  != "")
				pkg->setIcon(QIcon(""));
			pkg->setText(QString(new_it->name.c_str()));
		}

		if(expanded)
			list->expand(index);

		++old_it;
		++new_it;
		++line_nr;
	}

	if(old_it != content.end()){ // there are more old lines than new ones
		while(old_it != content.end()){

			// delete packages out of model
			list_model->removeRow(line_nr);
			++old_it;
		}

	}else if(new_it != new_content.end()){ // there are more new lines then old ones
		while(new_it != new_content.end()){

			// insert new package lines
			pkg = create_new_package(*new_it, line_nr);

			QModelIndex index = list_model->index(line_nr, 0, QModelIndex()); // downloads need the parent index

			//insert downloads
			int dl_line = 0;
			for(dit = new_it->dls.begin(); dit != new_it->dls.end(); ++dit){ // loop all downloads of that package

				create_new_download(*dit, pkg, dl_line);
				++dl_line;
			}

			list->expand(index);

			++line_nr;
			++new_it;
		}
	}

	list->setAnimated(true);
}
Example #18
0
QString QgsPgTableModel::layerURI( const QModelIndex &index, const QString &connInfo, bool useEstimatedMetadata )
{
  if ( !index.isValid() )
  {
    QgsDebugMsg( QStringLiteral( "invalid index" ) );
    return QString();
  }

  QgsWkbTypes::Type wkbType = ( QgsWkbTypes::Type ) itemFromIndex( index.sibling( index.row(), DbtmType ) )->data( Qt::UserRole + 2 ).toInt();
  if ( wkbType == QgsWkbTypes::Unknown )
  {
    QgsDebugMsg( QStringLiteral( "unknown geometry type" ) );
    // no geometry type selected
    return QString();
  }

  QStandardItem *pkItem = itemFromIndex( index.sibling( index.row(), DbtmPkCol ) );
  QSet<QString> s0( pkItem->data( Qt::UserRole + 1 ).toStringList().toSet() );
  QSet<QString> s1( pkItem->data( Qt::UserRole + 2 ).toStringList().toSet() );
  if ( !s0.isEmpty() && !s0.intersects( s1 ) )
  {
    // no valid primary candidate selected
    QgsDebugMsg( QStringLiteral( "no pk candidate selected" ) );
    return QString();
  }

  QString schemaName = index.sibling( index.row(), DbtmSchema ).data( Qt::DisplayRole ).toString();
  QString tableName = index.sibling( index.row(), DbtmTable ).data( Qt::DisplayRole ).toString();

  QString geomColumnName;
  QString srid;
  if ( wkbType != QgsWkbTypes::NoGeometry )
  {
    geomColumnName = index.sibling( index.row(), DbtmGeomCol ).data( Qt::DisplayRole ).toString();

    srid = index.sibling( index.row(), DbtmSrid ).data( Qt::DisplayRole ).toString();
    bool ok;
    srid.toInt( &ok );
    if ( !ok )
    {
      QgsDebugMsg( QStringLiteral( "srid not numeric" ) );
      return QString();
    }
  }

  bool selectAtId = itemFromIndex( index.sibling( index.row(), DbtmSelectAtId ) )->checkState() == Qt::Checked;
  QString sql = index.sibling( index.row(), DbtmSql ).data( Qt::DisplayRole ).toString();
  bool checkPrimaryKeyUnicity = itemFromIndex( index.sibling( index.row(), DbtmCheckPkUnicity ) )->checkState() == Qt::Checked;

  QgsDataSourceUri uri( connInfo );

  QStringList cols;
  const auto constS1 = s1;
  for ( const QString &col : constS1 )
  {
    cols << QgsPostgresConn::quotedIdentifier( col );
  }

  QgsSettings().setValue( QStringLiteral( "/PostgreSQL/connections/%1/keys/%2/%3" ).arg( mConnName, schemaName, tableName ), QVariant( s1.toList() ) );

  uri.setDataSource( schemaName, tableName, geomColumnName, sql, cols.join( ',' ) );
  uri.setUseEstimatedMetadata( useEstimatedMetadata );
  uri.setWkbType( wkbType );
  uri.setSrid( srid );
  uri.disableSelectAtId( !selectAtId );
  uri.setParam( QStringLiteral( "checkPrimaryKeyUnicity" ), checkPrimaryKeyUnicity ? QLatin1Literal( "1" ) : QLatin1Literal( "0" ) );

  QgsDebugMsg( QStringLiteral( "returning uri %1" ).arg( uri.uri( false ) ) );
  return uri.uri( false );
}
Example #19
0
void QgsGrassTools::addModules( QTreeWidgetItem *parent, QDomElement &element, QTreeWidget *modulesTreeWidget, QStandardItemModel * modulesListModel, bool direct )
{
  QDomNode n = element.firstChild();

  QTreeWidgetItem *item;
  QTreeWidgetItem *lastItem = 0;
  while ( !n.isNull() )
  {
    QDomElement e = n.toElement();
    if ( !e.isNull() )
    {
// QgsDebugMsg(QString("tag = %1").arg(e.tagName()));

      if ( e.tagName() != "section" && e.tagName() != "grass" )
      {
        QgsDebugMsg( QString( "Unknown tag: %1" ).arg( e.tagName() ) );
        continue;
      }

      // Check GRASS version
      QString version_min = e.attribute( "version_min" );
      QString version_max = e.attribute( "version_max" );

      if ( !QgsGrassModuleOption::checkVersion( e.attribute( "version_min" ), e.attribute( "version_max" ) ) )
      {
        n = n.nextSibling();
        continue;
      }

      if ( parent )
      {
        item = new QTreeWidgetItem( parent, lastItem );
      }
      else
      {
        item = new QTreeWidgetItem( modulesTreeWidget, lastItem );
      }

      if ( e.tagName() == "section" )
      {
        QString label = QApplication::translate( "grasslabel", e.attribute( "label" ).toUtf8() );
        QgsDebugMsg( QString( "label = %1" ).arg( label ) );
        item->setText( 0, label );
        item->setExpanded( false );

        addModules( item, e, modulesTreeWidget, modulesListModel, direct );

        lastItem = item;
      }
      else if ( e.tagName() == "grass" )
      { // GRASS module
        QString name = e.attribute( "name" );
        QgsDebugMsgLevel( QString( "name = %1" ).arg( name ), 1 );

        QString path = QgsApplication::pkgDataPath() + "/grass/modules/" + name;
        QgsGrassModule::Description description = QgsGrassModule::description( path );

        if ( !direct || description.direct )
        {
          QString label = description.label;
          QPixmap pixmap = QgsGrassModule::pixmap( path, 32 );

          item->setText( 0, name + " - " + label );
          item->setIcon( 0, QIcon( pixmap ) );
          item->setText( 1, name );
          lastItem = item;

          // Add this item to our list model
          QStandardItem * mypDetailItem = new QStandardItem( name + "\n" + label );
          mypDetailItem->setData( name, Qt::UserRole + 1 ); //for calling runModule later
          QString mySearchText = name + " - " + label;
          mypDetailItem->setData( mySearchText, Qt::UserRole + 2 ); //for filtering later
          mypDetailItem->setData( pixmap, Qt::DecorationRole );
          mypDetailItem->setCheckable( false );
          mypDetailItem->setEditable( false );
          // setData in the delegate with a variantised QgsDetailedItemData
          QgsDetailedItemData myData;
          myData.setTitle( name );
          myData.setDetail( label );
          myData.setIcon( pixmap );
          myData.setCheckable( false );
          myData.setRenderAsWidget( false );
          QVariant myVariant = qVariantFromValue( myData );
          mypDetailItem->setData( myVariant, Qt::UserRole );
          modulesListModel->appendRow( mypDetailItem );
        }
        else
        {
          delete item;
        }
      }
    }
    n = n.nextSibling();
  }

}
Example #20
0
void QgsPgTableModel::addTableEntry( const QgsPostgresLayerProperty &layerProperty )
{
  QgsDebugMsg( layerProperty.toString() );

  // is there already a root item with the given scheme Name?
  QStandardItem *schemaItem = nullptr;

  for ( int i = 0; i < layerProperty.size(); i++ )
  {
    QgsWkbTypes::Type wkbType = layerProperty.types[ i ];
    int srid = layerProperty.srids[ i ];

    if ( wkbType == QgsWkbTypes::Unknown && layerProperty.geometryColName.isEmpty() )
    {
      wkbType = QgsWkbTypes::NoGeometry;
    }

    QString tip;
    bool withTipButSelectable = false;
    if ( wkbType == QgsWkbTypes::Unknown )
    {
      tip = tr( "Specify a geometry type in the '%1' column" ).arg( tr( "Data Type" ) );
    }
    else if ( wkbType != QgsWkbTypes::NoGeometry && srid == std::numeric_limits<int>::min() )
    {
      tip = tr( "Enter a SRID into the '%1' column" ).arg( tr( "SRID" ) );
    }
    else if ( !layerProperty.pkCols.isEmpty() )
    {
      tip = tr( "Select columns in the '%1' column that uniquely identify features of this layer" ).arg( tr( "Feature id" ) );
      withTipButSelectable = true;
    }

    QStandardItem *schemaNameItem = new QStandardItem( layerProperty.schemaName );
    QStandardItem *typeItem = new QStandardItem( iconForWkbType( wkbType ), wkbType == QgsWkbTypes::Unknown ? tr( "Select…" ) : QgsPostgresConn::displayStringForWkbType( wkbType ) );
    typeItem->setData( wkbType == QgsWkbTypes::Unknown, Qt::UserRole + 1 );
    typeItem->setData( wkbType, Qt::UserRole + 2 );
    if ( wkbType == QgsWkbTypes::Unknown )
      typeItem->setFlags( typeItem->flags() | Qt::ItemIsEditable );

    QStandardItem *geomTypeItem = new QStandardItem( QgsPostgresConn::displayStringForGeomType( layerProperty.geometryColType ) );

    QStandardItem *tableItem = new QStandardItem( layerProperty.tableName );
    QStandardItem *commentItem = new QStandardItem( layerProperty.tableComment );
    QStandardItem *geomItem  = new QStandardItem( layerProperty.geometryColName );
    QStandardItem *sridItem  = new QStandardItem( wkbType != QgsWkbTypes::NoGeometry ? QString::number( srid ) : QString() );
    sridItem->setEditable( wkbType != QgsWkbTypes::NoGeometry && srid == std::numeric_limits<int>::min() );
    if ( sridItem->isEditable() )
    {
      sridItem->setText( tr( "Enter…" ) );
      sridItem->setFlags( sridItem->flags() | Qt::ItemIsEditable );
    }

    QStandardItem *pkItem = new QStandardItem( QString() );
    if ( !layerProperty.pkCols.isEmpty() )
    {
      pkItem->setText( tr( "Select…" ) );
      pkItem->setFlags( pkItem->flags() | Qt::ItemIsEditable );
    }
    else
      pkItem->setFlags( pkItem->flags() & ~Qt::ItemIsEditable );

    pkItem->setData( layerProperty.pkCols, Qt::UserRole + 1 );

    QStringList defPk( QgsSettings().value( QStringLiteral( "/PostgreSQL/connections/%1/keys/%2/%3" ).arg( mConnName, layerProperty.schemaName, layerProperty.tableName ), QStringList() ).toStringList() );

    if ( !layerProperty.pkCols.isEmpty() && defPk.isEmpty() )
    {
      // If we have a view with multiple possible columns to be used as the primary key, for convenience
      // let's select the first one - this is what the browser dock already does. We risk that a wrong column
      // will be used, but most of the time we should be fine.
      defPk = QStringList( layerProperty.pkCols[0] );
    }

    pkItem->setData( defPk, Qt::UserRole + 2 );
    if ( !defPk.isEmpty() )
      pkItem->setText( defPk.join( ',' ) );

    QStandardItem *selItem = new QStandardItem( QString() );
    selItem->setFlags( selItem->flags() | Qt::ItemIsUserCheckable );
    selItem->setCheckState( Qt::Checked );
    selItem->setToolTip( headerData( Columns::DbtmSelectAtId, Qt::Orientation::Horizontal, Qt::ToolTipRole ).toString() );

    QStandardItem *checkPkUnicityItem  = new QStandardItem( QString() );
    checkPkUnicityItem->setFlags( checkPkUnicityItem->flags() | Qt::ItemIsUserCheckable );

    // Legacy: default value is determined by project option to trust layer's metadata
    // TODO: remove this default from QGIS 4 and leave default value to false?
    // checkPkUnicity has only effect on views and materialized views, so we can safely disable it
    if ( layerProperty.isView || layerProperty.isMaterializedView )
    {
      checkPkUnicityItem->setCheckState( QgsProject::instance( )->trustLayerMetadata() ? Qt::CheckState::Unchecked : Qt::CheckState::Checked );
      checkPkUnicityItem->setToolTip( headerData( Columns::DbtmCheckPkUnicity, Qt::Orientation::Horizontal, Qt::ToolTipRole ).toString() );
    }
    else
    {
      checkPkUnicityItem->setCheckState( Qt::CheckState::Unchecked );
      checkPkUnicityItem->setFlags( checkPkUnicityItem->flags() & ~ Qt::ItemIsEnabled );
      checkPkUnicityItem->setToolTip( tr( "This option is only available for views and materialized views." ) );
    }

    QStandardItem *sqlItem = new QStandardItem( layerProperty.sql );

    QList<QStandardItem *> childItemList;

    childItemList << schemaNameItem;
    childItemList << tableItem;
    childItemList << commentItem;
    childItemList << geomItem;
    childItemList << geomTypeItem;
    childItemList << typeItem;
    childItemList << sridItem;
    childItemList << pkItem;
    childItemList << selItem;
    childItemList << checkPkUnicityItem;
    childItemList << sqlItem;

    const auto constChildItemList = childItemList;
    for ( QStandardItem *item : constChildItemList )
    {
      if ( tip.isEmpty() || withTipButSelectable )
        item->setFlags( item->flags() | Qt::ItemIsSelectable );
      else
        item->setFlags( item->flags() & ~Qt::ItemIsSelectable );

      if ( tip.isEmpty() && item != checkPkUnicityItem && item != selItem )
      {
        item->setToolTip( QString() );
      }
      else
      {
        if ( item == schemaNameItem )
          item->setData( QgsApplication::getThemeIcon( QStringLiteral( "/mIconWarning.svg" ) ), Qt::DecorationRole );

        if ( item == schemaNameItem || item == tableItem || item == geomItem )
        {
          item->setToolTip( tip );
        }
      }
    }

    if ( !schemaItem )
    {
      QList<QStandardItem *> schemaItems = findItems( layerProperty.schemaName, Qt::MatchExactly, DbtmSchema );

      // there is already an item for this schema
      if ( !schemaItems.isEmpty() )
      {
        schemaItem = schemaItems.at( DbtmSchema );
      }
      else
      {
        // create a new toplevel item for this schema
        schemaItem = new QStandardItem( layerProperty.schemaName );
        schemaItem->setFlags( Qt::ItemIsEnabled );
        invisibleRootItem()->setChild( invisibleRootItem()->rowCount(), schemaItem );
      }
    }

    schemaItem->appendRow( childItemList );

    ++mTableCount;
  }
}
Example #21
0
QSizeF QgsComposerLegend::paintAndDetermineSize( QPainter* painter )
{
  QSizeF size;
  double maxXCoord = 0;



  //go through model...
  QStandardItem* rootItem = mLegendModel.invisibleRootItem();
  if ( !rootItem )
  {
    return size;
  }


  if ( painter )
  {
    painter->save();
    drawBackground( painter );
    painter->setPen( QPen( QColor( 0, 0, 0 ) ) );
  }

  int numLayerItems = rootItem->rowCount();
  QStandardItem* currentLayerItem = 0;
  double currentYCoordinate = mBoxSpace;

  //font metrics

  //draw title
  currentYCoordinate += fontAscentMillimeters( mTitleFont );
  if ( painter )
  {
    painter->setPen( QColor( 0, 0, 0 ) );
    drawText( painter, mBoxSpace, currentYCoordinate, mTitle, mTitleFont );
  }


  maxXCoord = 2 * mBoxSpace + textWidthMillimeters( mTitleFont, mTitle );

  double currentItemMaxX = 0; //maximum x-coordinate for current item
  for ( int i = 0; i < numLayerItems; ++i )
  {
    currentLayerItem = rootItem->child( i );
    QgsComposerLegendItem* currentLegendItem = dynamic_cast<QgsComposerLegendItem*>( currentLayerItem );
    if ( currentLegendItem )
    {
      QgsComposerLegendItem::ItemType type = currentLegendItem->itemType();
      if ( type == QgsComposerLegendItem::GroupItem )
      {
        drawGroupItem( painter, dynamic_cast<QgsComposerGroupItem*>( currentLegendItem ), currentYCoordinate, currentItemMaxX );
        maxXCoord = qMax( maxXCoord, currentItemMaxX );
      }
      else if ( type == QgsComposerLegendItem::LayerItem )
      {
        drawLayerItem( painter, dynamic_cast<QgsComposerLayerItem*>( currentLegendItem ), currentYCoordinate, currentItemMaxX );
        maxXCoord = qMax( maxXCoord, currentItemMaxX );
      }
    }
  }

  currentYCoordinate += mBoxSpace;

  size.setHeight( currentYCoordinate );
  size.setWidth( maxXCoord );

  //adjust box if width or height is to small
  if ( painter && currentYCoordinate > rect().height() )
  {
    setSceneRect( QRectF( transform().dx(), transform().dy(), rect().width(), currentYCoordinate ) );
  }
  if ( painter && maxXCoord > rect().width() )
  {
    setSceneRect( QRectF( transform().dx(), transform().dy(), maxXCoord, rect().height() ) );
  }

  if ( painter )
  {
    painter->restore();

    //draw frame and selection boxes if necessary
    drawFrame( painter );
    if ( isSelected() )
    {
      drawSelectionBoxes( painter );
    }
  }

  return size;
}
Example #22
0
bool Peers::add_bss(const char *cmd)
{
	char reply[2048];
	size_t reply_len;

	if (hide_ap)
		return false;

	reply_len = sizeof(reply) - 1;
	if (wpagui->ctrlRequest(cmd, reply, &reply_len) < 0)
		return false;
	reply[reply_len] = '\0';

	QString bss(reply);
	if (bss.isEmpty() || bss.startsWith("FAIL"))
		return false;

	QString ssid, bssid, flags, wps_name, pri_dev_type;
	int id = -1;

	QStringList lines = bss.split(QRegExp("\\n"));
	for (QStringList::Iterator it = lines.begin();
	     it != lines.end(); it++) {
		int pos = (*it).indexOf('=') + 1;
		if (pos < 1)
			continue;

		if ((*it).startsWith("bssid="))
			bssid = (*it).mid(pos);
		else if ((*it).startsWith("id="))
			id = (*it).mid(pos).toInt();
		else if ((*it).startsWith("flags="))
			flags = (*it).mid(pos);
		else if ((*it).startsWith("ssid="))
			ssid = (*it).mid(pos);
		else if ((*it).startsWith("wps_device_name="))
			wps_name = (*it).mid(pos);
		else if ((*it).startsWith("wps_primary_device_type="))
			pri_dev_type = (*it).mid(pos);
	}

	QString name = wps_name;
	if (name.isEmpty())
		name = ssid + "\n" + bssid;

	QStandardItem *item = new QStandardItem(*ap_icon, name);
	if (item) {
		item->setData(bssid, peer_role_address);
		if (id >= 0)
			item->setData(id, peer_role_bss_id);
		int type;
		if (flags.contains("[WPS"))
			type = PEER_TYPE_AP_WPS;
		else
			type = PEER_TYPE_AP;
		item->setData(type, peer_role_type);

		for (int i = 0; i < lines.size(); i++) {
			if (lines[i].length() > 60) {
				lines[i].remove(60, lines[i].length());
				lines[i] += "..";
			}
		}
		item->setToolTip(ItemType(type));
		item->setData(lines.join("\n"), peer_role_details);
		if (!pri_dev_type.isEmpty())
			item->setData(pri_dev_type,
				      peer_role_pri_dev_type);
		if (!ssid.isEmpty())
			item->setData(ssid, peer_role_ssid);
		model.appendRow(item);

		lines = bss.split(QRegExp("\\n"));
		for (QStringList::Iterator it = lines.begin();
		     it != lines.end(); it++) {
			if ((*it).startsWith("p2p_group_client:"))
				add_p2p_group_client(item,
						     (*it).mid(18));
		}
	}

	return true;
}
Example #23
0
KoRecentDocumentsPane::KoRecentDocumentsPane(QWidget* parent, const QString& header)
        : KoDetailsPane(parent, header)
        , d(new KoRecentDocumentsPanePrivate)
{
    setFocusProxy(m_documentList);
    m_openButton->setText(i18n("Open This Document"));
    m_openButton->setIcon(koIcon("document-open"));

    m_alwaysUseCheckBox->hide();

    model()->setSortRole(0); // Disable sorting

    // load list of recent files from config
    KConfigGroup config(KSharedConfig::openConfig(), "RecentFiles");

    QString fileKey;
    QString fileValue;
    QUrl url;
    QString nameValue;
    KFileItemList fileList;
    QStandardItem* rootItem = model()->invisibleRootItem();

    for (int i = 1; i <= MAX_RECENTFILES_ENTRIES; ++i) {
        fileValue = config.readPathEntry(QString("File%1").arg(i), QString());

        // ignore empty entries
        if (fileValue.isEmpty()) {
            continue;
        }

        url = QUrl::fromUserInput(fileValue);

        // ignore entries for files known to no longer exist
        if (url.isLocalFile() && !QFile::exists(url.toLocalFile())) {
            continue;
        }
        // ignore duplicated entries
        if (!fileList.findByUrl(url).isNull()) {
            continue;
        }

        nameValue = config.readPathEntry(QString("Name%1").arg(i), QString());
        // handle name entries with empty strings
        if (nameValue.isEmpty()) {
            nameValue = url.fileName();
        }

        KFileItem fileItem(url);
        fileList.prepend(fileItem);
        const QIcon icon = QIcon::fromTheme(fileItem.iconName());
        KoFileListItem* item = new KoFileListItem(icon, nameValue, fileItem);
        item->setEditable(false);
        rootItem->insertRow(0, item);
    }


    //Select the first file
    QModelIndex firstIndex = model()->indexFromItem(model()->item(0));
    m_documentList->selectionModel()->select(firstIndex, QItemSelectionModel::Select);
    m_documentList->selectionModel()->setCurrentIndex(firstIndex, QItemSelectionModel::Select);

    QStringList availablePlugins = KIO::PreviewJob::availablePlugins();
    KIO::PreviewJob *previewJob = KIO::filePreview(fileList, QSize(IconExtent, IconExtent), &availablePlugins);

    d->m_previewJobs.append(previewJob);
    connect(previewJob, SIGNAL(result(KJob*)), SLOT(previewResult(KJob*)));
    connect(previewJob, SIGNAL(gotPreview(KFileItem,QPixmap)),
            SLOT(updateIcon(KFileItem,QPixmap)));
}
Example #24
0
void Peers::event_notify(WpaMsg msg)
{
	QString text = msg.getMsg();

	if (text.startsWith(WPS_EVENT_PIN_NEEDED)) {
		/*
		 * WPS-PIN-NEEDED 5a02a5fa-9199-5e7c-bc46-e183d3cb32f7
		 * 02:2a:c4:18:5b:f3
		 * [Wireless Client|Company|cmodel|123|12345|1-0050F204-1]
		 */
		QStringList items = text.split(' ');
		QString uuid = items[1];
		QString addr = items[2];
		QString name = "";

		QStandardItem *item = find_addr(addr);
		if (item)
			return;

		int pos = text.indexOf('[');
		if (pos >= 0) {
			int pos2 = text.lastIndexOf(']');
			if (pos2 >= pos) {
				items = text.mid(pos + 1, pos2 - pos - 1).
					split('|');
				name = items[0];
				items.append(addr);
			}
		}

		item = new QStandardItem(*laptop_icon, name);
		if (item) {
			item->setData(addr, peer_role_address);
			item->setData(PEER_TYPE_WPS_PIN_NEEDED,
				      peer_role_type);
			item->setToolTip(ItemType(PEER_TYPE_WPS_PIN_NEEDED));
			item->setData(items.join("\n"), peer_role_details);
			item->setData(items[5], peer_role_pri_dev_type);
			model.appendRow(item);
		}
		return;
	}

	if (text.startsWith(AP_STA_CONNECTED)) {
		/* AP-STA-CONNECTED 02:2a:c4:18:5b:f3 */
		QStringList items = text.split(' ');
		QString addr = items[1];
		QStandardItem *item = find_addr(addr);
		if (item == NULL || item->data(peer_role_type).toInt() !=
		    PEER_TYPE_ASSOCIATED_STATION)
			add_single_station(addr.toAscii().constData());
		return;
	}

	if (text.startsWith(AP_STA_DISCONNECTED)) {
		/* AP-STA-DISCONNECTED 02:2a:c4:18:5b:f3 */
		QStringList items = text.split(' ');
		QString addr = items[1];

		if (model.rowCount() == 0)
			return;

		QModelIndexList lst = model.match(model.index(0, 0),
						  peer_role_address, addr, -1);
		for (int i = 0; i < lst.size(); i++) {
			QStandardItem *item = model.itemFromIndex(lst[i]);
			if (item && item->data(peer_role_type).toInt() ==
			    PEER_TYPE_ASSOCIATED_STATION) {
				model.removeRow(lst[i].row());
				break;
			}
		}
		return;
	}

	if (text.startsWith(P2P_EVENT_DEVICE_FOUND)) {
		/*
		 * P2P-DEVICE-FOUND 02:b5:64:63:30:63
		 * p2p_dev_addr=02:b5:64:63:30:63 pri_dev_type=1-0050f204-1
		 * name='Wireless Client' config_methods=0x84 dev_capab=0x21
		 * group_capab=0x0
		 */
		QStringList items =
			text.split(QRegExp(" (?=[^']*('[^']*'[^']*)*$)"));
		QString addr = items[1];
		QString name = "";
		QString pri_dev_type;
		int config_methods = 0;
		for (int i = 0; i < items.size(); i++) {
			QString str = items.at(i);
			if (str.startsWith("name='"))
				name = str.section('\'', 1, -2);
			else if (str.startsWith("config_methods="))
				config_methods =
					str.section('=', 1).toInt(0, 0);
			else if (str.startsWith("pri_dev_type="))
				pri_dev_type = str.section('=', 1);
		}

		QStandardItem *item = find_addr(addr);
		if (item) {
			int type = item->data(peer_role_type).toInt();
			if (type == PEER_TYPE_P2P)
				return;
		}

		item = new QStandardItem(*default_icon, name);
		if (item) {
			item->setData(addr, peer_role_address);
			item->setData(config_methods,
				      peer_role_config_methods);
			item->setData(PEER_TYPE_P2P, peer_role_type);
			if (!pri_dev_type.isEmpty())
				item->setData(pri_dev_type,
					      peer_role_pri_dev_type);
			item->setData(items.join(QString("\n")),
				      peer_role_details);
			item->setToolTip(ItemType(PEER_TYPE_P2P));
			model.appendRow(item);
		}

		item = find_addr_type(addr,
				      PEER_TYPE_P2P_PERSISTENT_GROUP_CLIENT);
		if (item)
			item->setBackground(Qt::NoBrush);
	}

	if (text.startsWith(P2P_EVENT_GROUP_STARTED)) {
		/* P2P-GROUP-STARTED wlan0-p2p-0 GO ssid="DIRECT-3F"
		 * passphrase="YOyTkxID" go_dev_addr=02:40:61:c2:f3:b7
		 * [PERSISTENT] */
		QStringList items = text.split(' ');
		if (items.size() < 4)
			return;

		int pos = text.indexOf(" ssid=\"");
		if (pos < 0)
			return;
		QString ssid = text.mid(pos + 7);
		pos = ssid.indexOf(" passphrase=\"");
		if (pos < 0)
			pos = ssid.indexOf(" psk=");
		if (pos >= 0)
			ssid.truncate(pos);
		pos = ssid.lastIndexOf('"');
		if (pos >= 0)
			ssid.truncate(pos);

		QStandardItem *item = new QStandardItem(*group_icon, ssid);
		if (item) {
			item->setData(PEER_TYPE_P2P_GROUP, peer_role_type);
			item->setData(items[1], peer_role_ifname);
			QString details;
			if (items[2] == "GO") {
				details = tr("P2P GO for interface ") +
					items[1];
			} else {
				details = tr("P2P client for interface ") +
					items[1];
			}
			if (text.contains(" [PERSISTENT]"))
				details += "\nPersistent group";
			item->setData(details, peer_role_details);
			item->setToolTip(ItemType(PEER_TYPE_P2P_GROUP));
			model.appendRow(item);
		}
	}

	if (text.startsWith(P2P_EVENT_GROUP_REMOVED)) {
		/* P2P-GROUP-REMOVED wlan0-p2p-0 GO */
		QStringList items = text.split(' ');
		if (items.size() < 2)
			return;

		if (model.rowCount() == 0)
			return;

		QModelIndexList lst = model.match(model.index(0, 0),
						  peer_role_ifname, items[1]);
		for (int i = 0; i < lst.size(); i++)
			model.removeRow(lst[i].row());
		return;
	}

	if (text.startsWith(P2P_EVENT_PROV_DISC_SHOW_PIN)) {
		/* P2P-PROV-DISC-SHOW-PIN 02:40:61:c2:f3:b7 12345670 */
		QStringList items = text.split(' ');
		if (items.size() < 3)
			return;
		QString addr = items[1];
		QString pin = items[2];

		QStandardItem *item = find_addr_type(addr, PEER_TYPE_P2P);
		if (item == NULL)
			return;
		item->setData(SEL_METHOD_PIN_LOCAL_DISPLAY,
			      peer_role_selected_method);
		item->setData(pin, peer_role_selected_pin);
		QVariant var = item->data(peer_role_requested_method);
		if (var.isValid() &&
		    var.toInt() == SEL_METHOD_PIN_LOCAL_DISPLAY) {
			ctx_item = item;
			ctx_p2p_display_pin_pd();
		}
		return;
	}

	if (text.startsWith(P2P_EVENT_PROV_DISC_ENTER_PIN)) {
		/* P2P-PROV-DISC-ENTER-PIN 02:40:61:c2:f3:b7 */
		QStringList items = text.split(' ');
		if (items.size() < 2)
			return;
		QString addr = items[1];

		QStandardItem *item = find_addr_type(addr, PEER_TYPE_P2P);
		if (item == NULL)
			return;
		item->setData(SEL_METHOD_PIN_PEER_DISPLAY,
			      peer_role_selected_method);
		QVariant var = item->data(peer_role_requested_method);
		if (var.isValid() &&
		    var.toInt() == SEL_METHOD_PIN_PEER_DISPLAY) {
			ctx_item = item;
			ctx_p2p_connect();
		}
		return;
	}

	if (text.startsWith(P2P_EVENT_INVITATION_RECEIVED)) {
		/* P2P-INVITATION-RECEIVED sa=02:f0:bc:44:87:62 persistent=4 */
		QStringList items = text.split(' ');
		if (items.size() < 3)
			return;
		if (!items[1].startsWith("sa=") ||
		    !items[2].startsWith("persistent="))
			return;
		QString addr = items[1].mid(3);
		int id = items[2].mid(11).toInt();

		char cmd[100];
		char reply[100];
		size_t reply_len;

		snprintf(cmd, sizeof(cmd), "GET_NETWORK %d ssid", id);
		reply_len = sizeof(reply) - 1;
		if (wpagui->ctrlRequest(cmd, reply, &reply_len) < 0)
			return;
		reply[reply_len] = '\0';
		QString name;
		char *pos = strrchr(reply, '"');
		if (pos && reply[0] == '"') {
			*pos = '\0';
			name = reply + 1;
		} else
			name = reply;

		QStandardItem *item;
		item = find_addr_type(addr, PEER_TYPE_P2P_INVITATION);
		if (item)
			model.removeRow(item->row());

		item = new QStandardItem(*invitation_icon, name);
		if (!item)
			return;
		item->setData(PEER_TYPE_P2P_INVITATION, peer_role_type);
		item->setToolTip(ItemType(PEER_TYPE_P2P_INVITATION));
		item->setData(addr, peer_role_address);
		item->setData(id, peer_role_network_id);

		model.appendRow(item);

		enable_persistent(id);

		return;
	}

	if (text.startsWith(P2P_EVENT_INVITATION_RESULT)) {
		/* P2P-INVITATION-RESULT status=1 */
		/* TODO */
		return;
	}

	if (text.startsWith(WPS_EVENT_ER_AP_ADD)) {
		/*
		 * WPS-ER-AP-ADD 87654321-9abc-def0-1234-56789abc0002
		 * 02:11:22:33:44:55 pri_dev_type=6-0050F204-1 wps_state=1
		 * |Very friendly name|Company|Long description of the model|
		 * WAP|http://w1.fi/|http://w1.fi/hostapd/
		 */
		QStringList items = text.split(' ');
		if (items.size() < 5)
			return;
		QString uuid = items[1];
		QString addr = items[2];
		QString pri_dev_type = items[3].mid(13);
		int wps_state = items[4].mid(10).toInt();

		int pos = text.indexOf('|');
		if (pos < 0)
			return;
		items = text.mid(pos + 1).split('|');
		if (items.size() < 1)
			return;

		QStandardItem *item = find_uuid(uuid);
		if (item)
			return;

		item = new QStandardItem(*ap_icon, items[0]);
		if (item) {
			item->setData(uuid, peer_role_uuid);
			item->setData(addr, peer_role_address);
			int type = wps_state == 2 ? PEER_TYPE_WPS_ER_AP:
				PEER_TYPE_WPS_ER_AP_UNCONFIGURED;
			item->setData(type, peer_role_type);
			item->setToolTip(ItemType(type));
			item->setData(pri_dev_type, peer_role_pri_dev_type);
			item->setData(items.join(QString("\n")),
				      peer_role_details);
			model.appendRow(item);
		}

		return;
	}

	if (text.startsWith(WPS_EVENT_ER_AP_REMOVE)) {
		/* WPS-ER-AP-REMOVE 87654321-9abc-def0-1234-56789abc0002 */
		QStringList items = text.split(' ');
		if (items.size() < 2)
			return;
		if (model.rowCount() == 0)
			return;

		QModelIndexList lst = model.match(model.index(0, 0),
						  peer_role_uuid, items[1]);
		for (int i = 0; i < lst.size(); i++) {
			QStandardItem *item = model.itemFromIndex(lst[i]);
			if (item &&
			    (item->data(peer_role_type).toInt() ==
			     PEER_TYPE_WPS_ER_AP ||
			     item->data(peer_role_type).toInt() ==
			     PEER_TYPE_WPS_ER_AP_UNCONFIGURED))
				model.removeRow(lst[i].row());
		}
		return;
	}

	if (text.startsWith(WPS_EVENT_ER_ENROLLEE_ADD)) {
		/*
		 * WPS-ER-ENROLLEE-ADD 2b7093f1-d6fb-5108-adbb-bea66bb87333
		 * 02:66:a0:ee:17:27 M1=1 config_methods=0x14d dev_passwd_id=0
		 * pri_dev_type=1-0050F204-1
		 * |Wireless Client|Company|cmodel|123|12345|
		 */
		QStringList items = text.split(' ');
		if (items.size() < 3)
			return;
		QString uuid = items[1];
		QString addr = items[2];
		QString pri_dev_type = items[6].mid(13);
		int config_methods = -1;
		int dev_passwd_id = -1;

		for (int i = 3; i < items.size(); i++) {
			int pos = items[i].indexOf('=') + 1;
			if (pos < 1)
				continue;
			QString val = items[i].mid(pos);
			if (items[i].startsWith("config_methods=")) {
				config_methods = val.toInt(0, 0);
			} else if (items[i].startsWith("dev_passwd_id=")) {
				dev_passwd_id = val.toInt();
			}
		}

		int pos = text.indexOf('|');
		if (pos < 0)
			return;
		items = text.mid(pos + 1).split('|');
		if (items.size() < 1)
			return;
		QString name = items[0];
		if (name.length() == 0)
			name = addr;

		remove_enrollee_uuid(uuid);

		QStandardItem *item;
		item = new QStandardItem(*laptop_icon, name);
		if (item) {
			item->setData(uuid, peer_role_uuid);
			item->setData(addr, peer_role_address);
			item->setData(PEER_TYPE_WPS_ER_ENROLLEE,
				      peer_role_type);
			item->setToolTip(ItemType(PEER_TYPE_WPS_ER_ENROLLEE));
			item->setData(items.join(QString("\n")),
				      peer_role_details);
			item->setData(pri_dev_type, peer_role_pri_dev_type);
			if (config_methods >= 0)
				item->setData(config_methods,
					      peer_role_config_methods);
			if (dev_passwd_id >= 0)
				item->setData(dev_passwd_id,
					      peer_role_dev_passwd_id);
			model.appendRow(item);
		}

		return;
	}

	if (text.startsWith(WPS_EVENT_ER_ENROLLEE_REMOVE)) {
		/*
		 * WPS-ER-ENROLLEE-REMOVE 2b7093f1-d6fb-5108-adbb-bea66bb87333
		 * 02:66:a0:ee:17:27
		 */
		QStringList items = text.split(' ');
		if (items.size() < 2)
			return;
		remove_enrollee_uuid(items[1]);
		return;
	}

	if (text.startsWith(WPS_EVENT_ENROLLEE_SEEN)) {
		/* TODO: need to time out this somehow or remove on successful
		 * WPS run, etc. */
		/*
		 * WPS-ENROLLEE-SEEN 02:00:00:00:01:00
		 * 572cf82f-c957-5653-9b16-b5cfb298abf1 1-0050F204-1 0x80 4 1
		 * [Wireless Client]
		 * (MAC addr, UUID-E, pri dev type, config methods,
		 * dev passwd id, request type, [dev name])
		 */
		QStringList items = text.split(' ');
		if (items.size() < 7)
			return;
		QString addr = items[1];
		QString uuid = items[2];
		QString pri_dev_type = items[3];
		int config_methods = items[4].toInt(0, 0);
		int dev_passwd_id = items[5].toInt();
		QString name;

		QStandardItem *item = find_addr(addr);
		if (item) {
			int type = item->data(peer_role_type).toInt();
			if (type == PEER_TYPE_ASSOCIATED_STATION)
				return; /* already associated */
		}

		int pos = text.indexOf('[');
		if (pos >= 0) {
			int pos2 = text.lastIndexOf(']');
			if (pos2 >= pos) {
				QStringList items2 =
					text.mid(pos + 1, pos2 - pos - 1).
					split('|');
				name = items2[0];
			}
		}
		if (name.isEmpty())
			name = addr;

		item = find_uuid(uuid);
		if (item) {
			QVariant var = item->data(peer_role_config_methods);
			QVariant var2 = item->data(peer_role_dev_passwd_id);
			if ((var.isValid() && config_methods != var.toInt()) ||
			    (var2.isValid() && dev_passwd_id != var2.toInt()))
				remove_enrollee_uuid(uuid);
			else
				return;
		}

		item = new QStandardItem(*laptop_icon, name);
		if (item) {
			item->setData(uuid, peer_role_uuid);
			item->setData(addr, peer_role_address);
			item->setData(PEER_TYPE_WPS_ENROLLEE,
				      peer_role_type);
			item->setToolTip(ItemType(PEER_TYPE_WPS_ENROLLEE));
			item->setData(items.join(QString("\n")),
				      peer_role_details);
			item->setData(pri_dev_type, peer_role_pri_dev_type);
			item->setData(config_methods,
				      peer_role_config_methods);
			item->setData(dev_passwd_id, peer_role_dev_passwd_id);
			model.appendRow(item);
		}

		return;
	}

	if (text.startsWith(WPA_EVENT_BSS_ADDED)) {
		/* CTRL-EVENT-BSS-ADDED 34 00:11:22:33:44:55 */
		QStringList items = text.split(' ');
		if (items.size() < 2)
			return;
		char cmd[20];
		snprintf(cmd, sizeof(cmd), "BSS ID-%d", items[1].toInt());
		add_bss(cmd);
		return;
	}

	if (text.startsWith(WPA_EVENT_BSS_REMOVED)) {
		/* CTRL-EVENT-BSS-REMOVED 34 00:11:22:33:44:55 */
		QStringList items = text.split(' ');
		if (items.size() < 2)
			return;
		remove_bss(items[1].toInt());
		return;
	}
}
NavigatorTreeModel::ItemRow NavigatorTreeModel::createItemRow(const ModelNode &node)
{
    Q_ASSERT(node.isValid());

    uint hash = qHash(node);

    const bool dropEnabled = node.metaInfo().isValid();

    QStandardItem *idItem = new QStandardItem;
    idItem->setDragEnabled(true);
    idItem->setDropEnabled(dropEnabled);
    idItem->setEditable(true);
    idItem->setData(hash, Qt::UserRole);

    #ifdef _LOCK_ITEMS_
    QStandardItem *lockItem = new QStandardItem;
    lockItem->setDragEnabled(true);
    lockItem->setDropEnabled(dropEnabled);
    lockItem->setEditable(false);
    lockItem->setCheckable(true);
    lockItem->setData(hash, Qt::UserRole);
    #endif

    QStandardItem *visibilityItem = new QStandardItem;
    visibilityItem->setDropEnabled(dropEnabled);
    visibilityItem->setCheckable(true);
    visibilityItem->setEditable(false);
    visibilityItem->setData(hash, Qt::UserRole);
    if (node.isRootNode()) {
        visibilityItem->setCheckable(false);
    }

    #ifdef _LOCK_ITEMS_
    return ItemRow(idItem, lockItem, visibilityItem);
    #else
    return ItemRow(idItem, visibilityItem);
    #endif
}
ConfigurationContentsWidget::ConfigurationContentsWidget(Window *window) : ContentsWidget(window),
	m_model(new QStandardItemModel(this)),
	m_ui(new Ui::ConfigurationContentsWidget)
{
	m_ui->setupUi(this);

	QSettings defaults(QLatin1String(":/schemas/options.ini"), QSettings::IniFormat, this);
	const QStringList groups = defaults.childGroups();

	for (int i = 0; i < groups.count(); ++i)
	{
		QStandardItem *groupItem = new QStandardItem(Utils::getIcon(QLatin1String("inode-directory")), groups.at(i));

		defaults.beginGroup(groups.at(i));

		const QStringList keys = defaults.childGroups();

		for (int j = 0; j < keys.count(); ++j)
		{
			const QString key = QStringLiteral("%1/%2").arg(groups.at(i)).arg(keys.at(j));
			const QString type = defaults.value(QStringLiteral("%1/type").arg(keys.at(j))).toString();
			const QVariant defaultValue = SettingsManager::getDefaultValue(key);
			const QVariant value = SettingsManager::getValue(key);
			QList<QStandardItem*> optionItems;
			optionItems.append(new QStandardItem(keys.at(j)));
			optionItems.append(new QStandardItem(type));
			optionItems.append(new QStandardItem(value.toString()));
			optionItems[2]->setData(QSize(-1, 30), Qt::SizeHintRole);
			optionItems[2]->setData(key, Qt::UserRole);
			optionItems[2]->setData(type, (Qt::UserRole + 1));
			optionItems[2]->setData(((type == "enumeration") ? defaults.value(QStringLiteral("%1/choices").arg(keys.at(j))).toStringList() : QVariant()), (Qt::UserRole + 2));

			if (value != defaultValue)
			{
				QFont font = optionItems[0]->font();
				font.setBold(true);

				optionItems[0]->setFont(font);
			}

			groupItem->appendRow(optionItems);
		}

		defaults.endGroup();

		m_model->appendRow(groupItem);
	}

	QStringList labels;
	labels << tr("Name") << tr("Type") << tr("Value");

	m_model->setHorizontalHeaderLabels(labels);
	m_model->sort(0);

	m_ui->configurationView->setModel(m_model);
	m_ui->configurationView->setItemDelegate(new ItemDelegate(this));
	m_ui->configurationView->setItemDelegateForColumn(2, new OptionDelegate(false, this));
	m_ui->configurationView->header()->setTextElideMode(Qt::ElideRight);

	connect(SettingsManager::getInstance(), SIGNAL(valueChanged(QString,QVariant)), this, SLOT(optionChanged(QString,QVariant)));
	connect(m_ui->configurationView->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), this, SLOT(currentChanged(QModelIndex,QModelIndex)));
	connect(m_ui->filterLineEdit, SIGNAL(textChanged(QString)), this, SLOT(filterConfiguration(QString)));
}
Example #27
0
static  QStandardItem *createEditableItem(const QString &text)
{
    QStandardItem *rc = new QStandardItem(text);
    rc->setFlags(Qt::ItemIsEnabled|Qt::ItemIsEditable|Qt::ItemIsSelectable);
    return rc;
}
Example #28
0
void ArgumentsEditor::setupCall()
{
    m_model->clear();

    QStringList headers;
    headers.append(tr("Argument"));
    headers.append(tr("Value"));
    m_model->setColumnCount(2);
    m_model->setHorizontalHeaderLabels(headers);
    m_ui.argsTabWidget->removeTab(
        m_ui.argsTabWidget->indexOf(m_ui.shaderTab));

    if (!m_call)
        return;

    m_ui.callLabel->setText(m_call->name());
    QStandardItem *rootItem = m_model->invisibleRootItem();
    for (int i = 0; i < m_call->argNames().count(); ++i) {
        QString argName = m_call->argNames()[i];
        QVariant val = m_call->arguments()[i];
        QStandardItem *nameItem = new QStandardItem(argName);
        nameItem->setFlags(nameItem->flags() ^ Qt::ItemIsEditable);
        QList<QStandardItem*> topRow;
        topRow.append(nameItem);

        if (val.canConvert<ApiArray>()) {
            ApiArray array = val.value<ApiArray>();
            QVector<QVariant> vals = array.values();

            QVariant firstVal = vals.value(0);
            if (firstVal.userType() == QVariant::String) {
                m_ui.argsTabWidget->addTab(
                    m_ui.shaderTab, argName);
                setupShaderEditor(vals);
                delete nameItem;
                continue;
            } else if (isVariantEditable(firstVal)) {
                for (int i = 0; i < vals.count(); ++i) {
                    QList<QStandardItem*> row;

                    QStandardItem *idx = new QStandardItem();
                    idx->setFlags(idx->flags() ^ Qt::ItemIsEditable);
                    idx->setText(tr("%1)").arg(i));

                    QStandardItem *col = new QStandardItem();
                    col->setFlags(col->flags() | Qt::ItemIsEditable);
                    col->setData(vals[i], Qt::EditRole);
                    row.append(idx);
                    row.append(col);
                    nameItem->appendRow(row);
                }
            } else {
                qDebug()<<"\tUnsupported array = "<<firstVal;
                delete nameItem;
                continue;
            }
        } else  if (val.canConvert<ApiPointer>()) {
            ApiPointer ptr = val.value<ApiPointer>();
            QStandardItem *item = new QStandardItem();
            item->setFlags(item->flags() ^ Qt::ItemIsEditable);
            item->setText(ptr.toString());
            QIcon icon(":/resources/emblem-locked.png");
            item->setIcon(icon);
            item->setToolTip(tr("Argument is read-only"));
            topRow.append(item);
        } else if (val.canConvert<ApiEnum>()) {
            ApiEnum en = val.value<ApiEnum>();
            QStandardItem *item = new QStandardItem();
            item->setFlags(item->flags() ^ Qt::ItemIsEditable);
            item->setText(en.toString());
            QIcon icon(":/resources/emblem-locked.png");
            item->setIcon(icon);
            item->setToolTip(tr("Argument is read-only"));
            topRow.append(item);
        } else if (val.canConvert<ApiBitmask>()) {
            ApiBitmask mask = val.value<ApiBitmask>();
            QStandardItem *item = new QStandardItem();
            item->setFlags(item->flags() ^ Qt::ItemIsEditable);
            item->setText(mask.toString());
            QIcon icon(":/resources/emblem-locked.png");
            item->setIcon(icon);
            item->setToolTip(tr("Argument is read-only"));
            topRow.append(item);
        } else if (val.canConvert<ApiStruct>()) {
            ApiStruct str = val.value<ApiStruct>();
            QStandardItem *item = new QStandardItem();
            item->setFlags(item->flags() ^ Qt::ItemIsEditable);
            item->setText(str.toString());
            QIcon icon(":/resources/emblem-locked.png");
            item->setIcon(icon);
            item->setToolTip(tr("Argument is read-only"));
            topRow.append(item);
        } else if (val.userType() == QVariant::ByteArray) {
            QByteArray ba = val.value<QByteArray>();
            QStandardItem *item = new QStandardItem();
            item->setFlags(item->flags() ^ Qt::ItemIsEditable);
            item->setText(
                tr("<binary data, size = %1 bytes>").arg(ba.size()));
            QIcon icon(":/resources/emblem-locked.png");
            item->setIcon(icon);
            item->setToolTip(tr("Argument is read-only"));
            topRow.append(item);
        } else {
            QStandardItem *item
                = new QStandardItem();

            if (isVariantEditable(val)) {
                item->setFlags(item->flags() | Qt::ItemIsEditable);
            } else {
                QIcon icon(":/resources/emblem-locked.png");
                item->setIcon(icon);
                item->setFlags(item->flags() ^ Qt::ItemIsEditable);
                item->setToolTip(tr("Argument is read-only"));
            }
            item->setData(val, Qt::EditRole);
            topRow.append(item);
        }
        rootItem->appendRow(topRow);
    }
}
/** Redefined for custom sorting. */
bool LibraryFilterProxyModel::lessThan(const QModelIndex &idxLeft, const QModelIndex &idxRight) const
{
	bool result = false;
	QStandardItemModel *model = qobject_cast<QStandardItemModel *>(this->sourceModel());
	QStandardItem *left = model->itemFromIndex(idxLeft);
	QStandardItem *right = model->itemFromIndex(idxRight);

	int lType = left->type();
	int rType = right->type();
	switch (lType) {
	case Miam::IT_Artist:
		result = QSortFilterProxyModel::lessThan(idxLeft, idxRight);
		break;

	case Miam::IT_Album:
		if (rType == Miam::IT_Album) {
			int lYear = left->data(Miam::DF_Year).toInt();
			int rYear = right->data(Miam::DF_Year).toInt();
			if (SettingsPrivate::instance()->insertPolicy() == SettingsPrivate::IP_Artists && lYear >= 0 && rYear >= 0) {
				if (sortOrder() == Qt::AscendingOrder) {
					if (lYear == rYear) {
						result = QSortFilterProxyModel::lessThan(idxLeft, idxRight);
					} else {
						result = lYear < rYear;
					}
				} else {
					result = lYear > rYear;
				}
			} else {
				result = QSortFilterProxyModel::lessThan(idxLeft, idxRight);
			}
		} else {
			result = QSortFilterProxyModel::lessThan(idxLeft, idxRight);
		}
		break;

	case Miam::IT_Disc:
		if (rType == Miam::IT_Disc) {
			int dLeft = left->data(Miam::DF_DiscNumber).toInt();
			int dRight = right->data(Miam::DF_DiscNumber).toInt();
			result = (dLeft < dRight && sortOrder() == Qt::AscendingOrder) ||
					  (dRight < dLeft && sortOrder() == Qt::DescendingOrder);
		}
		break;

	case Miam::IT_Separator:
		// Separators have a different sorting order when Hierarchical Order starts with Years
		if (SettingsPrivate::instance()->insertPolicy() == SettingsPrivate::IP_Years) {
			if (sortOrder() == Qt::AscendingOrder) {
				result = left->data(Miam::DF_NormalizedString).toInt() <= right->data(Miam::DF_NormalizedString).toInt();
			} else {
				result = left->data(Miam::DF_NormalizedString).toInt() + 10 <= right->data(Miam::DF_NormalizedString).toInt();
			}
		} else {
			// Special case if an artist's name has only one character, be sure to put it after the separator
			// Example: M (or -M-, or Mathieu Chedid)
			if (QString::compare(left->data(Miam::DF_NormalizedString).toString(),
								 right->data(Miam::DF_NormalizedString).toString().left(1)) == 0) {
				result = (sortOrder() == Qt::AscendingOrder);
			} else if (left->data(Miam::DF_NormalizedString).toString() == "0" && sortOrder() == Qt::DescendingOrder) {
				// Again a very special case to keep the separator for "Various" on top of siblings
				result = "9" < right->data(Miam::DF_NormalizedString).toString().left(1);
			} else {
				result = QSortFilterProxyModel::lessThan(idxLeft, idxRight);
			}
		}
		break;

	// Sort tracks by their numbers
	case Miam::IT_Track: {
		int dLeft = left->data(Miam::DF_DiscNumber).toInt();
		int lTrackNumber = left->data(Miam::DF_TrackNumber).toInt();
		int dRight = right->data(Miam::DF_DiscNumber).toInt();
		if (rType == Miam::IT_Track) {
			int rTrackNumber = right->data(Miam::DF_TrackNumber).toInt();
			if (dLeft == dRight) {
				// If there are both remote and local tracks under the same album, display first tracks from hard disk
				// Otherwise tracks will be displayed like #1 - local, #1 - remote, #2 - local, #2 - remote, etc
				bool lIsRemote = left->data(Miam::DF_IsRemote).toBool();
				bool rIsRemote = right->data(Miam::DF_IsRemote).toBool();
				if (lIsRemote && rIsRemote || !lIsRemote && !rIsRemote) {
					result = (lTrackNumber < rTrackNumber && sortOrder() == Qt::AscendingOrder) ||
						(rTrackNumber < lTrackNumber && sortOrder() == Qt::DescendingOrder);
				} else {
					result = (rIsRemote && sortOrder() == Qt::AscendingOrder) ||
						(lIsRemote && sortOrder() == Qt::DescendingOrder);
				}
			} else {
				result = (dLeft < dRight && sortOrder() == Qt::AscendingOrder) ||
						  (dRight < dLeft && sortOrder() == Qt::DescendingOrder);
			}
		} else if (rType == Miam::IT_Disc) {
			result = (dLeft < dRight && sortOrder() == Qt::AscendingOrder) ||
					  (dRight < dLeft && sortOrder() == Qt::DescendingOrder);
		} else {
			result = QSortFilterProxyModel::lessThan(idxLeft, idxRight);
		}
		break;
	}
	case Miam::IT_Year: {
		int lYear = left->data(Miam::DF_NormalizedString).toInt();
		int rYear = right->data(Miam::DF_NormalizedString).toInt();
		result = (lYear < rYear && sortOrder() == Qt::AscendingOrder) ||
				  (rYear > lYear && sortOrder() == Qt::DescendingOrder);
		break;
	}
	default:
		result = QSortFilterProxyModel::lessThan(idxLeft, idxRight);
		break;
	}
	return result;
}
void QgsGrassTools::addModules( QTreeWidgetItem *parent, QDomElement &element )
{
  QDomNode n = element.firstChild();

  QTreeWidgetItem *item;
  QTreeWidgetItem *lastItem = 0;
  while ( !n.isNull() )
  {
    QDomElement e = n.toElement();
    if ( !e.isNull() )
    {
// QgsDebugMsg(QString("tag = %1").arg(e.tagName()));

      if ( e.tagName() == "section" && e.tagName() == "grass" )
      {
        QgsDebugMsg( QString( "Unknown tag: %1" ).arg( e.tagName() ) );
        continue;
      }

      if ( parent )
      {
        item = new QTreeWidgetItem( parent, lastItem );
      }
      else
      {
        item = new QTreeWidgetItem( mModulesTree, lastItem );
      }

      if ( e.tagName() == "section" )
      {
        QString label = e.attribute( "label" );
        QgsDebugMsg( QString( "label = %1" ).arg( label ) );
        item->setText( 0, label );
        item->setExpanded( false );

        addModules( item, e );

        lastItem = item;
      }
      else if ( e.tagName() == "grass" )
      { // GRASS module
        QString name = e.attribute( "name" );
        QgsDebugMsg( QString( "name = %1" ).arg( name ) );

        QString path = QgsApplication::pkgDataPath() + "/grass/modules/" + name;
        QString label = QgsGrassModule::label( path );
        QPixmap pixmap = QgsGrassModule::pixmap( path, 25 );

        item->setText( 0, name + " - " + label );
        item->setIcon( 0, QIcon( pixmap ) );
        item->setText( 1, name );
        lastItem = item;


        //
        // Experimental work by Tim - add this item to our list model
        //
        QStandardItem * mypDetailItem = new QStandardItem( name );
        mypDetailItem->setData( name, Qt::UserRole + 1 ); //for calling runModule later
        QString mySearchText = name + " - " + label;
        mypDetailItem->setData( mySearchText, Qt::UserRole + 2 ); //for filtering later
        mypDetailItem->setData( pixmap, Qt::DecorationRole );
        mypDetailItem->setCheckable( false );
        mypDetailItem->setEditable( false );
        // setData in the delegate with a variantised QgsDetailedItemData
        QgsDetailedItemData myData;
        myData.setTitle( name );
        myData.setDetail( label );
        myData.setIcon( pixmap );
        myData.setCheckable( false );
        myData.setRenderAsWidget( true );
        QVariant myVariant = qVariantFromValue( myData );
        mypDetailItem->setData( myVariant, Qt::UserRole );
        mModelTools->appendRow( mypDetailItem );
        //
        // End of experimental work by Tim
        //
      }
    }
    n = n.nextSibling();
  }
}