Ejemplo n.º 1
0
String PropertyUtils::getFormattedNumber( String numberStr, IsoString numberFormat )
{
   if ( numberStr.IsEmpty() )
      return numberStr;

   size_t im = numberFormat.Find( 'm' );
   if ( im == String::notFound )
      return String().Format( numberFormat.c_str(), stringToFloatSafe( numberStr ) );

   numberFormat.DeleteRight( im );
   numberFormat.DeleteLeft( 1 );
   StringList tokens;
   numberFormat.Break( tokens, '.', true/*trim*/ );
   size_t fraction = stringToIntSafe( tokens[1] );
   size_t width    = stringToIntSafe( tokens[0] ) - fraction;
   assert( width > 0 );
   int hours = Trunc( stringToFloatSafe( numberStr ) );
   switch ( fraction )
   {
   case 3:
      {
         int minutes = Trunc( (stringToFloatSafe( numberStr ) - hours)*60 );
         IsoString formatStr = '%' + IsoString().Format( "%dd",width ) + ":%02d";
         return String().Format( formatStr.c_str(), hours, Abs( minutes ) );
      }
   case 5:
      {
         int minutes     = Trunc( (stringToFloatSafe( numberStr ) - hours)*60 );
         int minutesfrac = Trunc( ((stringToFloatSafe( numberStr ) - hours)*60 - minutes)*10);
         IsoString formatStr = '%' + IsoString().Format( "%dd", width ) + ":%02d.%d";
         return String().Format( formatStr.c_str(), hours, Abs( minutes ), Abs( minutesfrac ) );
      }
   case 6:
      {
         int minutes     = Trunc( (stringToFloatSafe( numberStr ) - hours)*60 );
         int seconds     = Trunc( ((stringToFloatSafe( numberStr ) - hours)*60 - minutes)*60 );
         IsoString formatStr = '%' + IsoString().Format( "%dd", width ) + ":%02d:%02d";
         return String().Format( formatStr.c_str(), hours, Abs( minutes ), Abs( seconds ) );
      }
   case 8:
      {
         int minutes     = Trunc( (stringToFloatSafe( numberStr ) - hours)*60 );
         int seconds     = Trunc( ((stringToFloatSafe( numberStr ) - hours)*60 - minutes)*60 );
         int secondsfrac = Trunc( (((stringToFloatSafe( numberStr ) - hours)*60 - minutes)*60 - seconds)*10 );
         IsoString formatStr = '%' + IsoString().Format( "%dd", width ) + ":%02d:%02d.%d";
         return String().Format( formatStr.c_str(), hours, Abs( minutes ), Abs( seconds ), Abs( secondsfrac ) );
      }
   case 9:
      {
         int minutes     = Trunc( (stringToFloatSafe( numberStr ) - hours)*60 );
         int seconds     = Trunc( ((stringToFloatSafe( numberStr ) - hours)*60 - minutes)*60 );
         int secondsfrac = Trunc( (((stringToFloatSafe( numberStr ) - hours)*60 - minutes)*60 - seconds)*100 );
         IsoString formatStr = '%' + IsoString().Format( "%dd", width ) + ":%02d:%02d.%02d";
         return String().Format( formatStr.c_str(), hours, Abs( minutes ), Abs( seconds ), Abs( secondsfrac ) );
      }
   default:
      return String();
   }
}
Ejemplo n.º 2
0
static IsoString GetDemangledFunctionName( const char* symbol, IsoString& addrStr )
{
   IsoString symbolStr( symbol );
   addrStr.Clear();

   // Get mangled function name. Example:
   //    /opt/PixInsight/bin/lib/libQtGui.so.4(_ZN7QWidget5eventEP6QEvent+0x411) [0x7fa271347811]
   StringList tokens;
   symbolStr.Break( tokens, '(' , true/*trim*/ );
   if ( tokens.Length() != 2 )
      return symbolStr;

   // Take second token and split again.
   StringList tokens2;
   tokens[1].Break( tokens2, '+' , true/*trim*/ );
   if ( tokens2.Length() != 2 )
      return symbolStr;

   // If there is no function name, do not set the addr string.
   if ( !tokens2[0].IsEmpty() )
   {
      addrStr = tokens2[1];
      addrStr.DeleteChar( '(' );
      addrStr.DeleteChar( ')' );
   }

   // The first token of tokens2 contains the mangled string. Demangle it.
   size_t funcnameSize = 256;
   char funcname[ funcnameSize ];
   int status;
   IsoString token( tokens2[0] );
   const char* demangledFuncname = abi::__cxa_demangle( token.c_str(), funcname, &funcnameSize, &status );
   return (status == 0) ? IsoString( demangledFuncname ) : symbolStr;
}
Ejemplo n.º 3
0
IsoString MetaModule::ReadableVersion() const
{
   int major, minor, release, build;
   IsoString dum1, dum2;
   GetVersion( major, minor, release, build, dum1, dum2 );
   return Name() + IsoString().Format( " module version %02d.%02d.%02d.%04d", major, minor, release, build );
}
Ejemplo n.º 4
0
ImageDescriptionArray JPEGInstance::Open( const String& filePath, const IsoString& hints )
{
   Close();

   try
   {
      Exception::EnableConsoleOutput();

      JPEGImageOptions jpegOptions = JPEGFormat::DefaultOptions();
      IsoStringList theHints;
      hints.Break( theHints, ' ', true/*trim*/ );
      theHints.Remove( IsoString() );
      for ( IsoStringList::const_iterator i = theHints.Begin(); i < theHints.End(); ++i )
         if ( *i == "verbosity" )
         {
            if ( ++i == theHints.End() )
               break;
            int n;
            if ( i->TryToInt( n ) )
               jpegOptions.verbosity = Range( n, 0, 3 );
         }

      m_reader = new JPEGReader;
      m_reader->SetJPEGOptions( jpegOptions );
      m_reader->Open( filePath );
      return ImageDescriptionArray() << ImageDescription( m_reader->Info(), m_reader->Options() );
   }
   catch ( ... )
   {
      Close();
      throw;
   }
}
Ejemplo n.º 5
0
bool FileDataCacheItem::Load( const IsoString& keyPrefix, int index )
{
   String s;
   if ( !Settings::Read( keyPrefix + IsoString().Format( "%08d", index+1 ), s ) )
      return false;
   if ( s.IsEmpty() || !FromString( s ) )
      throw CatchedException();
   return true;
}
IsoString ExponentialFunctionType::ElementId( size_type i ) const
{
   switch ( i )
   {
   case PIP: return "PIP";
   case SMI: return "SMI";
   }

   return IsoString();
}
Ejemplo n.º 7
0
IsoString CSSColorName( RGBA c )
{
   if ( c == 0 )
      return "Transparent";
   SetAlpha( c, 0xFF );
   for ( const CSSColor& color : cssColors )
      if ( color.value == c )
         return color.name;
   return IsoString();
}
Ejemplo n.º 8
0
api_bool InternalIconEnumerator::ProcessCallback( const char* iconId, void* data )
{
#define enumeration reinterpret_cast<ProcessIconsByProcessIdEnumerationData*>( data )
   ProcessInstance instance( (*API->Process->CreateProcessInstanceFromIcon)( ModuleHandle(), iconId ) );
   if ( instance.IsNull() ) // ?! should not happen
      return api_false;
   if ( instance.ParentProcess().Id() == enumeration->processId )
      enumeration->icons.Add( IsoString( iconId ) );
   return api_true;
#undef enumeration
}
Ejemplo n.º 9
0
MessageBox::std_button MessageBox::Execute()
{
   if ( API == nullptr )
   {
      // Errors occurring before API initialization.

#ifdef __PCL_WINDOWS
      ::MessageBoxW( 0, (LPCWSTR)p->text.c_str(), (LPCWSTR)p->caption.c_str(), MB_OK|MB_ICONERROR|MB_TASKMODAL );
#else

      IsoString cmd( "xmessage -buttons Ok:0 -default Ok -center " );

      cmd.Append( '\"' );

      if ( !p->caption.IsEmpty() )
      {
         cmd.Append( IsoString( p->caption ) );
         cmd.Append( ": " );
      }

      if ( !p->text.IsEmpty() )
         cmd.Append( IsoString( p->text ) );

      cmd.Append( '\"' );

      system( cmd.c_str() );

#endif   // __PCL_WINDOWS

      return StdButton::Ok;
   }

   // Request a PixInsight MessageBox primitive.

   return std_button( (*API->Global->MessageBox)( p->text.c_str(), p->caption.c_str(),
                                                  p->button0, p->button1, p->button2,
                                                  p->defaultButton, p->escapeButton,
                                                  p->icon ) );
}
Ejemplo n.º 10
0
void JPEGInstance::Create( const String& filePath, int numberOfImages, const IsoString& hints )
{
   Close();

   Exception::EnableConsoleOutput();

   m_writer = new JPEGWriter;
   m_writer->Create( filePath );

   JPEGImageOptions jpegOptions = JPEGFormat::DefaultOptions();

   IsoStringList theHints;
   hints.Break( theHints, ' ', true/*trim*/ );
   theHints.Remove( IsoString() );
   for ( IsoStringList::const_iterator i = theHints.Begin(); i < theHints.End(); ++i )
   {
      if ( *i == "quality" )
      {
         if ( ++i == theHints.End() )
            break;
         int q = jpegOptions.quality;
         if ( i->TryToInt( q ) )
            jpegOptions.quality = Range( q, 0, 100 );
      }
      else if ( *i == "optimized" )
         jpegOptions.optimizedCoding = true;
      else if ( *i == "no-optimized" )
         jpegOptions.optimizedCoding = false;
      else if ( *i == "arithmetic" )
         jpegOptions.arithmeticCoding = true;
      else if ( *i == "huffman" )
         jpegOptions.arithmeticCoding = false;
      else if ( *i == "progressive" )
         jpegOptions.progressive = true;
      else if ( *i == "no-progressive" )
         jpegOptions.progressive = false;
      else if ( *i == "verbosity" )
      {
         if ( ++i == theHints.End() )
            break;
         int n;
         if ( i->TryToInt( n ) )
            jpegOptions.verbosity = Range( n, 0, 3 );
      }
   }

   m_writer->SetJPEGOptions( jpegOptions );
}
Ejemplo n.º 11
0
void FilterLibrary::SaveAs( const String& _filePath )
{
   File f;
   f.CreateForWriting( _filePath );
   if ( !filters.IsEmpty() )
      for ( filter_list::const_iterator i = filters.Begin(); ; )
      {
         f.OutText( i->ToSource() );
         if ( ++i == filters.End() )
            break;
         f.OutTextLn( IsoString() );
      }
   f.Close();

   filePath = _filePath;
}
Ejemplo n.º 12
0
static void FindPreviews( StringList& items, const String& imageId, const String& previewId )
{
   if ( imageId.HasWildcards() )
   {
      Array<ImageWindow> W = ImageWindow::AllWindows();
      for ( size_type i = 0; i < W.Length(); ++i )
         if ( String( W[i].MainView().Id() ).WildMatch( imageId ) )
            FindPreviews( items, W[i], previewId );
   }
   else
   {
      ImageWindow w = ImageWindow::WindowById( IsoString( imageId ) );
      if ( w.IsNull() )
         throw ParseError( "Image not found", imageId );
      FindPreviews( items, w, previewId );
   }
}
Ejemplo n.º 13
0
static void FindPreviews( StringList& items, const ImageWindow& w, const String& previewId )
{
   if ( previewId.HasWildcards() )
   {
      Array<View> P = w.Previews();
      for ( size_type i = 0; i < P.Length(); ++i )
         if ( String( P[i].Id() ).WildMatch( previewId ) )
            AddView( items, P[i] );
   }
   else
   {
      View p = w.PreviewById( IsoString( previewId ) );
      if ( p.IsNull() )
         throw ParseError( "Preview not found", previewId );
      AddView( items, p );
   }
}
IsoString CCDFrameProcess::Category() const
{
   return IsoString("INDI"); // No category
}
Ejemplo n.º 15
0
api_bool InternalIconEnumerator::IconCallback( const char* iconId, void* data )
{
   reinterpret_cast<IsoStringList*>( data )->Add( IsoString( iconId ) );
   return api_true;
}
Ejemplo n.º 16
0
void JPCInstance::Create( const String& filePath, int/*numberOfImages*/, const IsoString& hints )
{
   Close();

   Exception::EnableConsoleOutput();

   m_path = filePath;

   IsoStringList theHints;
   hints.Break( theHints, ' ', true/*trim*/ );
   theHints.Remove( IsoString() );
   for ( IsoStringList::const_iterator i = theHints.Begin(); i < theHints.End(); ++i )
   {
      if ( *i == "lossy" )
         m_jp2Options.lossyCompression = true;
      else if ( *i == "lossless" )
         m_jp2Options.lossyCompression = false;
      else if ( *i == "compression-rate" )
      {
         if ( ++i == theHints.End() )
            break;
         if ( i->TryToFloat( m_jp2Options.compressionRate ) )
            m_jp2Options.compressionRate = Range( m_jp2Options.compressionRate, 0.01F, 0.99F );
      }
      else if ( *i == "signed" )
         m_jp2Options.signedSample = true;
      else if ( *i == "unsigned" )
         m_jp2Options.signedSample = false;
      else if ( *i == "tiled" )
         m_jp2Options.tiledImage = true;
      else if ( *i == "untiled" )
         m_jp2Options.tiledImage = true;
      else if ( *i == "tile-width" )
      {
         if ( ++i == theHints.End() )
            break;
         if ( i->TryToInt( m_jp2Options.tileWidth ) )
            m_jp2Options.tileWidth = Range( m_jp2Options.tileWidth, 16, 8192 );
      }
      else if ( *i == "tile-height" )
      {
         if ( ++i == theHints.End() )
            break;
         if ( i->TryToInt( m_jp2Options.tileHeight ) )
            m_jp2Options.tileHeight = Range( m_jp2Options.tileHeight, 16, 8192 );
      }
      else if ( *i == "layers" )
      {
         if ( ++i == theHints.End() )
            break;
         if ( i->TryToInt( m_jp2Options.numberOfLayers ) )
            m_jp2Options.numberOfLayers = Range( m_jp2Options.numberOfLayers, 1, 10 );
      }
      else if ( *i == "lrcp" )
         m_jp2Options.progressionOrder = JPEG2000ProgressionOrder::LRCP;
      else if ( *i == "rlcp" )
         m_jp2Options.progressionOrder = JPEG2000ProgressionOrder::RLCP;
      else if ( *i == "rpcl" )
         m_jp2Options.progressionOrder = JPEG2000ProgressionOrder::RPCL;
      else if ( *i == "pcrl" )
         m_jp2Options.progressionOrder = JPEG2000ProgressionOrder::PCRL;
      else if ( *i == "cprl" )
         m_jp2Options.progressionOrder = JPEG2000ProgressionOrder::CPRL;
   }
}
Ejemplo n.º 17
0
FilterParser::token_list FilterParser::Tokenize( const IsoStringList& linesUTF8 )
{
   token_list tokenList;
   bool blockComment = false;
   int row = 0;
   for ( IsoStringList::const_iterator i = linesUTF8.Begin(); i < linesUTF8.End(); ++i, ++row )
   {
      IsoString token;
      int tokenCol = 0;
      for ( IsoString::const_iterator j = i->Begin(); j < i->End(); ++j )
      {
         if ( blockComment )
         {
            if ( *j == '*' )
               if ( ++j < i->End() )
                  if ( *j == '/' )
                  {
                     blockComment = false;
                     /*
                      * Uncomment the next line to turn block comments into
                      * separators.
                      *
                     tokenCol = j - i->Begin() + 1;
                      */
                  }
         }
         else
         {
            bool lineComment = false;
            switch ( *j )
            {
            case ' ':
            case '\t':
               if ( !token.IsEmpty() )
               {
                  tokenList.Add( Token( token, row, tokenCol ) );
                  token.Clear();
               }
               for ( IsoString::const_iterator k = j; ++k < i->End(); ++j )
                  if ( *k != ' ' && *k != '\t' )
                     break;
               tokenCol = j - i->Begin() + 1;
               break;
               /*
            case ',':
               if ( token.IsEmpty() )
                  throw SourceCodeError( "Expected a token before ','", row+1, int( j - i->Begin() + 1 ) );
               tokenList.Add( Token( token, row, tokenCol ) );
               token.Clear();
               tokenCol = j - i->Begin() + 1;
               break;
               */
            case '{':
            case '}':
               if ( !token.IsEmpty() )
               {
                  tokenList.Add( Token( token, row, tokenCol ) );
                  token.Clear();
               }
               tokenList.Add( Token( IsoString( *j ), row, int( j - i->Begin() ) ) );
               tokenCol = j - i->Begin() + 1;
               break;
            case '/':
               if ( ++j < i->End() )
               {
                  if ( *j == '/' )
                     lineComment = true;
                  else if ( *j == '*' )
                  {
                     blockComment = true;
                     /*
                      * Uncomment the next lines to turn block comments into
                      * separators.
                      *
                     if ( !token.IsEmpty() )
                     {
                        tokenList.Add( Token( token, row, tokenCol ) );
                        token.Clear();
                     }
                      */
                  }
                  else
                     token += *--j;
               }
               break;
            default:
               token += *j;
               break;
            }
            if ( lineComment )
               break;
         }
      }

      if ( !token.IsEmpty() )
         tokenList.Add( Token( token, row, tokenCol ) );
   }
   return tokenList;
}
Ejemplo n.º 18
0
void FileDataCacheItem::Save( const IsoString& keyPrefix, int index ) const
{
   Settings::Write( keyPrefix + IsoString().Format( "%08d", index+1 ), AsString() );
}
Ejemplo n.º 19
0
void INDIMountInterface::ComboItemSelected( ComboBox& sender, int itemIndex )
{
   if ( sender == GUI->MountDevice_Combo )
   {
      m_Device = sender.ItemText( itemIndex );
      if ( TheINDIDeviceControllerInterface != nullptr )
      {
         INDIDeviceControllerInstance* pInstance = &TheINDIDeviceControllerInterface->instance;
         if ( pInstance == nullptr )
            return;

         // Start update timer
         GUI->UpdateMount_Timer.Start();
      }

      pcl::Sleep( 2 );
      // Download stars from simbad database
      NetworkTransfer transfer;
      IsoString url( "http://simbad.u-strasbg.fr/simbad/sim-tap/sync?request=doQuery&lang=adql&format=text&query=" );
      //IsoString url( "http://simbad.cfa.harvard.edu/simbad/sim-tap/sync?request=doQuery&lang=adql&format=text&query=" );

      SkyMap::geoCoord geoCoord;
      geoCoord.geo_lat = m_geoLat;
      SkyMap::filter filter;
      filter.dec_lowerLimit = (m_geoLat < 0) ? 90.0 - m_geoLat : m_geoLat - 90.0;
      filter.dec_upperLimit = (m_geoLat < 0) ? -90.0 : 90.0;
      filter.v_upperLimit = m_limitStarMag;

      m_skymap = new SkyMap( filter, geoCoord );
      IsoString select_stmt = m_skymap->getASDLQueryString();
      Console().WriteLn( "QueryStr = " + m_skymap->getASDLQueryString() );
      url.Append( select_stmt );
      transfer.SetURL( url );
      transfer.OnDownloadDataAvailable(
         (NetworkTransfer::download_event_handler) &INDIMountInterface::DownloadObjectCoordinates, *this );
      if ( !transfer.Download() )
      {
         Console().WriteLn( "Download failed with error '" + transfer.ErrorInformation() + "'" );
         if ( transfer.WasAborted() )
            Console().WriteLn( "Download was aborted" );
      }
      else
      {
         Console().WriteLn( String().Format( "%u bytes downloaded @ %.3g KiB/s",
                                             transfer.BytesTransferred(), transfer.TotalSpeed() ) );
         StringList lines;
         m_downloadedFile.Break( lines, '\n', true/*trim*/ );
         Console().WriteLn( m_downloadedFile.c_str() );
         for ( size_t i = 0; i < lines.Length(); i++ )
         {
            if ( i <= 1 )
               continue;

            StringList tokens;
            lines[i].Break( tokens, '|', true/*trim*/ );
            if ( tokens.Length() != 5 )
               continue;
            if ( !tokens[1].IsNumeral() || !tokens[2].IsNumeral() || !tokens[3].IsNumeral() )
               continue;
            SkyMap::object star;
            star.mainId = tokens[0];
            star.ra = tokens[1].ToDouble();
            star.dec = tokens[2].ToDouble();
            star.v = tokens[3].ToDouble();
            star.spType = tokens[4];
#if DEBUG
            Console().WriteLn( IsoString().Format(
               "star=%s, ra=%f, dec=%f, vmag=%f, sp=%s", star.mainId.c_str(), star.ra, star.dec, star.v, star.spType.c_str() ) );
#endif
            m_skymap->addObject( star );
         }
      }
      m_downloadedFile.Clear();
   }
}
Ejemplo n.º 20
0
void INDIMountInterface::TabPageSelected( TabBox& sender, int pageIndex )
{
   if ( sender == GUI->SkyChart_TabBox )
   {
      if ( pageIndex == 0 ) // AllSky tab page
      {
         m_isAllSkyView = true;
      }
      else if ( pageIndex==1 ) // FoV tab page
      {
         double CCD_chipHeight = 2200;
         double CCD_chipWidth = 2750;
         double CCD_pixelSize = 4.54/1000;
         double TEL_focalLength = 700;
         double FoV_width = CCD_chipWidth*CCD_pixelSize / TEL_focalLength*3438/60;
         double FoV_height = CCD_chipHeight*CCD_pixelSize / TEL_focalLength*3438/60;
         double limitStarMag = 13;

         double ra_center = m_scopeRA*360/24;
         double dec_center = m_scopeDEC;

         // download stars
         NetworkTransfer transfer;
         IsoString url( "http://simbad.u-strasbg.fr/simbad/sim-tap/sync?request=doQuery&lang=adql&format=text&query=" );
         IsoString select_stmt = m_skymap->getASDLFoVQueryString( ra_center, dec_center, FoV_width, FoV_height, limitStarMag );
         Console().WriteLn( "QueryStr = " + select_stmt );
         url.Append( select_stmt );
         transfer.SetURL( url );
         transfer.OnDownloadDataAvailable(
               (NetworkTransfer::download_event_handler)&INDIMountInterface::DownloadObjectCoordinates, *this );
         if ( !transfer.Download() )
         {
            Console().WriteLn( "Download failed with error '" + transfer.ErrorInformation() + "'" );
         }
         else
         {
            Console().WriteLn( String().Format( "%d bytes downloaded @ %.3g KiB/s",
                                                transfer.BytesTransferred(), transfer.TotalSpeed() ) );
            StringList lines;
            m_downloadedFile.Break( lines, '\n', true/*trim*/ );
            m_skymap->clearFoVObjectList();
            if ( lines.Length() > 0 )
            {
               for ( size_t i = 0; i < lines.Length(); i++ )
               {
                  if (i <= 1)
                     continue;

                  StringList tokens;
                  lines[i].Break( tokens, '|', true/*trim*/ );
                  if ( tokens.Length() < 4 )
                     continue;
                  if ( !tokens[1].IsNumeral() || !tokens[2].IsNumeral() || !tokens[3].IsNumeral() )
                     continue;
                  SkyMap::object star;
                  star.mainId = tokens[0];
                  star.ra = tokens[1].ToDouble();
                  star.dec = tokens[2].ToDouble();
                  star.v = tokens[3].ToDouble();
                  if ( tokens.Length() == 6 )
                     star.spType = tokens[5];
#if DEBUG
                  Console().WriteLn( IsoString().Format( "star=%s, ra=%f, dec=%f", star.mainId.c_str(), star.ra, star.dec ) );
#endif
                  m_skymap->addObjectToFoV( star );
               }
            }
         }
         m_downloadedFile.Clear();
         m_isAllSkyView = false;
      }
   }
}
Ejemplo n.º 21
0
EditEqCoordPropertyDialog::EditEqCoordPropertyDialog(String raCoord, String decCoord):m_ra_hour(0),m_ra_minute(0),m_ra_second(0),m_dec_deg(0),m_dec_arcsecond(0),m_dec_arcminute(0),m_DEC_TargetCoord(String("")){
   pcl::Font fnt = Font();
   int labelWidth = fnt.Width(String('0', 20));
   int editWidth = fnt.Width(String('0', 4));

   CoordUtils::HMS ra_hms = CoordUtils::parse(raCoord);
   CoordUtils::HMS dec_hms = CoordUtils::parse(decCoord);

   SetWindowTitle( "Set equatorial coordinates for target object." );

   RA_Property_Label.SetMinWidth(labelWidth);
   RA_Property_Label.SetText( "RA (hh:mm:ss.ss)" );
   RA_Property_Label.SetTextAlignment(TextAlign::Left | TextAlign::VertCenter);

   RA_Hour_Edit.SetMaxWidth(editWidth);
   RA_Hour_Edit.SetText(IsoString(ra_hms.hour));
   RA_Hour_Edit.OnEditCompleted(
         (Edit::edit_event_handler) &EditEqCoordPropertyDialog::EditCompleted,
         *this);

   RA_Colon1_Label.SetText(":");

   RA_Minute_Edit.SetMaxWidth(editWidth);
   RA_Minute_Edit.SetText(IsoString(ra_hms.minute));
   RA_Minute_Edit.OnEditCompleted(
         (Edit::edit_event_handler) &EditEqCoordPropertyDialog::EditCompleted,
         *this);

   RA_Colon2_Label.SetText(":");

   RA_Second_Edit.SetMaxWidth(editWidth);
   RA_Second_Edit.SetText(IsoString(ra_hms.second));
   RA_Second_Edit.OnEditCompleted(
         (Edit::edit_event_handler) &EditEqCoordPropertyDialog::EditCompleted,
         *this);

   DEC_Property_Label.SetMinWidth(labelWidth);
   DEC_Property_Label.SetText( "Dec (dd:mm:ss.ss)" );
   DEC_Property_Label.SetTextAlignment(TextAlign::Left | TextAlign::VertCenter);

   DEC_Hour_Edit.SetMaxWidth(editWidth);
   DEC_Hour_Edit.SetText(IsoString(dec_hms.hour));
   DEC_Hour_Edit.OnEditCompleted(
         (Edit::edit_event_handler) &EditEqCoordPropertyDialog::EditCompleted,
         *this);

   DEC_Colon1_Label.SetText( ":" );

   DEC_Minute_Edit.SetMaxWidth(editWidth);
   DEC_Minute_Edit.SetText(IsoString(dec_hms.minute));
   DEC_Minute_Edit.OnEditCompleted(
         (Edit::edit_event_handler) &EditEqCoordPropertyDialog::EditCompleted,
         *this);

   DEC_Colon2_Label.SetText( ":" );

   DEC_Second_Edit.SetMaxWidth(editWidth);
   DEC_Second_Edit.SetText(IsoString(dec_hms.second));
   DEC_Second_Edit.OnEditCompleted(
         (Edit::edit_event_handler) &EditEqCoordPropertyDialog::EditCompleted,
         *this);

   OK_PushButton.SetText( "OK" );
   OK_PushButton.OnClick(
         (Button::click_event_handler) &EditEqCoordPropertyDialog::Ok_Button_Click,
         *this);
   Cancel_PushButton.SetText( "Cancel" );
   Cancel_PushButton.OnClick(
         (Button::click_event_handler) &EditEqCoordPropertyDialog::Cancel_Button_Click,
         *this);

   RA_Property_Sizer.SetMargin(10);
   RA_Property_Sizer.SetSpacing(4);
   RA_Property_Sizer.Add(RA_Property_Label);
   RA_Property_Sizer.Add(RA_Hour_Edit);
   RA_Property_Sizer.Add(RA_Colon1_Label);
   RA_Property_Sizer.Add(RA_Minute_Edit);
   RA_Property_Sizer.Add(RA_Colon2_Label);
   RA_Property_Sizer.Add(RA_Second_Edit);
   RA_Property_Sizer.AddStretch();

   DEC_Property_Sizer.SetMargin(10);
   DEC_Property_Sizer.SetSpacing(4);
   DEC_Property_Sizer.Add(DEC_Property_Label);
   DEC_Property_Sizer.Add(DEC_Hour_Edit);
   DEC_Property_Sizer.Add(DEC_Colon1_Label);
   DEC_Property_Sizer.Add(DEC_Minute_Edit);
   DEC_Property_Sizer.Add(DEC_Colon2_Label);
   DEC_Property_Sizer.Add(DEC_Second_Edit);
   DEC_Property_Sizer.AddStretch();

   Buttons_Sizer.SetSpacing(4);
   Buttons_Sizer.AddSpacing(10);
   Buttons_Sizer.AddStretch();
   Buttons_Sizer.Add(OK_PushButton);
   Buttons_Sizer.AddStretch();
   Buttons_Sizer.Add(Cancel_PushButton);
   Buttons_Sizer.AddStretch();

   Global_Sizer.Add(RA_Property_Sizer);
   Global_Sizer.Add(DEC_Property_Sizer);
   Global_Sizer.Add(Buttons_Sizer);

   SetSizer(Global_Sizer);
}
Ejemplo n.º 22
0
ArgumentList ExtractArguments( const StringList& argv, argument_item_mode mode, ArgumentOptions options )
{
   bool noItems             = mode == ArgumentItemMode::NoItems;
   bool itemsAsFiles        = mode == ArgumentItemMode::AsFiles;
   bool itemsAsViews        = mode == ArgumentItemMode::AsViews;
   bool allowWildcards      = !noItems && options.IsFlagSet( ArgumentOption::AllowWildcards );
   bool noPreviews          = itemsAsViews && options.IsFlagSet( ArgumentOption::NoPreviews );
   bool recursiveDirSearch  = itemsAsFiles && allowWildcards && options.IsFlagSet( ArgumentOption::RecursiveDirSearch );
   bool recursiveSearchArgs = recursiveDirSearch && options.IsFlagSet( ArgumentOption::RecursiveSearchArgs );

   // This is the recursive search mode flag, controlled by --r[+|-]
   bool recursiveSearch = false;

   // The list of existing view identifiers, in case itemsAsViews = true.
   SortedStringList imageIds;

   // The list of extracted arguments
   ArgumentList arguments;

   for ( StringList::const_iterator i = argv.Begin(); i != argv.End(); ++i )
   {
      if ( i->StartsWith( '-' ) )
      {
         Argument arg( i->At( 1 ) );

         if ( recursiveSearchArgs && arg.Id() == s_recursiveSearchArg )
         {
            if ( arg.IsSwitch() )
               recursiveSearch = arg.SwitchState();
            else if ( arg.IsLiteral() )
               recursiveSearch = true;
            else
               arguments.Add( arg );
         }
         else
            arguments.Add( arg );
      }
      else
      {
         if ( noItems )
            throw ParseError( "Non-parametric arguments are not allowed", *i  );

         StringList items;

         if ( itemsAsFiles )
         {
            String fileName = *i;
            if ( fileName.StartsWith( '\"' ) )
               fileName.Delete( 0 );
            if ( fileName.EndsWith( '\"' ) )
               fileName.Delete( fileName.UpperBound() );

            fileName.Trim();
            if ( fileName.IsEmpty() )
               throw ParseError( "Empty path specification", *i );

            fileName = File::FullPath( fileName );

            if ( fileName.HasWildcards() )
            {
               if ( !allowWildcards )
                  throw ParseError( "Wildcards not allowed", fileName );

               items = SearchDirectory( fileName, recursiveSearch );
            }
            else
               items.Add( fileName );
         }
         else if ( itemsAsViews )
         {
            String viewId = *i;

            if ( !allowWildcards )
               if ( viewId.HasWildcards() )
                  throw ParseError( "Wildcards not allowed", viewId );

            size_type p = viewId.Find( "->" );

            if ( p != String::notFound )
            {
               if ( noPreviews )
                  throw ParseError( "Preview identifiers not allowed", viewId );

               String imageId = viewId.Left( p );
               if ( imageId.IsEmpty() )
                  throw ParseError( "Missing image identifier", viewId );

               String previewId = viewId.Substring( p+2 );
               if ( previewId.IsEmpty() )
                  throw ParseError( "Missing preview identifier", viewId );

               FindPreviews( items, imageId, previewId );
            }
            else
            {
               if ( viewId.HasWildcards() )
               {
                  Array<ImageWindow> W = ImageWindow::AllWindows();
                  for ( size_type i = 0; i < W.Length(); ++i )
                  {
                     View v = W[i].MainView();
                     if ( String( v.Id() ).WildMatch( viewId ) )
                        AddView( items, v );
                  }
               }
               else
               {
                  ImageWindow w = ImageWindow::WindowById( IsoString( viewId ) );
                  if ( w.IsNull() )
                     throw ParseError( "Image not found", viewId );
                  AddView( items, w.MainView() );
               }
            }
         }
         else
            items.Add( *i );

         Argument arg( *i, items );
         arguments.Add( arg );
      }
   }

   return arguments;
}
Ejemplo n.º 23
0
int LinearFitProcess::ProcessCommandLine( const StringList& argv ) const
{
   ArgumentList arguments =
   ExtractArguments( argv, ArgumentItemMode::AsViews, ArgumentOption::AllowWildcards );

   LinearFitInstance instance( this );

   bool launchInterface = false;
   int count = 0;

   for ( ArgumentList::const_iterator i = arguments.Begin(); i != arguments.End(); ++i )
   {
      const Argument& arg = *i;

      if ( arg.IsNumeric() )
      {
         if ( arg.Id() == "r0" || arg.Id() == "reject-low" )
         {
            CHECK_IN_NORM_RANGE;
            instance.rejectLow = arg.NumericValue();
         }
         else if ( arg.Id() == "r1" || arg.Id() == "reject-high" )
         {
            CHECK_IN_NORM_RANGE;
            instance.rejectHigh = arg.NumericValue();
         }
         else
            throw Error( "Unknown numeric argument: " + arg.Token() );
      }
      else if ( arg.IsString() )
      {
         if ( arg.Id() == "v" || arg.Id() == "reference-view" )
            instance.referenceViewId = arg.StringValue();
         else
            throw Error( "Unknown string argument: " + arg.Token() );
      }
      else if ( arg.IsSwitch() )
      {
         throw Error( "Unknown switch argument: " + arg.Token() );
      }
      else if ( arg.IsLiteral() )
      {
         if ( arg.Id() == "-interface" )
            launchInterface = true;
         else if ( arg.Id() == "-help" )
         {
            ShowHelp();
            return 0;
         }
         else
            throw Error( "Unknown argument: " + arg.Token() );
      }
      else if ( arg.IsItemList() )
      {
         ++count;

         if ( arg.Items().IsEmpty() )
         {
            Console().WriteLn( "No view(s) found: " + arg.Token() );
            throw;
         }

         for ( StringList::const_iterator j = arg.Items().Begin(); j != arg.Items().End(); ++j )
         {
            View v = View::ViewById( *j );
            if ( v.IsNull() )
               throw Error( "No such view: " + *j );
            if ( v.FullId() != IsoString( instance.referenceViewId ).Trimmed() )
               instance.LaunchOn( v );
            else
               Console().WarningLn( "<end><cbr>** Skipping reference view: " + v.FullId() );
         }
      }
   }

   if ( launchInterface )
      instance.LaunchInterface();
   else if ( count == 0 )
   {
      if ( ImageWindow::ActiveWindow().IsNull() )
         throw Error( "There is no active image window." );
      instance.LaunchOnCurrentView();
   }

   return 0;
}
Ejemplo n.º 24
0
 void CCDFrameInterface::StartExposureButton_Click(Button& sender, bool checked){
	 if (ThePixInsightINDIInterface!=0){
#if defined(WIN32) 
	  const char* tmpDir = getenv("TMP");
#else
	  const char* tmpDir = getenv("TMPDIR");
#endif
	   if (tmpDir!=NULL) {
		PixInsightINDIInstance* pInstance=&ThePixInsightINDIInterface->instance;
		if (pInstance==NULL)
			return;
		GUI->StartExposure_PushButton.Disable();
		INDIPropertyListItem uploadLocal;
		bool serverSendsImage=true;
		if (pInstance->getINDIPropertyItem(m_Device,"UPLOAD_MODE","UPLOAD_LOCAL",uploadLocal)){
			serverSendsImage=!(uploadLocal.PropertyValue==String("ON"));
		}

		for (int num=0; num<m_NumOfExposures;++num){

			GUI->ExpFrame_Edit.SetText(String(num));

			INDINewPropertyListItem newPropertyListItem;
			newPropertyListItem.Device=m_Device;
			newPropertyListItem.Property=String("CCD_EXPOSURE");
			newPropertyListItem.Element=String("CCD_EXPOSURE_VALUE");
			newPropertyListItem.PropertyType=String("INDI_NUMBER");
			newPropertyListItem.NewPropertyValue=String(m_ExposureDuration);

			GUI->ExposureDuration_Timer.Start();
			bool send_ok = pInstance->sendNewPropertyValue(newPropertyListItem,true/*isAsynchCall*/);

			if (!send_ok){
				break;
			}


			// TODO enable abort
			if (serverSendsImage){
				while (!pInstance->getImageDownloadedFlag() && !pInstance->getInternalAbortFlag()){Sleep(1);ProcessEvents();}
				pInstance->setImageDownloadedFlag(false);
			} else {
				INDIPropertyListItem ccdExposure;
				bool serverExposureIsBusy=false;
				// timimg problem: wait until server sends  BUSY
				do {
					pInstance->getINDIPropertyItem(m_Device,"CCD_EXPOSURE","CCD_EXPOSURE_VALUE",ccdExposure);
					Sleep(1);
					ProcessEvents();
					serverExposureIsBusy = ccdExposure.PropertyState==IPS_BUSY ;
				} while (!serverExposureIsBusy && (GUI->ExpDur_Edit.Text().ToFloat() < pcl_timeout) && !pInstance->getInternalAbortFlag());

				do {

					pInstance->getINDIPropertyItem(m_Device,"CCD_EXPOSURE","CCD_EXPOSURE_VALUE",ccdExposure);
					Sleep(1);
					ProcessEvents();
				} while((ccdExposure.PropertyState==IPS_BUSY)&& !pInstance->getInternalAbortFlag());
			}

			if (pInstance->getInternalAbortFlag()){
				// stop timer
				GUI->ExposureDuration_Timer.Stop();
				GUI->ExposureDelay_Timer.Stop();
				break;
			}

			if (serverSendsImage) {
				Array<ImageWindow> imgArray = ImageWindow::Open(String(tmpDir)+ String("/Image.fits"), IsoString("image"));

				if (imgArray.Length()!=0){
					imgArray[0].ZoomToFit( false ); // don't allow zoom > 1
					imgArray[0].Show();
				}

				if (m_saveFrame) {
					IsoString source = IsoString(String(tmpDir)+ String("/Image.fits"));
					IsoString dest   = IsoString(m_FrameFolder) + IsoString(this->m_FramePrefix) + IsoString("_") +  IsoString(num) + IsoString(".fits");

					std::ifstream infile(source.c_str(), std::ifstream::binary);
					std::ofstream outfile(dest.c_str(), std::ofstream::binary);

					// get size of file
					infile.seekg(0, infile.end);
					long size = infile.tellg();
					infile.seekg(0);

					// allocate memory for file content
					char* buffer = new char[size];

					// read content of infile
					infile.read(buffer, size);

					// write to outfile
					outfile.write(buffer, size);

					// release dynamically-allocated memory
					delete[] buffer;

					outfile.close();
					infile.close();
				}
			}
			// wait until next exposure
			if (GUI->ExpDelayTime_Edit.Text().ToInt()!=0){
				GUI->ExposureDelay_Timer.Start();
				m_isWaiting=true;
			}
			while (m_isWaiting){ProcessEvents();}
		}
		pInstance->setInternalAbortFlag(false);
		GUI->StartExposure_PushButton.Enable();
	   } 

	 }
 }
Ejemplo n.º 25
0
   static void Apply( GenericImage<P>& img, const View& view, const FluxCalibrationInstance& instance )
   {
      FITSKeywordArray inputKeywords;
      view.Window().GetKeywords( inputKeywords );

      if ( KeywordExists( inputKeywords, "FLXMIN" ) ||
           KeywordExists( inputKeywords, "FLXRANGE" ) ||
           KeywordExists( inputKeywords, "FLX2DN" ) )
      {
         throw Error( "Already calibrated image" );
      }

      if ( img.IsColor() )
         throw Error( "Can't calibrate a color image" );

      float Wc       =             instance.p_wavelength.GetValue( inputKeywords );
      float Tr       =  Max( 1.0F, instance.p_transmissivity.GetValue( inputKeywords ) );
      float Delta    =             instance.p_filterWidth.GetValue( inputKeywords );
      float Ap       =             instance.p_aperture.GetValue( inputKeywords ) / 10; // mm -> cm
      float Cobs     =  Max( 0.0F, instance.p_centralObstruction.GetValue( inputKeywords ) ) / 10; // mm -> cm
      float ExpT     =             instance.p_exposureTime.GetValue( inputKeywords );
      float AtmE     =  Max( 0.0F, instance.p_atmosphericExtinction.GetValue( inputKeywords ) );
      float G        =  Max( 1.0F, instance.p_sensorGain.GetValue( inputKeywords ) );
      float QEff     =  Max( 1.0F, instance.p_quantumEfficiency.GetValue( inputKeywords ) );

      if ( Wc <= 0 )
         throw Error( "Invalid filter wavelength" );

      if ( Tr <= 0 || Tr > 1 )
         throw Error( "Invalid filter transmissivity" );

      if ( Delta <= 0 )
         throw Error( "Invalid filter width" );

      if ( Ap <= 0 )
         throw Error( "Invalid aperture" );

      if ( Cobs < 0 || Cobs >= Ap )
         throw Error( "Invalid central obstruction area" );

      if ( ExpT <= 0 )
         throw Error( "Invalid exposure time" );

      if ( AtmE < 0 || AtmE >= 1 )
         throw Error( "Invalid atmospheric extinction" );

      if ( G <= 0 )
         throw Error( "Invalid sensor gain" );

      if ( QEff <= 0 || QEff > 1 )
         throw Error( "Invalid quantum efficiency" );

      FITSKeywordArray keywords;
      float pedestal = 0;
      bool  foundPedestal = false;
      for ( FITSKeywordArray::const_iterator i = inputKeywords.Begin(); i != inputKeywords.End(); ++i )
         if ( i->name == "PEDESTAL" )
         {
            if ( i->value.TryToFloat( pedestal ) )
               foundPedestal = true;
            pedestal /= 65535; // 2^16-1 maximum value of a 16bit CCD.
         }
         else
            keywords.Add( *i );

      if ( foundPedestal )
         Console().NoteLn( "<end><cbr><br>* FluxCalibration: PEDESTAL keyword found: " + view.FullId() );

      // double F = Wc * inv_ch * (1 - Tr) * Delta * Ap * Cobs * ExpT * AtmE * G * QEff;
      double F = Wc * inv_ch * (1 - AtmE) * Delta * ( Const<double>::pi() / 4 * ( Ap*Ap - Cobs*Cobs  ) ) * ExpT * Tr * G * QEff;

      size_type N = img.NumberOfPixels();
            typename P::sample* f   = img.PixelData( 0 );
      const typename P::sample* fN  = f + N;

      double flxMin = DBL_MAX;
      double flxMax = 0;
      for ( ; f < fN; ++f, ++img.Status() )
      {
         double I; P::FromSample( I, *f );
         I = (I - pedestal)/F;
         *f = P::ToSample( I );
         if ( I < flxMin )
            flxMin = I;
         if ( I > flxMax )
            flxMax = I;
      }

      img.Rescale();

      keywords.Add( FITSHeaderKeyword( "FLXMIN",
                                       IsoString().Format( "%.8e", flxMin ),
                                       "" ) );
      keywords.Add( FITSHeaderKeyword( "FLXRANGE",
                                       IsoString().Format( "%.8e", flxMax - flxMin ),
                                       "FLXRANGE*pixel_value + FLXMIN = erg/cm^2/s/nm" ) );
      keywords.Add( FITSHeaderKeyword( "FLX2DN",
                                       IsoString().Format( "%.8e", F*65535 ),
                                       "(FLXRANGE*pixel_value + FLXMIN)*FLX2DN = DN" ) );

      view.Window().SetKeywords( keywords );
   }
Ejemplo n.º 26
0
IsoString SandboxProcess::Category() const
{
   return IsoString(); // No category
}
IsoString INDIMountProcess::Category() const
{
   return IsoString("INDI"); // No category
}
Ejemplo n.º 28
0
static void CriticalSignalHandler( int sig_num )
{
   sigset_t x;
   sigemptyset( &x );
   sigaddset( &x, SIGSEGV );
   sigaddset( &x, SIGBUS );
   sigaddset( &x, SIGFPE );
   sigaddset( &x, SIGILL );
   sigaddset( &x, SIGPIPE );
   //sigprocmask( SIG_UNBLOCK, &x, NULL );
   pthread_sigmask( SIG_UNBLOCK, &x, NULL );

   void* addrList[ STACK_DEPTH ];
   size_t addrLen = backtrace( addrList, sizeof( addrList )/sizeof( void* ) );
   char** symbolList = backtrace_symbols( addrList, addrLen );
   IsoString details;
   if ( symbolList != NULL )
   {
      if ( symbolList[0] != NULL )
      {
         details = STACK_TRACE_TITLE + IsoString().Format( STACK_TRACE_HEADER, sig_num, symbolList[0] );
         for ( size_t i = 1; i < addrLen; ++i )
         {
            if ( symbolList[i] != NULL )
            {
               IsoString addrOffsetStr;
               IsoString demangledFuncname = GetDemangledFunctionName( symbolList[i], addrOffsetStr );
               details.AppendFormat( "%d: ", addrLen-i );
               details += demangledFuncname;
               if ( !addrOffsetStr.IsEmpty() )
               {
                  details += "(+";
                  details += addrOffsetStr;
                  details += ')';
               }
               details += '\n';
            }
         }
         details += STACK_TRACE_BOTTOM;

         fprintf( stderr, "%s", details.c_str() );
      }

      // symbolList must be freed
      free( symbolList );
   }

   switch ( sig_num )
   {
   case SIGSEGV:
      throw EUnixSegmentationViolation( details );
   case SIGBUS:
      throw EUnixBusError( details );
   case SIGFPE:
      throw EUnixFloatingPointException( details );
   case SIGILL:
      throw EUnixIllegalInstructionException( details );
   case SIGPIPE:
      throw EUnixIBrokenPipeException( details );
   default:
      throw UnixSignalException( sig_num, details );
   }
}