Beispiel #1
0
void FusionLayersSelectPage::setViews(SpatialDataView* pPrimary, SpatialDataView* pSecondary)
{
   vector<Layer*> layers;

   vector<Layer*>::iterator it;
   SpatialDataView* pOldPrimaryView = getPrimaryView();
   if (pOldPrimaryView != NULL)
   {
      LayerList* pLayerList = pOldPrimaryView->getLayerList();
      if (pLayerList != NULL)
      {
         pLayerList->detach(SIGNAL_NAME(Subject, Deleted), Slot(this, &FusionLayersSelectPage::layerListDeleted));
         pLayerList->detach(SIGNAL_NAME(Subject, Modified), Slot(this, &FusionLayersSelectPage::layerListModified));
      }
   }

   FusionPage::setViews(pPrimary, pSecondary);

   if (pPrimary != NULL)
   {
      LayerList* pLayerList = pPrimary->getLayerList();
      if (pLayerList != NULL)
      {
         pLayerList->attach(SIGNAL_NAME(Subject, Deleted), Slot(this, &FusionLayersSelectPage::layerListDeleted));
         pLayerList->attach(SIGNAL_NAME(Subject, Modified), Slot(this, &FusionLayersSelectPage::layerListModified));
      }
   }
}
Beispiel #2
0
 Layer* deriveLayer(Layer* pLayer, const char* pName, const char* pType)
 {
    if (pLayer == NULL)
    {
       setLastError(SIMPLE_BAD_PARAMS);
       return NULL;
    }
    SpatialDataView* pView = dynamic_cast<SpatialDataView*>(pLayer->getView());
    if (pView == NULL)
    {
       setLastError(SIMPLE_WRONG_VIEW_TYPE);
       return NULL;
    }
    pLayer = pView->deriveLayer(pLayer, StringUtilities::fromXmlString<LayerType>(std::string(pType)));
    if (pLayer == NULL)
    {
       setLastError(SIMPLE_WRONG_TYPE);
       return NULL;
    }
    if (pName != NULL)
    {
       pView->getLayerList()->renameLayer(pLayer, std::string(pName));
    }
    setLastError(SIMPLE_NO_ERROR);
    return pLayer;
 }
Beispiel #3
0
bool DeriveLayer::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   VERIFY(pInArgList != NULL);
   StepResource pStep("Execute Wizard Item", "app", "56D70072-0716-4506-B70D-9E6BD10C96A3");
   pStep->addProperty("Item", getName());
   mpStep = pStep.get();

   if (!extractInputArgs(pInArgList))
   {
      reportError("Unable to extract input arguments.", "4DB42DD5-2198-4d1e-BBB5-9745D4242C9D");
      return false;
   }

   // Get the view
   SpatialDataView* pView = dynamic_cast<SpatialDataView*>(mpInputLayer->getView());
   if (pView == NULL)
   {
      reportError("Only layers in a spatial data view can be converted.", "{039ac767-e6d5-441b-9b27-bf59cbb9ee9d}");
      return false;
   }

   Layer* pNewLayer = NULL;
   if (mNewLayerName.empty())
   {
      pNewLayer = pView->convertLayer(mpInputLayer, mNewLayerType);
   }
   else
   {
      pNewLayer = pView->deriveLayer(mpInputLayer, mNewLayerType);
      if (pNewLayer != NULL)
      {
         if (!pView->getLayerList()->renameLayer(pNewLayer, mNewLayerName))
         {
            pView->deleteLayer(pNewLayer);
            reportError("Unable to derive a layer with the given name, because another layer "
               "with the same name already exists.", "{1e81e201-624f-4e96-83b5-8ceae01d7c1d}");
            return false;
         }
      }
   }
   if (pNewLayer == NULL)
   {
      reportError("Unable to convert the layer.", "{f09810c2-f2a2-4887-a0f0-6848d74ffd28}");
      return false;
   }

   // Set the output value
   if (pOutArgList != NULL)
   {
      if (!pOutArgList->setPlugInArgValue("Layer", pNewLayer) ||
          !pOutArgList->setPlugInArgValue("Element", pNewLayer->getDataElement()))
      {
         reportError("Could not set the output value!", "3E2591B0-F41B-4de1-9D76-45245F9EF343");
         return false;
      }
   }

   reportComplete();
   return true;
}
void MeasurementObjectImp::updateGeoreferenceAttachment()
{
   if (mpGeoreference.get() != NULL)
   {
      return;
   }

   RasterElement* pGeoreference = NULL;

   // Must find Georeference through the view, since the GraphicElement is a root element.
   GraphicLayer* pLayer = getLayer();
   if (pLayer != NULL)
   {
      SpatialDataView* pView = dynamic_cast<SpatialDataView*>(pLayer->getView());
      if (pView != NULL)
      {
         LayerList* pLayerList = pView->getLayerList();
         VERIFYNRV(pLayerList != NULL);
         pGeoreference = pLayerList->getPrimaryRasterElement();
      }
   }

   if (pGeoreference != NULL && pGeoreference->isGeoreferenced())
   {
      mpGeoreference.reset(pGeoreference);
      enableGeo();
      generateGeoStrings();
   }
}
Beispiel #5
0
bool BandMath::createReturnGuiElement()
{
   bool bSuccess = false;

   if (mbInteractive || (mbDisplayResults && Service<ApplicationServices>()->isBatch() == false))
   {
      SpatialDataWindow* pWindow = NULL;
      if (mbAsLayerOnExistingView)
      {
         pWindow = static_cast<SpatialDataWindow*>(mpDesktop->getWindow(mpCube->getName(), SPATIAL_DATA_WINDOW));
      }
      else
      {
         pWindow = static_cast<SpatialDataWindow*>(mpDesktop->createWindow(mResultsName.c_str(), SPATIAL_DATA_WINDOW));
      }

      if (pWindow == NULL)
      {
         return false;
      }

      SpatialDataView* pView = pWindow->getSpatialDataView();
      VERIFYRV(pView != NULL, NULL);

      UndoLock lock(pView);

      if (!mbAsLayerOnExistingView)
      {
         pView->setPrimaryRasterElement(mpResultData);
      }

      LayerList* pLayerList = pView->getLayerList();
      if (pLayerList != NULL)
      {
         Layer* pLayer = pLayerList->getLayer(RASTER, mpResultData);
         if (pLayer == NULL)
         {
            if (pView->createLayer(RASTER, mpResultData) != NULL)
            {
               bSuccess = true;
            }
            if (!mbAsLayerOnExistingView)
            {
               Service<ModelServices> pModel;
               vector<DataElement*> elements = pModel->getElements(mpResultData, "GcpList");
               for_each(elements.begin(), elements.end(), 
                  boost::bind(&SpatialDataView::createLayer, pView, GCP_LAYER, _1));
            }
         }
      }
   }
   else // no GUI required, method has successfully noop'd
   {
      bSuccess = true;
   }
   return bSuccess;
}
Beispiel #6
0
bool PrintView::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   StepResource pStep("Execute Wizard Item", "app", "4EA89098-57C8-4b93-B04F-3197C59B0D58");
   pStep->addProperty("Item", getName());
   mpStep = pStep.get();

   if (!extractInputArgs(pInArgList))
   {
      reportError("Unable to extract input arguments.", "9FC540AC-4BCF-4041-9E8E-484A494AF6AD");
      return false;
   }

   // Get the window
   SpatialDataWindow* pWindow = NULL;

   vector<Window*> windows;
   Service<DesktopServices> pDesktop;
   if (pDesktop.get() != NULL)
   {
      pDesktop->getWindows(SPATIAL_DATA_WINDOW, windows);
   }

   for (vector<Window*>::iterator iter = windows.begin(); iter != windows.end(); ++iter)
   {
      SpatialDataWindow* pCurrentWindow = static_cast<SpatialDataWindow*>(*iter);
      if (pCurrentWindow != NULL)
      {
         SpatialDataView* pView = pCurrentWindow->getSpatialDataView();
         if (pView != NULL)
         {
            LayerList* pLayerList = pView->getLayerList();
            if (pLayerList != NULL)
            {
               RasterElement* pRasterElement = pLayerList->getPrimaryRasterElement();
               if (pRasterElement != NULL && pRasterElement == mpRasterElement)
               {
                  pWindow = pCurrentWindow;
                  break;
               }
            }
         }
      }
   }

   if (pWindow == NULL)
   {
      reportError("Could not get the window for the data set!", "28355746-8AE3-44a4-9253-58684E1964C1");
      return false;
   }

   // Print the view
   pWindow->print(mbPrintDialog);

   reportComplete();
   return true;
}
Beispiel #7
0
void GetLayer<T>::populateTreeWidgetItemWithLayers(QTreeWidgetItem* pRoot)
{
   VERIFYNR(pRoot != NULL);
   QVariant value = pRoot->data(GetSessionItemBase<T>::NameColumn, GetSessionItemBase<T>::SessionItemRole);
   void* pValue = value.value<void*>();
   View* const pView = reinterpret_cast<View*>(pValue);
   VERIFYNR(pView != NULL);

   std::vector<Layer*> layers;
   SpatialDataView* pSpatialDataView = dynamic_cast<SpatialDataView*>(pView);
   if (pSpatialDataView != NULL)
   {
      LayerList* pLayerList = pSpatialDataView->getLayerList();
      if (pLayerList != NULL)
      {
         pLayerList->getLayers(layers);
      }
   }

   ProductView* pProductView = dynamic_cast<ProductView*>(pView);
   if (pProductView != NULL)
   {
      layers.push_back(pProductView->getLayoutLayer());
      layers.push_back(pProductView->getClassificationLayer());
   }

   PlotView* pPlotView = dynamic_cast<PlotView*>(pView);
   if (pPlotView != NULL)
   {
      layers.push_back(pPlotView->getAnnotationLayer());
   }

   // Add the layer items in reverse order so that the top-most layer is added first
   for (std::vector<Layer*>::reverse_iterator iter = layers.rbegin(); iter != layers.rend(); ++iter)
   {
      Layer* pLayer = *iter;
      if (pLayer == NULL || pLayer->isKindOf(TypeConverter::toString<T>()) == false)
      {
         continue;
      }

      QTreeWidgetItem* pChild = new QTreeWidgetItem;
      std::string name = pLayer->getDisplayName();
      if (name.empty() == true)
      {
         name = pLayer->getName();
      }

      pChild->setText(GetSessionItemBase<T>::NameColumn, QString::fromStdString(name));
      pChild->setData(GetSessionItemBase<T>::NameColumn,
         GetSessionItemBase<T>::SessionItemRole, QVariant::fromValue<void*>(pLayer));
      pChild->setText(GetSessionItemBase<T>::TypeColumn, QString::fromStdString(StringUtilities::toDisplayString(pLayer->getLayerType())));
      pChild->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
      pRoot->addChild(pChild);
   }
}
    Image(SpatialDataView* iPView) : pView(iPView) {
        LayerList* pLayerList = pView->getLayerList(); VERIFYNRV(pLayerList != NULL);
        pRaster = dynamic_cast<RasterElement*>(pLayerList->getPrimaryRasterElement()); VERIFYNRV(pRaster != NULL);
        pDataDescriptor = dynamic_cast<const RasterDataDescriptor*>(pRaster->getDataDescriptor()); VERIFYNR(pDataDescriptor != NULL);
/*        Service<DesktopServices> pDesktop;
        VERIFYNRV(pDesktop.get() != NULL);
        SpatialDataWindow* pWindow = dynamic_cast<SpatialDataWindow*>(pDesktop->getWindow(pRaster->getName(), SPATIAL_DATA_WINDOW));
        VERIFYNRV(pWindow != NULL);
        VERIFYNRV(pDesktop->setCurrentWorkspaceWindow(pWindow));*/
    }
Beispiel #9
0
 Layer* getViewLayer(View* pView, uint32_t index)
 {
    if (pView == NULL)
    {
       setLastError(SIMPLE_BAD_PARAMS);
       return NULL;
    }
    SpatialDataView* pSdv = dynamic_cast<SpatialDataView*>(pView);
    if (pSdv == NULL)
    {
       setLastError(SIMPLE_WRONG_VIEW_TYPE);
       return NULL;
    }
    if (index >= pSdv->getLayerList()->getNumLayers())
    {
       setLastError(SIMPLE_NOT_FOUND);
       return NULL;
    }
    std::vector<Layer*> layers;
    pSdv->getLayerList()->getLayers(layers);
    setLastError(SIMPLE_NO_ERROR);
    return layers[index];
 }
Beispiel #10
0
 DataElement* getViewPrimaryRasterElement(View* pView)
 {
    if (pView == NULL)
    {
       setLastError(SIMPLE_BAD_PARAMS);
       return NULL;
    }
    SpatialDataView* pSdv = dynamic_cast<SpatialDataView*>(pView);
    if (pSdv == NULL)
    {
       setLastError(SIMPLE_WRONG_VIEW_TYPE);
       return NULL;
    }
    setLastError(SIMPLE_NO_ERROR);
    return pSdv->getLayerList()->getPrimaryRasterElement();
 }
Beispiel #11
0
 uint32_t getViewLayerCount(View* pView)
 {
    if (pView == NULL)
    {
       setLastError(SIMPLE_BAD_PARAMS);
       return 0;
    }
    SpatialDataView* pSdv = dynamic_cast<SpatialDataView*>(pView);
    if (pSdv == NULL)
    {
       setLastError(SIMPLE_WRONG_VIEW_TYPE);
       return 0;
    }
    setLastError(SIMPLE_NO_ERROR);
    return pSdv->getLayerList()->getNumLayers();
 }
Beispiel #12
0
void FrameLabelObjectImp::setAnimations(View* pView)
{
   if (getLocked() == false)
   {
      reset();
      vector<Animation*> pAnimations;
      if (pView != NULL)
      {
         SpatialDataView* pSpatialDataView = dynamic_cast<SpatialDataView*>(pView);
         if (pSpatialDataView == NULL)
         {
            mpView.reset(pView);
            mpAnimationController.reset(mpView->getAnimationController());
            if (mpAnimationController.get() != NULL)
            {
               pAnimations = mpAnimationController->getAnimations();
            }
         }
         else
         {
            mpLayerList.reset(pSpatialDataView->getLayerList());
            VERIFYNRV(mpLayerList.get() != NULL);

            vector<Layer*> pLayers;
            mpLayerList->getLayers(RASTER, pLayers);
            for (vector<Layer*>::iterator iter = pLayers.begin(); iter != pLayers.end(); ++iter)
            {
               RasterLayer* pRasterLayer = dynamic_cast<RasterLayer*>(*iter);
               VERIFYNRV(pRasterLayer != NULL);
               pRasterLayer->attach(SIGNAL_NAME(RasterLayer, AnimationChanged),
                  Slot(this, &FrameLabelObjectImp::updateAnimations));
               pRasterLayer->attach(SIGNAL_NAME(Subject, Deleted),
                  Slot(this, &FrameLabelObjectImp::layerDeleted));
               mLayers.push_back(pRasterLayer);
               if (pRasterLayer->getAnimation() != NULL)
               {
                  pAnimations.push_back(pRasterLayer->getAnimation());
               }
            }
         }
      }

      insertAnimations(pAnimations);
   }
}
SpatialDataView* ChippingWindow::createChipView() const
{
   if (mpView == NULL)
   {
      return NULL;
   }

   SpatialDataView* pChipView = dynamic_cast<SpatialDataView*>(mpView->copy());
   if (pChipView != NULL)
   {
      vector<std::pair<View*, LinkType> > linkedViews;
      pChipView->getLinkedViews(linkedViews);
      for (unsigned int i = 0; i < linkedViews.size(); ++i)
      {
         if (linkedViews[i].second == NO_LINK)
         {
            continue;
         }

         pChipView->unlinkView(linkedViews[i].first);
      }

      LayerList* pLayerList = pChipView->getLayerList();
      if (pLayerList != NULL)
      {
         vector<Layer*> layers;
         pLayerList->getLayers(layers);
         for (unsigned int i = 0; i < layers.size(); i++)
         {
            Layer* pLayer = layers.at(i);
            if (dynamic_cast<RasterLayer*>(pLayer) == NULL)
            {
               pChipView->deleteLayer(pLayer);
            }
         }
      }
   }

   return pChipView;
}
/**
 * Get the number of layers in a window.
 *
 * @param[in] WINDOW @opt
 *            The name of the window. Defaults to the active window.
 * @return The number of layers in the window.
 * @usage num_layers = get_num_layers()
 * @endusage
 */
IDL_VPTR get_num_layers(int argc, IDL_VPTR pArgv[], char* pArgk)
{
   typedef struct
   {
      IDL_KW_RESULT_FIRST_FIELD;
      int windowExists;
      IDL_STRING windowName;
   } KW_RESULT;

   //IDL_KW_FAST_SCAN is the type of scan we are using, following it is the
   //name of the keyword, followed by the type, the mask(which should be 1),
   //flags, a boolean whether the value was populated and finally the value itself
   static IDL_KW_PAR kw_pars[] = {
      IDL_KW_FAST_SCAN,
      {"WINDOW", IDL_TYP_STRING, 1, 0, reinterpret_cast<int*>(IDL_KW_OFFSETOF(windowExists)),
         reinterpret_cast<char*>(IDL_KW_OFFSETOF(windowName))},
      {NULL}
   };

   IdlFunctions::IdlKwResource<KW_RESULT> kw(argc, pArgv, pArgk, kw_pars, 0, 1);

   std::string windowName;
   int layers = 0;

   if (kw->windowExists)
   {
      windowName = IDL_STRING_STR(&kw->windowName);
   }

   SpatialDataView* pView = dynamic_cast<SpatialDataView*>(IdlFunctions::getViewByWindowName(windowName));
   if (pView != NULL)
   {
      LayerList* pList = pView->getLayerList();
      if (pList != NULL)
      {
         layers = pList->getNumLayers();
      }
   }
   return IDL_GettmpInt(layers);
}
Beispiel #15
0
bool TimelineWidget::saveAnimationTimes(Animation  *pAnim)
{
   if(pAnim == NULL)
   {
      return false;
   }
   bool success = false;
   const std::vector<AnimationFrame> frames = pAnim->getFrames();
   std::vector<double> times(frames.size(), 0.0);
   for(unsigned int idx = 0; idx < frames.size(); idx++)
   {
      times[idx] = frames[idx].mTime;
   }

   std::vector<Window*> windows;
   Service<DesktopServices>()->getWindows(SPATIAL_DATA_WINDOW, windows);
   for(std::vector<Window*>::iterator window = windows.begin(); window != windows.end(); ++window)
   {
      SpatialDataView *pView = static_cast<SpatialDataWindow*>(*window)->getSpatialDataView();
      std::vector<Layer*> layers;
      pView->getLayerList()->getLayers(RASTER, layers);
      for(std::vector<Layer*>::iterator layer = layers.begin(); layer != layers.end(); ++layer)
      {
         RasterLayer *pLayer = static_cast<RasterLayer*>(*layer);
         if(pLayer->getAnimation() == pAnim)
         {
            RasterElement *pElement = static_cast<RasterElement*>(pLayer->getDataElement());
            DynamicObject *pMetadata = static_cast<RasterDataDescriptor*>(pElement->getDataDescriptor())->getMetadata();
            if(pMetadata != NULL)
            {
               success = success || pMetadata->setAttributeByPath(FRAME_TIMES_METADATA_PATH, times);
            }
         }
      }
   }
   return success;
}
Correlator<RasterElement>::Correlator()
{
    vector<DataElement*> allElements = Service<ModelServices>()->getElements("RasterElement");

    RasterElement* pPrimary = NULL;
    SpatialDataView* pView = dynamic_cast<SpatialDataView*>(Service<DesktopServices>()->getCurrentWorkspaceWindowView());
    if (pView != NULL)
    {
        pPrimary = RM_NULLCHK(pView->getLayerList())->getPrimaryRasterElement();
    }

    int index = 1;
    for (vector<DataElement*>::iterator ppElement=allElements.begin(); ppElement!=allElements.end(); ++ppElement)
    {
        RasterElement* pElement = dynamic_cast<RasterElement*>(*ppElement);
        if (pElement == pPrimary)
        {
            mElements[index++] = pPrimary;
            break;
        }
    }

    init(allElements, index, pPrimary);
}
Beispiel #17
0
bool CgmImporter::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   Progress* pProgress = NULL;
   DataElement* pElement = NULL;
   StepResource pStep("Import cgm element", "app", "8D5522FE-4A89-44cb-9735-6920A3BFC903");

   // get input arguments and log some useful info about them
   { // scope the MessageResource
      MessageResource pMsg("Input arguments", "app", "A1735AC7-C182-45e6-826F-690DBA15D84A");

      pProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg());
      pMsg->addBooleanProperty("Progress Present", (pProgress != NULL));
      
      pElement = pInArgList->getPlugInArgValue<DataElement>(Importer::ImportElementArg());
      if (pElement == NULL)
      {
         if (pProgress != NULL)
         {
            pProgress->updateProgress("No data element", 0, ERRORS);
         }
         pStep->finalize(Message::Failure, "No data element");
         return false;
      }
      pMsg->addProperty("Element name", pElement->getName());
   }
   if (pProgress != NULL)
   {
      pProgress->updateProgress((string("Read and parse file ") + pElement->getFilename()), 20, NORMAL);
   }

   // Create a new annotation layer for a spatial data view or get the layout layer for a product view
   if (pProgress != NULL)
   {
      pProgress->updateProgress("Create a new layer", 30, NORMAL);
   }

   View* pView = mpDesktop->getCurrentWorkspaceWindowView();
   if (pView == NULL)
   {
      if (pProgress != NULL)
      {
         pProgress->updateProgress("Could not access the current view.", 0, ERRORS);
      }

      pStep->finalize(Message::Failure, "Could not access the current view.");
      return false;
   }

   UndoGroup undoGroup(pView, "Import CGM");
   AnnotationLayer* pLayer = NULL;

   SpatialDataView* pSpatialDataView = dynamic_cast<SpatialDataView*>(pView);
   if (pSpatialDataView != NULL)
   {
      // Set the parent element of the annotation element to the primary raster element
      LayerList* pLayerList = pSpatialDataView->getLayerList();
      if (pLayerList != NULL)
      {
         RasterElement* pNewParentElement = pLayerList->getPrimaryRasterElement();
         if (pNewParentElement != NULL)
         {
            Service<ModelServices> pModel;
            pModel->setElementParent(pElement, pNewParentElement);
         }
      }

      pLayer = dynamic_cast<AnnotationLayer*>(pSpatialDataView->createLayer(ANNOTATION, pElement));
   }
   else
   {
      ProductView* pProductView = dynamic_cast<ProductView*>(mpDesktop->getCurrentWorkspaceWindowView());
      if (pProductView != NULL)
      {
         pLayer = pProductView->getLayoutLayer();
      }
   }

   if (pLayer == NULL)
   {
      if (pProgress != NULL)
      {
         pProgress->updateProgress("Unable to get the annotation layer", 0, ERRORS);
      }

      pStep->finalize(Message::Failure, "Unable to get the annotation layer");
      return false;
   }

   // add the CGM object
   if (pProgress != NULL)
   {
      pProgress->updateProgress("Create the CGM object", 60, NORMAL);
   }
   CgmObject* pCgmObject = dynamic_cast<CgmObject*>(pLayer->addObject(CGM_OBJECT));
   if (pCgmObject == NULL)
   {
      if (pProgress != NULL)
      {
         pProgress->updateProgress("Unable to create the CGM object", 0, ERRORS);
      }
      pStep->finalize(Message::Failure, "Unable to create the CGM object");
      return false;
   }

   // load the CGM file
   if (pProgress != NULL)
   {
      pProgress->updateProgress("Load the CGM file", 90, NORMAL);
   }
   string fname = pElement->getDataDescriptor()->getFileDescriptor()->getFilename().getFullPathAndName();
   if (!pCgmObject->deserializeCgm(fname))
   {
      if (pProgress != NULL)
      {
         pProgress->updateProgress("Error loading the CGM element", 0, ERRORS);
      }
      pStep->finalize(Message::Failure, "Unable to parse the CGM file.");
      return false;
   }

   if (pProgress != NULL)
   {
      pProgress->updateProgress("Successfully loaded the CGM file", 100, NORMAL);
   }
   pStep->finalize(Message::Success);
   return true;
}
Beispiel #18
0
QWidget* ResultsExporter::getExportOptionsWidget(const PlugInArgList *pInArgList)
{
    const DataDescriptor* pDescriptor = NULL;
    if (pInArgList != NULL)
    {
        RasterElement* pElement = pInArgList->getPlugInArgValue<RasterElement>(Exporter::ExportItemArg());
        if (pElement != NULL)
        {
            pDescriptor = pElement->getDataDescriptor();
        }
    }
    if (mpOptionsWidget == NULL)
    {
        Service<DesktopServices> pDesktop;
        VERIFY(pDesktop.get() != NULL);

        mpOptionsWidget = new ResultsOptionsWidget(pDesktop->getMainWidget());
    }

    if (mpOptionsWidget != NULL)
    {
        const string& name = pDescriptor->getName();
        const string& type = pDescriptor->getType();
        DataElement* pParent = pDescriptor->getParent();

        RasterElement* pResults = dynamic_cast<RasterElement*>(mpModel->getElement(name, type, pParent));
        if (pResults != NULL)
        {
            PassArea passArea = MIDDLE;
            double dFirstThreshold = 0.0;
            double dSecondThreshold = 0.0;

            SpatialDataWindow* pWindow = dynamic_cast<SpatialDataWindow*>(mpDesktop->getCurrentWorkspaceWindow());
            if (pWindow != NULL)
            {
                SpatialDataView* pView = pWindow->getSpatialDataView();
                if (pView != NULL)
                {
                    LayerList* pLayerList = pView->getLayerList();
                    if (pLayerList != NULL)
                    {
                        ThresholdLayer* pThresholdLayer =
                            static_cast<ThresholdLayer*>(pLayerList->getLayer(THRESHOLD, pResults));
                        if (pThresholdLayer != NULL)
                        {
                            passArea = pThresholdLayer->getPassArea();
                            dFirstThreshold = pThresholdLayer->getFirstThreshold();
                            dSecondThreshold = pThresholdLayer->getSecondThreshold();
                        }
                        else
                        {
                            Statistics* pStatistics = pResults->getStatistics();
                            if (pStatistics != NULL)
                            {
                                dFirstThreshold = pStatistics->getMin();
                                dSecondThreshold = pStatistics->getMax();
                            }
                        }
                    }

                    LatLonLayer* pLatLonLayer = static_cast<LatLonLayer*>(pView->getTopMostLayer(LAT_LONG));
                    if (pLatLonLayer != NULL)
                    {
                        GeocoordType geocoordType = pLatLonLayer->getGeocoordType();
                        mpOptionsWidget->setGeocoordType(geocoordType);
                    }
                }
            }

            mpOptionsWidget->setPassArea(passArea);
            mpOptionsWidget->setFirstThreshold(dFirstThreshold);
            mpOptionsWidget->setSecondThreshold(dSecondThreshold);
        }
    }

    return mpOptionsWidget;
}
bool ResamplerPlugIn::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   VERIFY(pInArgList != NULL && pOutArgList != NULL);
   ProgressTracker progress(pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg()),
      "Executing Spectral Resampler.", "spectral", "{88CD3E49-A522-431A-AE2A-96A6B2EB4012}");

   Service<DesktopServices> pDesktop;

   const DataElement* pElement(NULL);
   std::string waveFilename;

   // get default resampling options from user config
   std::string resampleMethod = ResamplerOptions::getSettingResamplerMethod();
   double dropOutWindow = ResamplerOptions::getSettingDropOutWindow();
   double fwhm = ResamplerOptions::getSettingFullWidthHalfMax();
   bool useFillValue = ResamplerOptions::getSettingUseFillValue();
   double fillValue = ResamplerOptions::getSettingSignatureFillValue();

   std::vector<Signature*> originalSignatures;
   std::auto_ptr<std::vector<Signature*> > pResampledSignatures(new std::vector<Signature*>);
   std::string errorMsg;

   if (isBatch())
   {
      VERIFY(pInArgList->getPlugInArgValue("Signatures to resample", originalSignatures));
      if (originalSignatures.empty())
      {
         Signature* pSignature = pInArgList->getPlugInArgValue<Signature>("Signature to resample");
         if (pSignature != NULL)
         {
            originalSignatures.push_back(pSignature);
         }
      }
      if (originalSignatures.empty())
      {
         progress.report("No signatures are available to be resampled.", 0, ERRORS, true);
         return false;
      }
      pElement = pInArgList->getPlugInArgValue<DataElement>("Data element wavelength source");
      Filename* pWaveFilename = pInArgList->getPlugInArgValue<Filename>("Wavelengths Filename");
      if (pWaveFilename != NULL)
      {
         waveFilename = pWaveFilename->getFullPathAndName();
      }
      VERIFY(pInArgList->getPlugInArgValue("Resampling Method", resampleMethod));
      VERIFY(pInArgList->getPlugInArgValue("Drop out window", dropOutWindow));
      VERIFY(pInArgList->getPlugInArgValue("FWHM", fwhm));
      VERIFY(pInArgList->getPlugInArgValue("Use fill value", useFillValue));
      VERIFY(pInArgList->getPlugInArgValue("Fill value", fillValue));
   }
   else
   {
      ResamplerPlugInDlg dlg(pDesktop->getMainWidget());
      if (dlg.exec() == QDialog::Rejected)
      {
         progress.report("User canceled resampling.", 0, ABORT, true);
         progress.upALevel();
         return false;
      }
      originalSignatures = dlg.getSignaturesToResample();
      resampleMethod = dlg.getResamplingMethod();
      dropOutWindow = dlg.getDropOutWindow();
      fwhm = dlg.getFWHM();
      useFillValue = dlg.getUseFillValue();
      fillValue = dlg.getFillValue();
      pElement = dlg.getWavelengthsElement();
      waveFilename = dlg.getWavelengthsFilename();
   }

   std::string resampledTo;
   FactoryResource<Wavelengths> pWavelengths;
   if (pElement != NULL)  // try loading wavelengths from user specified data element
   {
      if (getWavelengthsFromElement(pElement, pWavelengths.get(), errorMsg) == false)
      {
         progress.report(errorMsg, 0, ERRORS, true);
         return false;
      }
      resampledTo = pElement->getName();
   }
   else if (waveFilename.empty() == false)  // if no user provided raster, look for a wavelengths file
   {
      if (QFile::exists(QString::fromStdString(waveFilename)))
      {
         if (getWavelengthsFromFile(waveFilename, pWavelengths.get(), errorMsg) == false)
         {
            progress.report(errorMsg, 0, ERRORS, true);
            return false;
         }
      }
      else
      {
         errorMsg = "The wavelengths file \"" + waveFilename + "\" could not be found.";
         progress.report(errorMsg, 0, ERRORS, true);
         return false;
      }
      resampledTo = waveFilename;
   }
   else  // if no wavelength source provided, look for raster in current active spatial data view
   {
      SpatialDataView* pView = dynamic_cast<SpatialDataView*>(pDesktop->getCurrentWorkspaceWindowView());
      if (pView != NULL)
      {
         LayerList* pLayerList = pView->getLayerList();
         if (pLayerList != NULL)
         {
            pElement = pLayerList->getPrimaryRasterElement();
            pWavelengths->initializeFromDynamicObject(pElement->getMetadata(), false);
            if (pWavelengths->isEmpty())
            {
               progress.report("No target wavelengths are available for resampling the signatures.", 0, ERRORS, true);
               return false;
            }
            resampledTo = pElement->getName();
         }
      }
   }

   PlugInResource pPlugIn("Resampler");
   Resampler* pResampler = dynamic_cast<Resampler*>(pPlugIn.get());
   if (pResampler == NULL)
   {
      progress.report("The \"Resampler\" plug-in is not available so the signatures can not be resampled.",
         0, ERRORS, true);
      return false;
   }
   std::string dataName("Reflectance");
   std::string wavelengthName("Wavelength");

   // save user config settings - Resampler doesn't have interface to set them separately from user config
   std::string configMethod = ResamplerOptions::getSettingResamplerMethod();
   ResamplerOptions::setSettingResamplerMethod(resampleMethod);
   double configDropout = ResamplerOptions::getSettingDropOutWindow();
   ResamplerOptions::setSettingDropOutWindow(dropOutWindow);
   double configFwhm = ResamplerOptions::getSettingFullWidthHalfMax();
   ResamplerOptions::setSettingFullWidthHalfMax(fwhm);

   std::vector<double> toWavelengths = pWavelengths->getCenterValues();
   std::vector<double> toFwhm = pWavelengths->getFwhm();
   if (toFwhm.size() != toWavelengths.size())
   {
      toFwhm.clear();  // Resampler will use the default config setting fwhm if this vector is empty
   }

   unsigned int numSigs = originalSignatures.size();
   unsigned int numSigsResampled(0);
   progress.report("Begin resampling signatures...", 0, NORMAL);
   for (unsigned int index = 0; index < numSigs; ++index)
   {
      if (isAborted())
      {
         progress.report("Resampling aborted by user", 100 * index / numSigs, ABORT, true);
         return false;
      }
      if (originalSignatures[index] == NULL)
      {
         continue;
      }

      // check if signature has target wavelength centers and doesn't need to be resampled
      if (needToResample(originalSignatures[index], pWavelengths.get()) == false)
      {
         pResampledSignatures->push_back(originalSignatures[index]);
         ++numSigsResampled;
         continue;
      }

      DataVariant var = originalSignatures[index]->getData(dataName);
      if (var.isValid() == false)
      {
         continue;
      }
      std::vector<double> fromData;
      if (!var.getValue(fromData))
      {
         continue;
      }
      var = originalSignatures[index]->getData(wavelengthName);
      if (var.isValid() == false)
      {
         continue;
      }
      std::vector<double> fromWavelengths;
      if (!var.getValue(fromWavelengths))
      {
         continue;
      }
      std::string resampledSigName = originalSignatures[index]->getName() + "_resampled";
      int suffix(2);
      ModelResource<Signature> pSignature(resampledSigName, NULL);

      // probably not needed but just in case resampled name already used
      while (pSignature.get() == NULL)
      {
         pSignature = ModelResource<Signature>(resampledSigName + StringUtilities::toDisplayString(suffix), NULL);
         ++suffix;
      }
      if (resampledTo.empty() == false)
      {
         DynamicObject* pMetaData = pSignature->getMetadata();
         if (pMetaData != NULL)
         {
            pMetaData->setAttribute(CommonSignatureMetadataKeys::ResampledTo(), resampledTo);
         }
      }
      std::vector<double> toData;
      std::vector<int> toBands;
      if (pResampler->execute(fromData, toData, fromWavelengths, toWavelengths, toFwhm, toBands, errorMsg))
      {
         if (toWavelengths.size() != toBands.size())
         {
            if (toBands.size() < 2)  // no need to try if only one point
            {
               continue;
            }

            if (useFillValue)
            {
               std::vector<double> values(toWavelengths.size(), fillValue);
               for (unsigned int i = 0; i < toBands.size(); ++i)
               {
                  values[static_cast<unsigned int>(toBands[i])] = toData[i];
               }
               toData.swap(values);
               DynamicObject* pMetaData = pSignature->getMetadata();
               if (pMetaData != NULL)
               {
                  pMetaData->setAttribute(CommonSignatureMetadataKeys::FillValue(), fillValue);
               }
            }
            else
            {
               std::vector<double> wavelengths(toBands.size());
               for (unsigned int i = 0; i < toBands.size(); ++i)
               {
                  wavelengths[i] = toWavelengths[static_cast<unsigned int>(toBands[i])];
               }
               toWavelengths.swap(wavelengths);
            }
         }
         pSignature->setData(dataName, toData);
         pSignature->setData(wavelengthName, toWavelengths);
         SignatureDataDescriptor* pDesc = dynamic_cast<SignatureDataDescriptor*>(pSignature->getDataDescriptor());
         if (pDesc == NULL)
         {
            continue;
         }
         pDesc->setUnits(dataName, originalSignatures[index]->getUnits(dataName));
         pResampledSignatures->push_back(pSignature.release());
         ++numSigsResampled;
      }
      std::string progressStr =
         QString("Resampled signature %1 of %2 signatures").arg(index + 1).arg(numSigs).toStdString();
      progress.report(progressStr, (index + 1) * 100 / numSigs, NORMAL);
   }

   // reset config options
   ResamplerOptions::setSettingResamplerMethod(configMethod);
   ResamplerOptions::setSettingDropOutWindow(configDropout);
   ResamplerOptions::setSettingFullWidthHalfMax(configFwhm);

   if (numSigsResampled == numSigs)
   {
      progress.report("Complete", 100, NORMAL);
      progress.upALevel();
   }
   else
   {
      errorMsg = QString("Only %1 of the %2 signatures were successfully resampled.").arg(
         numSigsResampled).arg(numSigs).toStdString();
      progress.report(errorMsg, 100, WARNING, true);
   }

   VERIFY(pOutArgList->setPlugInArgValue("Resampled signatures", pResampledSignatures.release()));
   return true;
}
/**
 * Get the names of all the data elements which are children of the primary raster element.
 *
 * @param[in] WINDOW @opt
 *            The name of the window. Defaults to the active window.
 * @return An array of data element names or the string "failure" if an error occurred.
 * @usage names = get_data_element_names()
 * @endusage
 */
IDL_VPTR get_data_element_names(int argc, IDL_VPTR pArgv[], char* pArgk)
{
   typedef struct
   {
      IDL_KW_RESULT_FIRST_FIELD;
      int windowExists;
      IDL_STRING windowName;
   } KW_RESULT;

   //IDL_KW_FAST_SCAN is the type of scan we are using, following it is the
   //name of the keyword, followed by the type, the mask(which should be 1),
   //flags, a boolean whether the value was populated and finally the value itself
   static IDL_KW_PAR kw_pars[] = {
      IDL_KW_FAST_SCAN,
      {"WINDOW", IDL_TYP_STRING, 1, 0, reinterpret_cast<int*>(IDL_KW_OFFSETOF(windowExists)),
         reinterpret_cast<char*>(IDL_KW_OFFSETOF(windowName))},
      {NULL}
   };

   IdlFunctions::IdlKwResource<KW_RESULT> kw(argc, pArgv, pArgk, kw_pars, 0, 1);
   std::string windowName;
   std::string name;
   bool bSuccess = false;
   IDL_VPTR idlPtr;
   unsigned int total = 0;
   IDL_STRING* pStrarr = NULL;

   if (kw->windowExists)
   {
      windowName = IDL_STRING_STR(&kw->windowName);
   }

   SpatialDataWindow* pWindow = NULL;
   if (windowName.empty())
   {
      pWindow = dynamic_cast<SpatialDataWindow*>(Service<DesktopServices>()->getCurrentWorkspaceWindow());
   }
   else
   {
      pWindow = dynamic_cast<SpatialDataWindow*>(
         Service<DesktopServices>()->getWindow(windowName, SPATIAL_DATA_WINDOW));
   }
   if (pWindow != NULL)
   {
      SpatialDataView* pView = pWindow->getSpatialDataView();
      if (pView != NULL)
      {
         LayerList* pList = pView->getLayerList();
         if (pList != NULL)
         {
            RasterElement* pElement = pList->getPrimaryRasterElement();
            if (pElement != NULL)
            {
               std::vector<std::string> names = Service<ModelServices>()->getElementNames(pElement, "");
               total = names.size();
               if (total > 0)
               {
                  pStrarr = reinterpret_cast<IDL_STRING*>(malloc(total * sizeof(IDL_STRING)));
                  for (unsigned int i=0; i < total; ++i)
                  {
                     IDL_StrStore(&(pStrarr[i]), const_cast<char*>(names[i].c_str()));
                  }
                  bSuccess = true;
               }
            }
         }
      }
   }
   else if (windowName == "all")
   {
      std::vector<std::string> names = Service<ModelServices>()->getElementNames("RasterElement");
      total = names.size();
      if (total > 0)
      {
         pStrarr = reinterpret_cast<IDL_STRING*>(malloc(total* sizeof(IDL_STRING)));
         for (unsigned int i=0; i < total; ++i)
         {
            IDL_StrStore(&(pStrarr[i]), const_cast<char*>(names[i].c_str()));
         }
         bSuccess = true;
      }
   }
   if (!bSuccess)
   {
      IDL_Message(IDL_M_GENERIC, IDL_MSG_RET, "No elements matched.");
      return IDL_StrToSTRING("failure");
   }
   IDL_MEMINT dims[] = {total};
   idlPtr = IDL_ImportArray(1, dims, IDL_TYP_STRING, reinterpret_cast<UCHAR*>(pStrarr),
      reinterpret_cast<IDL_ARRAY_FREE_CB>(free), NULL);
   return idlPtr;
}
void EastArrowObjectImp::orient()
{
   if (isOriented() == true)
   {
      return;
   }

   GraphicLayer* pLayer = NULL;
   pLayer = getLayer();
   if (pLayer == NULL)
   {
      return;
   }

   View* pView = NULL;
   pView = pLayer->getView();
   if (pView == NULL)
   {
      return;
   }

   SpatialDataView* pSpatialDataView = NULL;
   if (pView->isKindOf("SpatialDataView") == true)
   {
      pSpatialDataView = static_cast<SpatialDataView*> (pView);
   }
   else if (pView->isKindOf("ProductView") == true)
   {
      ProductView* pProductView = static_cast<ProductView*> (pView);

      GraphicLayer* pLayoutLayer = NULL;
      pLayoutLayer = pProductView->getLayoutLayer();
      if (pLayoutLayer == pLayer)
      {
         list<GraphicObject*> viewObjects;
         pLayoutLayer->getObjects(VIEW_OBJECT, viewObjects);

         list<GraphicObject*>::iterator iter = viewObjects.begin();
         while (iter != viewObjects.end())
         {
            GraphicObject* pObject = *iter;
            if (pObject != NULL)
            {
               View* pObjectView = pObject->getObjectView();
               if (pObjectView != NULL)
               {
                  if (pObjectView->isKindOf("SpatialDataView") == true)
                  {
                     pSpatialDataView = static_cast<SpatialDataView*> (pObjectView);
                  }
               }
            }

            ++iter;
         }
      }
   }

   if (pSpatialDataView == NULL)
   {
      return;
   }

   LayerList* pLayerList = pSpatialDataView->getLayerList();
   VERIFYNRV(pLayerList != NULL);
   RasterElement* pRaster = pLayerList->getPrimaryRasterElement();
   VERIFYNRV(pRaster != NULL);
   if (!pRaster->isGeoreferenced())
   {
      return;
   }

   // Calculate the angle of the object relative to the pixel coordinates
   updateHandles();

   LocationType pixelStart = mHandles[7];

   ProductView* pProductView = dynamic_cast<ProductView*> (pView);
   if (pProductView != NULL)
   {
      // Convert to the screen coordinate system
      double dScreenX = 0;
      double dScreenY = 0;
      pLayer->translateDataToWorld(pixelStart.mX, pixelStart.mY, pixelStart.mX, pixelStart.mY);
      pProductView->translateWorldToScreen(pixelStart.mX, pixelStart.mY, dScreenX, dScreenY);
      
      // Convert to the spatial data view coordinate system
      pSpatialDataView->translateScreenToWorld(dScreenX,
         dScreenY, pixelStart.mX, pixelStart.mY);
      pLayer->translateWorldToData(pixelStart.mX, pixelStart.mY, pixelStart.mX, pixelStart.mY);
   }

   double dAngle;
   if (GeoAlgorithms::getAngleToNorth(pRaster, dAngle, pixelStart) == false)
   {
      return;
   }

   // Update the angle if the object is in the layout layer
   if (pProductView != NULL)
   {
      // Rotation
      dAngle -= pSpatialDataView->getRotation();

      // Pitch
      double dPitch = pSpatialDataView->getPitch();
      if (dPitch > 0.0)
      {
         dAngle *= -1.0;
      }
   }

   // Rotate the object
   setRotation(dAngle);

   // Update the orientation flag
   DirectionalArrowObjectImp::orient();
}
Beispiel #22
0
bool SetDataSetWavelengths::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   if (pInArgList == NULL)
   {
      return false;
   }

   StepResource pStep(string("Execute ") + getName(), "Spectral", "863CB0EE-5BC0-4A49-8FCB-FBC385F1AD2D");

   // Extract the input args
   Progress* pProgress = pInArgList->getPlugInArgValue<Progress>(ProgressArg());

   RasterElement* pDataset = pInArgList->getPlugInArgValue<RasterElement>(DataElementArg());
   if ((pDataset == NULL) && (isBatch() == false))
   {
      SpatialDataView* pView = pInArgList->getPlugInArgValue<SpatialDataView>(ViewArg());
      if (pView != NULL)
      {
         LayerList* pLayerList = pView->getLayerList();
         if (pLayerList != NULL)
         {
            pDataset = pLayerList->getPrimaryRasterElement();
         }
      }
   }

   if (pDataset == NULL)
   {
      string message = "The data set input value is invalid.";
      if (pProgress != NULL)
      {
         pProgress->updateProgress(message, 0, ERRORS);
      }

      pStep->finalize(Message::Failure, message);
      return false;
   }

   DynamicObject* pWavelengthData = pInArgList->getPlugInArgValue<DynamicObject>(Wavelengths::WavelengthsArg());
   if (pWavelengthData == NULL)
   {
      string message = "The " + Wavelengths::WavelengthsArg() + " input value is invalid.";
      if (pProgress != NULL)
      {
         pProgress->updateProgress(message, 0, ERRORS);
      }

      pStep->finalize(Message::Failure, message);
      return false;
   }

   // Apply the wavelength data to the data set
   Wavelengths wavelengths(pWavelengthData);
   if (wavelengths.applyToDataset(pDataset) == false)
   {
      string message = "The wavelengths could not be applied to the data set.  The number of wavelength values "
         "may not match the number of bands in the data set.";
      if (pProgress != NULL)
      {
         pProgress->updateProgress(message, 0, ERRORS);
      }

      pStep->finalize(Message::Failure, message);
      return false;
   }

   pStep->finalize(Message::Success);
   return true;
}
SpatialDataView* RasterElementImporterShell::createView() const
{
   if (mpRasterElement == NULL)
   {
      return NULL;
   }

   StepResource pStep("Create view", "app", "F41DCDE3-A5C9-4CE7-B9D4-7DF5A9063840");
   if (mpProgress != NULL)
   {
      mpProgress->updateProgress("Creating view...", 99, NORMAL);
   }

   // Get the data set name
   const string& name = mpRasterElement->getName();
   if (name.empty() == true)
   {
      string message = "The data set name is invalid!  A view cannot be created.";
      if (mpProgress != NULL)
      {
         mpProgress->updateProgress(message, 0, ERRORS);
      }

      pStep->finalize(Message::Failure, message);
      return NULL;
   }

   // Create the spatial data window
   SpatialDataView* pView = NULL;

   SpatialDataWindow* pWindow = static_cast<SpatialDataWindow*>(mpDesktop->createWindow(name, SPATIAL_DATA_WINDOW));
   if (pWindow != NULL)
   {
      pView = pWindow->getSpatialDataView();
   }

   if (pView == NULL)
   {
      string message = "Could not create the view window!";
      if (mpProgress != NULL)
      {
         mpProgress->updateProgress(message, 0, ERRORS);
      }

      pStep->finalize(Message::Failure, message);
      return NULL;
   }

   // Set the spatial data in the view
   pView->setPrimaryRasterElement(mpRasterElement);

   // Create the layers
   {
      UndoLock lock(pView);
      createRasterLayer(pView, pStep.get());
      createGcpLayer(pView, pStep.get());

      const RasterDataDescriptor* pRasterDescriptor =
         dynamic_cast<const RasterDataDescriptor*>(mpRasterElement->getDataDescriptor());
      if (pRasterDescriptor != NULL)
      {
         const GeoreferenceDescriptor* pGeorefDescriptor = pRasterDescriptor->getGeoreferenceDescriptor();
         if ((pGeorefDescriptor != NULL) && (pGeorefDescriptor->getCreateLayer() == true))
         {
            createLatLonLayer(pView, pStep.get());
         }
      }
   }

   // Check for at least one layer in the view
   LayerList* pLayerList = pView->getLayerList();
   VERIFYRV(pLayerList != NULL, NULL);

   if (pLayerList->getNumLayers() == 0)
   {
      mpDesktop->deleteWindow(pWindow);

      string message = "The view contains no layers, so it will not be created.";
      if (mpProgress != NULL)
      {
         mpProgress->updateProgress(message, 0, ERRORS);
      }

      pStep->finalize(Message::Failure, message);
      return NULL;
   }

   pStep->finalize(Message::Success);
   return pView;
}
Beispiel #24
0
string TextObjectImp::getSubstitutedText()
{
   string txt = getText();

   DataElement* pParent = getElement();
   pParent = (pParent == NULL) ? NULL : pParent->getParent();
   DataDescriptor* pParentDesc = (pParent == NULL) ? NULL : pParent->getDataDescriptor();
   DynamicObject* pParentMetadata = (pParentDesc == NULL) ? NULL : pParentDesc->getMetadata();
   for (int i = 0; i < 50; ++i)
   {
      //each pass does replacement of $M(a) currently in the string.
      //do 50 passes to perform sub-expansion at most fifty times, ie. prevent infinite loop
      //for non-terminating recursive expansion
      string::size_type pos = txt.find("$");
      while (pos != string::npos)
      {
         if (pos + 1 >= txt.size())
         {
            break;
         }
         string type = txt.substr(pos+1, 1);
         if (type != "$") //ie. not $$, the escape sequence so continue
         {
            bool replaced = false;
            if (pos+4 < txt.size()) //ie. $M(a)
            {
               if (txt[pos+2] == '(')
               {
                  string::size_type closeParen = txt.find(')', pos+2);
                  if (closeParen == string::npos)
                  {
                     closeParen = txt.size();
                  }
                  string variableName = txt.substr(pos+3, closeParen-(pos+2)-1);
                  string replacementString;
                  if (type == "M" || type == "S")
                  {
                     DataElement* pElmnt = pParent;
                     DynamicObject* pMetadata = pParentMetadata;
                     if (variableName.substr(0, 2) == "//")
                     {
                        string::size_type endNamePos = variableName.find("//", 2);
                        if (endNamePos != string::npos)
                        {
                           string elementName = variableName.substr(2, endNamePos - 2);
                           variableName = variableName.substr(endNamePos + 2);
                           if (!variableName.empty())
                           {
                              if (elementName[0] == '[' && elementName[elementName.size() - 1] == ']')
                              {
                                 elementName = elementName.substr(1, elementName.size() - 2);
                                 std::list<GraphicObject*> objects;
                                 getLayer()->getObjects(VIEW_OBJECT, objects);
                                 for (std::list<GraphicObject*>::iterator object = objects.begin();
                                    object != objects.end(); ++object)
                                 {
                                    GraphicObject* pObj = *object;
                                    if (pObj->getName() == elementName)
                                    {
                                       SpatialDataView* pSdv = dynamic_cast<SpatialDataView*>(pObj->getObjectView());
                                       if (pSdv != NULL)
                                       {
                                          pElmnt = pSdv->getLayerList()->getPrimaryRasterElement();
                                          DataDescriptor* pDesc =
                                             (pElmnt == NULL) ? NULL : pElmnt->getDataDescriptor();
                                          pMetadata = (pDesc == NULL) ? NULL : pDesc->getMetadata();
                                       }
                                       break;
                                    }
                                 }
                              }
                              else
                              {
                                 pElmnt = Service<ModelServices>()->getElement(elementName,
                                    TypeConverter::toString<RasterElement>(), NULL);
                                 DataDescriptor* pDesc = (pElmnt == NULL) ? NULL : pElmnt->getDataDescriptor();
                                 pMetadata = (pDesc == NULL) ? NULL : pDesc->getMetadata();
                              }
                           }
                           else
                           {
                              pElmnt = NULL;
                              pMetadata = NULL;
                           }
                        }
                     }
                     bool success = false;
                     if (type == "M" && pMetadata != NULL)
                     {
                        DataVariant var = pMetadata->getAttributeByPath(variableName);
                        if (var.isValid())
                        {
                           DataVariant::Status status;
                           replacementString = var.toDisplayString(&status);
                           success = (status == DataVariant::SUCCESS);
                           if (mMetadataObjects.find(pMetadata) == mMetadataObjects.end())
                           {
                              mMetadataObjects.insert(make_pair(pMetadata, new AttachmentPtr<DynamicObject>(
                                 pMetadata, SIGNAL_NAME(Subject, Modified),
                                 Slot(this, &TextObjectImp::invalidateTexture))));
                           }
                        }
                     }
                     else if (type == "S" && pElmnt != NULL && variableName == "CLASSIFICATION")
                     {
                        Classification* pClass = pElmnt->getDataDescriptor()->getClassification();
                        pClass->getClassificationText(replacementString);
                        success = true;
                        if (mClassificationObjects.find(pClass) == mClassificationObjects.end())
                        {
                           mClassificationObjects.insert(make_pair(pClass, new AttachmentPtr<Classification>(
                              pClass, SIGNAL_NAME(Subject, Modified),
                              Slot(this, &TextObjectImp::invalidateTexture))));
                        }
                     }
                     if (!success)
                     {
                        replacementString = "Error!";
                     }
                     replaced = true;
                  }
                  if (replaced)
                  {
                     txt.replace(pos, closeParen-pos+1, replacementString);
                     pos = txt.find("$", pos+replacementString.size());
                  }
               }
            }
            if (!replaced)
            {
               pos = txt.find("$", pos+1);
            }
         }
         else
         {
            pos = txt.find("$", pos+2);
         }
      }
   }
   string::size_type pos = txt.find("$$");
   while (pos != string::npos)
   {
      txt.replace(pos, 2, "$");
      pos = txt.find("$$");
   }

   return txt;
}
string MeasurementObjectImp::generateGeoStrings() const
{
   LocationType llCorner = getLlCorner();
   LocationType urCorner = getUrCorner();
   LocationType llCornerLatLon;
   LocationType urCornerLatLon;
   bool unitsValid = false;

   // Get lat lon coordinates and terrain raster
   const RasterElement* pTerrain = NULL;

   bool geoValid(false);
   if (mpGeoreference.get() != NULL)
   {
      GraphicLayer* pLayer = getLayer();
      if (pLayer != NULL)
      {
         SpatialDataView* pView = dynamic_cast<SpatialDataView*>(pLayer->getView());
         if (pView != NULL)
         {
            LayerList* pLayerList = pView->getLayerList();
            VERIFYRV(pLayerList != NULL, "");
            VERIFYRV(pLayerList->getPrimaryRasterElement() == mpGeoreference.get(), "");

            pTerrain = mpGeoreference->getTerrain();

            Layer* pPrimaryRasterLayer = pLayerList->getLayer(RASTER, mpGeoreference.get());
            if (pPrimaryRasterLayer != NULL)
            {
               pPrimaryRasterLayer->translateWorldToData(llCorner.mX, llCorner.mY, llCorner.mX, llCorner.mY);
               pPrimaryRasterLayer->translateWorldToData(urCorner.mX, urCorner.mY, urCorner.mX, urCorner.mY);
            }
         }
      }

      if (mpGeoreference->isGeoreferenced())
      {
         bool llValid(false);
         bool urValid(false);
         llCornerLatLon = mpGeoreference->convertPixelToGeocoord(llCorner, false, &llValid);
         urCornerLatLon = mpGeoreference->convertPixelToGeocoord(urCorner, false, &urValid);
         geoValid = llValid && urValid;
      }
   }

   mUsingInaccurateGeocoords = !geoValid;
   unitsValid = geoValid;

   //String Variables
   string startLoc = "";
   string endLoc = "";
   string distance = "";
   string bearing = "";
   string distanceUnit = "";

   GeoAlgorithms algs;
   double distanceVal = 0;
   double azimuthVal = 0;

   // Create GeoPoint objects
   LatLonPoint startLlPoint = llCornerLatLon;
   LatLonPoint endLlPoint = urCornerLatLon;
   UtmPoint startUtmPoint = startLlPoint;
   UtmPoint endUtmPoint = endLlPoint;
   MgrsPoint startMgrsPoint = startLlPoint;
   MgrsPoint endMgrsPoint = endLlPoint;

   // find elevations
   double elevation1(0.0);
   double elevation2(0.0);
   if (pTerrain != NULL)
   {
      const RasterDataDescriptor* pDescriptor =
         dynamic_cast<const RasterDataDescriptor*>(pTerrain->getDataDescriptor());
      if (pDescriptor != NULL)
      {
         const vector<DimensionDescriptor>& activeRows = pDescriptor->getRows();
         const vector<DimensionDescriptor>& activeColumns = pDescriptor->getColumns();
         if ( llCorner.mY >= 0 && llCorner.mY < activeRows.size() &&
              llCorner.mX >= 0 && llCorner.mX < activeColumns.size() &&
              urCorner.mY >= 0 && urCorner.mY < activeRows.size() &&
              urCorner.mX >= 0 && urCorner.mX < activeColumns.size() )
         {
            DimensionDescriptor llRowDim(activeRows[llCorner.mY]);
            DimensionDescriptor llColumnDim(activeColumns[llCorner.mX]);
            DimensionDescriptor urRowDim(activeRows[urCorner.mY]);
            DimensionDescriptor urColumnDim(activeColumns[urCorner.mX]);
            elevation1 = pTerrain->getPixelValue(llColumnDim, llRowDim, DimensionDescriptor(), COMPLEX_MAGNITUDE);
            elevation2 = pTerrain->getPixelValue(urColumnDim, urRowDim, DimensionDescriptor(), COMPLEX_MAGNITUDE);
            const Units* pElevationUnits = pDescriptor->getUnits();
            if (pElevationUnits != NULL)
            {
               double scale = pElevationUnits->getScaleFromStandard();
               elevation1 *= scale;
               elevation2 *= scale;
            }
         }
      }
   }

   if (unitsValid == true)
   {
      // Calculate bearing and distance
      distanceVal = algs.getPythagoreanOrVincentyDistance(startLlPoint.getLatitude().getValue(),
         startLlPoint.getLongitude().getValue(), endLlPoint.getLatitude().getValue(),
         endLlPoint.getLongitude().getValue(), elevation1, elevation2);
      azimuthVal = algs.getVincentyAzimuth(startLlPoint.getLatitude().getValue(),
         startLlPoint.getLongitude().getValue(), endLlPoint.getLatitude().getValue(),
         endLlPoint.getLongitude().getValue());
      azimuthVal = GeoConversions::convertRadToDeg(azimuthVal);

      // Set distance text
      if (mDrawnDistanceUnit == KILOMETER)
      {
         distanceUnit = "km";
         distanceVal = distanceVal/1000;
      }
      else if (mDrawnDistanceUnit == MILE)
      {
         distanceUnit = "mi";
         distanceVal = GeoConversions::convertMetersToMiles(distanceVal);
      }
      else if (mDrawnDistanceUnit == NAUTICAL_MILE)
      {
         distanceUnit = "Nm";
         distanceVal = GeoConversions::convertMetersToNm(distanceVal);
      }
      else if (mDrawnDistanceUnit == METER)
      {
         distanceUnit = "m";
      }
      else if (mDrawnDistanceUnit == YARD)
      {
         distanceUnit = "yd";
         distanceVal = GeoConversions::convertMetersToFeet(distanceVal)/3;
      }
      else if (mDrawnDistanceUnit == FOOT)
      {
         distanceUnit = "ft";
         distanceVal = GeoConversions::convertMetersToFeet(distanceVal);
      }

      // set location text
      switch (mDrawnGeocoord)
      {
      case GEOCOORD_LATLON:
         startLoc = startLlPoint.getText(mDrawnDmsFormat, mEndPointsPrecision);
         endLoc = endLlPoint.getText(mDrawnDmsFormat, mEndPointsPrecision);
         break;

      case GEOCOORD_UTM:
         startLoc = startUtmPoint.getText();
         endLoc = endUtmPoint.getText();
         break;

      case GEOCOORD_MGRS:
         startLoc = startMgrsPoint.getText();
         endLoc = endMgrsPoint.getText();
         break;

      default:
         startLoc = "(" + QString::number(llCorner.mX, 'f', mEndPointsPrecision).toStdString() + ", " +
            QString::number(llCorner.mY, 'f', mEndPointsPrecision).toStdString() + ")";
         endLoc = "(" + QString::number(urCorner.mX, 'f', mEndPointsPrecision).toStdString() + ", " +
            QString::number(urCorner.mY, 'f', mEndPointsPrecision).toStdString() + ")";
         break;
      }
   }
   else
   {
      startLoc = "(" + QString::number(llCorner.mX, 'f', mEndPointsPrecision).toStdString() + ", " +
         QString::number(llCorner.mY, 'f', mEndPointsPrecision).toStdString() + ")";
      endLoc = "(" + QString::number(urCorner.mX, 'f', mEndPointsPrecision).toStdString() + ", " +
         QString::number(urCorner.mY, 'f', mEndPointsPrecision).toStdString() + ")";
      azimuthVal = algs.getPythagoreanAzimuth(llCorner.mX, llCorner.mY, urCorner.mX, urCorner.mY);
      azimuthVal = GeoConversions::convertRadToDeg(azimuthVal);
      distanceVal = algs.getPythagoreanDistance(urCorner.mX, urCorner.mY, llCorner.mX, llCorner.mY);
      distanceUnit = "pix";
   }

   bearing = QString::number(azimuthVal, 'f', mBearingPrecision).toStdString();
   distance = QString::number(distanceVal, 'f', mDistancePrecision).toStdString();

   QString bearingText = QString::fromStdString(bearing) + " deg";
   QString distanceText = QString::fromStdString(distance) + " " + QString::fromStdString(distanceUnit);
   QString startLocText = QString::fromStdString(startLoc);
   QString endLocText = QString::fromStdString(endLoc);

   // Final strings
   if (bearingText != mBearingText)
   {
      mBearingText = bearingText;
      mBearingTextTexture.invalidate();
   }

   if (distanceText != mDistanceText)
   {
      mDistanceText = distanceText;
      mDistanceTextTexture.invalidate();
   }
   if (startLocText != mStartLocText)
   {
      mStartLocText = startLocText;
      mStartLocTextTexture.invalidate();
   }
   if (endLocText != mEndLocText)
   {
      mEndLocText = endLocText;
      mEndLocTextTexture.invalidate();
   }

   string rtnVal = "DISTANCE: " + distanceText.toStdString() + " : LOCATION: " + startLoc + " to " +
      endLoc + " at " + bearingText.toStdString();
   return rtnVal;
}
Beispiel #26
0
bool RasterTimingTest::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   if (isBatch())
   {
      VERIFY(pOutArgList != NULL);
   }
   Service<DesktopServices> pDesktop;
   SpatialDataView* pView = dynamic_cast<SpatialDataView*>(pDesktop->getCurrentWorkspaceWindowView());
   if (pView)
   {
      UndoLock lock(pView);

      RasterElement* pElement = pView->getLayerList()->getPrimaryRasterElement();
      RasterDataDescriptor* pDesc = dynamic_cast<RasterDataDescriptor*>(pElement->getDataDescriptor());
      int bands = pDesc->getBandCount();
      int frameNumber = 0;
      RasterLayer* pLayer = NULL;
      vector<Layer*> layers;
      pView->getLayerList()->getLayers(RASTER, layers);
      for (vector<Layer*>::iterator iter = layers.begin(); iter != layers.end(); ++iter)
      {
         RasterLayer* pRasterLayer = static_cast<RasterLayer*>(*iter);
         if (pRasterLayer != NULL)
         {
            RasterElement* pCurrentRasterElement = dynamic_cast<RasterElement*>(pRasterLayer->getDataElement());
            if (pCurrentRasterElement == pElement)
            {
               pLayer = pRasterLayer;
               break;
            }
         }
      }
      for (int i = 0; i < bands; ++i)
      {
         pElement->getStatistics(pDesc->getActiveBand(i))->getMin();
      }
      // set grayscale display mode
      DisplayMode initialDisplayMode = pLayer->getDisplayMode();
      pLayer->setDisplayMode(GRAYSCALE_MODE);
      const int frameiterations = 10000;
      clock_t startTime = clock();
      QWidget* pWidget = pView->getWidget();
      int i = 0;
      for (i = 0; i < frameiterations; ++i, ++frameNumber)
      {
         if (frameNumber >= bands)
         {
            frameNumber = 0;
         }

         pLayer->setDisplayedBand(GRAY, pDesc->getActiveBand(frameNumber));
         if (pWidget)
         {
            pWidget->repaint();
         }

         if ((i + 1) % (frameiterations / 100) == 0)
         {
            QString message = QString("Frame ") + QString::number(i+1) + QString(" of ") +
               QString::number(frameiterations);
            pDesktop->setStatusBarMessage(message.toStdString());
         }
         if ((i + 1) % 20 == 0)
         {
            clock_t stopTime = clock();
            double elapsedTime = static_cast<double>(stopTime - startTime) / CLOCKS_PER_SEC;
            if (elapsedTime > 30)
            {
               ++i;
               break;
            }
         }
      }
      clock_t stopTime = clock();
      double framesPerSec = i / (static_cast<double>(stopTime - startTime) / CLOCKS_PER_SEC);

      // restore display mode
      pLayer->setDisplayMode(initialDisplayMode);

      if (isBatch())
      {
         pOutArgList->setPlugInArgValue<double>("Framerate", &framesPerSec);
      }
      else
      {
         QMessageBox::information(pDesktop->getMainWidget(), "Frame Rate", 
            QString("The number of frames per second was: %1\nGPU Acceleration was%2 enabled\n").arg(framesPerSec)
                     .arg(pLayer->isGpuImageEnabled() ? "" : " not"));
      }

      return true;
   }

   return false;
}
LocateDialog::LocateDialog(const RasterElement* pRaster, QWidget* pParent) :
   QDialog(pParent, Qt::WindowCloseButtonHint),
   mpRaster(pRaster),
   mLayerNameBase("Spectral Library Match Locate Results - "),
   mpAlgCombo(NULL),
   mpThreshold(NULL),
   mpOutputLayerName(NULL),
   mpUseAoi(NULL),
   mpAoiCombo(NULL),
   mpSaveSettings(NULL)
{
   setWindowTitle("Locate Matched Signatures Settings");

   // layout
   QGridLayout* pGrid = new QGridLayout(this);
   pGrid->setSpacing(5);
   pGrid->setMargin(10);

   QLabel* pNameLabel = new QLabel("Dataset:", this);
   QLabel* pDataLabel = new QLabel(QString::fromStdString(pRaster->getDisplayName(true)), this);
   pDataLabel->setToolTip(QString::fromStdString(pRaster->getName()));
   QLabel* pAlgLabel = new QLabel("Algorithm:", this);
   mpAlgCombo = new QComboBox(this);
   QLabel* pThresLabel = new QLabel("Threshold:", this);
   mpThreshold = new QDoubleSpinBox(this);
   mpThreshold->setSingleStep(0.1);
   QLabel* pLayerLabel = new QLabel("Output Layer Name:", this);
   mpOutputLayerName = new QLineEdit(this);
   mpUseAoi = new QCheckBox("Area of Interest:", this);
   mpUseAoi->setToolTip("Check box to limit the Locate function to an AOI");
   mpAoiCombo = new QComboBox(this);
   mpAoiCombo->setEnabled(false);
   mpSaveSettings = new QCheckBox("Save the algorithm and threshold settings", this);
   QFrame* pLineSeparator = new QFrame(this);
   pLineSeparator->setFrameStyle(QFrame::HLine | QFrame::Sunken);
   QDialogButtonBox* pButtons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
      Qt::Horizontal, this);

   pGrid->addWidget(pNameLabel, 0, 0, Qt::AlignRight);
   pGrid->addWidget(pDataLabel, 0, 1);
   pGrid->addWidget(pAlgLabel, 1, 0, Qt::AlignRight);
   pGrid->addWidget(mpAlgCombo, 1, 1);
   pGrid->addWidget(pThresLabel, 2, 0, Qt::AlignRight);
   pGrid->addWidget(mpThreshold, 2, 1);
   pGrid->addWidget(pLayerLabel, 3, 0, Qt::AlignRight);
   pGrid->addWidget(mpOutputLayerName, 3, 1);
   pGrid->addWidget(mpUseAoi, 4, 0, Qt::AlignRight);
   pGrid->addWidget(mpAoiCombo, 4, 1);
   pGrid->addWidget(mpSaveSettings, 5, 1);
   pGrid->addWidget(pLineSeparator, 7, 0, 1, 2);
   pGrid->addWidget(pButtons, 8, 0, 1, 2, Qt::AlignRight);
   pGrid->setRowStretch(6, 10);
   pGrid->setColumnStretch(1, 10);

   // initialize algorithm combo
   std::vector<std::string> algNames =
      StringUtilities::getAllEnumValuesAsDisplayString<SpectralLibraryMatch::LocateAlgorithm>();
   for (std::vector<std::string>::const_iterator it = algNames.begin(); it != algNames.end(); ++it)
   {
      mpAlgCombo->addItem(QString::fromStdString(*it));
   }

   // set up algorithm threshold map
   std::vector<std::string> algorithmNames =
      StringUtilities::getAllEnumValuesAsDisplayString<SpectralLibraryMatch::LocateAlgorithm>();
   for (std::vector<std::string>::iterator it = algorithmNames.begin();
      it != algorithmNames.end(); ++it)
   {
      float threshold(0.0f);
      switch (StringUtilities::fromDisplayString<SpectralLibraryMatch::LocateAlgorithm>(*it))
      {
      case SpectralLibraryMatch::SLLA_CEM:
         threshold = SpectralLibraryMatchOptions::getSettingLocateCemThreshold();
         break;

      case SpectralLibraryMatch::SLLA_SAM:
         threshold = SpectralLibraryMatchOptions::getSettingLocateSamThreshold();
         break;

      case SpectralLibraryMatch::SLLA_WBI:
         threshold = SpectralLibraryMatchOptions::getSettingLocateWbiThreshold();
         break;

      default:
         threshold = 0.0f;
         break;
      }

      mLocateThresholds.insert(std::pair<std::string, float>(*it, threshold));
   }

   // load aoi combo
   std::vector<DataElement*> aois =
      Service<ModelServices>()->getElements(pRaster, TypeConverter::toString<AoiElement>());
   for (std::vector<DataElement*>::const_iterator it = aois.begin(); it != aois.end(); ++it)
   {
      mpAoiCombo->addItem(QString::fromStdString((*it)->getName()));
   }

   // try to determine the active aoi layer and set combo to the element for that layer
   std::vector<Window*> windows;
   SpatialDataView* pView(NULL);
   Service<DesktopServices>()->getWindows(SPATIAL_DATA_WINDOW, windows);
   for (std::vector<Window*>::iterator it = windows.begin(); it != windows.end(); ++it)
   {
      SpatialDataWindow* pWindow = dynamic_cast<SpatialDataWindow*>(*it);
      if (pWindow != NULL)
      {
         SpatialDataView* pTmpView = dynamic_cast<SpatialDataView*>(pWindow->getView());
         if (pTmpView != NULL)
         {
            LayerList* pLayerList = pTmpView->getLayerList();
            if (pLayerList != NULL)
            {
               if (pRaster == pLayerList->getPrimaryRasterElement())
               {
                  pView = pTmpView;
                  break;
               }
            }
         }
      }
   }

   if (pView != NULL)
   {
      Layer* pLayer = pView->getActiveLayer();
      if (pLayer != NULL)
      {
         DataElement* pElement = pLayer->getDataElement();
         if (pElement != NULL)
         {
            std::string elementName = pElement->getName();
            int index = mpAoiCombo->findText(QString::fromStdString(elementName));
            if (index != -1)
            {
               mpAoiCombo->setCurrentIndex(index);
            }
         }
      }
   }
   if (mpAoiCombo->count() == 0)
   {
      mpUseAoi->setEnabled(false);
   }

   // Initialize From Settings
   SpectralLibraryMatch::LocateAlgorithm locType =
      StringUtilities::fromXmlString<SpectralLibraryMatch::LocateAlgorithm>(
      SpectralLibraryMatchOptions::getSettingLocateAlgorithm());
   mpAlgCombo->setCurrentIndex(mpAlgCombo->findText(QString::fromStdString(
      StringUtilities::toDisplayString<SpectralLibraryMatch::LocateAlgorithm>(locType))));
   mpThreshold->setValue(mLocateThresholds[mpAlgCombo->currentText().toStdString()]);
   QString layerName = mLayerNameBase;
   switch (locType)
   {
   case SpectralLibraryMatch::SLLA_CEM:
      layerName += "CEM";
      break;

   case SpectralLibraryMatch::SLLA_SAM:
      layerName += "SAM";
      break;

   case SpectralLibraryMatch::SLLA_WBI:
      layerName += "WBI";
      break;

   default:
      layerName += "Unknown Algorithm";
      break;
   }
   mpOutputLayerName->setText(layerName);

   // connections
   VERIFYNR(connect(pButtons, SIGNAL(accepted()), this, SLOT(accept())));
   VERIFYNR(connect(pButtons, SIGNAL(rejected()), this, SLOT(reject())));
   VERIFYNR(connect(mpAlgCombo, SIGNAL(currentIndexChanged(const QString&)),
      this, SLOT(algorithmChanged(const QString&))));
   VERIFYNR(connect(mpThreshold, SIGNAL(valueChanged(double)),
      this, SLOT(thresholdChanged(double))));
   VERIFYNR(connect(mpUseAoi, SIGNAL(toggled(bool)), mpAoiCombo, SLOT(setEnabled(bool))));
}
void ChippingWindow::createView()
{
   if (mpChippingWidget == NULL)
   {
      return;
   }

   RasterElement* pRaster = getRasterElement();
   if (pRaster == NULL)
   {
      return;
   }

   // Create the new raster element from the primary element of the source.
   // Note that this does not chip displayed elements if they differ from the primary element.
   // This causes a special case below where the stretch values are being applied to the chipped layer.
   RasterElement* pRasterChip = pRaster->createChip(pRaster->getParent(), "_chip",
      mpChippingWidget->getChipRows(), mpChippingWidget->getChipColumns(), mpChippingWidget->getChipBands());
   if (pRasterChip == NULL)
   {
      QMessageBox::critical(this, windowTitle(), "Unable to create a new cube!");
      return;
   }

   const RasterDataDescriptor* pDescriptor =
      dynamic_cast<const RasterDataDescriptor*>(pRasterChip->getDataDescriptor());
   VERIFYNRV(pDescriptor != NULL);

   // Create a view for the new chip
   SpatialDataWindow* pWindow = dynamic_cast<SpatialDataWindow*>(
      Service<DesktopServices>()->createWindow(pRasterChip->getName(), SPATIAL_DATA_WINDOW));
   if (pWindow == NULL)
   {
      return;
   }

   SpatialDataView* pView = pWindow->getSpatialDataView();
   if (pView == NULL)
   {
      Service<DesktopServices>()->deleteWindow(pWindow);
      return;
   }

   UndoLock lock(pView);
   if (pView->setPrimaryRasterElement(pRasterChip) == false)
   {
      Service<DesktopServices>()->deleteWindow(pWindow);
      return;
   }

   // RasterLayerImp is needed for the call to setCurrentStretchAsOriginalStretch().
   RasterLayerImp* pLayer = dynamic_cast<RasterLayerImp*>(pView->createLayer(RASTER, pRasterChip));
   if (pLayer == NULL)
   {
      Service<DesktopServices>()->deleteWindow(pWindow);
      return;
   }

   string origName = pRaster->getName();

   SpatialDataWindow* pOrigWindow = dynamic_cast<SpatialDataWindow*>(
      Service<DesktopServices>()->getWindow(origName, SPATIAL_DATA_WINDOW));
   if (pOrigWindow != NULL)
   {
      SpatialDataView* pOrigView = pOrigWindow->getSpatialDataView();
      if (pOrigView != NULL)
      {
         LayerList* pLayerList = pOrigView->getLayerList();
         if (pLayerList != NULL)
         {
            RasterLayer* pOrigLayer = static_cast<RasterLayer*>(pLayerList->getLayer(RASTER, pRaster));
            if (pOrigLayer != NULL)
            {
               // Set the stretch type first so that stretch values are interpreted correctly.
               pLayer->setStretchType(GRAYSCALE_MODE, pOrigLayer->getStretchType(GRAYSCALE_MODE));
               pLayer->setStretchType(RGB_MODE, pOrigLayer->getStretchType(RGB_MODE));
               pLayer->setDisplayMode(pOrigLayer->getDisplayMode());

               // Set the properties of the cube layer in the new view.
               // For each channel, display the first band if the previously displayed band was chipped.
               vector<RasterChannelType> channels = StringUtilities::getAllEnumValues<RasterChannelType>();
               for (vector<RasterChannelType>::const_iterator iter = channels.begin(); iter != channels.end(); ++iter)
               {
                  bool bandCopied = true;
                  DimensionDescriptor newBand;
                  DimensionDescriptor oldBand = pOrigLayer->getDisplayedBand(*iter);
                  if (oldBand.isOriginalNumberValid() == true)
                  {
                     newBand = pDescriptor->getOriginalBand(oldBand.getOriginalNumber());
                  }

                  if (newBand.isValid() == false)
                  {
                     bandCopied = false;
                     newBand = pDescriptor->getBands().front();
                  }

                  // No need to explicitly set the RasterElement here since the new view only has one RasterElement.
                  pLayer->setDisplayedBand(*iter, newBand);

                  // Use the default stretch properties if the displayed band was removed from the view or
                  // if the non-primary raster element was displayed. Otherwise, copy the stretch properties.
                  if (bandCopied && pRaster == pOrigLayer->getDisplayedRasterElement(*iter))
                  {
                     // Set the stretch units first so that stretch values are interpreted correctly.
                     pLayer->setStretchUnits(*iter, pOrigLayer->getStretchUnits(*iter));

                     double lower;
                     double upper;
                     pOrigLayer->getStretchValues(*iter, lower, upper);
                     pLayer->setStretchValues(*iter, lower, upper);
                  }
               }

               pLayer->setCurrentStretchAsOriginalStretch();
               pView->refresh();
            }
         }
      }
   }

   // Create a GCP layer
   if (pRaster->isGeoreferenced() == true)
   {
      const vector<DimensionDescriptor>& rows = mpChippingWidget->getChipRows();
      const vector<DimensionDescriptor>& columns = mpChippingWidget->getChipColumns();
      if ((rows.empty() == false) && (columns.empty() == false))
      {
         // Get the geocoordinates at the chip corners
         VERIFYNRV(rows.front().isActiveNumberValid() == true);
         VERIFYNRV(rows.back().isActiveNumberValid() == true);
         VERIFYNRV(columns.front().isActiveNumberValid() == true);
         VERIFYNRV(columns.back().isActiveNumberValid() == true);

         unsigned int startRow = rows.front().getActiveNumber();
         unsigned int endRow = rows.back().getActiveNumber();
         unsigned int startCol = columns.front().getActiveNumber();
         unsigned int endCol = columns.back().getActiveNumber();

         GcpPoint ulPoint;
         ulPoint.mPixel = LocationType(startCol, startRow);
         ulPoint.mCoordinate = pRaster->convertPixelToGeocoord(ulPoint.mPixel);

         GcpPoint urPoint;
         urPoint.mPixel = LocationType(endCol, startRow);
         urPoint.mCoordinate = pRaster->convertPixelToGeocoord(urPoint.mPixel);

         GcpPoint llPoint;
         llPoint.mPixel = LocationType(startCol, endRow);
         llPoint.mCoordinate = pRaster->convertPixelToGeocoord(llPoint.mPixel);

         GcpPoint lrPoint;
         lrPoint.mPixel = LocationType(endCol, endRow);
         lrPoint.mCoordinate = pRaster->convertPixelToGeocoord(lrPoint.mPixel);

         GcpPoint centerPoint;
         centerPoint.mPixel = LocationType((startCol + endCol) / 2, (startRow + endRow) / 2);
         centerPoint.mCoordinate = pRaster->convertPixelToGeocoord(centerPoint.mPixel);

         // Reset the coordinates to be in active numbers relative to the chip
         const vector<DimensionDescriptor>& chipRows = pDescriptor->getRows();
         const vector<DimensionDescriptor>& chipColumns = pDescriptor->getColumns();

         VERIFYNRV(chipRows.front().isActiveNumberValid() == true);
         VERIFYNRV(chipRows.back().isActiveNumberValid() == true);
         VERIFYNRV(chipColumns.front().isActiveNumberValid() == true);
         VERIFYNRV(chipColumns.back().isActiveNumberValid() == true);

         unsigned int chipStartRow = chipRows.front().getActiveNumber();
         unsigned int chipEndRow = chipRows.back().getActiveNumber();
         unsigned int chipStartCol = chipColumns.front().getActiveNumber();
         unsigned int chipEndCol = chipColumns.back().getActiveNumber();
         ulPoint.mPixel = LocationType(chipStartCol, chipStartRow);
         urPoint.mPixel = LocationType(chipEndCol, chipStartRow);
         llPoint.mPixel = LocationType(chipStartCol, chipEndRow);
         lrPoint.mPixel = LocationType(chipEndCol, chipEndRow);
         centerPoint.mPixel = LocationType((chipStartCol + chipEndCol) / 2, (chipStartRow + chipEndRow) / 2);

         // Create the GCP list
         Service<ModelServices> pModel;

         GcpList* pGcpList = static_cast<GcpList*>(pModel->createElement("Corner Coordinates",
            TypeConverter::toString<GcpList>(), pRasterChip));
         if (pGcpList != NULL)
         {
            list<GcpPoint> gcps;
            gcps.push_back(ulPoint);
            gcps.push_back(urPoint);
            gcps.push_back(llPoint);
            gcps.push_back(lrPoint);
            gcps.push_back(centerPoint);

            pGcpList->addPoints(gcps);

            // Create the layer
            if (pView->createLayer(GCP_LAYER, pGcpList) == NULL)
            {
               QMessageBox::warning(this, windowTitle(), "Could not create a GCP layer.");
            }
         }
         else
         {
            QMessageBox::warning(this, windowTitle(), "Could not create a GCP list.");
         }
      }
   }
}
bool ConvolutionFilterShell::extractInputArgs(PlugInArgList* pInArgList)
{
   VERIFY(pInArgList);
   mProgress = ProgressTracker(pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg()),
      "Executing " + getName(), "app", "{64097F31-84D0-41bf-BBAF-F60DAF212836}");
   if ((mInput.mpRaster = pInArgList->getPlugInArgValue<RasterElement>(Executable::DataElementArg())) == NULL)
   {
      mProgress.report("No raster element.", 0, ERRORS, true);
      return false;
   }
   mInput.mpDescriptor = static_cast<const RasterDataDescriptor*>(mInput.mpRaster->getDataDescriptor());
   mpAoi = pInArgList->getPlugInArgValue<AoiElement>("AOI");
   if (mpAoi == NULL && !isBatch())
   {
      SpatialDataView* pView = pInArgList->getPlugInArgValue<SpatialDataView>(Executable::ViewArg());
      if (pView != NULL)
      {
         std::vector<Layer*> layers;
         pView->getLayerList()->getLayers(AOI_LAYER, layers);
         if (!layers.empty())
         {
            QStringList layerNames;
            layerNames << "<none>";
            for (std::vector<Layer*>::const_iterator layer = layers.begin(); layer != layers.end(); ++layer)
            {
               layerNames << QString::fromStdString((*layer)->getName());
            }
            bool ok = true;
            std::string selectedLayer = QInputDialog::getItem(
               Service<DesktopServices>()->getMainWidget(), "Choose an AOI",
               "Select an AOI or <none> to process the entire image", layerNames, 0, false, &ok).toStdString();
            if (!ok)
            {
               mProgress.report("User cancelled " + getName(), 0, ABORT, true);
               return false;
            }
            for (std::vector<Layer*>::const_iterator layer = layers.begin(); layer != layers.end(); ++layer)
            {
               if ((*layer)->getName() == selectedLayer)
               {
                  mpAoi = static_cast<AoiElement*>((*layer)->getDataElement());
                  break;
               }
            }
         }
      }
   }
   std::vector<unsigned int> bandNumbers;
   if (!pInArgList->getPlugInArgValue("Band Numbers", bandNumbers))
   {
      mProgress.report("Error getting band numbers.", 0, ERRORS, true);
      return false;
   }
   if (!bandNumbers.empty())
   {
      mInput.mBands = bandNumbers;
   }
   pInArgList->getPlugInArgValue("Result Name", mResultName);
   if (mResultName.empty())
   {
      mResultName = mInput.mpRaster->getName() + " Convolved";
      if (!isBatch())
      {
         bool ok = true;
         mResultName = QInputDialog::getText(Service<DesktopServices>()->getMainWidget(), "Output data name",
            "Choose a name for the output data cube", QLineEdit::Normal,
            QString::fromStdString(mResultName), &ok).toStdString();
         if (!ok)
         {
            mProgress.report("User cancelled " + getName(), 0, ABORT, true);
         }
      }
   }

   if (!pInArgList->getPlugInArgValue("Offset", mInput.mOffset))
   {
      mProgress.report("Error getting offset.", 0, ERRORS, true);
      return false;
   }

   if (!pInArgList->getPlugInArgValue("Force Float", mInput.mForceFloat))
   {
      mProgress.report("Error getting float output.", 0, ERRORS, true);
      return false;
   }
   return true;
}
Beispiel #30
0
bool LayerImporter::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   Layer* pLayer = NULL;
   Progress* pProgress = NULL;
   DataElement* pElement = NULL;
   SpatialDataView* pView = NULL;
   StepResource pStep("Import layer", "app", "DF24688A-6B34-4244-98FF-5FFE2063AC05");

   // get input arguments and log some useful info about them
   { // scope the MessageResource
      MessageResource pMsg("Input arguments", "app", "C0A532DE-0E19-44D3-837C-16ABD267B2C1");

      pProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg());
      pMsg->addBooleanProperty("Progress Present", (pProgress != NULL));

      pElement = pInArgList->getPlugInArgValue<DataElement>(Importer::ImportElementArg());
      if (pElement == NULL)
      {
         if (pProgress != NULL)
         {
            pProgress->updateProgress("No data element", 100, ERRORS);
         }
         pStep->finalize(Message::Failure, "No data element");
         return false;
      }
      pMsg->addProperty("Element name", pElement->getName());
      pView = pInArgList->getPlugInArgValue<SpatialDataView>(Executable::ViewArg());
      if (pView != NULL)
      {
         pMsg->addProperty("View name", pView->getName());
      }
   }

   if (pProgress != NULL)
   {
      pProgress->updateProgress((string("Read and parse file ") + pElement->getFilename()),
         20, NORMAL);
   }

   // parse the xml
   XmlReader xml(Service<MessageLogMgr>()->getLog());

   XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument* pDomDocument = xml.parse(pElement->getFilename());
   if (pDomDocument == NULL)
   {
      if (pProgress != NULL)
      {
         pProgress->updateProgress("Unable to parse the file", 100, ERRORS);
      }
      pStep->finalize(Message::Failure, "Unable to parse the file");
      return false;
   }

   DOMElement* pRootElement = pDomDocument->getDocumentElement();
   VERIFY(pRootElement != NULL);

   if (pProgress != NULL)
   {
      pProgress->updateProgress("Create the layer", 40, NORMAL);
   }

   string name(A(pRootElement->getAttribute(X("name"))));
   string type(A(pRootElement->getAttribute(X("type"))));
   unsigned int formatVersion = atoi(A(pRootElement->getAttribute(X("version"))));

   { // scope the MessageResource
      MessageResource pMsg("Layer information", "app", "AA358F7A-107E-456E-8D11-36DDBE5B1645");
      pMsg->addProperty("name", name);
      pMsg->addProperty("type", type);
      pMsg->addProperty("format version", formatVersion);
   }


   // If user requested pixel coordinates be used.
   bool usePixelCoords = false;
   DataDescriptor* pDesc = pElement->getDataDescriptor();
   VERIFY( pDesc );
   pDesc->getMetadata()->getAttributeByPath( "Layer/Import Options/Use Pixel Coordinates" ).getValue( usePixelCoords );
   if (usePixelCoords)
   {
      // Remove geoVertices and geoBox elements.
      removeGeoNodes(pRootElement);
   }

   if (pView == NULL)
   {
      //no view provided, so find current view
      SpatialDataWindow* pWindow = dynamic_cast<SpatialDataWindow*>(mpDesktop->getCurrentWorkspaceWindow());
      if (pWindow != NULL)
      {
         pView = pWindow->getSpatialDataView();
      }
   }

   if (pView == NULL)
   {
      if (pProgress != NULL)
      {
         pProgress->updateProgress("Could not access the view to create the layer.", 100, ERRORS);
      }

      pStep->finalize(Message::Failure, "Could not access the view to create the layer.");
      return false;
   }

   bool error = false;
   LayerType layerType = StringUtilities::fromXmlString<LayerType>(type, &error);
   if (error == true)
   {
      if (pProgress != NULL)
      {
         pProgress->updateProgress("The layer type is invalid.", 100, ERRORS);
      }

      pStep->finalize(Message::Failure, "The layer type is invalid.");
      return false;
   }

   LayerList* pLayerList = pView->getLayerList();
   if (pLayerList != NULL)
   {
      RasterElement* pNewParentElement = pLayerList->getPrimaryRasterElement();
      if (pNewParentElement != NULL)
      {
         Service<ModelServices> pModel;
         if (pModel->setElementParent(pElement, pNewParentElement) == false)
         {
            pProgress->updateProgress("The layer already exists.", 100, ERRORS);
            pStep->finalize(Message::Failure, "The layer already exists.");
            return false;
         }
      }
   }

   UndoGroup group(pView, "Import " + StringUtilities::toDisplayString(layerType) + " Layer");

   pLayer = pView->createLayer(layerType, pElement);
   if (pLayer == NULL)
   {
      if (pProgress != NULL)
      {
         pProgress->updateProgress("Unable to create the layer", 100, ERRORS);
      }
      pStep->finalize(Message::Failure, "Unable to create the layer");
      return false;
   }

   if (pProgress != NULL)
   {
      pProgress->updateProgress("Build the layer", 60, NORMAL);
   }

   // deserialize the layer
   try
   {
      if (pLayer->fromXml(pRootElement, formatVersion) == false)
      {
         pProgress->updateProgress("Problem with layer file.", 100, ERRORS);
         pStep->finalize(Message::Failure, "Problem with layer file.");
         return false;
      }
   }
   catch (XmlReader::DomParseException&)
   {
      return false;
   }

   pStep->finalize(Message::Success);
   if (pProgress != NULL)
   {
      pProgress->updateProgress("Finished loading the layer", 100, NORMAL);
   }

   // Add the layer to the view
   pView->addLayer(pLayer);
   pView->setActiveLayer(pLayer);
   pView->setMouseMode("LayerMode");

   if (pOutArgList != NULL)
   {
      // set the output arguments
      pOutArgList->setPlugInArgValue("Layer", pLayer);
   }

   return true;
}