Exemple #1
0
QString
ShaderFactory::genDefaultSliceShaderString(bool bit16,
					   bool lighting,
					   bool emissive,
					   QList<CropObject> crops,
					   bool peel, int peelType,
					   float peelMin, float peelMax, float peelMix)
{
  bool cropPresent = false;
  bool tearPresent = false;
  bool viewPresent = false;
  bool glowPresent = false;
  for(int i=0; i<crops.count(); i++)
    if (crops[i].cropType() < CropObject::Tear_Tear)
      cropPresent = true;
    else if (crops[i].cropType() < CropObject::View_Tear)
      tearPresent = true;
    else if (crops[i].cropType() < CropObject::Glow_Ball)
      viewPresent = true;
    else
      glowPresent = true;

  for(int i=0; i<crops.count(); i++)
    if (crops[i].cropType() >= CropObject::View_Tear &&
	crops[i].cropType() <= CropObject::View_Block &&
	crops[i].magnify() > 1.0)
      tearPresent = true;

  bool pathCropPresent = PathShaderFactory::cropPresent();
  bool pathViewPresent = PathShaderFactory::blendPresent();

  float lastSet = (Global::lutSize()-1.0)/Global::lutSize();
  QString shader;

  shader =  "#extension GL_ARB_texture_rectangle : enable\n";
  shader += "varying vec3 pointpos;\n";
  shader += "uniform sampler2D lutTex;\n";
  shader += "uniform sampler2DRect dataTex;\n";
  shader += "uniform sampler1D paintTex;\n";

  shader += "uniform float tfSet;\n";
  shader += "uniform vec3 delta;\n";
  shader += "uniform vec3 eyepos;\n";
  shader += "uniform vec3 lightpos;\n";
  shader += "uniform float ambient;\n";
  shader += "uniform float diffuse;\n";
  shader += "uniform float specular;\n";
  shader += "uniform float speccoeff;\n";
  shader += "uniform int gridx;\n";
  shader += "uniform int tsizex;\n";
  shader += "uniform int tsizey;\n";
  shader += "uniform float depthcue;\n";

  shader += "uniform sampler2DRect lightTex;\n";
  shader += "uniform int lightgridx;\n";
  shader += "uniform int lightgridy;\n";
  shader += "uniform int lightgridz;\n";
  shader += "uniform int lightnrows;\n";
  shader += "uniform int lightncols;\n";
  shader += "uniform int lightlod;\n";

  shader += "uniform sampler2DRect pruneTex;\n";
  shader += "uniform int prunegridx;\n";
  shader += "uniform int prunetsizex;\n";
  shader += "uniform int prunetsizey;\n";
  shader += "uniform float prunelod;\n";
  shader += "uniform int zoffset;\n";

  shader += "uniform vec2 dataMin;\n";
  shader += "uniform vec2 dataSize;\n";
  shader += "uniform int tminz;\n";

  shader += "uniform int lod;\n";
  shader += "uniform vec3 dirFront;\n";
  shader += "uniform vec3 dirUp;\n";
  shader += "uniform vec3 dirRight;\n";

  shader += "uniform vec3 brickMin;\n";
  shader += "uniform vec3 brickMax;\n";

  shader += genTextureCoordinate();

  if (tearPresent) shader += TearShaderFactory::generateTear(crops);
  if (cropPresent) shader += CropShaderFactory::generateCropping(crops);
  if (glowPresent) shader += GlowShaderFactory::generateGlow(crops);  
  if (viewPresent) shader += BlendShaderFactory::generateBlend(crops);
  if (pathCropPresent) shader += PathShaderFactory::applyPathCrop();
  if (pathViewPresent) shader += PathShaderFactory::applyPathBlend();

  shader += "void main(void)\n";
  shader += "{\n";

  shader += "  vec3 lightcol = vec3(1.0,1.0,1.0);\n";

  shader += "  vec3 texCoord = gl_TexCoord[0].xyz;\n";

  shader += "if (any(lessThan(texCoord,brickMin)) || any(greaterThan(texCoord, brickMax)))\n";
  shader += "  discard;\n";

  if (crops.count() > 0)
    {
      shader += "  vec3 otexCoord = texCoord;\n";
      shader += "  float feather = 1.0;\n";
    }
  else
    {
      if (pathCropPresent)
	shader += "  float feather = 1.0;\n";
      if (pathViewPresent)
	shader += "  vec3 otexCoord = texCoord;\n";
    }

  if (tearPresent)
    {
      shader += "vec4 tcf = dissect(texCoord);\n";
      shader += "texCoord = tcf.xyz;\n";
      shader += "feather *= tcf.w;\n";
    }
  if (cropPresent) shader += "feather *= crop(texCoord, true);\n";
  if (pathCropPresent) shader += "feather *= pathcrop(texCoord, true);\n";

  shader += "texCoord.x = 1.0 + float(tsizex-2)*(texCoord.x-dataMin.x)/dataSize.x;\n";
  shader += "texCoord.y = 1.0 + float(tsizey-2)*(texCoord.y-dataMin.y)/dataSize.y;\n";

//----------------------------------------------------------
// Manipulate z-coordinate for non linear depth levels
//  int levels = 4;
//  float origT[10], newT[10];
//  origT[0] = 00.00;  newT[0] = 00.0;
//  origT[1] = 01.20;  newT[1] = 11.0;
//  origT[2] = 04.00;  newT[2] = 23.0;
//  origT[3] = 37.62;  newT[3] = 56.0;
//  origT[4] = 62.00;  newT[4] = 62.0;
//
//  for(int o=0; o<levels; o++)
//    {
//      if (o > 0)
//	shader += "else ";
//      shader += QString("if (texCoord.z >= float(%1) && texCoord.z < float(%2))\n").\
//	arg(origT[o]).\
//	arg(origT[o+1]);
//      shader += "  {\n"; 
//
//      shader += QString("    float tz = (texCoord.z-float(%1))/(float(%2)-float(%1));\n").\
//	arg(origT[o]).							\
//	arg(origT[o+1]);
//
//      shader += QString("    texCoord.z = float(%1) + tz * (float(%2)-float(%1));\n").\
//	arg(newT[o]).\
//	arg(newT[o+1]);
//      shader += "  }\n";
//    }
//----------------------------------------------------------
  
  shader += "texCoord.z = 1.0 + (texCoord.z-float(tminz))/float(lod);\n";

  shader += genVgx();

  //----------------------------------
  shader += " if (lightlod > 0)\n";
  shader += "   {\n"; // calculate light color
  shader += "     vec3 lc;\n";
  shader += "     vec2 pvg = texCoord.xy / prunelod;\n";
  shader += "     pvg /= vec2(lightlod,lightlod);\n";
  shader += "     vec2 pvg0 = getTextureCoordinate(int(float(zoffset+slice)/prunelod)/lightlod, ";
  shader += "            lightncols, lightgridx, lightgridy, pvg);\n";
  shader += "     vec2 pvg1 = getTextureCoordinate(int(float(zoffset+slice+1)/prunelod)/lightlod, ";
  shader += "            lightncols, lightgridx, lightgridy, pvg);\n";
  shader += "     vec3 lc0 = texture2DRect(lightTex, pvg0).xyz;\n";
  shader += "     vec3 lc1 = texture2DRect(lightTex, pvg1).xyz;\n";
  shader += "     lightcol = mix(lc0, lc1, slicef);\n";
  shader += "     lightcol = 1.0-pow((vec3(1,1,1)-lightcol),vec3(lod,lod,lod));\n";
  shader += "   }\n";
  shader += " else\n";
  shader += "   lightcol = vec3(1.0,1.0,1.0);\n";
  //----------------------------------

  if (peel || lighting || !Global::use1D())
    shader += getNormal();


  if (bit16)
    {
      shader += "int h0 = int(65535.0*vg.x);\n";
      shader += "int h1 = h0 / 256;\n";
      shader += "h0 = int(mod(float(h0),256.0));\n";
      shader += "float fh0 = float(h0)/256.0;\n";
      shader += "float fh1 = float(h1)/256.0;\n";

      shader += QString("vg.xy = vec2(fh0, fh1*%1);\n").arg(1.0/Global::lutSize());
    }
  else
    {
      if (Global::use1D())
	shader += "  vg.y = 0.0;\n";
      else
	shader += QString("  vg.y = grad*%1;\n").arg(1.0/Global::lutSize());
    }


  shader += "  vg1 = vg;\n";
  shader += "  vg.y += tfSet;\n";
  shader += "  gl_FragColor = texture2D(lutTex, vg.xy);\n";

  if (Global::emptySpaceSkip())
    {
      shader += "  gl_FragColor.rgba = mix(vec4(0.0,0.0,0.0,0.0), gl_FragColor.rgba, prunefeather.x);\n";
      if (PruneHandler::blend())
	shader += blendVolume();
      else
	shader += tagVolume();
    }


  if (tearPresent || cropPresent || pathCropPresent)
    shader += "  gl_FragColor.rgba = mix(gl_FragColor.rgba, vec4(0.0,0.0,0.0,0.0), feather);\n";

  if (viewPresent) shader += "  blend(otexCoord, vg, gl_FragColor);\n";
  
  if (pathViewPresent) shader += "pathblend(otexCoord, vg, gl_FragColor);\n";
  

//---------------------------------
  if (Global::emptySpaceSkip())
    {
      shader += "if (delta.x > 1.0)\n";
      shader += "  { gl_FragColor = vec4(vg.x*step(0.001,gl_FragColor.a),";
      shader += "gl_FragColor.a, prunefeather.z, 1.0); return; }\n";
    }
  else
    {
      shader += "if (delta.x > 1.0)\n";
      shader += "  { gl_FragColor = vec4(vg.x*step(0.001,gl_FragColor.a),";
      shader += "gl_FragColor.a, 0.0, 1.0); return; }\n";
    }
//---------------------------------

//------------------------------------
  shader += "gl_FragColor = 1.0-pow((vec4(1,1,1,1)-gl_FragColor),";
  shader += "vec4(lod,lod,lod,lod));\n";
//------------------------------------

  shader += "\n";
  shader += "  if (gl_FragColor.a < 0.005)\n";
  shader += "	discard;\n";

  if (lighting)
    shader += addLighting();

  shader += genPeelShader(peel, peelType,
			  peelMin, peelMax, peelMix,
			  lighting);

  if (emissive)
    {
      shader += QString("  vg1.y += float(%1);\n").arg(lastSet);
      shader += "  gl_FragColor.rgb += texture2D(lutTex, vg1.xy).rgb;\n";
    }

  // -- depth cueing
  shader += "  gl_FragColor.rgb *= depthcue;\n";

  if (glowPresent) shader += "  gl_FragColor.rgb += glow(otexCoord);\n";

  shader += "  gl_FragColor = clamp(gl_FragColor, vec4(0.0,0.0,0.0,0.0), vec4(1.0,1.0,1.0,1.0));\n";

  shader += "}\n";

  return shader;
}
void KonqPopupMenuPrivate::populate()
{
    Q_ASSERT(m_popupItemProperties.items().count() >= 1);

    bool bTrashIncluded = false;

    const KFileItemList lstItems = m_popupItemProperties.items();
    KFileItemList::const_iterator it = lstItems.constBegin();
    const KFileItemList::const_iterator kend = lstItems.constEnd();
    for (; it != kend; ++it) {
        const QUrl url = (*it).url();
        if (!bTrashIncluded && ((url.scheme() == QLatin1String("trash") && url.path().length() <= 1))) {
            bTrashIncluded = true;
        }
    }

    const bool isDirectory = m_popupItemProperties.isDirectory();
    const bool sReading = m_popupItemProperties.supportsReading();
    bool sDeleting = (m_popupFlags & KonqPopupMenu::NoDeletion) == 0
                     && m_popupItemProperties.supportsDeleting();
    const bool sWriting = m_popupItemProperties.supportsWriting();
    const bool sMoving = sDeleting && m_popupItemProperties.supportsMoving();

    QUrl url = m_sViewURL.adjusted(QUrl::NormalizePathSegments);

    bool isTrashLink     = false;
    bool isCurrentTrash = false;
    bool currentDir     = false;
    bool isSymLink = false;
    bool isSymLinkInSameDir = false; // true for "ln -s foo bar", false for links to foo/sub or /foo

    //check if url is current directory
    if (lstItems.count() == 1) {
        KFileItem firstPopupItem(lstItems.first());
        if (firstPopupItem.isLink()) {
            isSymLink = true;
            isSymLinkInSameDir = !firstPopupItem.linkDest().contains(QLatin1Char('/'));
        }
        QUrl firstPopupURL(firstPopupItem.url().adjusted(QUrl::NormalizePathSegments));
        //kDebug(1203) << "View path is " << url.url();
        //kDebug(1203) << "First popup path is " << firstPopupURL.url();
        currentDir = (firstPopupURL.matches(url, QUrl::StripTrailingSlash));
        if (firstPopupItem.isDesktopFile()) {
            KDesktopFile desktopFile(firstPopupItem.localPath());
            const KConfigGroup cfg = desktopFile.desktopGroup();
            isTrashLink = cfg.readEntry("Type") == QLatin1String("Link")
                          && cfg.readEntry("URL") == QLatin1String("trash:/");
        }

        if (isTrashLink) {
            sDeleting = false;
        }

        // isCurrentTrash: popup on trash:/ itself, or on the trash.desktop link
        isCurrentTrash = (firstPopupURL.scheme() == QLatin1String("trash") && firstPopupURL.path().length() <= 1)
                         || isTrashLink;
    }

    const bool isIntoTrash = (url.scheme() == QLatin1String("trash")) && !isCurrentTrash; // trashed file, not trash:/ itself

    const bool bIsLink  = (m_popupFlags & KonqPopupMenu::IsLink);

    //kDebug() << "isLocal=" << isLocal << " url=" << url << " isCurrentTrash=" << isCurrentTrash << " isIntoTrash=" << isIntoTrash << " bTrashIncluded=" << bTrashIncluded;

    //////////////////////////////////////////////////////////////////////////

    addGroup(KonqPopupMenu::TopActions); // used e.g. for ShowMenuBar. includes a separator at the end

    QAction *act;

    QAction *actNewWindow = 0;

#if 0 // TODO in the desktop code itself.
    if ((flags & KonqPopupMenu::ShowProperties) && isOnDesktop &&
            !KAuthorized::authorizeKAction("editable_desktop_icons")) {
        flags &= ~KonqPopupMenu::ShowProperties; // remove flag
    }
#endif

    // Either 'newview' is in the actions we're given (probably in the tabhandling group)
    // or we need to insert it ourselves (e.g. for the desktop).
    // In the first case, actNewWindow must remain 0.
    if (((m_popupFlags & KonqPopupMenu::ShowNewWindow) != 0) && sReading) {
        const QString openStr = i18n("&Open");
        actNewWindow = new QAction(m_parentWidget /*for status tips*/);
        m_ownActions.append(actNewWindow);
        actNewWindow->setIcon(QIcon::fromTheme(QStringLiteral("window-new")));
        actNewWindow->setText(openStr);
        QObject::connect(actNewWindow, &QAction::triggered, [this]() {
            slotPopupNewView();
        });
    }

    if (isDirectory && sWriting && !isCurrentTrash) { // A dir, and we can create things into it
        const bool mkdirRequested = m_popupFlags & KonqPopupMenu::ShowCreateDirectory;
        if ((currentDir || mkdirRequested) && m_pMenuNew) { // Current dir -> add the "new" menu
            // As requested by KNewFileMenu :
            m_pMenuNew->checkUpToDate();
            m_pMenuNew->setPopupFiles(m_popupItemProperties.urlList());

            q->addAction(m_pMenuNew);
            q->addSeparator();
        } else if (mkdirRequested) {
            QAction *actNewDir = new QAction(m_parentWidget);
            m_ownActions.append(actNewDir);
            actNewDir->setIcon(QIcon::fromTheme(QStringLiteral("folder-new")));
            actNewDir->setText(i18n("Create &Folder..."));
            QObject::connect(actNewDir, &QAction::triggered, [this]() {
                slotPopupNewDir();
            });
            q->addAction(actNewDir);
            q->addSeparator();
        }
    } else if (isIntoTrash) {
        // Trashed item, offer restoring
        act = new QAction(m_parentWidget /*for status tips*/);
        m_ownActions.append(act);
        act->setText(i18n("&Restore"));
        //PORT QT5 act->setHelpText(i18n("Restores this file or directory, back to the location where it was deleted from initially"));
        QObject::connect(act, &QAction::triggered, [this]() {
            slotPopupRestoreTrashedItems();
        });
        q->addAction(act);
    }

    if (m_popupFlags & KonqPopupMenu::ShowNavigationItems) {
        if (m_popupFlags & KonqPopupMenu::ShowUp) {
            addNamedAction("go_up");
        }
        addNamedAction("go_back");
        addNamedAction("go_forward");
        if (m_popupFlags & KonqPopupMenu::ShowReload) {
            addNamedAction("reload");
        }
        q->addSeparator();
    }

    if (!currentDir && isSymLink && !isSymLinkInSameDir) {
        // #65151: offer to open the target's parent dir
        act = new QAction(m_parentWidget);
        m_ownActions.append(act);
        act->setText(isDirectory ? i18n("Show Original Directory") : i18n("Show Original File"));
        //PORT TO QT5 act->setHelpText(i18n("Opens a new file manager window showing the target of this link, in its parent directory."));
        QObject::connect(act, &QAction::triggered, [this]() {
            slotShowOriginalFile();
        });
        q->addAction(act);
    }

    // "open in new window" is either provided by us, or by the tabhandling group
    if (actNewWindow) {
        q->addAction(actNewWindow);
        q->addSeparator();
    }
    addGroup(KonqPopupMenu::TabHandlingActions);   // includes a separator at the end

    if (m_popupFlags & KonqPopupMenu::ShowUrlOperations) {
        if (!currentDir && sReading) {
            if (sDeleting) {
                addNamedAction("cut");
            }
            addNamedAction("copy");
        }

        if (isDirectory && sWriting) {
            if (currentDir) {
                addNamedAction("paste");
            } else {
                addNamedAction("pasteto");
            }
        }
    }
    if (isCurrentTrash) {
        act = new QAction(m_parentWidget);
        m_ownActions.append(act);
        act->setIcon(QIcon::fromTheme(QStringLiteral("trash-empty")));
        act->setText(i18n("&Empty Trash Bin"));
        KConfig trashConfig(QStringLiteral("trashrc"), KConfig::SimpleConfig);
        act->setEnabled(!trashConfig.group("Status").readEntry("Empty", true));
        QObject::connect(act, &QAction::triggered, [this]() {
            slotPopupEmptyTrashBin();
        });
        q->addAction(act);
    }
    if (isCurrentTrash) {
        act = new QAction(m_parentWidget);
        m_ownActions.append(act);
        act->setIcon(QIcon::fromTheme(QStringLiteral("trash-empty")));
        act->setText(i18n("&Configure Trash Bin"));
        QObject::connect(act, &QAction::triggered, [this]() {
            slotConfigTrashBin();
        });
        q->addAction(act);
    }

    // This is used by KHTML, see khtml_popupmenu.rc (copy, selectAll, searchProvider etc.)
    // and by DolphinPart (rename, trash, delete)
    addGroup(KonqPopupMenu::EditActions);

    if (m_popupFlags & KonqPopupMenu::ShowTextSelectionItems) {
        // OK, we have to stop here.

        // Anything else that is provided by the part
        addGroup(KonqPopupMenu::CustomActions);
        return;
    }

    if (!isCurrentTrash && !isIntoTrash && (m_popupFlags & KonqPopupMenu::ShowBookmark)) {
        QString caption;
        if (currentDir) {
            const bool httpPage = m_sViewURL.scheme().startsWith(QLatin1String("http"), Qt::CaseInsensitive);
            if (httpPage) {
                caption = i18n("&Bookmark This Page");
            } else {
                caption = i18n("&Bookmark This Location");
            }
        } else if (isDirectory) {
            caption = i18n("&Bookmark This Folder");
        } else if (bIsLink) {
            caption = i18n("&Bookmark This Link");
        } else {
            caption = i18n("&Bookmark This File");
        }

        act = new QAction(m_parentWidget);
        m_ownActions.append(act);
        act->setObjectName(QLatin1String("bookmark_add"));   // for unittest
        act->setIcon(QIcon::fromTheme(QStringLiteral("bookmark-new")));
        act->setText(caption);
        QObject::connect(act, &QAction::triggered, [this]() {
            slotPopupAddToBookmark();
        });
        if (lstItems.count() > 1) {
            act->setEnabled(false);
        }
        if (KAuthorized::authorizeKAction(QStringLiteral("bookmarks"))) {
            q->addAction(act);
        }
        if (bIsLink) {
            addGroup(KonqPopupMenu::LinkActions);    // see khtml
        }
    }

    // "Open With" actions

    m_menuActions.setItemListProperties(m_popupItemProperties);

    if (sReading) {
        m_menuActions.addOpenWithActionsTo(q, QStringLiteral("DesktopEntryName != 'kfmclient' and DesktopEntryName != 'kfmclient_dir' and DesktopEntryName != 'kfmclient_html'"));

        QList<QAction *> previewActions = m_actionGroups.value(KonqPopupMenu::PreviewActions);
        if (!previewActions.isEmpty()) {
            if (previewActions.count() == 1) {
                q->addAction(previewActions.first());
            } else {
                QMenu *subMenu = new QMenu(i18n("Preview In"), q);
                subMenu->menuAction()->setObjectName(QLatin1String("preview_submenu"));   // for the unittest
                q->addMenu(subMenu);
                subMenu->addActions(previewActions);
            }
        }
    }

    // Second block, builtin + user
    m_menuActions.addServiceActionsTo(q);

    q->addSeparator();

    // Use the Dolphin setting for showing the "Copy To" and "Move To" actions
    KSharedConfig::Ptr dolphin = KSharedConfig::openConfig(QStringLiteral("dolphinrc"));

    // CopyTo/MoveTo menus
    if (m_popupFlags & KonqPopupMenu::ShowUrlOperations &&
            KConfigGroup(dolphin, "General").readEntry("ShowCopyMoveMenu", false)) {

        m_copyToMenu.setItems(lstItems);
        m_copyToMenu.setReadOnly(sMoving == false);
        m_copyToMenu.addActionsTo(q);
        q->addSeparator();
    }

    if (!isCurrentTrash && !isIntoTrash && sReading &&
            (m_popupFlags & KonqPopupMenu::NoPlugins) == 0) {
        addPlugins(); // now it's time to add plugins
    }

    if ((m_popupFlags & KonqPopupMenu::ShowProperties) && KPropertiesDialog::canDisplay(lstItems)) {
        act = new QAction(m_parentWidget);
        m_ownActions.append(act);
        act->setObjectName(QLatin1String("properties"));   // for unittest
        act->setText(i18n("&Properties"));
        QObject::connect(act, &QAction::triggered, [this]() {
            slotPopupProperties();
        });
        q->addAction(act);
    }

    while (!q->actions().isEmpty() &&
            q->actions().last()->isSeparator()) {
        delete q->actions().last();
    }

    // Anything else that is provided by the part
    addGroup(KonqPopupMenu::CustomActions);

    QObject::connect(&m_menuActions, &KFileItemActions::openWithDialogAboutToBeShown, q, &KonqPopupMenu::openWithDialogAboutToBeShown);
}
Exemple #3
0
void wizardDisk::generateConfirmationText()
{
  // If running in expert mode, we just create a simple config / confirmation
  if ( radioExpert->isChecked() ) {
    QStringList filesystem;
    filesystem << "MANUAL" << "/mnt" ;
    sysFinalDiskLayout << filesystem;
    textConfirmation->setText(tr("Installing to file-system mounted at /mnt"));
    return;
  }

  QList<QStringList> copyList;
  QStringList summaryList;
  QString tmp, workingDisk, workingSlice, tmpSlice, XtraTmp, startPart, sliceSize;
  int disk = 0;

  // Copy over the list to a new variable we can mangle without modifying the original
  copyList = sysFinalDiskLayout;

  // Start our summary
  summaryList << "";
  summaryList << "<b>" + tr("The disk will be setup with the following configuration:") + "</b>";

  while ( ! copyList.empty() )
  {
    workingDisk = copyList.at(0).at(0);
    workingSlice = copyList.at(0).at(1);
    tmpSlice = workingSlice;

    // Check if this is an install to "Unused Space"
    for (int z=0; z < sysDisks.count(); ++z)
      if ( sysDisks.at(z).at(0) == "SLICE" \
        && sysDisks.at(z).at(2) == workingDisk + workingSlice \
        && sysDisks.at(z).at(4) == "Unused Space" )
          tmpSlice = "free";

    // Check for any mirror for this device
    for (int i=0; i < copyList.count(); ++i) {
       if ( copyList.at(i).at(2).indexOf("MIRROR(" + workingDisk + ")") != -1 )
       {
         summaryList << tr("Disk:") + copyList.at(i).at(0) + " " + tr("Mirroring:") + workingDisk;
         copyList.removeAt(i);
         break;
       }
    }

    // If after doing the mirror, our list is empty, break out
    if ( copyList.empty() )
      break;
    
    // If there is a dedicated /boot partition, need to list that first, see what is found
    for (int i=0; i < copyList.count(); ++i) {
      QStringList mounts = copyList.at(i).at(2).split(",");
      for (int z = 0; z < mounts.size(); ++z) {
        if ( copyList.at(i).at(0) == workingDisk \
          && copyList.at(i).at(1) == workingSlice \
          && mounts.at(z) == "/boot" )
		startPart="/boot";
      }
    }

    // If no dedicated /boot partition, then lets list "/" first
    if(startPart.isEmpty())
	startPart="/";

    // Start by looking for the root partition
    for (int i=0; i < copyList.count(); ++i) {
      QStringList mounts = copyList.at(i).at(2).split(",");
      for (int z = 0; z < mounts.size(); ++z) {
        if ( copyList.at(i).at(0) == workingDisk \
          && copyList.at(i).at(1) == workingSlice \
          && mounts.at(z) == startPart ) {

          // Check if we have any extra arguments to throw on the end
          XtraTmp="";
          if ( ! copyList.at(i).at(5).isEmpty() )
            XtraTmp=" (" + copyList.at(i).at(5) + ")" ;

          // Write the user summary
          summaryList << "";
          summaryList << tr("Partition:") + " " + workingDisk + "(" + workingSlice + "):";
          summaryList << tr("FileSystem:") + " " + copyList.at(i).at(3);
          summaryList << tr("Size:") + " " + copyList.at(i).at(4) + "MB ";

	  if ( copyList.at(i).at(3) == "ZFS" || copyList.at(i).at(3) == "ZFS.eli" ) {
	    QStringList zDS = copyList.at(i).at(2).split(",/");
	    QString zTMP;
	    for (int ds = 0; ds < zDS.size(); ++ds) {
	      if ( zDS.at(ds) != "/" )
                zDS.replace(ds, "/" + zDS.at(ds));
	      if ( zDS.at(ds).indexOf("(") != -1 ) {
		zTMP = zDS.at(ds);
		zTMP.replace("(", " (");
                zDS.replace(ds, zTMP );
	      }
	    }
            summaryList << tr("ZFS Datasets:<br>") + " " + zDS.join("<br>");
	  } else {
            summaryList << tr("Mount:") + " " + copyList.at(i).at(2);
	  }
	  if ( ! XtraTmp.isEmpty() ) {
            summaryList << tr("Options:") + " " + copyList.at(i).at(5);
          }

          // Done with this item, remove it now
          copyList.removeAt(i);
          break;
        }
      }
    }


    // Now look for SWAP
    for (int i=0; i < copyList.count(); ++i) {
      if ( copyList.at(i).at(0) == workingDisk \
        && copyList.at(i).at(1) == workingSlice \
        && copyList.at(i).at(2) == "SWAP.eli" ) {

        // Write the user summary
        summaryList << "";
        summaryList << tr("Partition:") + " " + workingDisk + "(" + workingSlice + "):";
        summaryList << tr("FileSystem:") + " " + copyList.at(i).at(3);
        summaryList << tr("Size:") + " " + copyList.at(i).at(4) + "MB ";

        // Done with this item, remove it now
        copyList.removeAt(i);
        break;
      }
    }

 
    // Now look for any other partitions
    int count = copyList.count();
    for (int i=0; i < count; ++i) {
      if ( copyList.at(i).at(0) == workingDisk \
        && copyList.at(i).at(1) == workingSlice ) {

        // Check if we have any extra arguments to throw on the end
        XtraTmp="";
        if ( ! copyList.at(i).at(5).isEmpty() )
          XtraTmp=" (" + copyList.at(i).at(5) + ")" ;

	// If we are working on the last partition, set the size to 0 to use remaining disk
	if ( i == (count - 1) ) 
		sliceSize = "0";
	else
		sliceSize=copyList.at(i).at(4);

        // Write the user summary
        summaryList << "";
        summaryList << tr("Partition:") + " " + workingDisk + "(" + workingSlice + "):";
        summaryList << tr("FileSystem:") + " " + copyList.at(i).at(3);
        summaryList << tr("Size:") + " " + copyList.at(i).at(4) + "MB ";
        summaryList << tr("Mount:") + " " + copyList.at(i).at(2);
	if ( ! XtraTmp.isEmpty() ) {
          summaryList << tr("Options:") + " " + copyList.at(i).at(5);
        }

        // Done with this item, remove it now
        copyList.removeAt(i);
        i--;
        count--;
      }
    }

    // Increment our disk counter
    disk++;
  }

  textConfirmation->setText(summaryList.join("<br>"));
}
static QCFType<CFPropertyListRef> macValue(const QVariant &value)
{
    CFPropertyListRef result = 0;

    switch (value.type()) {
    case QVariant::ByteArray:
        {
            QByteArray ba = value.toByteArray();
            result = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(ba.data()),
                                  CFIndex(ba.size()));
        }
        break;
    // should be same as below (look for LIST)
    case QVariant::List:
    case QVariant::StringList:
    case QVariant::Polygon:
        result = macList(value.toList());
        break;
    case QVariant::Map:
        {
            /*
                QMap<QString, QVariant> is potentially a multimap,
                whereas CFDictionary is a single-valued map. To allow
                for multiple values with the same key, we store
                multiple values in a CFArray. To avoid ambiguities,
                we also wrap lists in a CFArray singleton.
            */
            QMap<QString, QVariant> map = value.toMap();
            QMap<QString, QVariant>::const_iterator i = map.constBegin();

            int maxUniqueKeys = map.size();
            int numUniqueKeys = 0;
            QVarLengthArray<QCFType<CFPropertyListRef> > cfkeys(maxUniqueKeys);
            QVarLengthArray<QCFType<CFPropertyListRef> > cfvalues(maxUniqueKeys);

            while (i != map.constEnd()) {
                const QString &key = i.key();
                QList<QVariant> values;

                do {
                    values << i.value();
                    ++i;
                } while (i != map.constEnd() && i.key() == key);

                bool singleton = (values.count() == 1);
                if (singleton) {
                    switch (values.first().type()) {
                    // should be same as above (look for LIST)
                    case QVariant::List:
                    case QVariant::StringList:
                    case QVariant::Polygon:
                        singleton = false;
                    default:
                        ;
                    }
                }

                cfkeys[numUniqueKeys] = QCFString::toCFStringRef(key);
                cfvalues[numUniqueKeys] = singleton ? macValue(values.first()) : macList(values);
                ++numUniqueKeys;
            }

            result = CFDictionaryCreate(kCFAllocatorDefault,
                                        reinterpret_cast<const void **>(cfkeys.data()),
                                        reinterpret_cast<const void **>(cfvalues.data()),
                                        CFIndex(numUniqueKeys),
                                        &kCFTypeDictionaryKeyCallBacks,
                                        &kCFTypeDictionaryValueCallBacks);
        }
        break;
    case QVariant::DateTime:
        {
            /*
                CFDate, unlike QDateTime, doesn't store timezone information.
            */
            QDateTime dt = value.toDateTime();
            if (dt.timeSpec() == Qt::LocalTime) {
                QDateTime reference;
                reference.setTime_t((uint)kCFAbsoluteTimeIntervalSince1970);
                result = CFDateCreate(kCFAllocatorDefault, CFAbsoluteTime(reference.secsTo(dt)));
            } else {
                goto string_case;
            }
        }
        break;
    case QVariant::Bool:
        result = value.toBool() ? kCFBooleanTrue : kCFBooleanFalse;
        break;
    case QVariant::Int:
    case QVariant::UInt:
        {
            int n = value.toInt();
            result = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &n);
        }
        break;
    case QVariant::Double:
        {
            double n = value.toDouble();
            result = CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &n);
        }
        break;
    case QVariant::LongLong:
    case QVariant::ULongLong:
        {
            qint64 n = value.toLongLong();
            result = CFNumberCreate(0, kCFNumberLongLongType, &n);
        }
        break;
    case QVariant::String:
    string_case:
    default:
        result = QCFString::toCFStringRef(QSettingsPrivate::variantToString(value));
    }
    return result;
}
void ThemeImporter::readCalendarItems( const QString &viewType, const int year,
                                       const int month, const int day )
{
  Q_ASSERT( isStartElement() && name() == "calendar-items" );

  // As the available settings are the same for the various calendar items
  // types, we use a "stack" to keep in mind where we are in the hierarchy
  // while having the possibility of using the same methods to read the
  // settings' tags.
  QList< QPair<QString, QString> > stack;
  stack.append( qMakePair( QString(), QString( "CalendarItems" ) ) );

  while ( !atEnd() ) {
    readNext();

    if ( isEndElement() ) {
      if ( stack.count() > 1 ) {
        stack.removeLast();  // We are going down one level
      } else {
        break;
      }
    }

    if ( isStartElement() ) {
      /* Item type tags: first level */
      if ( stack.count() == 1 && name() == "events" ) {
        stack.append( qMakePair( QString( "events" ),
                                 QString( "CalendarItems Events" ) ) );
      } else if ( stack.count() == 1 && name() == "to-dos" ) {
        stack.append( qMakePair( QString( "to-dos" ),
                                 QString( "CalendarItems ToDos" ) ) );
      /* Sub-elements of to-dos (second level) */
      } else if ( stack.count() == 2 && stack.last().first == "to-dos" &&
                  name() == "overdue" ) {
        stack.append( qMakePair( QString( "to-dos/overdue" ),
                                 QString( "CalendarItems ToDos Overdue" ) ) );
      } else if ( stack.count() == 2 && stack.last().first == "to-dos" &&
                  name() == "due-today" ) {
        stack.append( qMakePair( QString( "to-dos/due-today" ),
                      QString( "CalendarItems ToDos DueToday" ) ) );
      /* The sub-elements of these tags allow free text */
      } else if ( stack.count() == 1 && name() == "categories" ) {
        stack.append( qMakePair( QString( "categories" ),
                                 // When a setting applies to all categories,
                                 // it applies to all items.
                                 QString( "CalendarItems" ) ) );
      } else if ( stack.count() == 1 && name() == "resources" ) {
        stack.append( qMakePair( QString( "resources" ),
                                 // When a setting applies to all resources,
                                 // it applies to all items.
                                 QString( "CalendarItems" ) ) );
      }
      /* The said sub-elements */
      else if ( stack.count() == 2 && stack.last().first == "categories" &&
                name() == "category" ) {
        QString n = attributes().value( "name" ).toString();
        stack.append( qMakePair( QString( "categories/" + n ),
                                 QString( "CalendarItems Categories " + n ) ) );
      } else if ( stack.count() == 2 && stack.last().first == "resources" &&
                  name() == "resource" ) {
        QString n = attributes().value( "name" ).toString();
        stack.append( qMakePair( QString( "resources/" + n ),
                                 QString( "CalendarItems Resources " + n ) ) );
      }
      /* Settings' tags */
      else if ( name() == "background" ) {
        setColor( viewType, year, month, day,
                  stack.last().second + " Background Color",
                  attributes().value( "color" ).toString() );
        setPath( viewType, year, month, day,
                 stack.last().second + " Background Image",
                 attributes().value( "src" ).toString() );
        readNext();
      } else if ( name() == "font" ) {
        setFont( viewType, year, month, day,
                 stack.last().second + " Font",
                 attributes().value( "family" ).toString(),
                 attributes().value( "style-hint" ).toString(),
                 attributes().value( "point-size" ).toString().toInt(),
                 attributes().value( "weight" ).toString().toInt(),
                 attributes().value( "style" ).toString(),
                 attributes().value( "stretch-factor" ).toString().toInt() );
        readNext();
      } else if ( name() == "frame" ) {
        setColor( viewType, year, month, day,
                  stack.last().second + " Frame Color",
                  attributes().value( "color" ).toString() );
        readNext();
      } else if ( name() == "icon" ) {
        setString( viewType, year, month, day,
                   stack.last().second + " Icon",
                   attributes().value( "name" ).toString() );
        setPath( viewType, year, month, day,
                 stack.last().second + " IconFile",
                 attributes().value( "src" ).toString() );
        readNext();
      } else {
        readUnknownElement();
      }
    }
  }
}
Exemple #6
0
void ImageFilesWidget::SetupTable(int sort_column, Qt::SortOrder sort_order)
{
    m_ItemModel->clear();

    QStringList header;

    header.append(tr("Name" ));
    header.append(tr("File Size (KB)" ));
    header.append(tr("Times Used" ));
    header.append(tr("Width" ));
    header.append(tr("Height" ));
    header.append(tr("Pixels" ));
    header.append(tr("Color" ));
    if (m_ThumbnailSize) {
        header.append(tr("Image" ));
    }

    m_ItemModel->setHorizontalHeaderLabels(header);

    ui.imageTree->setSelectionBehavior(QAbstractItemView::SelectRows);

    ui.imageTree->setModel(m_ItemModel);

    ui.imageTree->header()->setSortIndicatorShown(true);

    QSize icon_size(m_ThumbnailSize, m_ThumbnailSize);
    ui.imageTree->setIconSize(icon_size);

    double total_size = 0;
    int total_links = 0;
    QHash<QString, QStringList> image_html_files_hash = m_Book->GetHTMLFilesUsingImages();

    foreach (Resource *resource, m_ImageResources) {
            QString filepath = "../" + resource->GetRelativePathToOEBPS();
            QString path = resource->GetFullPath();
            QImage image(path);

            QList<QStandardItem *> rowItems;

            // Filename
            QStandardItem *name_item = new QStandardItem();
            name_item->setText(resource->Filename());
            name_item->setToolTip(filepath);
            rowItems << name_item;

            // File Size
            double ffsize = QFile(path).size() / 1024.0;
            total_size += ffsize;
            QString fsize = QLocale().toString(ffsize, 'f', 2);
            NumericItem *size_item = new NumericItem();
            size_item->setText(fsize);
            rowItems << size_item;

            // Times Used
            QStringList image_html_files = image_html_files_hash[filepath];
            total_links += image_html_files.count();
            NumericItem *link_item = new NumericItem();
            link_item->setText(QString::number(image_html_files.count()));
            if (!image_html_files.isEmpty()) {
                link_item->setToolTip(image_html_files.join("\n"));
            }
            rowItems << link_item;

            // Width
            NumericItem *width_item = new NumericItem();
            width_item->setText(QString::number(image.width()));
            rowItems << width_item;

            // Height
            NumericItem *height_item = new NumericItem();
            height_item->setText(QString::number(image.width()));
            rowItems << height_item;

            // Pixels
            NumericItem *pixel_item = new NumericItem();
            pixel_item->setText(QString::number(image.width() * image.height()));
            rowItems << pixel_item;

            // Color
            QStandardItem *color_item = new QStandardItem();
            color_item->setText(image.allGray() ? "Grayscale" : "Color");
            rowItems << color_item;

            // Thumbnail
            if (m_ThumbnailSize) {
                QPixmap pixmap(resource->GetFullPath());
                if (pixmap.height() > m_ThumbnailSize || pixmap.width() > m_ThumbnailSize) {
                    pixmap = pixmap.scaled(QSize(m_ThumbnailSize, m_ThumbnailSize), Qt::KeepAspectRatio);
                }
                QStandardItem *icon_item = new QStandardItem();
                icon_item->setIcon(QIcon(pixmap));
                rowItems << icon_item;
            }

            for (int i = 0; i < rowItems.count(); i++) {
                rowItems[i]->setEditable(false);
            }
            m_ItemModel->appendRow(rowItems);
    }
void QgsMarkerLineSymbolLayerV2::renderPolyline( const QPolygonF& points, QgsSymbolV2RenderContext& context )
{
  double offset = mOffset;
  QgsExpression* offsetExpression = expression( "offset" );
  if ( offsetExpression )
  {
    offset = offsetExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toDouble();
  }

  Placement placement = mPlacement;
  QgsExpression* placementExpression = expression( "placement" );
  if ( placementExpression )
  {
    QString placementString = placementExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toString();
    if ( placementString.compare( "vertex", Qt::CaseInsensitive ) == 0 )
    {
      placement = Vertex;
    }
    else if ( placementString.compare( "lastvertex", Qt::CaseInsensitive ) == 0 )
    {
      placement = LastVertex;
    }
    else if ( placementString.compare( "firstvertex", Qt::CaseInsensitive ) == 0 )
    {
      placement = FirstVertex;
    }
    else if ( placementString.compare( "centerpoint", Qt::CaseInsensitive ) == 0 )
    {
      placement = CentralPoint;
    }
    else
    {
      placement = Interval;
    }
  }

  if ( offset == 0 )
  {
    if ( placement == Interval )
      renderPolylineInterval( points, context );
    else if ( placement == CentralPoint )
      renderPolylineCentral( points, context );
    else
      renderPolylineVertex( points, context, placement );
  }
  else
  {
    QList<QPolygonF> mline = ::offsetLine( points, offset * QgsSymbolLayerV2Utils::lineWidthScaleFactor( context.renderContext(), mOffsetUnit, mOffsetMapUnitScale ), context.feature() ? context.feature()->geometry()->type() : QGis::Line );

    for ( int part = 0; part < mline.count(); ++part )
    {
      const QPolygonF &points2 = mline[ part ];

      if ( placement == Interval )
        renderPolylineInterval( points2, context );
      else if ( placement == CentralPoint )
        renderPolylineCentral( points2, context );
      else
        renderPolylineVertex( points2, context, placement );
    }
  }
}
Exemple #8
0
void Window::createGeneralOptionsGroupBox()
{
    /*
    QGroupBox *generalOptionsGroupBox;
    QLabel *localeLabel;
    QLabel *firstDayLabel;
    QLabel *selectionModeLabel;
    QLabel *horizontalHeaderLabel;
    QLabel *verticalHeaderLabel;
    QComboBox *localeCombo;
    QComboBox *firstDayCombo;
    QComboBox *selectionModeCombo;
    QCheckBox *gridCheckBox;
    QCheckBox *navigationCheckBox;
    QComboBox *horizontalHeaderCombo;
    QComboBox *verticalHeaderCombo;
    */

    generalOptionsGroupBox = new QGroupBox(tr("GeneralOptions"));

    localeCombo = new QComboBox;
    int currentIndex = -1;
    int index = 0;
    for(int _lang = QLocale::C; _lang <= QLocale::LastLanguage; ++_lang)
    {
        QLocale::Language lang = static_cast<QLocale::Language>(_lang);
        QList<QLocale::Country> countries = QLocale::countriesForLanguage(lang);
        for(int i=0; i<countries.count(); i++)
        {
            QLocale::Country country = countries.at(i);
            QLocale locale(lang, country);
            QString label = QLocale::languageToString(lang);
            label += QLatin1Char('/');
            label += QLocale::countryToString(country);
            if(this->locale().language() == lang && this->locale().country() == country)
            {
                currentIndex = index;
            }
            localeCombo->addItem(label, locale);
            ++index;
        }
    }

    if(currentIndex != -1)
        localeCombo->setCurrentIndex(currentIndex);

    localeLabel = new QLabel(tr("Locale"));
    localeLabel->setBuddy(localeCombo);

    firstDayCombo = new QComboBox;
    firstDayCombo->addItem(tr("Sunday"), Qt::Sunday);
    firstDayCombo->addItem(tr("Monday"), Qt::Monday);
    firstDayCombo->addItem(tr("Tuesday"), Qt::Tuesday);
    firstDayCombo->addItem(tr("Wednesday"), Qt::Wednesday);
    firstDayCombo->addItem(tr("Thursday"), Qt::Thursday);
    firstDayCombo->addItem(tr("Friday"), Qt::Friday);
    firstDayCombo->addItem(tr("Saturday"), Qt::Saturday);

    firstDayLabel = new QLabel(tr("firstDay"));
    firstDayLabel->setBuddy(firstDayCombo);

    selectionModeCombo = new QComboBox;
    selectionModeCombo->addItem(tr("Singleselection"), QCalendarWidget::SingleSelection);
    selectionModeCombo->addItem(tr("None"), QCalendarWidget::NoSelection);

    selectionModeLabel = new QLabel(tr("SelectionMode"));
    selectionModeLabel->setBuddy(selectionModeCombo);

    horizontalHeaderCombo = new QComboBox;
    horizontalHeaderCombo->addItem(tr("Singleletter"), QCalendarWidget::SingleLetterDayNames);
    horizontalHeaderCombo->addItem(tr("Shortday"), QCalendarWidget::ShortDayNames);
    horizontalHeaderCombo->addItem(tr("None"), QCalendarWidget::NoHorizontalHeader);

    horizontalHeaderLabel = new QLabel(tr("HorizontalHeader"));
    horizontalHeaderLabel->setBuddy(horizontalHeaderCombo);

    verticalHeaderCombo = new QComboBox;
    verticalHeaderCombo->addItem(tr("ISOWeek"), QCalendarWidget::ISOWeekNumbers);
    verticalHeaderCombo->addItem(tr("None"), QCalendarWidget::NoVerticalHeader);

    verticalHeaderLabel = new QLabel(tr("VerticalHeader"));
    verticalHeaderLabel->setBuddy(verticalHeaderCombo);

    gridCheckBox = new QCheckBox(tr("GridVisible"));
    gridCheckBox->setChecked(calendar->isGridVisible());
    navigationCheckBox = new QCheckBox(tr("NavigationBar"));
    navigationCheckBox->setChecked(calendar->isNavigationBarVisible());

    connect(localeCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(localeChanged(int)));
    connect(firstDayCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(firstDayChanged(int)));
    connect(selectionModeCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(selectionModeChanged(int)));
    connect(horizontalHeaderCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(horizontalHeaderChanged(int)));
    connect(verticalHeaderCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(verticalHeaderChanged(int)));
    connect(gridCheckBox, SIGNAL(toggled(bool)), calendar, SLOT(setGridVisible(bool)));
    connect(navigationCheckBox, SIGNAL(toggled(bool)), calendar, SLOT(setNavigationBarVisible(bool)));

    QHBoxLayout *hLayout = new QHBoxLayout;
    hLayout->addWidget(gridCheckBox);
    hLayout->addStretch();
    hLayout->addWidget(navigationCheckBox);

    QGridLayout *generalLayout = new QGridLayout;
    generalLayout->addWidget(localeLabel, 0, 0);
    generalLayout->addWidget(localeCombo, 0, 1);
    generalLayout->addWidget(firstDayLabel, 1, 0);
    generalLayout->addWidget(firstDayCombo, 1, 1);
    generalLayout->addWidget(selectionModeLabel, 2, 0);
    generalLayout->addWidget(selectionModeCombo, 2, 1);
    generalLayout->addLayout(hLayout, 3, 0, 1, 2);
    generalLayout->addWidget(horizontalHeaderLabel, 4, 0);
    generalLayout->addWidget(horizontalHeaderCombo, 4, 1);
    generalLayout->addWidget(verticalHeaderLabel, 5, 0);
    generalLayout->addWidget(verticalHeaderCombo, 5, 1);

    generalOptionsGroupBox->setLayout(generalLayout);
}
void LedDeviceArdulight::setColors(const QList<QRgb> & colors)
{
	DEBUG_MID_LEVEL << Q_FUNC_INFO << colors;

	// Save colors for showing changes of the brightness
	m_colorsSaved = colors;

	resizeColorsBuffer(colors.count());

	applyColorModifications(colors, m_colorsBuffer);

	for(int i=0; i < m_colorsBuffer.count(); i++) {
		m_colorsBuffer[i].r = m_colorsBuffer[i].r >> 4;
		m_colorsBuffer[i].g = m_colorsBuffer[i].g >> 4;
		m_colorsBuffer[i].b = m_colorsBuffer[i].b >> 4;
		PrismatikMath::maxCorrection(254, m_colorsBuffer[i]);
	}

	m_writeBuffer.clear();
	m_writeBuffer.append(m_writeBufferHeader);

	for (int i = 0; i < m_colorsBuffer.count(); i++)
	{
		StructRgb color = m_colorsBuffer[i];

		if (m_colorSequence == "RBG")
		{
			m_writeBuffer.append(color.r);
			m_writeBuffer.append(color.b);
			m_writeBuffer.append(color.g);
		}
		else if (m_colorSequence == "BRG")
		{
			m_writeBuffer.append(color.b);
			m_writeBuffer.append(color.r);
			m_writeBuffer.append(color.g);
		}
		else if (m_colorSequence == "BGR")
		{
			m_writeBuffer.append(color.b);
			m_writeBuffer.append(color.g);
			m_writeBuffer.append(color.r);
		}
		else if (m_colorSequence == "GRB")
		{
			m_writeBuffer.append(color.g);
			m_writeBuffer.append(color.r);
			m_writeBuffer.append(color.b);
		}
		else if (m_colorSequence == "GBR")
		{
			m_writeBuffer.append(color.g);
			m_writeBuffer.append(color.b);
			m_writeBuffer.append(color.r);
		}
		else
		{
			m_writeBuffer.append(color.r);
			m_writeBuffer.append(color.g);
			m_writeBuffer.append(color.b);
		}
	}

	bool ok = writeBuffer(m_writeBuffer);

	emit commandCompleted(ok);
}
Exemple #10
0
void ImportWindow::sImport()
{
    _log->append(tr("Import Started..."));
    QList<QListWidgetItem *> list = _reports->selectedItems();
    if(list.empty())
    {
        if(QMessageBox::question(this, tr("No Reports Selected"),
                                 tr("You have not selected any reports to import. Would you like to select all loaded reports now?"),
                                 QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes)
        {
            _reports->selectAll();
            list = _reports->selectedItems();
        }
    }
    QSqlQuery qtrig;
    QSqlError err;
    if(!qtrig.exec(getSqlFromTag("fmt16", QSqlDatabase::database().driverName())))
    {
        err = qtrig.lastError();
        _log->append(tr("<font color=red>The following error was encountered disabling the trigger:\n"
                        "\t%1\n\t%2\n</font>")
                     .arg(err.driverText())
                     .arg(err.databaseText()));
        return;
    }

    for(int i = 0; i < list.count(); i++)
    {
        QListWidgetItem * item = list.at(i);
        QString xml_file = item->text();

        QString metasql_name  = QString::null;
        QString metasql_group = QString::null;
        QString metasql_desc  = QString::null;
        QString metasql_src   = QString::null;

        if(!xml_file.isEmpty())
        {
            QFile file(xml_file);
            if(file.open(QIODevice::ReadOnly))
            {
                QByteArray contents = file.readAll();
                metasql_src = contents;
                if(!contents.isEmpty())
                {
                    MQLUtil::extractMetadata(contents, metasql_group,
                                             metasql_name, metasql_desc);

                    if(!metasql_name.isEmpty() && !metasql_group.isEmpty())
                    {
                        QSqlQuery qry;
                        QSqlQuery query;

                        query.prepare(getSqlFromTag("fmt17", QSqlDatabase::database().driverName()));
                        query.bindValue(":name",  metasql_name);
                        query.bindValue(":group", metasql_group);
                        query.bindValue(":notes", metasql_desc);
                        query.bindValue(":query", metasql_src);
                        query.bindValue(":system",QVariant(false));
                        query.bindValue(":schema",(_schema->currentText().isEmpty() ? "public" : _schema->currentText()));
                        if(!query.exec())
                        {
                            err = query.lastError();
                            _log->append(tr("<font color=red>The following error was encountered while trying to import %1 into the database:\n"
                                            "\t%2\n\t%3\n</font>")
                                         .arg(xml_file)
                                         .arg(err.driverText())
                                         .arg(err.databaseText()));
                        }
                        else
                        {
                            if (query.first())
                            {
                                int metasqlid = query.value(0).toInt();
                                if (metasqlid < 0)
                                {
                                    _log->append(tr("The saveMetasql stored procedure failed for %1, returning %2.")
                                                 .arg(xml_file).arg(metasqlid));
                                }
                                else
                                    _log->append(tr("Import successful of %1").arg(xml_file));
                            }
                            else
                                _log->append(tr("No results returned from query for %1").arg(xml_file));
                        }
                    }
                    else
                        _log->append(tr("<font color=orange>The document %1 does not have a name and/or group defined\n</font>")
                                     .arg(xml_file));
                }
                else
                    _log->append(tr("<font color=red>Error reading file %1 or file was empty\n</font>")
                                 .arg(xml_file));
            }
            else
                _log->append(tr("<font color=red>Could not open the specified file: %1\n</font>")
                             .arg(xml_file));
        }
        else
            _log->append("<font color=red>Encountered and empty entry: No file name was given.\n</font>");
    }
    if(!qtrig.exec(getSqlFromTag("fmt18", QSqlDatabase::database().driverName())))
    {
        err = qtrig.lastError();
        _log->append(tr("<font color=red>The following error was encountered re-enabling the trigger:\n"
                        "\t%1\n\t%2\n</font>")
                     .arg(err.driverText())
                     .arg(err.databaseText()));
    }
    _log->append(tr("Import complete!\n\n\n"));
}
Exemple #11
0
  /**
   * Repaint the viewport
   *
   * @internal
   *   @history 2011-08-23  Tracie Sucharski - Use the GetMeasuresInCube method
   *                           from ControlNet to get list of measures rather
   *                           than searching through entire net.
   *   @history 2011-11-09 Tracie Sucharski - If there are no measures for
   *                          this cube, return.
   */
  void ChipViewport::paintEvent(QPaintEvent *e) {
    QPainter painter(this);

    if (p_tempView != NULL) {
      painter.drawImage(0, 0, *(p_tempView->p_image));
    }
    else {
      painter.drawImage(0, 0, *p_image);
    }

    if (p_cross == true) {
      painter.setPen(Qt::red);
      painter.drawLine(0, (p_height - 1) / 2, p_width - 1, (p_height - 1) / 2);
      painter.drawLine((p_width - 1) / 2, 0, (p_width - 1) / 2, p_height - 1);
    }

    if (p_circle == true) {
      painter.setPen(Qt::red);
      painter.drawEllipse((p_height - 1) / 2 - p_circleSize / 2,
                          (p_width - 1) / 2 - p_circleSize / 2,
                          p_circleSize, p_circleSize);
    }

    QString serialNumber = p_chipCube? SerialNumber::Compose(*p_chipCube) : QString();
    if (p_controlNet && !serialNumber.isEmpty() && p_controlNet->GetCubeSerials().contains(
                             serialNumber)) {
      // draw measure locations if we have a control network
      //  If the serial number is Unknown, we probably have a ground source
      //  file or level 2 which means it does not exist in the network
      //  TODO:  Is there a better way to handle this?
      if (p_showPoints && serialNumber.compare("Unknown") &&
          p_controlNet->GetNumPoints() != 0) {
        QList<ControlMeasure *> measures =
                                   p_controlNet->GetMeasuresInCube(serialNumber);
        // loop through all points in the control net
        for (int i = 0; i < measures.count(); i++) {
          ControlMeasure *m = measures[i];
          // Find the measurments on the viewport
          double samp = m->GetSample();
          double line = m->GetLine();
          int x, y;

          cubeToViewport(samp, line, x, y);
          // Determine pen color
          // if the point or measure is ignored set to yellow
          if (m->Parent()->IsIgnored() ||
             (!m->Parent()->IsIgnored() && m->IsIgnored())) {
            painter.setPen(QColor(255, 255, 0)); // set point marker yellow
          }
          // check for ground measure
          else if (m->Parent()->GetType() == ControlPoint::Fixed) {
            painter.setPen(Qt::magenta);// set point marker magenta
          }
          else {
            painter.setPen(Qt::green); // set all other point markers green
          }

          // draw points which are not under cross
          if (x != (p_width - 1) / 2 || y != (p_height - 1) / 2) {
            painter.drawLine(x - 5, y, x + 5, y);
            painter.drawLine(x, y - 5, x, y + 5);
          }
        }
      }
    }

    p_tempView = NULL;
    //painter.end();

  }
Exemple #12
0
void ScHelpTreeModel::setupModelData(const QString &dataFile, TreeItem *parent, QMap<QString, QString>* indexToBuild)
{
	QFile file( dataFile );
	if ( !file.open( QIODevice::ReadOnly ) )
		return;
	QDomDocument doc( "menuentries" );
	if ( !doc.setContent( &file ) )
	{
		file.close();
		return;
	}
	file.close();

	QList<TreeItem*> parents;
	QList<int> indentations;
	parents << parent;
	indentations << 0;
	QDomElement docElem = doc.documentElement();
	QDomNode n = docElem.firstChild();
//	bool haveTutorials=false;
	QList<QVariant> columnData;
	int position=0;
	while( !n.isNull() )
	{
		QDomElement e = n.toElement(); // try to convert the node to an element.
		if( !e.isNull() )
		{
			if (e.hasAttribute( "text" ) && e.hasAttribute( "file" ))
			{
				QDomAttr textAttr = e.attributeNode( "text" );
				QDomAttr fileAttr = e.attributeNode( "file" );
				columnData.clear();
				columnData << textAttr.value() <<  fileAttr.value();
				if (position > indentations.last()) 
				{
					// The last child of the current parent is now the new parent
					// unless the current parent has no children.
		
					if (parents.last()->childCount() > 0) 
					{
						parents << parents.last()->child(parents.last()->childCount()-1);
						indentations << position;
					}
				}
				else 
				{
					while (position < indentations.last() && parents.count() > 0) {
						parents.pop_back();
						indentations.pop_back();
					}
				}
				// Append a new item to the current parent's list of children.
				parents.last()->appendChild(new TreeItem(columnData, parents.last()));
				if (indexToBuild)
					indexToBuild->insert(textAttr.value(), fileAttr.value());
			}

			QDomNodeList nl=n.childNodes();
			if (nl.count()>0)
				position=1;
			for(int i=0 ; i<= nl.count() ; i++)
			{
				QDomNode child=nl.item(i);
				if (child.isElement())
				{
					QDomElement ec = child.toElement();
					if (!ec.isNull())
					{
						if (ec.hasAttribute( "text" ) && ec.hasAttribute( "file" ))
						{
							QDomAttr textAttr = ec.attributeNode( "text" );
							QDomAttr fileAttr = ec.attributeNode( "file" );
							columnData.clear();
							columnData << textAttr.value() <<  fileAttr.value();
							if (position > indentations.last()) 
							{
								// The last child of the current parent is now the new parent
								// unless the current parent has no children.
					
								if (parents.last()->childCount() > 0) 
								{
									parents << parents.last()->child(parents.last()->childCount()-1);
									indentations << position;
								}
							}
							else 
							{
								while (position < indentations.last() && parents.count() > 0) {
									parents.pop_back();
									indentations.pop_back();
								}
							}
							// Append a new item to the current parent's list of children.
							parents.last()->appendChild(new TreeItem(columnData, parents.last()));
							if (indexToBuild)
								indexToBuild->insert(textAttr.value(), fileAttr.value());
						}
						//3rd level
						QDomNodeList nl2=child.childNodes();
						if (nl2.count()>0)
							position=2;
						for(int i2=0 ; i2<= nl2.count() ; i2++)
						{
							QDomNode childchild=nl2.item(i2);
							if (childchild.isElement())
							{
								QDomElement ecc = childchild.toElement();
								if (!ecc.isNull())
								{
									QDomAttr textAttr = ecc.attributeNode( "text" );
									QDomAttr fileAttr = ecc.attributeNode( "file" );
									columnData.clear();
									columnData << textAttr.value() <<  fileAttr.value();
									if (position > indentations.last()) 
									{
										// The last child of the current parent is now the new parent
										// unless the current parent has no children.
							
										if (parents.last()->childCount() > 0) 
										{
											parents << parents.last()->child(parents.last()->childCount()-1);
											indentations << position;
										}
									}
									else 
									{
										while (position < indentations.last() && parents.count() > 0) {
											parents.pop_back();
											indentations.pop_back();
										}
									}
									// Append a new item to the current parent's list of children.
									parents.last()->appendChild(new TreeItem(columnData, parents.last()));
									if (indexToBuild)
										indexToBuild->insert(textAttr.value(), fileAttr.value());
								}
							}
						}
						position=1;
					}
				}
			}
			position=0;
		}
		n = n.nextSibling();
	}
}
void LYGithubManager::onIssuesReturned(){

	QList<QByteArray> headerList = getIssuesReply_->rawHeaderList();
	for(int x = 0; x < headerList.count(); x++){
		if(headerList.at(x) == "Link" && lastPageNumber_ == -1){
			QString linkHeader = getIssuesReply_->rawHeader(headerList.at(x));
			int lastPageNumber = -1;
			int nextPageNumber = -1;
			QStringList linkHeaderItems = linkHeader.split(',');
			for(int y = 0; y < linkHeaderItems.count(); y++){
				if(linkHeaderItems.at(y).contains("; rel=\"last\""))
					lastPageNumber = pageNumberFromURLString(linkHeaderItems.at(y));
				if(linkHeaderItems.at(y).contains("; rel=\"next\""))
					nextPageNumber = pageNumberFromURLString(linkHeaderItems.at(y));
			}

			lastPageNumber_ = lastPageNumber;
		}
	}

	int currentPageNumber = -1;
	if(lastPageNumber_ != -1)
		currentPageNumber = pageNumberFromURLString(lastGetIssuesRequest_);

	QJson::Parser parser;
	QVariant githubFullReply = parser.parse(getIssuesReply_->readAll());
	bool doEmit = false;
	QList<QVariantMap> localRetVal;
	QVariantMap oneIssue;
	if(githubFullReply.canConvert(QVariant::List)){
		QVariantList githubListReply = githubFullReply.toList();
		if(githubListReply.at(0).canConvert(QVariant::Map)){
			if((lastPageNumber_ == -1) || (currentPageNumber == lastPageNumber_) )
				doEmit = true;
			for(int x = 0; x < githubListReply.count(); x++){
				oneIssue = githubListReply.at(x).toMap();
				localRetVal.append(oneIssue);
			}
		}
	}

	fullIssuesReply_.append(localRetVal);

	disconnect(getIssuesReply_, 0);
	getIssuesReply_->deleteLater();
	getIssuesReply_ = 0;

	if((lastPageNumber_ != -1) && (currentPageNumber != lastPageNumber_)){

		QNetworkRequest request;

		QString currentPageNumberString = QString("&page=%1").arg(currentPageNumber);
		QString nextPageNumberString = QString("&page=%1").arg(currentPageNumber+1);
		lastGetIssuesRequest_.replace(currentPageNumberString, nextPageNumberString);
		request.setUrl(QUrl(lastGetIssuesRequest_));

		QString userInfo = userName_+":"+password_;
		QByteArray userData = userInfo.toLocal8Bit().toBase64();
		QString headerData = "Basic " + userData;
		request.setRawHeader("Authorization", headerData.toLocal8Bit());

		LYGithubProductBacklogStatusLog::statusLog()->appendStatusMessage(QString("Processed page %1 of %2 for getIssues request").arg(currentPageNumber).arg(lastPageNumber_));

		getIssuesReply_ = manager_->get(request);
		connect(getIssuesReply_, SIGNAL(readyRead()), this, SLOT(onIssuesReturned()));
		return;
	}

	if(doEmit){
		LYGithubProductBacklogStatusLog::statusLog()->appendStatusMessage("Processed final getIssues request");

		lastPageNumber_ = -1;
		emit issuesReturned(fullIssuesReply_);
		return;
	}
	LYGithubProductBacklogStatusLog::statusLog()->appendStatusMessage("Something went wrong in getIssues request");
}
Exemple #14
0
/**
 * Counts all notes that are not tagged
 */
int Note::countAllNotTagged() {
    QList<Note> noteList = Note::fetchAllNotTagged();
    return noteList.count();
}
DriverWidget::DriverWidget(const Device &device, QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Form)
    , m_radioGroup(new QButtonGroup(this))
{
    ui->setupUi(this);
    ui->label->setText(xi18nc("@info %1 is hardware vendor, %2 is hardware model",
                              "<title>%1 %2</title>",
                              device.vendor,
                              device.model));

    // We want to sort drivers so they have consistent order across starts.
    QList<Driver> driverList = device.drivers;
    qSort(driverList);

    foreach (const Driver &driver, driverList) {
        // This driver is not manual, but also has no package, hence we cannot
        // do anything with it and should not display anything.
        if (driver.package == nullptr && !driver.manualInstall){
            qDebug() << "encountered invalid driver" << driver.package << driver.manualInstall << "for" << device.model;
            continue;
        }

        QAbstractButton *button;
        if (driverList.count() <= 1) {
            button = new QCheckBox(this);
            m_radioGroup->setExclusive(false);
        } else {
            button = new QRadioButton(this);
        }
        button->setProperty("package", driver.packageName);
        button->setProperty("builtin", driver.builtin);
        ui->verticalLayout->addWidget(button);
        m_radioGroup->addButton(button);

        if (driver.fuzzyActive) {
            button->setChecked(true);
        }

        if (driver.manualInstall) {
            button->setText(i18nc("Manually installed 3rd party driver",
                                  "This device is using a manually-installed driver : (%1)",
                                  driver.packageName));
            break; // Manually installed drivers have no additional information available.
        }

        if (driver.recommended) {
            button->setText(i18nc("%1 is description and %2 is package name; when driver is recommended for use",
                                  "Using %1 from %2 (Recommended Driver)",
                                  driver.package->shortDescription(),
                                  driver.package->name()));
        } else { // !recommended
            button->setText(i18nc("%1 is description and %2 is package name",
                                  "Using %1 from %2",
                                  driver.package->shortDescription(),
                                  driver.package->name()));
        }

        if (driver.free) {
            button->setToolTip(i18nc("The driver is under a open source license",
                                     "Open Source Driver"));
        } else { // !free
            button->setToolTip(i18nc("The driver is under a proprietary license",
                                     "Proprietary Driver"));
        }
    }

    m_indexSelected = m_radioGroup->checkedId();
    m_defaultSelection = m_indexSelected;
    connect(m_radioGroup, SIGNAL(buttonClicked(QAbstractButton*)), this, SIGNAL(selectionChanged()));
}
Exemple #16
0
int QDeclarativeTimeLinePrivate::advance(int t)
{
    int pauseTime = -1;

    // XXX - surely there is a more efficient way?
    do {
        pauseTime = -1;
        // Minimal advance time
        int advanceTime = t;
        for (Ops::Iterator iter = ops.begin(); iter != ops.end(); ++iter) {
            TimeLine &tl = *iter;
            Op &op = tl.ops.first();
            int length = op.length - tl.consumedOpLength;
                
            if (length < advanceTime) {
                advanceTime = length;
                if (advanceTime == 0)
                    break;
            }
        }
        t -= advanceTime;

        // Process until then.  A zero length advance time will only process 
        // sets.
        QList<QPair<int, Update> > updates;

        for (Ops::Iterator iter = ops.begin(); iter != ops.end(); ) {
            QDeclarativeTimeLineValue *v = static_cast<QDeclarativeTimeLineValue *>(iter.key());
            TimeLine &tl = *iter;
            Q_ASSERT(!tl.ops.isEmpty());

            do {
                Op &op = tl.ops.first();
                if (advanceTime == 0 && op.length != 0)
                    continue;

                if (tl.consumedOpLength == 0 && 
                   op.type != Op::Pause && 
                   op.type != Op::Execute)
                    tl.base = v->value();

                if ((tl.consumedOpLength + advanceTime) == op.length) {
                    if (op.type == Op::Execute) {
                        updates << qMakePair(op.order, Update(op.event));
                    } else {
                        bool changed = false;
                        qreal val = value(op, op.length, tl.base, &changed);
                        if (changed)
                            updates << qMakePair(op.order, Update(v, val));
                    }
                    tl.length -= qMin(advanceTime, tl.length);
                    tl.consumedOpLength = 0;
                    tl.ops.removeFirst();
                } else {
                    tl.consumedOpLength += advanceTime;
                    bool changed = false;
                    qreal val = value(op, tl.consumedOpLength, tl.base, &changed);
                    if (changed)
                        updates << qMakePair(op.order, Update(v, val));
                    tl.length -= qMin(advanceTime, tl.length);
                    break;
                }

            } while(!tl.ops.isEmpty() && advanceTime == 0 && tl.ops.first().length == 0);


            if (tl.ops.isEmpty()) {
                iter = ops.erase(iter);
                v->_t = 0;
            } else {
                if (tl.ops.first().type == Op::Pause && pauseTime != 0) {
                    int opPauseTime = tl.ops.first().length - tl.consumedOpLength;
                    if (pauseTime == -1 || opPauseTime < pauseTime)
                        pauseTime = opPauseTime;
                } else {
                    pauseTime = 0;
                }
                ++iter;
            }
        }

        length -= qMin(length, advanceTime);
        syncPoint -= advanceTime;

        qSort(updates.begin(), updates.end());
        updateQueue = &updates;
        for (int ii = 0; ii < updates.count(); ++ii) {
            const Update &v = updates.at(ii).second;
            if (v.g) {
                v.g->setValue(v.v);
            } else {
                v.e.d0(v.e.d1);
            }
        }
        updateQueue = 0;
    } while(t);

    return pauseTime;
}
Exemple #17
0
void GraphUtils::minCut(QList<ConnectorItem *> & connectorItems, QList<SketchWidget *> & foreignSketchWidgets, ConnectorItem * source, ConnectorItem * sink, QList<ConnectorEdge *> & minCut) 
{
	// this helped:  http://boost.2283326.n4.nabble.com/graph-edmund-karp-max-flow-vs-kolmogorov-max-flow-color-map-td2565611.html
	
	using namespace boost;

	typedef adjacency_list_traits < vecS, vecS, directedS > Traits;
    typedef property < vertex_color_t, boost::default_color_type > COLOR;
	typedef property < vertex_index_t, long, COLOR > VERTEX;
    typedef property < edge_reverse_t, Traits::edge_descriptor > REVERSE;
    typedef property < edge_residual_capacity_t, long, REVERSE > RESIDUAL;
	typedef property < edge_capacity_t, long, RESIDUAL > EDGE;
	typedef adjacency_list < listS, vecS, directedS, VERTEX, EDGE > Graph;

	Graph g;

	property_map < Graph, edge_capacity_t >::type capacity = get(edge_capacity, g);
	property_map < Graph, edge_residual_capacity_t >::type residual_capacity = get(edge_residual_capacity, g);
	property_map < Graph, edge_reverse_t >::type reverse = get(edge_reverse, g);

	property_map < Graph, vertex_color_t >::type color = get(vertex_color, g);
	property_map < Graph, vertex_index_t >::type index = get(vertex_index, g);

	Traits::vertex_descriptor s, t;

	QList<Wire *> visitedWires;
	QList<int> indexes;
	QHash<ConnectorItem *, int> vertices;
	QList<ConnectorEdge *> edges;
	QVector<Traits::vertex_descriptor> verts;

	vertices.insert(source, 0);
	vertices.insert(sink, 1);
	verts.append(s = add_vertex(g));
	verts.append(t = add_vertex(g));

	foreach (ConnectorItem * connectorItem, connectorItems) {
		//connectorItem->debugInfo("input");
		if (connectorItem->attachedToItemType() == ModelPart::Wire) {
			Wire * wire = qobject_cast<Wire *>(connectorItem->attachedTo());
			if (visitedWires.contains(wire)) continue;

			QList<Wire *> wires;
			QList<ConnectorItem *> ends;
			wire->collectChained(wires, ends);
			visitedWires.append(wires);
			if (ends.count() < 2) continue;

			foreach (ConnectorItem * end, ends) {
				appendVertIf(end, vertices, verts);
			}

			for (int i = 0; i < ends.count(); i++) {
				ConnectorItem * end = ends[i];
				for (int j = i + 1; j < ends.count(); j++) {
					ConnectorEdge * connectorEdge = makeConnectorEdge(edges, end, ends[j], 1000, wire);
					connectorEdge->setHeadTail(vertices.value(connectorEdge->c0), vertices.value(connectorEdge->c1));
				}
			}
			continue;
		}
Exemple #18
0
/*!
   \brief Calculate minor/medium ticks for major ticks

   \param majorTicks Major ticks
   \param maxMinorSteps Maximum number of minor steps
   \param stepSize Step size
   \param minorTicks Array to be filled with the calculated minor ticks
   \param mediumTicks Array to be filled with the calculated medium ticks
*/
void QwtLogScaleEngine::buildMinorTicks(
    const QList<double> &majorTicks,
    int maxMinorSteps, double stepSize,
    QList<double> &minorTicks,
    QList<double> &mediumTicks ) const
{
    const double logBase = base();

    if ( stepSize < 1.1 )          // major step width is one base
    {
        double minStep = divideInterval( stepSize, maxMinorSteps + 1 );
        if ( minStep == 0.0 )
            return;
        
        const int numSteps = qRound( stepSize / minStep ); 

        int mediumTickIndex = -1;
        if ( ( numSteps > 2 ) && ( numSteps % 2 == 0 ) )
            mediumTickIndex = numSteps / 2;

        for ( int i = 0; i < majorTicks.count() - 1; i++ )
        {
            const double v = majorTicks[i];
            const double s = logBase / numSteps;

            if ( s >= 1.0 )
            {
                for ( int j = 2; j < numSteps; j++ )
                {
                    minorTicks += v * j * s;
                }
            }
            else
            {
                for ( int j = 1; j < numSteps; j++ )
                {
                    const double tick = v + j * v * ( logBase - 1 ) / numSteps;
                    if ( j == mediumTickIndex )
                        mediumTicks += tick;
                    else
                        minorTicks += tick;
                }
            }
        }
    }
    else
    {
        double minStep = divideInterval( stepSize, maxMinorSteps );
        if ( minStep == 0.0 )
            return;

        if ( minStep < 1.0 )
            minStep = 1.0;

        // # subticks per interval
        int numTicks = qRound( stepSize / minStep ) - 1;

        // Do the minor steps fit into the interval?
        if ( qwtFuzzyCompare( ( numTicks +  1 ) * minStep,
            stepSize, stepSize ) > 0 )
        {
            numTicks = 0;
        }

        if ( numTicks < 1 )
            return; 

        int mediumTickIndex = -1;
        if ( ( numTicks > 2 ) && ( numTicks % 2 ) )
            mediumTickIndex = numTicks / 2;

        // substep factor = base^substeps
        const qreal minFactor = qMax( qPow( logBase, minStep ), qreal( logBase ) );

        for ( int i = 0; i < majorTicks.count(); i++ )
        {
            double tick = majorTicks[i];
            for ( int j = 0; j < numTicks; j++ )
            {
                tick *= minFactor;

                if ( j == mediumTickIndex )
                    mediumTicks += tick;
                else
                    minorTicks += tick;
            }
        }
    }
}
void QWebSettingsPrivate::apply()
{
    if (settings) {
        settings->setTextAreasAreResizable(true);

        QWebSettingsPrivate *global = QWebSettings::globalSettings()->d;

        QString family = fontFamilies.value(QWebSettings::StandardFont,
                                            global->fontFamilies.value(QWebSettings::StandardFont));
        settings->setStandardFontFamily(family);

        family = fontFamilies.value(QWebSettings::FixedFont,
                                    global->fontFamilies.value(QWebSettings::FixedFont));
        settings->setFixedFontFamily(family);

        family = fontFamilies.value(QWebSettings::SerifFont,
                                    global->fontFamilies.value(QWebSettings::SerifFont));
        settings->setSerifFontFamily(family);

        family = fontFamilies.value(QWebSettings::SansSerifFont,
                                    global->fontFamilies.value(QWebSettings::SansSerifFont));
        settings->setSansSerifFontFamily(family);

        family = fontFamilies.value(QWebSettings::CursiveFont,
                                    global->fontFamilies.value(QWebSettings::CursiveFont));
        settings->setCursiveFontFamily(family);

        family = fontFamilies.value(QWebSettings::FantasyFont,
                                    global->fontFamilies.value(QWebSettings::FantasyFont));
        settings->setFantasyFontFamily(family);

        int size = fontSizes.value(QWebSettings::MinimumFontSize,
                                   global->fontSizes.value(QWebSettings::MinimumFontSize));
        settings->setMinimumFontSize(size);

        size = fontSizes.value(QWebSettings::MinimumLogicalFontSize,
                                   global->fontSizes.value(QWebSettings::MinimumLogicalFontSize));
        settings->setMinimumLogicalFontSize(size);

        size = fontSizes.value(QWebSettings::DefaultFontSize,
                                   global->fontSizes.value(QWebSettings::DefaultFontSize));
        settings->setDefaultFontSize(size);

        size = fontSizes.value(QWebSettings::DefaultFixedFontSize,
                                   global->fontSizes.value(QWebSettings::DefaultFixedFontSize));
        settings->setDefaultFixedFontSize(size);

        bool value = attributes.value(QWebSettings::AutoLoadImages,
                                      global->attributes.value(QWebSettings::AutoLoadImages));
        settings->setLoadsImagesAutomatically(value);

        value = attributes.value(QWebSettings::JavascriptEnabled,
                                      global->attributes.value(QWebSettings::JavascriptEnabled));
        settings->setJavaScriptEnabled(value);

        value = attributes.value(QWebSettings::JavascriptCanOpenWindows,
                                      global->attributes.value(QWebSettings::JavascriptCanOpenWindows));
        settings->setJavaScriptCanOpenWindowsAutomatically(value);

        value = attributes.value(QWebSettings::JavaEnabled,
                                      global->attributes.value(QWebSettings::JavaEnabled));
        settings->setJavaEnabled(value);

        value = attributes.value(QWebSettings::PluginsEnabled,
                                      global->attributes.value(QWebSettings::PluginsEnabled));
        settings->setPluginsEnabled(value);

        value = attributes.value(QWebSettings::PrivateBrowsingEnabled,
                                      global->attributes.value(QWebSettings::PrivateBrowsingEnabled));
        settings->setPrivateBrowsingEnabled(value);

        value = attributes.value(QWebSettings::JavascriptCanAccessClipboard,
                                      global->attributes.value(QWebSettings::JavascriptCanAccessClipboard));
        settings->setDOMPasteAllowed(value);

        value = attributes.value(QWebSettings::DeveloperExtrasEnabled,
                                      global->attributes.value(QWebSettings::DeveloperExtrasEnabled));
        settings->setDeveloperExtrasEnabled(value);

        QUrl location = !userStyleSheetLocation.isEmpty() ? userStyleSheetLocation : global->userStyleSheetLocation;
        settings->setUserStyleSheetLocation(WebCore::KURL(location));

        QString localStoragePath = !localStorageDatabasePath.isEmpty() ? localStorageDatabasePath : global->localStorageDatabasePath;
        settings->setLocalStorageDatabasePath(localStoragePath);

        value = attributes.value(QWebSettings::ZoomTextOnly,
                                 global->attributes.value(QWebSettings::ZoomTextOnly));
        settings->setZoomsTextOnly(value);

        value = attributes.value(QWebSettings::PrintElementBackgrounds,
                                      global->attributes.value(QWebSettings::PrintElementBackgrounds));
        settings->setShouldPrintBackgrounds(value);

        value = attributes.value(QWebSettings::OfflineStorageDatabaseEnabled,
                                      global->attributes.value(QWebSettings::OfflineStorageDatabaseEnabled));
        settings->setDatabasesEnabled(value);

        value = attributes.value(QWebSettings::OfflineWebApplicationCacheEnabled,
                                      global->attributes.value(QWebSettings::OfflineWebApplicationCacheEnabled));
        settings->setOfflineWebApplicationCacheEnabled(value);

        value = attributes.value(QWebSettings::LocalStorageDatabaseEnabled,
                                      global->attributes.value(QWebSettings::LocalStorageDatabaseEnabled));
        settings->setLocalStorageEnabled(value);
    } else {
        QList<QWebSettingsPrivate *> settings = *::allSettings();
        for (int i = 0; i < settings.count(); ++i)
            settings[i]->apply();
    }
}
Exemple #20
0
int runKMyMoney(KApplication *a, KStartupLogo *splash)
{
  int rc = 0;
  do {
    if (QDBusConnection::sessionBus().interface()->isServiceRegistered("org.kde.kmymoney")) {
      const QList<QString> instances = kmymoney->instanceList();
      if (instances.count() > 0) {

        // If the user launches a second copy of the app and includes a file to
        // open, they are probably attempting a "WebConnect" session.  In this case,
        // we'll check to make sure it's an importable file that's passed in, and if so, we'll
        // notify the primary instance of the file and kill ourselves.

        if (args->count() > 0) {
          KUrl url = args->url(0);
          if (kmymoney->isImportableFile(url.path())) {
            // if there are multiple instances, we'll send this to the first one
            QString primary = instances[0];

            // send a message to the primary client to import this file
            QDBusInterface remoteApp(primary, "/KMymoney", "org.kde.kmymoney");
            remoteApp.call("webConnect", url.path(), kapp->startupId());

            // Before we delete the application, we make sure that we destroy all
            // widgets by running the event loop for some time to catch all those
            // widgets that are requested to be destroyed using the deleteLater() method.
            QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents, 10);

            delete kmymoney;
            delete splash;
            break;
          }
        }

        if (KMessageBox::questionYesNo(0, i18n("Another instance of KMyMoney is already running. Do you want to quit?")) == KMessageBox::Yes) {
          rc = 1;
          delete kmymoney;
          delete splash;
          break;
        }
      }
    } else {
      qDebug("D-Bus registration failed. Some functions are not available.");
    }
    kmymoney->show();
    kmymoney->centralWidget()->setEnabled(false);

    delete splash;

    // force complete paint of widgets
    qApp->processEvents();

    QString importfile;
    KUrl url;
    // make sure, we take the file provided on the command
    // line before we go and open the last one used
    if (args->count() > 0) {
      url = args->url(0);

      // Check to see if this is an importable file, as opposed to a loadable
      // file.  If it is importable, what we really want to do is load the
      // last used file anyway and then immediately import this file.  This
      // implements a "web connect" session where there is not already an
      // instance of the program running.

      if (kmymoney->isImportableFile(url.path())) {
        importfile = url.path();
        url = kmymoney->readLastUsedFile();
      }

    } else {
      url = kmymoney->readLastUsedFile();
    }

    KTipDialog::showTip(kmymoney, "", false);
    if (url.isValid() && !args->isSet("n")) {
      kmymoney->slotFileOpenRecent(url);
    } else if (KMyMoneyGlobalSettings::firstTimeRun()) {
      kmymoney->slotFileNew();
    }
    KMyMoneyGlobalSettings::setFirstTimeRun(false);

    if (! importfile.isEmpty())
      kmymoney->webConnect(importfile, kapp->startupId());

    if (kmymoney != 0) {
      kmymoney->updateCaption();
      args->clear();
      kmymoney->centralWidget()->setEnabled(true);
      rc = a->exec();
    }
  } while (0);
  return rc;
}
Exemple #21
0
QList<QgsMapToolIdentify::IdentifyResult> QgsMapToolIdentify::identify( int x, int y, IdentifyMode mode, QList<QgsMapLayer*> layerList, LayerType layerType )
{
  QList<IdentifyResult> results;

  mLastPoint = mCanvas->getCoordinateTransform()->toMapCoordinates( x, y );
  mLastExtent = mCanvas->extent();
  mLastMapUnitsPerPixel = mCanvas->mapUnitsPerPixel();

  if ( mode == DefaultQgsSetting )
  {
    QSettings settings;
    mode = static_cast<IdentifyMode>( settings.value( "/Map/identifyMode", 0 ).toInt() );
  }

  if ( mode == LayerSelection )
  {
    QList<IdentifyResult> results = identify( x, y, TopDownAll, layerList, layerType );
    QPoint globalPos = mCanvas->mapToGlobal( QPoint( x + 5, y + 5 ) );
    return mIdentifyMenu->exec( results, globalPos );
  }
  else if ( mode == ActiveLayer && layerList.isEmpty() )
  {
    QgsMapLayer *layer = mCanvas->currentLayer();

    if ( !layer )
    {
      emit identifyMessage( tr( "No active layer. To identify features, you must choose an active layer." ) );
      return results;
    }

    QApplication::setOverrideCursor( Qt::WaitCursor );

    identifyLayer( &results, layer, mLastPoint, mLastExtent, mLastMapUnitsPerPixel, layerType );
  }
  else
  {
    QApplication::setOverrideCursor( Qt::WaitCursor );

    QStringList noIdentifyLayerIdList = QgsProject::instance()->readListEntry( "Identify", "/disabledLayers" );

    int layerCount;
    if ( layerList.isEmpty() )
      layerCount = mCanvas->layerCount();
    else
      layerCount = layerList.count();


    for ( int i = 0; i < layerCount; i++ )
    {

      QgsMapLayer *layer;
      if ( layerList.isEmpty() )
        layer = mCanvas->layer( i );
      else
        layer = layerList.value( i );

      emit identifyProgress( i, mCanvas->layerCount() );
      emit identifyMessage( tr( "Identifying on %1..." ).arg( layer->name() ) );

      if ( noIdentifyLayerIdList.contains( layer->id() ) )
        continue;

      if ( identifyLayer( &results, layer,  mLastPoint, mLastExtent, mLastMapUnitsPerPixel, layerType ) )
      {
        if ( mode == TopDownStopAtFirst )
          break;
      }
    }

    emit identifyProgress( mCanvas->layerCount(), mCanvas->layerCount() );
    emit identifyMessage( tr( "Identifying done." ) );
  }

  QApplication::restoreOverrideCursor();

  return results;
}
// Arranges widgets and returns height required.
int PackedLayout::arrange(const QRect& rect, bool set) const
{
    int x = rect.x();
    int y = rect.y();
    int yrow = 0;
    QList<QRect> posn;
    int end = mItems.count();
    QList<QLayoutItem*> items;
    for (int i = 0;  i < end;  ++i)
    {
        QLayoutItem* item = mItems[i];
        if (item->isEmpty())
            continue;
        QSize size = item->sizeHint();
        int right = x + size.width();
        if (right > rect.right()  &&  x > rect.x())
        {
            x = rect.x();
            y = y + yrow + spacing();
            right = x + size.width();
            yrow = size.height();
        }
        else
            yrow = qMax(yrow, size.height());
        items.append(item);
        posn.append(QRect(QPoint(x, y), size));
        x = right + spacing();
    }
    if (set)
    {
        int count = items.count();
        if (mAlignment == Qt::AlignLeft)
        {
            // Left aligned: no position adjustment needed
            // Set the positions of all the layout items
            for (int i = 0;  i < count;  ++i)
                items[i]->setGeometry(posn[i]);
        }
        else
        {
            // Set the positions of all the layout items
            for (int i = 0;  i < count; )
            {
                // Adjust item positions a row at a time
                y = posn[i].y();
                int last;   // after last item in this row
                for (last = i + 1;  last < count && posn[last].y() == y;  ++last) ;
                int n = last - i;   // number of items in this row
                int free = rect.right() - posn[last - 1].right();
                switch (mAlignment)
                {
                    case Qt::AlignJustify:
                        if (n == 1)
                        {
                            items[i]->setGeometry(posn[i]);
                            ++i;
                        }
                        else if (n > 1)
                        {
                            for (int j = 0;  i < last;  ++j, ++i)
                                items[i]->setGeometry(QRect(QPoint(posn[i].x() + (free * j)/(n - 1), y), posn[i].size()));
                        }
                        break;
                    case Qt::AlignHCenter:
                        free /= 2;
                        // fall through to AlignRight
                    case Qt::AlignRight:
                        for ( ;  i < last;  ++i)
                            items[i]->setGeometry(QRect(QPoint(posn[i].x() + free, y), posn[i].size()));
                        break;
                    default:
                        break;
                }
            }
        }
    }
    return y + yrow - rect.y();
}
void ListItemsHelper::recalculate()
{
    //kDebug(32500);
    const QTextListFormat format = m_textList->format();
    const KoListStyle::Style listStyle = static_cast<KoListStyle::Style>(m_textList->format().style());

    const QString prefix = format.stringProperty(KoListStyle::ListItemPrefix);
    const QString suffix = format.stringProperty(KoListStyle::ListItemSuffix);
    const int level = format.intProperty(KoListStyle::Level);
    int dp = format.intProperty(KoListStyle::DisplayLevel);
    if (dp > level)
        dp = level;
    const int displayLevel = dp ? dp : 1;

    int startValue = 1;
    if (format.hasProperty(KoListStyle::StartValue))
        startValue = format.intProperty(KoListStyle::StartValue);
    if (format.boolProperty(KoListStyle::ContinueNumbering)) {
        // Look for the index of a previous list of the same numbering style and level
        for (QTextBlock tb = m_textList->item(0).previous(); tb.isValid(); tb = tb.previous()) {
            if (!tb.textList() || tb.textList() == m_textList)
                continue; // no list here or it's the same list; keep looking

            QTextListFormat otherFormat = tb.textList()->format();
            if (otherFormat.intProperty(KoListStyle::Level) != level)
                break; // found a different list but of a different level

            if (otherFormat.style() == format.style()) {
                if (KoTextBlockData *data = dynamic_cast<KoTextBlockData *>(tb.userData()))
                    startValue = data->counterIndex() + 1; // Start from previous list value + 1
            }

            break;
        }
    }

    int index = startValue;
    QList<QTextList*> sublistsToRecalculate;
    qreal width = format.doubleProperty(KoListStyle::MinimumWidth);
    for (int i = 0; i < m_textList->count(); i++) {
        QTextBlock tb = m_textList->item(i);
        //kDebug(32500) <<" *" << tb.text();
        KoTextBlockData *data = dynamic_cast<KoTextBlockData*>(tb.userData());
        if (!data) {
            data = new KoTextBlockData();
            tb.setUserData(data);
        }
        QTextBlockFormat blockFormat = tb.blockFormat();

        if (blockFormat.boolProperty(KoParagraphStyle::UnnumberedListItem)
            || blockFormat.boolProperty(KoParagraphStyle::IsListHeader)) {
            data->setCounterText(QString());
            data->setPartialCounterText(QString());
            continue;
        }

        if (blockFormat.boolProperty(KoParagraphStyle::RestartListNumbering))
            index = format.intProperty(KoListStyle::StartValue);
        const int paragIndex = blockFormat.intProperty(KoParagraphStyle::ListStartValue);
        if (paragIndex > 0)
            index = paragIndex;

        //check if this is the first of this level meaning we should start from startvalue
        QTextBlock b = tb.previous();
        for (;b.isValid(); b = b.previous()) {
            if (b.textList() == m_textList)
                break; // all fine
            if (b.textList() == 0)
                continue;
            QTextListFormat otherFormat = b.textList()->format();
            if (otherFormat.style() != format.style())
                continue; // uninteresting for us
            if (b.textList()->format().intProperty(KoListStyle::Level) < level) {
                index = startValue;
                break;
            }
        }

        QString item;
        if (displayLevel > 1) {
            int checkLevel = level;
            int tmpDisplayLevel = displayLevel;
            for (QTextBlock b = tb.previous(); tmpDisplayLevel > 1 && b.isValid(); b = b.previous()) {
                if (b.textList() == 0)
                    continue;
                QTextListFormat lf = b.textList()->format();
                if (lf.style() != format.style())
                    continue; // uninteresting for us
                const int otherLevel  = lf.intProperty(KoListStyle::Level);
                if (checkLevel <= otherLevel)
                    continue;
                /*if(needsRecalc(b->textList())) {
                      TODO
                  } */
                KoTextBlockData *otherData = dynamic_cast<KoTextBlockData*>(b.userData());
                if (! otherData) {
                    kWarning(32500) << "Missing KoTextBlockData, Skipping textblock";
                    continue;
                }
                if (tmpDisplayLevel - 1 < otherLevel) { // can't just copy it fully since we are
                    // displaying less then the full counter
                    item += otherData->partialCounterText();
                    tmpDisplayLevel--;
                    checkLevel--;
                    for (int i = otherLevel + 1; i < level; i++) {
                        tmpDisplayLevel--;
                        item += ".1"; // add missing counters.
                    }
                } else { // just copy previous counter as prefix
                    QString otherPrefix = lf.stringProperty(KoListStyle::ListItemPrefix);
                    QString otherSuffix = lf.stringProperty(KoListStyle::ListItemSuffix);
                    QString pureCounter = otherData->counterText().mid(otherPrefix.size());
                    pureCounter = pureCounter.left(pureCounter.size() - otherSuffix.size());
                    item += pureCounter;
                    for (int i = otherLevel + 1; i < level; i++)
                        item += ".1"; // add missing counters.
                    tmpDisplayLevel = 0;
                    break;
                }
            }
            for (int i = 1; i < tmpDisplayLevel; i++)
                item = "1." + item; // add missing counters.
        }

        if ((listStyle == KoListStyle::DecimalItem || listStyle == KoListStyle::AlphaLowerItem ||
                listStyle == KoListStyle::UpperAlphaItem ||
                listStyle == KoListStyle::RomanLowerItem ||
                listStyle == KoListStyle::UpperRomanItem) &&
                !(item.isEmpty() || item.endsWith('.') || item.endsWith(' '))) {
            item += '.';
        }
        bool calcWidth = true;
        QString partialCounterText;
        switch (listStyle) {
        case KoListStyle::DecimalItem:
            partialCounterText = QString::number(index);
            break;
        case KoListStyle::AlphaLowerItem:
            partialCounterText = intToAlpha(index, Lowercase,
                                            m_textList->format().boolProperty(KoListStyle::LetterSynchronization));
            break;
        case KoListStyle::UpperAlphaItem:
            partialCounterText = intToAlpha(index, Uppercase,
                                            m_textList->format().boolProperty(KoListStyle::LetterSynchronization));
            break;
        case KoListStyle::RomanLowerItem:
            partialCounterText = intToRoman(index);
            break;
        case KoListStyle::UpperRomanItem:
            partialCounterText = intToRoman(index).toUpper();
            break;
        case KoListStyle::SquareItem:
        case KoListStyle::DiscItem:
        case KoListStyle::CircleItem:
        case KoListStyle::HeavyCheckMarkItem:
        case KoListStyle::BallotXItem:
        case KoListStyle::RightArrowItem:
        case KoListStyle::RightArrowHeadItem:
        case KoListStyle::RhombusItem:
        case KoListStyle::BoxItem: {
            calcWidth = false;
            item = ' ';
            width = m_displayFont.pointSizeF();
            int percent = format.intProperty(KoListStyle::BulletSize);
            if (percent > 0)
                width = width * (percent / 100.0);
            break;
        }
        case KoListStyle::CustomCharItem:
            calcWidth = false;
            if (format.intProperty(KoListStyle::BulletCharacter))
                item = QString(QChar(format.intProperty(KoListStyle::BulletCharacter)));
            width = m_fm.width(item);
            break;
        case KoListStyle::None:
            calcWidth = false;
            width =  10.0; // simple indenting
            break;
        case KoListStyle::Bengali:
        case KoListStyle::Gujarati:
        case KoListStyle::Gurumukhi:
        case KoListStyle::Kannada:
        case KoListStyle::Malayalam:
        case KoListStyle::Oriya:
        case KoListStyle::Tamil:
        case KoListStyle::Telugu:
        case KoListStyle::Tibetan:
        case KoListStyle::Thai:
            partialCounterText = intToScript(index, listStyle);
            break;
        case KoListStyle::Abjad:
        case KoListStyle::ArabicAlphabet:
        case KoListStyle::AbjadMinor:
            partialCounterText = intToScriptList(index, listStyle);
            break;
        case KoListStyle::ImageItem:
            calcWidth = false;
            width = qMax(format.doubleProperty(KoListStyle::Width), (qreal)1.0);
            break;
        default:  // others we ignore.
            calcWidth = false;
        }

        data->setCounterIsImage(listStyle == KoListStyle::ImageItem);
        data->setPartialCounterText(partialCounterText);
        data->setCounterIndex(index);
        item += partialCounterText;
        if (calcWidth)
            width = qMax(width, m_fm.width(item));
        data->setCounterText(prefix + item + suffix);
        index++;

        // have to recalculate any sublists under this element too
        QTextBlock nb = tb.next();
        while (nb.isValid() && nb.textList() == 0)
            nb = nb.next();
        if (nb.isValid()) {
            QTextListFormat lf = nb.textList()->format();
            if ((lf.style() == format.style())
              && nb.textList()->format().intProperty(KoListStyle::Level) > level) {
                // this is a sublist
                // have to remember to recalculate this list after the current level is done
                // cant do it right away since the sublist's prefix text is dependant on this level
                sublistsToRecalculate.append(nb.textList());
            }
        }
    }

    for (int i = 0; i < sublistsToRecalculate.count(); i++) {
        ListItemsHelper lih(sublistsToRecalculate.at(i), m_displayFont);
        lih.recalculate();
    }

    qreal counterSpacing = m_fm.width(' ');
    counterSpacing = qMax(format.doubleProperty(KoListStyle::MinimumDistance), counterSpacing);
    width += m_fm.width(prefix + suffix); // same for all
    width = qMax(format.doubleProperty(KoListStyle::MinimumWidth), width);
    for (int i = 0; i < m_textList->count(); i++) {
        QTextBlock tb = m_textList->item(i);
        KoTextBlockData *data = dynamic_cast<KoTextBlockData*>(tb.userData());
        Q_ASSERT(data);
        data->setCounterWidth(width);
        data->setCounterSpacing(counterSpacing);
        //kDebug(32500) << data->counterText() <<"" << tb.text();
        //kDebug(32500) <<"    setCounterWidth:" << width;
    }
    //kDebug(32500);
}
Exemple #24
0
void QWebSettingsPrivate::apply()
{
    if (settings) {
        settings->setTextAreasAreResizable(true);

        QWebSettingsPrivate* global = QWebSettings::globalSettings()->d;

        QString family = fontFamilies.value(QWebSettings::StandardFont,
                                            global->fontFamilies.value(QWebSettings::StandardFont));
        settings->setStandardFontFamily(family);

        family = fontFamilies.value(QWebSettings::FixedFont,
                                    global->fontFamilies.value(QWebSettings::FixedFont));
        settings->setFixedFontFamily(family);

        family = fontFamilies.value(QWebSettings::SerifFont,
                                    global->fontFamilies.value(QWebSettings::SerifFont));
        settings->setSerifFontFamily(family);

        family = fontFamilies.value(QWebSettings::SansSerifFont,
                                    global->fontFamilies.value(QWebSettings::SansSerifFont));
        settings->setSansSerifFontFamily(family);

        family = fontFamilies.value(QWebSettings::CursiveFont,
                                    global->fontFamilies.value(QWebSettings::CursiveFont));
        settings->setCursiveFontFamily(family);

        family = fontFamilies.value(QWebSettings::FantasyFont,
                                    global->fontFamilies.value(QWebSettings::FantasyFont));
        settings->setFantasyFontFamily(family);

        int size = fontSizes.value(QWebSettings::MinimumFontSize,
                                   global->fontSizes.value(QWebSettings::MinimumFontSize));
        settings->setMinimumFontSize(size);

        size = fontSizes.value(QWebSettings::MinimumLogicalFontSize,
                                   global->fontSizes.value(QWebSettings::MinimumLogicalFontSize));
        settings->setMinimumLogicalFontSize(size);

        size = fontSizes.value(QWebSettings::DefaultFontSize,
                                   global->fontSizes.value(QWebSettings::DefaultFontSize));
        settings->setDefaultFontSize(size);

        size = fontSizes.value(QWebSettings::DefaultFixedFontSize,
                                   global->fontSizes.value(QWebSettings::DefaultFixedFontSize));
        settings->setDefaultFixedFontSize(size);

        bool value = attributes.value(QWebSettings::AutoLoadImages,
                                      global->attributes.value(QWebSettings::AutoLoadImages));
        settings->setLoadsImagesAutomatically(value);

        value = attributes.value(QWebSettings::JavascriptEnabled,
                                      global->attributes.value(QWebSettings::JavascriptEnabled));
        settings->setJavaScriptEnabled(value);
#if USE(ACCELERATED_COMPOSITING)
        value = attributes.value(QWebSettings::AcceleratedCompositingEnabled,
                                      global->attributes.value(QWebSettings::AcceleratedCompositingEnabled));

        settings->setAcceleratedCompositingEnabled(value);
#endif
#if ENABLE(3D_CANVAS)
        value = attributes.value(QWebSettings::WebGLEnabled,
                                 global->attributes.value(QWebSettings::WebGLEnabled));

        settings->setWebGLEnabled(value);
#endif
 
        value = attributes.value(QWebSettings::JavascriptCanOpenWindows,
                                      global->attributes.value(QWebSettings::JavascriptCanOpenWindows));
        settings->setJavaScriptCanOpenWindowsAutomatically(value);

        value = attributes.value(QWebSettings::JavaEnabled,
                                      global->attributes.value(QWebSettings::JavaEnabled));
        settings->setJavaEnabled(value);

        value = attributes.value(QWebSettings::PluginsEnabled,
                                      global->attributes.value(QWebSettings::PluginsEnabled));
        settings->setPluginsEnabled(value);

        value = attributes.value(QWebSettings::PrivateBrowsingEnabled,
                                      global->attributes.value(QWebSettings::PrivateBrowsingEnabled));
        settings->setPrivateBrowsingEnabled(value);

        value = attributes.value(QWebSettings::SpatialNavigationEnabled,
                                      global->attributes.value(QWebSettings::SpatialNavigationEnabled));
        settings->setSpatialNavigationEnabled(value);

        value = attributes.value(QWebSettings::JavascriptCanAccessClipboard,
                                      global->attributes.value(QWebSettings::JavascriptCanAccessClipboard));
        settings->setDOMPasteAllowed(value);
        settings->setJavaScriptCanAccessClipboard(value);

        value = attributes.value(QWebSettings::DeveloperExtrasEnabled,
                                      global->attributes.value(QWebSettings::DeveloperExtrasEnabled));
        settings->setDeveloperExtrasEnabled(value);

        value = attributes.value(QWebSettings::FrameFlatteningEnabled,
                                      global->attributes.value(QWebSettings::FrameFlatteningEnabled));
        settings->setFrameFlatteningEnabled(value);

        QUrl location = !userStyleSheetLocation.isEmpty() ? userStyleSheetLocation : global->userStyleSheetLocation;
        settings->setUserStyleSheetLocation(WebCore::KURL(location));

        QString encoding = !defaultTextEncoding.isEmpty() ? defaultTextEncoding: global->defaultTextEncoding;
        settings->setDefaultTextEncodingName(encoding);

        QString storagePath = !localStoragePath.isEmpty() ? localStoragePath : global->localStoragePath;
        settings->setLocalStorageDatabasePath(storagePath);

        value = attributes.value(QWebSettings::ZoomTextOnly,
                                 global->attributes.value(QWebSettings::ZoomTextOnly));
        settings->setZoomMode(value ? WebCore::ZoomTextOnly : WebCore::ZoomPage);

        value = attributes.value(QWebSettings::PrintElementBackgrounds,
                                      global->attributes.value(QWebSettings::PrintElementBackgrounds));
        settings->setShouldPrintBackgrounds(value);

#if ENABLE(DATABASE)
        value = attributes.value(QWebSettings::OfflineStorageDatabaseEnabled,
                                      global->attributes.value(QWebSettings::OfflineStorageDatabaseEnabled));
        WebCore::Database::setIsAvailable(value);
#endif

        value = attributes.value(QWebSettings::OfflineWebApplicationCacheEnabled,
                                      global->attributes.value(QWebSettings::OfflineWebApplicationCacheEnabled));
        settings->setOfflineWebApplicationCacheEnabled(value);

        value = attributes.value(QWebSettings::LocalStorageEnabled,
                                      global->attributes.value(QWebSettings::LocalStorageEnabled));
        settings->setLocalStorageEnabled(value);

        value = attributes.value(QWebSettings::LocalContentCanAccessRemoteUrls,
                                      global->attributes.value(QWebSettings::LocalContentCanAccessRemoteUrls));
        settings->setAllowUniversalAccessFromFileURLs(value);

        value = attributes.value(QWebSettings::LocalContentCanAccessFileUrls,
                                      global->attributes.value(QWebSettings::LocalContentCanAccessFileUrls));
        settings->setAllowFileAccessFromFileURLs(value);

        value = attributes.value(QWebSettings::XSSAuditingEnabled,
                                      global->attributes.value(QWebSettings::XSSAuditingEnabled));
        settings->setXSSAuditorEnabled(value);

#if ENABLE(TILED_BACKING_STORE)
        value = attributes.value(QWebSettings::TiledBackingStoreEnabled,
                                      global->attributes.value(QWebSettings::TiledBackingStoreEnabled));
        settings->setTiledBackingStoreEnabled(value);
#endif

        value = attributes.value(QWebSettings::SiteSpecificQuirksEnabled,
                                      global->attributes.value(QWebSettings::SiteSpecificQuirksEnabled));
        settings->setNeedsSiteSpecificQuirks(value);

        settings->setUsesPageCache(WebCore::pageCache()->capacity());
    } else {
        QList<QWebSettingsPrivate*> settings = *::allSettings();
        for (int i = 0; i < settings.count(); ++i)
            settings[i]->apply();
    }
}
Exemple #25
0
void TraceLoader::parseTrace()
{
    QList<ApiTraceFrame*> frames;
    ApiTraceFrame *currentFrame = 0;
    int frameCount = 0;
    QStack<ApiTraceCall*> groups;
    QVector<ApiTraceCall*> topLevelItems;
    QVector<ApiTraceCall*> allCalls;
    quint64 binaryDataSize = 0;

    int lastPercentReport = 0;

    trace::Call *call = m_parser.parse_call();
    while (call) {
        //std::cout << *call;
        if (!currentFrame) {
            currentFrame = new ApiTraceFrame();
            currentFrame->number = frameCount;
            ++frameCount;
        }
        ApiTraceCall *apiCall =
            apiCallFromTraceCall(call, m_helpHash, currentFrame, groups.isEmpty() ? 0 : groups.top(), this);
        allCalls.append(apiCall);
        if (groups.count() == 0) {
            topLevelItems.append(apiCall);
        }
        if (call->flags & trace::CALL_FLAG_MARKER_PUSH) {
            groups.push(apiCall);
        } else if (call->flags & trace::CALL_FLAG_MARKER_POP) {
            groups.top()->finishedAddingChildren();
            groups.pop();
        }
        if (!groups.isEmpty()) {
            groups.top()->addChild(apiCall);
        }
        if (apiCall->hasBinaryData()) {
            QByteArray data =
                apiCall->arguments()[apiCall->binaryDataIndex()].toByteArray();
            binaryDataSize += data.size();
        }
        if (call->flags & trace::CALL_FLAG_END_FRAME) {
            allCalls.squeeze();
            topLevelItems.squeeze();
            if (topLevelItems.count() == allCalls.count()) {
                currentFrame->setCalls(allCalls, allCalls, binaryDataSize);
            } else {
                currentFrame->setCalls(topLevelItems, allCalls, binaryDataSize);
            }
            allCalls.clear();
            groups.clear();
            topLevelItems.clear();
            frames.append(currentFrame);
            currentFrame = 0;
            binaryDataSize = 0;
            if (frames.count() >= FRAMES_TO_CACHE) {
                emit framesLoaded(frames);
                frames.clear();
            }
            if (m_parser.percentRead() - lastPercentReport >= 5) {
                emit parsed(m_parser.percentRead());
                lastPercentReport = m_parser.percentRead();
            }
        }
        delete call;
        call = m_parser.parse_call();
    }

    //last frames won't have markers
    //  it's just a bunch of Delete calls for every object
    //  after the last SwapBuffers
    if (currentFrame) {
        allCalls.squeeze();
        if (topLevelItems.count() == allCalls.count()) {
            currentFrame->setCalls(allCalls, allCalls, binaryDataSize);
        } else {
            currentFrame->setCalls(topLevelItems, allCalls, binaryDataSize);
        }
        frames.append(currentFrame);
        currentFrame = 0;
    }
    if (frames.count()) {
        emit framesLoaded(frames);
    }
}
Exemple #26
0
/*******************************************************
 * StorageFactory::StorageFactory
 ******************************************************/
StorageFactory::StorageFactory(): m_storageId(0),
        m_storagePluginsPath(pluginLocation), m_newObjectHandle(0),
        m_newPuoid(0), m_objectPropertyCache(new ObjectPropertyCache)
{
    //TODO For now handle only the file system storage plug-in. As we have more storages
    // make this generic.
#if 0
    void *pluginHandle;
    QDir dir( m_storagePluginsPath );
    dir.setFilter( QDir::Files | QDir::NoDotAndDotDot );
    QStringList dirContents = dir.entryList();
    for( quint32 i = 0; i < dirContents.size(); ++i )
    {
        QString pluginName = dirContents.at(i);
        if( !pluginName.endsWith( ".so" ) )
        {
            continue;
        }
        QString pluginFullPath = m_storagePluginsPath + "/" + pluginName;
        pluginHandle = dlopen( pluginFullPath.toStdString().c_str(), RTLD_NOW );
        if( !pluginHandle )
        {
            MTP_LOG_WARNING("Failed to dlopen::" << pluginFullPath << dlerror());
            continue;
        }
        CREATE_STORAGE_PLUGIN_FPTR createStoragePluginFptr = ( CREATE_STORAGE_PLUGIN_FPTR )dlsym( pluginHandle, CREATE_STORAGE_PLUGIN.toStdString().c_str() );
        if( char * error = dlerror() )
        {
            MTP_LOG_WARNING("Failed to dlsym because " << error);
            dlclose( pluginHandle );
            continue;
        }

        quint32 storageId = assignStorageId(i,1);
        StoragePlugin *storagePlugin = (*createStoragePluginFptr)( storageId );

        // Connect the storage plugin's eventGenerated signal
        QObject::connect(storagePlugin, SIGNAL(eventGenerated(MTPEventCode, const QVector<quint32>&, QString)), this, SLOT(eventReceived(MTPEventCode, const QVector<quint32>&, QString)));

        // Add this storage to all storages list.
        m_allStorages[storageId] = storagePlugin;

        PluginHandlesInfo_ pluginHandlesInfo;
        pluginHandlesInfo.storagePluginPtr = storagePlugin;
        pluginHandlesInfo.storagePluginHandle = pluginHandle;
        m_pluginHandlesInfoVector.append( pluginHandlesInfo );
    }
#endif

    void *pluginHandle = 0;
    QString pluginFullPath = m_storagePluginsPath + "/libfsstorage.so";
    QByteArray ba = pluginFullPath.toUtf8();

    pluginHandle = dlopen( ba.constData(), RTLD_NOW );
    if( !pluginHandle )
    {
        MTP_LOG_WARNING("Failed to dlopen::" << pluginFullPath << dlerror());
    }
    else
    {
        ba = CREATE_STORAGE_PLUGINS.toUtf8();
        CREATE_STORAGE_PLUGINS_FPTR createStoragePluginsFptr =
        ( CREATE_STORAGE_PLUGINS_FPTR )dlsym( pluginHandle, ba.constData() );
        if( char *error = dlerror() )
        {
            MTP_LOG_WARNING("Failed to dlsym because " << error);
            dlclose( pluginHandle );
        }
        else
        {
            quint32 storageId = assignStorageId(1, 1);
            QList<StoragePlugin *> storages = (*createStoragePluginsFptr)(storageId);
            for( quint8 i = 0; i < storages.count(); ++i )
            {
                // Add this storage to all storages list.
                m_allStorages[storageId + i] = storages[i];

                PluginHandlesInfo_ pluginHandlesInfo;
                pluginHandlesInfo.storagePluginPtr = storages[i];
                pluginHandlesInfo.storagePluginHandle = pluginHandle;
                m_pluginHandlesInfoVector.append( pluginHandlesInfo );
            }
        }
    }
}
gNodeComponentWidget::gNodeComponentWidget(sJarvisNodeComponent* comp,QWidget *parent) :
    QGroupBox(parent), m_component(comp),
    ui(new Ui::gNodeComponentWidget)
{
    ui->setupUi(this);

    this->setTitle(m_component->getId());

    QList<jarvisActions> actions = m_component->getActions();
    for(int i = 0 ; i < actions.count() ; i++)
    {
        jarvisActions action = actions[i];
        //qDebug() << QString::number(int(action));
        QToolButton* b = new QToolButton(ui->actionsBox);
        QGridLayout* l = (QGridLayout*)ui->actionsBox->layout();

        if      (action == A_DIMM){
            b->deleteLater();
            QSlider* w = new QSlider(this);
            w->setMaximum(100);
            w->setValue(50);
            l->addWidget(w,l->count()/2,l->count()%2);
            connect(w,SIGNAL(valueChanged(int)),m_component,SLOT(dimm(int)));

        }else if(action == A_SET_COLOR){
            connect(b,SIGNAL(clicked()),this,SLOT(selectComponentColor()));
            b->setText(m_component->actionName((m_component->getActions()[i])));
            l->addWidget(b,l->count()/2,l->count()%2);

        }else if(action == A_SET_LEDS){
            connect(b,SIGNAL(clicked()),this,SLOT(sendImage()));
            b->setText(m_component->actionName((m_component->getActions()[i])));
            l->addWidget(b,l->count()/2,l->count()%2);

        }else if(action == A_DISPLAY){
            connect(b,SIGNAL(clicked()),this,SLOT(sendImage()));
            b->setText(m_component->actionName((m_component->getActions()[i])));
            l->addWidget(b,l->count()/2,l->count()%2);
        }else if(action == A_PLAYRTTTL){
            connect(b,SIGNAL(clicked()),this,SLOT(openRtttlPlayer()));
            b->setText(m_component->actionName((m_component->getActions()[i])));
            l->addWidget(b,l->count()/2,l->count()%2);
        }else{
            QString slotName = m_component->slotName(m_component->getActions()[i]);
            b->setText(m_component->actionName((m_component->getActions()[i])));
            l->addWidget(b,l->count()/2,l->count()%2);
            connect(b,SIGNAL(clicked()),m_component,slotName.toStdString().c_str());
        }
    }

    QList<jarvisEvents> events = m_component->getCapableEvents();
    for(int i = 0 ; i < events.count() ; i++)
    {
        gBlinkWidget* w = new gBlinkWidget(ui->eventsBox);
        QLabel* label = new QLabel(ui->eventsBox);
        QGridLayout* l = (QGridLayout*)ui->eventsBox->layout();
        l->addWidget(label,i,0);
        l->addWidget(w,i,1);
        w->setMaximumHeight(50);
        if(events[i] == E_RAW_READ)
        {
            connect(m_component,SIGNAL(rawRead()),w,SLOT(blink()));
            connect(m_component,SIGNAL(rawRead(QStringList)),w,SLOT(displayRead(QStringList)));
            label->setText(m_component->eventName((m_component->getCapableEvents()[i])));

        }else if(events[i] == E_DATA_READ)
        {
            connect(m_component,SIGNAL(dataRead()),w,SLOT(blink()));
            connect(m_component,SIGNAL(dataRead(QStringList)),w,SLOT(displayRead(QStringList)));
            label->setText(m_component->eventName((m_component->getCapableEvents()[i])));

        }else
        {
            QString signalName = m_component->signalName(m_component->getCapableEvents()[i]);
            label->setText(m_component->eventName((m_component->getCapableEvents()[i])));
            connect(m_component,signalName.toStdString().c_str(),w,SLOT(blink()));
        }
        //w->setMinimumSize(32,32);
        //w->setMaximumSize(32,32);
    }
}
Exemple #28
0
bool File::Mol::generate()
{
  int atomTypes = 0;
  float x, y, z;

  clear();

  addString(basisType_);
  addString(basisSet_);
  addString(comment_);

  QList<Chemistry::Atom*> atomsList;

  for (quint16 i = 0; i < molecule().atomsCount(); ++i)
  {
    atomsList << &molecule().atom(i);
  }

  while (atomsList.count() > 0)
  {
    QList<Chemistry::Atom*> atomsOfTheSameTypeList;
    atomsOfTheSameTypeList << atomsList.takeFirst();
    quint8 charge = atomsOfTheSameTypeList[0]->atomicNumber();
    int n = atomsList.count();
    int i = 0;
    while (i < n)
    {
      if (atomsList[i]->atomicNumber() == charge)
      {
        atomsOfTheSameTypeList << atomsList.takeAt(i);
        n--;
      }
      else
      {
        i++;
      }
    }

    QString atomsOfTheSameTypeHeader = QString("Charge=%1 Atoms=%2").arg(
        charge).arg(atomsOfTheSameTypeList.count());

    if (basisType_ == "ATOMBASIS")
      atomsOfTheSameTypeHeader += QString(" Basis=%1").arg(
          hashBasisSets_[charge]);

    addString(atomsOfTheSameTypeHeader);

    for (quint16 i = 0; i < atomsOfTheSameTypeList.count(); ++i)
    {
      x = atomsOfTheSameTypeList[i]->centre().x();
      y = atomsOfTheSameTypeList[i]->centre().y();
      z = atomsOfTheSameTypeList[i]->centre().z();

      if (unitOfLength() == UnitOfLengthBohr)
      {
        x = x / bohrsToAngstroms;
        y = y / bohrsToAngstroms;
        z = z / bohrsToAngstroms;
      }

      QString temp = QString("%1%2\t%3%4%5").arg(
          atomsOfTheSameTypeList[i]->symbol()).arg(
              i + 1).arg(
                  x, 12, 'f', 6).arg(
                      y, 12, 'f', 6).arg(
                          z, 12, 'f', 6);

      if (atomsOfTheSameTypeList[i]->isotope() != 0)
        temp += QString("\tIsotope=%1").arg(atomsOfTheSameTypeList[i]->isotope());

      addString(temp);
    }
    atomTypes++;
  }

  setAtomTypes(atomTypes);

  QString generalString(QString("Atomtypes=%1").arg(atomTypes));

  if (unitOfLength() == UnitOfLengthAngstrom)
    generalString.append(" Angstrom");

  if (molecule().charge() != 0)
    generalString.append(QString(" Charge=%1").arg(molecule().charge()));

  if (gaussiansType() == GaussiansTypeCartesian)
    generalString.append(" Cartesian");

  insertString(generalStringIndex_ - 1, generalString);

  return true;
}
void DeviceDiscoveryBroadcastReceiver::onReceive(JNIEnv *env, jobject context, jobject intent)
{
    Q_UNUSED(context);
    Q_UNUSED(env);

    QAndroidJniObject intentObject(intent);
    const QString action = intentObject.callObjectMethod("getAction", "()Ljava/lang/String;").toString();

    qCDebug(QT_BT_ANDROID) << "DeviceDiscoveryBroadcastReceiver::onReceive() - event:" << action;

    if (action == valueForStaticField(JavaNames::BluetoothAdapter,
                                      JavaNames::ActionDiscoveryFinished).toString()) {
        emit finished();
    } else if (action == valueForStaticField(JavaNames::BluetoothAdapter,
               JavaNames::ActionDiscoveryStarted).toString()) {

    } else if (action == valueForStaticField(JavaNames::BluetoothDevice,
               JavaNames::ActionFound).toString()) {
        //get BluetoothDevice
        QAndroidJniObject keyExtra = valueForStaticField(JavaNames::BluetoothDevice,
                                     JavaNames::ExtraDevice);
        const QAndroidJniObject bluetoothDevice =
            intentObject.callObjectMethod("getParcelableExtra",
                                          "(Ljava/lang/String;)Landroid/os/Parcelable;",
                                          keyExtra.object<jstring>());

        if (!bluetoothDevice.isValid())
            return;

        const QString deviceName = bluetoothDevice.callObjectMethod<jstring>("getName").toString();
        const QBluetoothAddress deviceAddress(bluetoothDevice.callObjectMethod<jstring>("getAddress").toString());
        keyExtra = valueForStaticField(JavaNames::BluetoothDevice,
                                       JavaNames::ExtraRssi);

        int rssi = intentObject.callMethod<jshort>("getShortExtra",
                   "(Ljava/lang/String;S)S",
                   keyExtra.object<jstring>(),
                   0);
        const QAndroidJniObject bluetoothClass = bluetoothDevice.callObjectMethod("getBluetoothClass",
                "()Landroid/bluetooth/BluetoothClass;");
        if (!bluetoothClass.isValid())
            return;
        int classType = bluetoothClass.callMethod<jint>("getDeviceClass");


        static QList<qint32> services;
        if (services.count() == 0)
            services << QBluetoothDeviceInfo::PositioningService
                     << QBluetoothDeviceInfo::NetworkingService
                     << QBluetoothDeviceInfo::RenderingService
                     << QBluetoothDeviceInfo::CapturingService
                     << QBluetoothDeviceInfo::ObjectTransferService
                     << QBluetoothDeviceInfo::AudioService
                     << QBluetoothDeviceInfo::TelephonyService
                     << QBluetoothDeviceInfo::InformationService;

        //Matching BluetoothClass.Service values
        qint32 result = 0;
        qint32 current = 0;
        for (int i = 0; i < services.count(); i++) {
            current = services.at(i);
            int id = (current << 16);
            if (bluetoothClass.callMethod<jboolean>("hasService", "(I)Z", id))
                result |= current;
        }

        result = result << 13;
        classType |= result;

        QBluetoothDeviceInfo info(deviceAddress, deviceName, classType);
        info.setRssi(rssi);

        emit deviceDiscovered(info);
    }
}
Exemple #30
0
QString
ShaderFactory::genSliceShadowShaderString(bool bit16,
					  float shadowintensity,
					  float r, float g, float b,
					  QList<CropObject> crops,
					  bool peel, int peelType,
					  float peelMin, float peelMax, float peelMix)
{
  bool cropPresent = false;
  bool tearPresent = false;
  bool viewPresent = false;
  bool glowPresent = false;
  for(int i=0; i<crops.count(); i++)
    if (crops[i].cropType() < CropObject::Tear_Tear)
      cropPresent = true;
    else if (crops[i].cropType() < CropObject::View_Tear)
      tearPresent = true;
    else if (crops[i].cropType() < CropObject::Glow_Ball)
      viewPresent = true;
    else
      glowPresent = true;

  for(int i=0; i<crops.count(); i++)
    if (crops[i].cropType() >= CropObject::View_Tear &&
	crops[i].cropType() <= CropObject::View_Block &&
	crops[i].magnify() > 1.0)
      tearPresent = true;

  bool pathCropPresent = PathShaderFactory::cropPresent();
  bool pathViewPresent = PathShaderFactory::blendPresent();

  QString shader;
  float maxrgb = qMax(r, qMax(g, b));
  if (maxrgb > 1)
    maxrgb = 1.0/maxrgb;
  else
    maxrgb = 1.0;

  shader =  "#extension GL_ARB_texture_rectangle : enable\n";
  shader += "varying vec3 pointpos;\n";
  shader += "uniform sampler2D lutTex;\n";
  shader += "uniform sampler2DRect dataTex;\n";
  shader += "uniform sampler1D paintTex;\n";

  shader += "uniform vec3 eyepos;\n";
  shader += "uniform float tfSet;\n";
  shader += "uniform int gridx;\n";
  shader += "uniform int tsizex;\n";
  shader += "uniform int tsizey;\n";
  shader += "\n";

  shader += "uniform sampler2DRect pruneTex;\n";
  shader += "uniform int prunegridx;\n";
  shader += "uniform int prunetsizex;\n";
  shader += "uniform int prunetsizey;\n";
  shader += "uniform float prunelod;\n";
  shader += "uniform int zoffset;\n";

  shader += "uniform vec2 dataMin;\n";
  shader += "uniform vec2 dataSize;\n";
  shader += "uniform int tminz;\n";

  shader += "uniform int lod;\n";
  shader += "uniform vec3 dirFront;\n";
  shader += "uniform vec3 dirUp;\n";
  shader += "uniform vec3 dirRight;\n";

  shader += "uniform vec3 brickMin;\n";
  shader += "uniform vec3 brickMax;\n";

  shader += genTextureCoordinate();
  
  if (tearPresent) shader += TearShaderFactory::generateTear(crops);
  if (cropPresent) shader += CropShaderFactory::generateCropping(crops);
  if (glowPresent) shader += GlowShaderFactory::generateGlow(crops);  
  if (viewPresent) shader += BlendShaderFactory::generateBlend(crops);
  if (pathCropPresent) shader += PathShaderFactory::applyPathCrop();
  if (pathViewPresent) shader += PathShaderFactory::applyPathBlend();

  shader += "void main(void)\n";
  shader += "{\n";

  shader += "  vec3 texCoord = gl_TexCoord[0].xyz;\n";

  shader += "if (any(lessThan(texCoord,brickMin)) || any(greaterThan(texCoord, brickMax)))\n";
  shader += "  discard;\n";

  if (crops.count() > 0)
    {
      shader += "  vec3 otexCoord = texCoord;\n";
      shader += "  float feather = 1.0;\n";
    }
  else
    {
      if (pathCropPresent)
	shader += "  float feather = 1.0;\n";
      if (pathViewPresent)
	shader += "  vec3 otexCoord = texCoord;\n";
    }

  if (glowPresent)
    {
      shader += "  vec3 glowColor = glow(otexCoord);\n";
      shader += "  float glowMix = max(glowColor.r, max(glowColor.g, glowColor.b));\n";
      shader += "  if (glowMix > 0.05) discard;";
    }

  if (tearPresent)
    {
      shader += "vec4 tcf = dissect(texCoord);\n";
      shader += "texCoord = tcf.xyz;\n";
      shader += "feather *= tcf.w;\n";
    }
  if (cropPresent) shader += "feather *= crop(texCoord, true);\n";
  if (pathCropPresent) shader += "feather *= pathcrop(texCoord, true);\n";


  shader += "texCoord.x = 1.0 + float(tsizex-2)*(texCoord.x-dataMin.x)/dataSize.x;\n";
  shader += "texCoord.y = 1.0 + float(tsizey-2)*(texCoord.y-dataMin.y)/dataSize.y;\n";
  shader += "texCoord.z = 1.0 + (float(texCoord.z)-float(tminz))/float(lod);\n";

  shader += genVgx();

  shader += getNormal();

  if (bit16)
    {
      shader += "int h0 = int(65535.0*vg.x);\n";
      shader += "int h1 = h0 / 256;\n";
      shader += "h0 = int(mod(float(h0),256.0));\n";
      shader += "float fh0 = float(h0)/256.0;\n";
      shader += "float fh1 = float(h1)/256.0;\n";

      shader += QString("vg.xy = vec2(fh0, fh1*%1 + tfSet);\n").arg(1.0/Global::lutSize());
    }
  else
    {
      if (Global::use1D())
	shader += "  vg.y = tfSet;\n";
      else
	{
	  shader += QString("  vg.y = grad*%1;\n").arg(1.0/Global::lutSize());
	  
	  shader += "  vg.y += tfSet;\n";
	}
    }

  shader += "  gl_FragColor = texture2D(lutTex, vg.xy);\n";

  shader += genPeelShader(peel, peelType,
			  peelMin, peelMax, peelMix,
			  false);
  
  if (Global::emptySpaceSkip())
    {
      shader += "  gl_FragColor.rgba = mix(vec4(0.0,0.0,0.0,0.0), gl_FragColor.rgba, prunefeather.x);\n";
      if (PruneHandler::blend())
	shader += blendVolume();
      else
	shader += tagVolume();
    }

  if (tearPresent || cropPresent || pathCropPresent)
    shader += "  gl_FragColor.rgba = mix(gl_FragColor.rgba, vec4(0.0,0.0,0.0,0.0), feather);\n";

  if (viewPresent) shader += "blend(otexCoord, vg, gl_FragColor);\n";
  if (pathViewPresent) shader += "pathblend(otexCoord, vg, gl_FragColor);\n";

//------------------------------------
  shader += "gl_FragColor = 1.0-pow((vec4(1,1,1,1)-gl_FragColor),";
  shader += "vec4(lod,lod,lod,lod));\n";
//------------------------------------

  // --- modulate shadow by homogenity
  shader += QString("  gl_FragColor.rgba *= 1.0-smoothstep(0.0, float(%1), grad);\n").arg(shadowintensity);

  shader += "  if (gl_FragColor.a < 0.01)\n";
  shader += "	discard;\n";
  shader += "\n";
  shader += QString("  gl_FragColor.rgba *= vec4(%1, %2, %3, %4);\n").\
                                        arg(r).arg(g).arg(b).arg(maxrgb);

//  shader += "  gl_FragColor.r = clamp(gl_FragColor.r, 0.0, 1.0);\n";
//  shader += "  gl_FragColor.g = clamp(gl_FragColor.g, 0.0, 1.0);\n";
//  shader += "  gl_FragColor.b = clamp(gl_FragColor.b, 0.0, 1.0);\n";
//  shader += "  gl_FragColor.a = clamp(gl_FragColor.a, 0.0, 1.0);\n";

  shader += "}\n";

  return shader;
}