Ejemplo n.º 1
0
void MyFrame::ShowProgress( wxCommandEvent& WXUNUSED(event) )
{
#if wxUSE_STOPWATCH && wxUSE_LONGLONG
    // check the performance
    int countrandomnumbers = 0, count = 0;
    wxTimeSpan tsTest(0,0,0,250);
    wxDateTime DT2, DT1 = wxDateTime::UNow();
    srand(0);
    while(1)
    {
        rand();
        ++countrandomnumbers;
        if ( countrandomnumbers == 1000 )
        {
            srand(0);
            countrandomnumbers = 0;
            ++count;
            DT2 = wxDateTime::UNow();
            wxTimeSpan ts = DT2.Subtract( DT1 );
            if ( ts.IsLongerThan( tsTest ) )
            {
                break;
            }
        }
    }
    const int max = 40 * count;
#else
    static const int max = 10;
#endif // wxUSE_STOPWATCH && wxUSE_LONGLONG

    wxProgressDialog dialog(_T("Progress dialog example"),
                            _T("An informative message"),
                            max,    // range
                            this,   // parent
                            wxPD_CAN_ABORT |
                            wxPD_CAN_SKIP |
                            wxPD_APP_MODAL |
                            // wxPD_AUTO_HIDE | -- try this as well
                            wxPD_ELAPSED_TIME |
                            wxPD_ESTIMATED_TIME |
                            wxPD_REMAINING_TIME |
                            wxPD_SMOOTH);

    bool cont = true;
    bool skip = false;
    // each skip will move progress about quarter forward
    for ( int i = 0; i <= max; i = wxMin(i+(skip?int(max/4):1), max+1), skip = false )
    {
#if wxUSE_STOPWATCH && wxUSE_LONGLONG
        // do (almost) the same operations as we did for the performance test
        srand(0);
        for ( int j = 0; j < 1000; j++ )
        {
            rand();
            if ( j == 999 )
            {
                DT2 = wxDateTime::UNow();
                wxTimeSpan ts = DT2.Subtract( DT1 );
                if ( ts.IsLongerThan( tsTest ) )
                {
                    // nothing to do
                }
            }
        }
#else
        wxSleep(1);
#endif

        wxString msg;

        if ( i == max )
        {
            msg = _T("That's all, folks!");
        }
        else if ( i > max / 2 )
        {
            msg = _T("Only a half left (very long message)!");
        }

#if wxUSE_STOPWATCH && wxUSE_LONGLONG
        if ( (i % (max/100)) == 0 ) // // only 100 updates, this makes it much faster
        {
            cont = dialog.Update(i, msg, &skip);
        }
#else
        cont = dialog.Update(i, msg, &skip);
#endif

        if ( !cont )
        {
            if ( wxMessageBox(_T("Do you really want to cancel?"),
                              _T("Progress dialog question"),  // caption
                              wxYES_NO | wxICON_QUESTION) == wxYES )
                break;

            cont = true;
            dialog.Resume();
        }
    }

    if ( !cont )
    {
        wxLogStatus(wxT("Progress dialog aborted!"));
    }
    else
    {
        wxLogStatus(wxT("Countdown from %d finished"), max);
    }
}
Ejemplo n.º 2
0
bool EffectChangeSpeed::Process()
{
   // Similar to EffectSoundTouch::Process()

   // Iterate over each track.
   // Track::All is needed because this effect needs to introduce
   // silence in the sync-lock group tracks to keep sync
   this->CopyInputTracks(Track::All); // Set up mOutputTracks.
   bool bGoodResult = true;

   TrackListIterator iter(mOutputTracks);
   Track* t;
   mCurTrackNum = 0;
   mMaxNewLength = 0.0;

   mFactor = 100.0 / (100.0 + m_PercentChange);

   t = iter.First();
   while (t != NULL)
   {
      if (t->GetKind() == Track::Label) {
         if (t->GetSelected() || t->IsSyncLockSelected())
         {
            if (!ProcessLabelTrack(t)) {
               bGoodResult = false;
               break;
            }
         }
      }
      else if (t->GetKind() == Track::Wave && t->GetSelected())
      {
         WaveTrack *pOutWaveTrack = (WaveTrack*)t;
         //Get start and end times from track
         mCurT0 = pOutWaveTrack->GetStartTime();
         mCurT1 = pOutWaveTrack->GetEndTime();

         //Set the current bounds to whichever left marker is
         //greater and whichever right marker is less:
         mCurT0 = wxMax(mT0, mCurT0);
         mCurT1 = wxMin(mT1, mCurT1);

         // Process only if the right marker is to the right of the left marker
         if (mCurT1 > mCurT0) {
            //Transform the marker timepoints to samples
            sampleCount start = pOutWaveTrack->TimeToLongSamples(mCurT0);
            sampleCount end = pOutWaveTrack->TimeToLongSamples(mCurT1);

            //ProcessOne() (implemented below) processes a single track
            if (!ProcessOne(pOutWaveTrack, start, end))
            {
               bGoodResult = false;
               break;
            }
         }
         mCurTrackNum++;
      }
      else if (t->IsSyncLockSelected())
      {
         t->SyncLockAdjust(mT1, mT0 + (mT1 - mT0) * mFactor);
      }

      //Iterate to the next track
      t=iter.Next();
   }

   if (bGoodResult)
      ReplaceProcessedTracks(bGoodResult);

   mT1 = mT0 + mMaxNewLength; // Update selection.

   return bGoodResult;
}
Ejemplo n.º 3
0
char* wxFindAccelerator( const char *s )
{
#if 1
    wxUnusedVar(s);
    // VZ: this function returns incorrect keysym which completely breaks kbd
    //     handling
    return NULL;
#else
    // The accelerator text is after the \t char.
    s = strchr( s, '\t' );

    if( !s ) return NULL;

    /*
    Now we need to format it as X standard:

      input            output

        F7           --> <Key>F7
        Ctrl+N       --> Ctrl<Key>N
        Alt+k        --> Meta<Key>k
        Ctrl+Shift+A --> Ctrl Shift<Key>A

        and handle Ctrl-N & similia
    */

    static char buf[256];

    buf[0] = '\0';
    wxString tmp = s + 1; // skip TAB
    size_t index = 0;

#if defined(__INTEL_COMPILER) && 1 /* VDM auto patch */
#   pragma ivdep
#   pragma swp
#   pragma unroll
#   pragma prefetch
#   if 0
#       pragma simd noassert
#   endif
#endif /* VDM auto patch */
    while( index < tmp.length() )
    {
        size_t plus  = tmp.find( '+', index );
        size_t minus = tmp.find( '-', index );

        // neither '+' nor '-', add <Key>
        if( plus == wxString::npos && minus == wxString::npos )
        {
            strcat( buf, "<Key>" );
            strcat( buf, tmp.c_str() + index );

            return buf;
        }

        // OK: npos is big and positive
        size_t sep = wxMin( plus, minus );
        wxString mod = tmp.substr( index, sep - index );

        // Ctrl  -> Ctrl
        // Shift -> Shift
        // Alt   -> Meta
        if( mod == "Alt" )
            mod = "Meta";

        if( buf[0] )
            strcat( buf, " " );

        strcat( buf, mod.c_str() );

        index = sep + 1;
    }

    return NULL;
#endif
}
Ejemplo n.º 4
0
// SetListColumnOrder() is called mostly from OnRestoreState(), so we don't
// call OnSaveState() from here.  CDlgHiddenColumns calls OnSaveState()
// when we really need to do that.
//
// Unfortunately, we have no way of immediately calling OnSaveState() when
// the user manually reorders columns because that does not generate a
// notification from MS Windows so wxWidgets can't generate an event.
void CBOINCListCtrl::SetListColumnOrder(wxArrayString& orderArray) {
    int i, stdCount, columnPosition;
    int colCount = GetColumnCount();
    int shownColCount = orderArray.GetCount();
    int columnIndex = 0;    // Column number among shown columns before re-ordering
    int columnID = 0;       // ID of column, e.g. COLUMN_PROJECT, COLUMN_STATUS, etc.
    int sortColumnIndex = -1;
    wxArrayInt aOrder(shownColCount);
    
    CBOINCBaseView* pView = (CBOINCBaseView*)GetParent();
    wxASSERT(wxDynamicCast(pView, CBOINCBaseView));
    
    pView->m_iColumnIndexToColumnID.Clear();
    for (i=colCount-1; i>=0; --i) {
        DeleteColumn(i);
    }
    
    stdCount = pView->m_aStdColNameOrder->GetCount();

    pView->m_iColumnIDToColumnIndex.Clear();
    for (columnID=0; columnID<stdCount; ++columnID) {
        pView->m_iColumnIDToColumnIndex.Add(-1);
    }
    
    for (columnID=0; columnID<stdCount; ++columnID) {
        for (columnPosition=0; columnPosition<shownColCount; ++columnPosition) {
            if (orderArray[columnPosition].IsSameAs(pView->m_aStdColNameOrder->Item(columnID))) {
                aOrder[columnPosition] = columnIndex;
                pView->AppendColumn(columnID);
                pView->m_iColumnIndexToColumnID.Add(columnID);
                pView->m_iColumnIDToColumnIndex[columnID] = columnIndex;

                ++columnIndex;
                break;
            }
        }
    }
    
    // Prevent a crash bug if we just changed to a new locale.
    //
    // If a column has the same name in both the old and new locale, we guard against
    // changing the sort column to that column.
    //
    // CBOINCListCtrl::OnRestoreState() may have incorrectly added the column names in
    // the new locale as "new" columns, so check against both shownColCount and stdCount.
    int limit = wxMin(shownColCount, stdCount);
    if (columnIndex < limit) {
        SetStandardColumnOrder();
        for (columnID=0; columnID<limit; ++columnID) {
            aOrder[columnID] = columnID;
            pView->AppendColumn(columnID);
            pView->m_iColumnIndexToColumnID.Add(columnID);
            pView->m_iColumnIDToColumnIndex[columnID] = columnID;
        }
    }
    
    // If sort column is now hidden, set the new first column as sort column
    if (pView->m_iSortColumnID >= 0) {
        sortColumnIndex = pView->m_iColumnIDToColumnIndex[pView->m_iSortColumnID];
        if (sortColumnIndex < 0) {
            pView->m_iSortColumnID = pView->m_iColumnIndexToColumnID[0];
            pView->m_bReverseSort = false;
            pView->SetSortColumn(0);
        } else {
            // Redraw the sort arrow, etc.
            pView->SetSortColumn(sortColumnIndex);
        }
    }
    
#ifdef wxHAS_LISTCTRL_COLUMN_ORDER
    colCount = GetColumnCount();
    if ((shownColCount > 0) && (shownColCount <= stdCount) && (colCount == shownColCount)) {
        SetColumnsOrder(aOrder);
    }
#endif
}
Ejemplo n.º 5
0
// More efficient: erase and redraw simultaneously if possible
bool wxGenericDragImage::RedrawImage(const wxPoint& oldPos,
                                     const wxPoint& newPos,
                                     bool eraseOld, bool drawNew)
{
    if (!m_windowDC)
        return false;

#ifdef wxHAS_NATIVE_OVERLAY
    wxUnusedVar(oldPos);

    wxDCOverlay dcoverlay( m_overlay, (wxWindowDC*) m_windowDC ) ;
    if ( eraseOld )
        dcoverlay.Clear() ;
    if (drawNew)
        DoDrawImage(*m_windowDC, newPos);
#else // !wxHAS_NATIVE_OVERLAY
    wxBitmap* backing = (m_pBackingBitmap ? m_pBackingBitmap : (wxBitmap*) & m_backingBitmap);
    if (!backing->Ok())
        return false;

    wxRect oldRect(GetImageRect(oldPos));
    wxRect newRect(GetImageRect(newPos));

    wxRect fullRect;

    // Full rect: the combination of both rects
    if (eraseOld && drawNew)
    {
        int oldRight = oldRect.GetRight();
        int oldBottom = oldRect.GetBottom();
        int newRight = newRect.GetRight();
        int newBottom = newRect.GetBottom();

        wxPoint topLeft = wxPoint(wxMin(oldPos.x, newPos.x), wxMin(oldPos.y, newPos.y));
        wxPoint bottomRight = wxPoint(wxMax(oldRight, newRight), wxMax(oldBottom, newBottom));

        fullRect.x = topLeft.x; fullRect.y = topLeft.y;
        fullRect.SetRight(bottomRight.x);
        fullRect.SetBottom(bottomRight.y);
    }
    else if (eraseOld)
        fullRect = oldRect;
    else if (drawNew)
        fullRect = newRect;

    // Make the bitmap bigger than it need be, so we don't
    // keep reallocating all the time.
    int excess = 50;

    if (!m_repairBitmap.Ok() || (m_repairBitmap.GetWidth() < fullRect.GetWidth() || m_repairBitmap.GetHeight() < fullRect.GetHeight()))
    {
        m_repairBitmap = wxBitmap(fullRect.GetWidth() + excess, fullRect.GetHeight() + excess);
    }

    wxMemoryDC memDC;
    memDC.SelectObject(* backing);

    wxMemoryDC memDCTemp;
    memDCTemp.SelectObject(m_repairBitmap);

    // Draw the backing bitmap onto the repair bitmap.
    // If full-screen, we may have specified the rect on the
    // screen that we're using for our backing bitmap.
    // So subtract this when we're blitting from the backing bitmap
    // (translate from screen to backing-bitmap coords).

    memDCTemp.Blit(0, 0, fullRect.GetWidth(), fullRect.GetHeight(), & memDC, fullRect.x - m_boundingRect.x, fullRect.y - m_boundingRect.y);

    // If drawing, draw the image onto the mem DC
    if (drawNew)
    {
        wxPoint pos(newPos.x - fullRect.x, newPos.y - fullRect.y) ;
        DoDrawImage(memDCTemp, pos);
    }

    // Now blit to the window
    // Finally, blit the temp mem DC to the window.
    m_windowDC->Blit(fullRect.x, fullRect.y, fullRect.width, fullRect.height, & memDCTemp, 0, 0);

    memDCTemp.SelectObject(wxNullBitmap);
    memDC.SelectObject(wxNullBitmap);
#endif // wxHAS_NATIVE_OVERLAY/!wxHAS_NATIVE_OVERLAY

    return true;
}
Ejemplo n.º 6
0
void wxsGrid::OnBuildCreatingCode()
{
    switch ( GetLanguage() )
    {
        case wxsCPP:
        {
            AddHeader(_T("<wx/grid.h>"),GetInfo().ClassName,0);
            AddHeader(_T("<wx/grid.h>"),_T("wxGridEvent"),0);

            Codef( _T("%C(%W, %I, %P, %S, %T, %N);\n") );

            if ( GetPropertiesFlags() & flSource )
            {
                if ( m_ColsCount>=0 && m_RowsCount>=0 && (m_ColsCount>0 || m_RowsCount>0) )
                {
                    Codef( _T("%ACreateGrid(%d,%d);\n"), m_RowsCount, m_ColsCount );
                    BuildSetupWindowCode();

                    Codef( _T("%AEnableEditing(%b);\n"),  !m_ReadOnly);
                    Codef( _T("%AEnableGridLines(%b);\n"), m_GridLines);

                    if (m_LabelRowHeight > 0) Codef(_T("%ASetColLabelSize(%d);\n"), m_LabelRowHeight);
                    if (m_LabelColWidth  > 0) Codef(_T("%ASetRowLabelSize(%d);\n"), m_LabelColWidth);

                    if (m_DefaultRowSize  > 0) Codef(_T("%ASetDefaultRowSize(%d, %b);\n"), m_DefaultRowSize, true);
                    if (m_DefaultColSize  > 0) Codef(_T("%ASetDefaultColSize(%d, %b);\n"), m_DefaultColSize, true);

                    wxString ss = m_LabelTextColour.BuildCode( GetCoderContext() );
                    if (ss.Len() > 0) Codef(_T("%ASetLabelTextColour(%s);\n"), ss.wx_str());

                    ss = GetCoderContext()->GetUniqueName( _T("GridLabelFont") );
                    wxString tt = m_LabelFont.BuildFontCode(ss, GetCoderContext());
                    if (tt.Len() > 0)
                    {
                        Codef(_T("%s"), tt.wx_str());
                        Codef(_T("%ASetLabelFont(%s);\n"), ss.wx_str());
                    }

                    int n = wxMin( (int)m_ColLabels.GetCount(), m_ColsCount );
                    for ( int i=0; i<n; i++ )
                    {
                        Codef(_T("%ASetColLabelValue(%d, %t);\n"), i, m_ColLabels[i].wx_str());
                    }

                    n = wxMin( (int)m_RowLabels.GetCount(), m_RowsCount );
                    for ( int i=0; i<n; i++)
                    {
                        Codef(_T("%ASetRowLabelValue(%d, %t);\n"), i, m_RowLabels[i].wx_str());
                    }

                    n = (int)m_CellText.GetCount();
                    int i = 0;
                    for ( int j=0; j<m_RowsCount && i<n; j++ )
                    {
                        for ( int k=0; k<m_ColsCount && i<n; k++, i++ )
                        {
                            Codef( _T("%ASetCellValue(%d, %d, %t);\n"), j, k, m_CellText[i].wx_str());
                        }
                    }

                    // default cell font and text colour

                    Codef(_T("%ASetDefaultCellFont( %AGetFont() );\n"));

                    Codef(_T("%ASetDefaultCellTextColour( %AGetForegroundColour() );\n"));

                }
            }

            return;
        }

        case wxsUnknownLanguage: // fall-through
        default:
        {
            wxsCodeMarks::Unknown(_T("wxsGrid::OnBuildCreatingCode"),GetLanguage());
        }
    }
}
Ejemplo n.º 7
0
bool EffectSBSMS::Process()
{
   bool bGoodResult = true;

   //Iterate over each track
   //Track::All is needed because this effect needs to introduce silence in the group tracks to keep sync
   this->CopyInputTracks(Track::All); // Set up mOutputTracks.
   TrackListIterator iter(mOutputTracks);
   Track* t;
   mCurTrackNum = 0;

   double maxDuration = 0.0;

   // Must sync if selection length will change
   bool mustSync = (rateStart != rateEnd);
   Slide rateSlide(rateSlideType,rateStart,rateEnd);
   Slide pitchSlide(pitchSlideType,pitchStart,pitchEnd);
   mTotalStretch = rateSlide.getTotalStretch();

   t = iter.First();
   while (t != NULL) {
      if (t->GetKind() == Track::Label &&
            (t->GetSelected() || (mustSync && t->IsSyncLockSelected())) )
      {
         if (!ProcessLabelTrack(t)) {
            bGoodResult = false;
            break;
         }
      }
      else if (t->GetKind() == Track::Wave && t->GetSelected() )
      {
         WaveTrack* leftTrack = (WaveTrack*)t;

         //Get start and end times from track
         mCurT0 = leftTrack->GetStartTime();
         mCurT1 = leftTrack->GetEndTime();

         //Set the current bounds to whichever left marker is
         //greater and whichever right marker is less
         mCurT0 = wxMax(mT0, mCurT0);
         mCurT1 = wxMin(mT1, mCurT1);

         // Process only if the right marker is to the right of the left marker
         if (mCurT1 > mCurT0) {
            sampleCount start;
            sampleCount end;
            start = leftTrack->TimeToLongSamples(mCurT0);
            end = leftTrack->TimeToLongSamples(mCurT1);

            WaveTrack* rightTrack = NULL;
            if (leftTrack->GetLinked()) {
               double t;
               rightTrack = (WaveTrack*)(iter.Next());

               //Adjust bounds by the right tracks markers
               t = rightTrack->GetStartTime();
               t = wxMax(mT0, t);
               mCurT0 = wxMin(mCurT0, t);
               t = rightTrack->GetEndTime();
               t = wxMin(mT1, t);
               mCurT1 = wxMax(mCurT1, t);

               //Transform the marker timepoints to samples
               start = leftTrack->TimeToLongSamples(mCurT0);
               end = leftTrack->TimeToLongSamples(mCurT1);

               mCurTrackNum++; // Increment for rightTrack, too.
            }
            sampleCount trackStart = leftTrack->TimeToLongSamples(leftTrack->GetStartTime());
            sampleCount trackEnd = leftTrack->TimeToLongSamples(leftTrack->GetEndTime());

            // SBSMS has a fixed sample rate - we just convert to its sample rate and then convert back
            float srTrack = leftTrack->GetRate();
            float srProcess = bLinkRatePitch?srTrack:44100.0;

            // the resampler needs a callback to supply its samples
            ResampleBuf rb;
            sampleCount maxBlockSize = leftTrack->GetMaxBlockSize();
            rb.blockSize = maxBlockSize;
            rb.buf = (audio*)calloc(rb.blockSize,sizeof(audio));
            rb.leftTrack = leftTrack;
            rb.rightTrack = rightTrack?rightTrack:leftTrack;
            rb.leftBuffer = (float*)calloc(maxBlockSize,sizeof(float));
            rb.rightBuffer = (float*)calloc(maxBlockSize,sizeof(float));

            // Samples in selection
            sampleCount samplesIn = end-start;

            // Samples for SBSMS to process after resampling
            sampleCount samplesToProcess = (sampleCount) ((float)samplesIn*(srProcess/srTrack));

            SlideType outSlideType;
            SBSMSResampleCB outResampleCB;

            sampleCount processPresamples = 0;
            sampleCount trackPresamples = 0;

            if(bLinkRatePitch) {
              rb.bPitch = true;
              outSlideType = rateSlideType;
              outResampleCB = resampleCB;
              rb.offset = start;
              rb.end = end;
              rb.iface = new SBSMSInterfaceSliding(&rateSlide,&pitchSlide,
                                                       bPitchReferenceInput,
                                                       samplesToProcess,0,
                                                       NULL);
            } else {
              rb.bPitch = false;
              outSlideType = (srProcess==srTrack?SlideIdentity:SlideConstant);
              outResampleCB = postResampleCB;
              rb.ratio = srProcess/srTrack;
              rb.quality = new SBSMSQuality(&SBSMSQualityStandard);
              rb.resampler = new Resampler(resampleCB, &rb, srProcess==srTrack?SlideIdentity:SlideConstant);
              rb.sbsms = new SBSMS(rightTrack?2:1,rb.quality,true);
              rb.SBSMSBlockSize = rb.sbsms->getInputFrameSize();
              rb.SBSMSBuf = (audio*)calloc(rb.SBSMSBlockSize,sizeof(audio));

              processPresamples = wxMin(rb.quality->getMaxPresamples(),
                                        (long)((float)(start-trackStart)*(srProcess/srTrack)));
              trackPresamples = wxMin(start-trackStart,
                                      (long)((float)(processPresamples)*(srTrack/srProcess)));
              rb.offset = start - trackPresamples;
              rb.end = trackEnd;
              rb.iface = new SBSMSEffectInterface(rb.resampler,
                                                      &rateSlide,&pitchSlide,
                                                      bPitchReferenceInput,
                                                      samplesToProcess,processPresamples,
                                                      rb.quality);
            }

            Resampler resampler(outResampleCB,&rb,outSlideType);

            audio outBuf[SBSMSOutBlockSize];
            float outBufLeft[2*SBSMSOutBlockSize];
            float outBufRight[2*SBSMSOutBlockSize];

            // Samples in output after SBSMS
            sampleCount samplesToOutput = rb.iface->getSamplesToOutput();

            // Samples in output after resampling back
            sampleCount samplesOut = (sampleCount) ((float)samplesToOutput * (srTrack/srProcess));

            // Duration in track time
            double duration =  (mCurT1-mCurT0) * mTotalStretch;

            if(duration > maxDuration)
               maxDuration = duration;

            TimeWarper *warper = createTimeWarper(mCurT0,mCurT1,maxDuration,rateStart,rateEnd,rateSlideType);
            SetTimeWarper(warper);

            rb.outputLeftTrack = mFactory->NewWaveTrack(leftTrack->GetSampleFormat(),
                                                        leftTrack->GetRate());
            if(rightTrack)
               rb.outputRightTrack = mFactory->NewWaveTrack(rightTrack->GetSampleFormat(),
                                                            rightTrack->GetRate());
            long pos = 0;
            long outputCount = -1;

            // process
            while(pos<samplesOut && outputCount) {
               long frames;
               if(pos+SBSMSOutBlockSize>samplesOut) {
                  frames = samplesOut - pos;
               } else {
                  frames = SBSMSOutBlockSize;
               }
               outputCount = resampler.read(outBuf,frames);
               for(int i = 0; i < outputCount; i++) {
                  outBufLeft[i] = outBuf[i][0];
                  if(rightTrack)
                     outBufRight[i] = outBuf[i][1];
               }
               pos += outputCount;
               rb.outputLeftTrack->Append((samplePtr)outBufLeft, floatSample, outputCount);
               if(rightTrack)
                  rb.outputRightTrack->Append((samplePtr)outBufRight, floatSample, outputCount);

               double frac = (double)pos/(double)samplesOut;
               int nWhichTrack = mCurTrackNum;
               if(rightTrack) {
                  nWhichTrack = 2*(mCurTrackNum/2);
                  if (frac < 0.5)
                     frac *= 2.0; // Show twice as far for each track, because we're doing 2 at once.
                  else {
                     nWhichTrack++;
                     frac -= 0.5;
                     frac *= 2.0; // Show twice as far for each track, because we're doing 2 at once.
                  }
               }
               if (TrackProgress(nWhichTrack, frac))
                  return false;
            }
            rb.outputLeftTrack->Flush();
            if(rightTrack)
               rb.outputRightTrack->Flush();

            bool bResult =
               leftTrack->ClearAndPaste(mCurT0, mCurT1, rb.outputLeftTrack,
                                          true, false, GetTimeWarper());
            wxASSERT(bResult); // TO DO: Actually handle this.

            if(rightTrack)
            {
               bResult =
                  rightTrack->ClearAndPaste(mCurT0, mCurT1, rb.outputRightTrack,
                                             true, false, GetTimeWarper());
               wxASSERT(bResult); // TO DO: Actually handle this.
            }
         }
         mCurTrackNum++;
      }
      else if (mustSync && t->IsSyncLockSelected())
      {
         t->SyncLockAdjust(mCurT1, mCurT0 + (mCurT1 - mCurT0) * mTotalStretch);
      }
      //Iterate to the next track
      t = iter.Next();
   }

   if (bGoodResult)
      ReplaceProcessedTracks(bGoodResult);

   // Update selection
   mT0 = mCurT0;
   mT1 = mCurT0 + maxDuration;

   return bGoodResult;
}
Ejemplo n.º 8
0
void Styler_SearchHL::Style(StyleRun& sr) {
	const unsigned int rstart =  sr.GetRunStart();
	const unsigned int rend = sr.GetRunEnd();

	// Style the run with search ranges
	if (!m_searchRanges.empty()) {
		for (size_t i = 0;  i < m_searchRanges.size(); ++i) {
			const interval& r = m_searchRanges[i];

			if (r.end > rstart && r.start < rend) {
				unsigned int start = wxMax(rstart, r.start);
				unsigned int end   = wxMin(rend, r.end);
				sr.SetBackgroundColor(start, end, m_rangeColor);

				//const unsigned int cursor = m_cursors[i];
				//if (cursor > rstart && cursor < rend) sr.SetBackgroundColor(cursor, cursor, m_hlcolor);
			}
		}
	}

	// No need for more styling if no search text
	if (m_text.empty()) return;

	// Extend stylerun start/end to get better search results (round up to whole EXTSIZEs)
	unsigned int sr_start = rstart> 100 ? rstart - 100 : 0;
	const unsigned int ext_end = ((rend/EXTSIZE) * EXTSIZE) + EXTSIZE;
	unsigned int sr_end = ext_end < m_lines.GetLength() ? ext_end : m_lines.GetLength();

	// Make sure the extended positions are valid
	cxLOCKDOC_READ(m_doc)
		sr_start = doc.GetValidCharPos(sr_start);
		if (sr_end != m_lines.GetLength()) sr_end = doc.GetValidCharPos(sr_end);
	cxENDLOCK

	//wxLogDebug("Style %u %u", rstart, rend);
	//wxLogDebug(" %u %u - %u %u", sr_start, sr_end, m_search_start, m_search_end);
	// Check if we need to do a new search
	if (sr_start < m_search_start || m_search_end < sr_end) {
		// Check if there is overlap so we can just extend the search area
		if (sr_end > m_search_start && sr_start < m_search_end) {
			sr_start = wxMin(sr_start, m_search_start);
			sr_end = wxMax(sr_end, m_search_end);
		}
		else {
			// Else we have to move it
			m_matches.clear();
			m_search_start = 0;
			m_search_end = 0;
		}

		// Do the search
		if (sr_start < m_search_start) {
			// Search from top
			DoSearch(sr_start, sr_end);
		}
		else if (sr_end > m_search_end) {
			// Search from bottom
			DoSearch(sr_start, sr_end, true);
		}
		else wxASSERT(false);

		m_search_start = sr_start;
		m_search_end = sr_end;
	}

	// Style the run with matches
	for (vector<interval>::iterator p = m_matches.begin(); p != m_matches.end(); ++p) {
		if (p->start > rend) break;

		// Check for overlap (or zero-length sel at start-of-line)
		if ((p->end > rstart && p->start < rend) || (p->start == p->end && p->end == rstart)) {
			unsigned int start = wxMax(rstart, p->start);
			unsigned int end   = wxMin(rend, p->end);

			// Only draw it if it is in range
			if (!m_searchRanges.empty()) {
				bool inRange = false;
				for (vector<interval>::const_iterator s = m_searchRanges.begin(); s != m_searchRanges.end(); ++s) {
					if (start >= s->start && start < s->end) {
						inRange = true;
						break;
					}
				}
				if (!inRange) continue;
			}

			sr.SetBackgroundColor(start, end, m_hlcolor);
			sr.SetShowHidden(start, end, true);
		}
	}
}
Ejemplo n.º 9
0
/// Creates a suitable HTML fragment for a definition
wxString wxRichTextStyleListBox::CreateHTML(wxRichTextStyleDefinition* def) const
{
    // TODO: indicate list format for list style types

    wxString str;

    bool isCentred = false;

    wxRichTextAttr attr(def->GetStyleMergedWithBase(GetStyleSheet()));

    if (attr.HasAlignment() && attr.GetAlignment() == wxTEXT_ALIGNMENT_CENTRE)
        isCentred = true;

    if (isCentred)
        str << wxT("<center>");


    str << wxT("<table><tr>");

    if (attr.GetLeftIndent() > 0)
    {
        wxClientDC dc((wxWindow*) this);

        str << wxT("<td width=") << wxMin(50, (ConvertTenthsMMToPixels(dc, attr.GetLeftIndent())/2)) << wxT("></td>");
    }

    if (isCentred)
        str << wxT("<td nowrap align=\"center\">");
    else
        str << wxT("<td nowrap>");

#ifdef __WXMSW__
    int size = 2;
#else
    int size = 3;
#endif

    // Guess a standard font size
    int stdFontSize = 0;

    // First see if we have a default/normal style to base the size on
    wxString normalTranslated(_("normal"));
    wxString defaultTranslated(_("default"));
    size_t i;
    for (i = 0; i < GetStyleSheet()->GetParagraphStyleCount(); i++)
    {
        wxRichTextStyleDefinition* d = GetStyleSheet()->GetParagraphStyle(i);
        wxString name = d->GetName().Lower();
        if (name.Find(wxT("normal")) != wxNOT_FOUND || name.Find(normalTranslated) != wxNOT_FOUND ||
            name.Find(wxT("default")) != wxNOT_FOUND || name.Find(defaultTranslated) != wxNOT_FOUND)
        {
            wxRichTextAttr attr2(d->GetStyleMergedWithBase(GetStyleSheet()));
            if (attr2.HasFontPointSize())
            {
                stdFontSize = attr2.GetFontSize();
                break;
            }
        }
    }

    if (stdFontSize == 0)
    {
        // Look at sizes up to 20 points, and see which is the most common
        wxArrayInt sizes;
        size_t maxSize = 20;
        for (i = 0; i <= maxSize; i++)
            sizes.Add(0);
        for (i = 0; i < m_styleNames.GetCount(); i++)
        {
            wxRichTextStyleDefinition* d = GetStyle(i);
            if (d)
            {
                wxRichTextAttr attr2(d->GetStyleMergedWithBase(GetStyleSheet()));
                if (attr2.HasFontPointSize())
                {
                    if (attr2.GetFontSize() <= (int) maxSize)
                        sizes[attr2.GetFontSize()] ++;
                }
            }
        }
        int mostCommonSize = 0;
        for (i = 0; i <= maxSize; i++)
        {
            if (sizes[i] > mostCommonSize)
                mostCommonSize = i;
        }
        if (mostCommonSize > 0)
            stdFontSize = mostCommonSize;
    }

    if (stdFontSize == 0)
        stdFontSize = 12;

    int thisFontSize = attr.HasFontPointSize() ? attr.GetFontSize() : stdFontSize;

    if (thisFontSize < stdFontSize)
        size --;
    else if (thisFontSize > stdFontSize)
        size ++;

    str += wxT("<font");

    str << wxT(" size=") << size;

    if (!attr.GetFontFaceName().IsEmpty())
        str << wxT(" face=\"") << attr.GetFontFaceName() << wxT("\"");

    if (attr.GetTextColour().IsOk())
        str << wxT(" color=\"#") << ColourToHexString(attr.GetTextColour()) << wxT("\"");

    str << wxT(">");

    bool hasBold = false;
    bool hasItalic = false;
    bool hasUnderline = false;

    if (attr.GetFontWeight() == wxFONTWEIGHT_BOLD)
        hasBold = true;
    if (attr.GetFontStyle() == wxFONTSTYLE_ITALIC)
        hasItalic = true;
    if (attr.GetFontUnderlined())
        hasUnderline = true;

    if (hasBold)
        str << wxT("<b>");
    if (hasItalic)
        str << wxT("<i>");
    if (hasUnderline)
        str << wxT("<u>");

    str += def->GetName();

    if (hasUnderline)
        str << wxT("</u>");
    if (hasItalic)
        str << wxT("</i>");
    if (hasBold)
        str << wxT("</b>");

    if (isCentred)
        str << wxT("</centre>");

    str << wxT("</font>");

    str << wxT("</td></tr></table>");

    if (isCentred)
        str << wxT("</center>");

    return str;
}
Ejemplo n.º 10
0
bool EffectSoundTouch::Process()
{
   // Assumes that mSoundTouch has already been initialized
   // by the subclass for subclass-specific parameters. The
   // time warper should also be set.

   // Check if this effect will alter the selection length; if so, we need
   // to operate on sync-lock selected tracks.
   bool mustSync = true;
   if (mT1 == GetTimeWarper()->Warp(mT1)) {
      mustSync = false;
   }

   //Iterate over each track
   // Needs Track::All for sync-lock grouping.
   this->CopyInputTracks(Track::All);
   bool bGoodResult = true;

   TrackListIterator iter(mOutputTracks);
   Track* t;
   mCurTrackNum = 0;
   m_maxNewLength = 0.0;

   t = iter.First();
   while (t != NULL) {
      if (t->GetKind() == Track::Label &&
            (t->GetSelected() || (mustSync && t->IsSyncLockSelected())) )
      {
         if (!ProcessLabelTrack(t))
         {
            bGoodResult = false;
            break;
         }
      }
#ifdef USE_MIDI
      else if (t->GetKind() == Track::Note &&
               (t->GetSelected() || (mustSync && t->IsSyncLockSelected())))
      {
         if (!ProcessNoteTrack(t))
         {
            bGoodResult = false;
            break;
         }
      }
#endif
      else if (t->GetKind() == Track::Wave && t->GetSelected())
      {
         WaveTrack* leftTrack = (WaveTrack*)t;
         //Get start and end times from track
         mCurT0 = leftTrack->GetStartTime();
         mCurT1 = leftTrack->GetEndTime();

         //Set the current bounds to whichever left marker is
         //greater and whichever right marker is less
         mCurT0 = wxMax(mT0, mCurT0);
         mCurT1 = wxMin(mT1, mCurT1);

         // Process only if the right marker is to the right of the left marker
         if (mCurT1 > mCurT0) {
            sampleCount start, end;

            if (leftTrack->GetLinked()) {
               double t;
               WaveTrack* rightTrack = (WaveTrack*)(iter.Next());

               //Adjust bounds by the right tracks markers
               t = rightTrack->GetStartTime();
               t = wxMax(mT0, t);
               mCurT0 = wxMin(mCurT0, t);
               t = rightTrack->GetEndTime();
               t = wxMin(mT1, t);
               mCurT1 = wxMax(mCurT1, t);

               //Transform the marker timepoints to samples
               start = leftTrack->TimeToLongSamples(mCurT0);
               end = leftTrack->TimeToLongSamples(mCurT1);

               //Inform soundtouch there's 2 channels
               mSoundTouch->setChannels(2);

               //ProcessStereo() (implemented below) processes a stereo track
               if (!ProcessStereo(leftTrack, rightTrack, start, end))
               {
                  bGoodResult = false;
                  break;
               }
               mCurTrackNum++; // Increment for rightTrack, too.
            } else {
               //Transform the marker timepoints to samples
               start = leftTrack->TimeToLongSamples(mCurT0);
               end = leftTrack->TimeToLongSamples(mCurT1);

               //Inform soundtouch there's a single channel
               mSoundTouch->setChannels(1);

               //ProcessOne() (implemented below) processes a single track
               if (!ProcessOne(leftTrack, start, end))
               {
                  bGoodResult = false;
                  break;
               }
            }
         }
         mCurTrackNum++;
      }
      else if (mustSync && t->IsSyncLockSelected()) {
         t->SyncLockAdjust(mT1, GetTimeWarper()->Warp(mT1));
      }

      //Iterate to the next track
      t = iter.Next();
   }

   if (bGoodResult)
      ReplaceProcessedTracks(bGoodResult);

   delete mSoundTouch;
   mSoundTouch = NULL;

//   mT0 = mCurT0;
//   mT1 = mCurT0 + m_maxNewLength; // Update selection.

   return bGoodResult;
}
Ejemplo n.º 11
0
void DashboardInstrument_WindDirHistory::SetData(int st, double data, wxString unit)
{
  if (st == OCPN_DBP_STC_TWD || st == OCPN_DBP_STC_TWS) {
    if (st == OCPN_DBP_STC_TWD) {
      m_WindDir = data;
      if(m_DirRecCnt++ <=5) m_DirStartVal+=data;
    }
    if (st == OCPN_DBP_STC_TWS) {
      m_WindSpd = data;
      if(m_SpdRecCnt++<=5) m_SpdStartVal+=data;
    }
    if ( m_SpdRecCnt == 5 && m_DirRecCnt == 5) {
      m_WindSpd=  m_SpdStartVal/5;
      m_WindDir = m_DirStartVal/5;
      m_oldDirVal=m_WindDir; // make sure we don't get a diff > or <180 in the initial run
    }
    //start working after we collected 5 records each, as start values for the smoothed curves
    if (m_SpdRecCnt > 5 && m_DirRecCnt > 5) {
      m_IsRunning=true;
      m_SampleCount = m_SampleCount<WIND_RECORD_COUNT? m_SampleCount+1:WIND_RECORD_COUNT;
      m_MaxWindDir = 0;
      m_MinWindDir = 360;
      m_MaxWindSpd = 0;
      //data shifting
      for (int idx = 1; idx < WIND_RECORD_COUNT; idx++) {
        if (WIND_RECORD_COUNT-m_SampleCount <= idx)
          m_MinWindDir = wxMin(m_ArrayWindDirHistory[idx],m_MinWindDir);
        m_MaxWindDir = wxMax(m_ArrayWindDirHistory[idx-1],m_MaxWindDir);
        m_MaxWindSpd   = wxMax(m_ArrayWindSpdHistory[idx-1],m_MaxWindSpd);
        m_ArrayWindDirHistory[idx-1] = m_ArrayWindDirHistory[idx];
        m_ArrayWindSpdHistory[idx-1] = m_ArrayWindSpdHistory[idx];
        m_ExpSmoothArrayWindSpd[idx-1]=m_ExpSmoothArrayWindSpd[idx];
        m_ExpSmoothArrayWindDir[idx-1]=m_ExpSmoothArrayWindDir[idx];
        m_ArrayRecTime[idx-1]=m_ArrayRecTime[idx];
      }
      double diff=m_WindDir - m_oldDirVal;
      if (diff < -270) {
        m_WindDir+=360;
      }
      else
      if( diff > 270) {
        m_WindDir-=360;
      }
      m_ArrayWindDirHistory[WIND_RECORD_COUNT-1] = m_WindDir;
      m_ArrayWindSpdHistory[WIND_RECORD_COUNT-1] = m_WindSpd;
      if( m_SampleCount<2) {
        m_ArrayWindSpdHistory[WIND_RECORD_COUNT-2] = m_WindSpd;
        m_ExpSmoothArrayWindSpd[WIND_RECORD_COUNT-2]= m_WindSpd;
        m_ArrayWindDirHistory[WIND_RECORD_COUNT-2] = m_WindDir;
        m_ExpSmoothArrayWindDir[WIND_RECORD_COUNT-2]= m_WindDir;
      }
      m_ExpSmoothArrayWindSpd[WIND_RECORD_COUNT-1]=alpha*m_ArrayWindSpdHistory[WIND_RECORD_COUNT-2]+(1-alpha)*m_ExpSmoothArrayWindSpd[WIND_RECORD_COUNT-2];
      m_ExpSmoothArrayWindDir[WIND_RECORD_COUNT-1]=alpha*m_ArrayWindDirHistory[WIND_RECORD_COUNT-2]+(1-alpha)*m_ExpSmoothArrayWindDir[WIND_RECORD_COUNT-2];
      m_ArrayRecTime[WIND_RECORD_COUNT-1]=wxDateTime::Now();
      m_oldDirVal=m_ExpSmoothArrayWindDir[WIND_RECORD_COUNT-1];
      //include the new/latest value in the max/min value test too
      m_MaxWindDir = wxMax(m_WindDir,m_MaxWindDir);
      m_MinWindDir = wxMin(m_WindDir,m_MinWindDir);
      m_MaxWindSpd   = wxMax(m_WindSpd,m_MaxWindSpd);
      //get the overall max Wind Speed
      m_TotalMaxWindSpd = wxMax(m_WindSpd,m_TotalMaxWindSpd);

      // set wind angle scale to full +/- 90° depending on the real max/min value recorded
      SetMinMaxWindScale();
    }
  }
}
Ejemplo n.º 12
0
void BacklashTool::DecMeasurementStep(const PHD_Point& currentCamLoc)
{
    double decDelta = 0.;
    double amt = 0;
    // double fakeDeltas []= {0, -5, -2, 2, 4, 5, 5, 5, 5 };
    PHD_Point currMountLocation;
    try
    {
        if (m_scope->TransformCameraCoordinatesToMountCoordinates(currentCamLoc, currMountLocation))
            throw ERROR_INFO("BLT: CamToMount xForm failed");
        if (m_bltState != BLT_STATE_INITIALIZE)
        {
            decDelta = currMountLocation.Y - m_markerPoint.Y;
            m_cumClearingDistance += decDelta;                                    // use signed value
            //if (m_bltState == BLT_STATE_CLEAR_NORTH)                            // DEBUG ONLY
            //    decDelta = fakeDeltas[wxMin(m_stepCount, 7)];
        }
        switch (m_bltState)
        {
        case BLT_STATE_INITIALIZE:
            m_stepCount = 0;
            m_markerPoint = currMountLocation;
            m_startingPoint = currMountLocation;
            // Compute pulse size for clearing backlash - just use the last known guide rate
            if (m_lastDecGuideRate <= 0)
                m_lastDecGuideRate = GetLastDecGuideRate();             // try it again, maybe the user has since calibrated
            if (m_lastDecGuideRate > 0)
            {
                m_pulseWidth = BACKLASH_EXPECTED_DISTANCE * 1.25 / m_lastDecGuideRate;      // px/px_per_ms, bump it to sidestep near misses
                m_acceptedMoves = 0;
                m_lastClearRslt = 0;
                m_cumClearingDistance = 0;
                m_backlashExemption = false;
                m_Rslt = MEASUREMENT_VALID;
                // Get this state machine in synch with the guider state machine - let it drive us, starting with backlash clearing step
                m_bltState = BLT_STATE_CLEAR_NORTH;
                m_scope->SetGuidingEnabled(true);
                pFrame->pGuider->EnableMeasurementMode(true);                   // Measurement results now come to us
            }
            else
            {
                m_bltState = BLT_STATE_ABORTED;
                m_lastStatus = _("Backlash measurement cannot be run - Dec guide rate not available");
                Debug.Write("BLT: Could not get calibration data\n");
            }
            break;

        case BLT_STATE_CLEAR_NORTH:
            // Want to see the mount moving north for 3 consecutive moves of >= expected distance pixels
            if (m_stepCount == 0)
            {
                // Get things moving with the first clearing pulse
                Debug.Write(wxString::Format("BLT starting North backlash clearing using pulse width of %d,"
                    " looking for moves >= %d px\n", m_pulseWidth, BACKLASH_EXPECTED_DISTANCE));
                pFrame->ScheduleCalibrationMove(m_scope, NORTH, m_pulseWidth);
                m_stepCount = 1;
                m_lastStatus = wxString::Format(_("Clearing North backlash, step %d"), m_stepCount);
                break;
            }
            if (fabs(decDelta) >= BACKLASH_EXPECTED_DISTANCE)
            {
                if (m_acceptedMoves == 0 || (m_lastClearRslt * decDelta) > 0)    // Just starting or still moving in same direction
                {
                    m_acceptedMoves++;
                    Debug.Write(wxString::Format("BLT accepted clearing move of %0.2f\n", decDelta));
                }
                else
                {
                    m_acceptedMoves = 0;            // Reset on a direction reversal
                    Debug.Write(wxString::Format("BLT rejected clearing move of %0.2f, direction reversal\n", decDelta));
                }
            }
            else
                Debug.Write(wxString::Format("BLT backlash clearing move of %0.2f px was not large enough\n", decDelta));
            if (m_acceptedMoves < BACKLASH_MIN_COUNT)                    // More work to do
            {
                if (m_stepCount < MAX_CLEARING_STEPS)
                {
                    if (fabs(m_cumClearingDistance) > BACKLASH_EXEMPTION_DISTANCE)
                    {
                        // We moved the mount a substantial distance north but the individual moves were too small - probably a bad calibration,
                        // so let the user proceed with backlash measurement before we push the star too far
                        Debug.Write(wxString::Format("BLT: Cum backlash of %0.2f px is at least half of expected, continue with backlash measurement\n", m_cumClearingDistance));
                        m_backlashExemption = true;
                    }
                    else
                    {
                        if (!OutOfRoom(pCamera->FullSize, currentCamLoc.X, currentCamLoc.Y, pFrame->pGuider->GetMaxMovePixels()))
                        {
                            pFrame->ScheduleCalibrationMove(m_scope, NORTH, m_pulseWidth);
                            m_stepCount++;
                            m_markerPoint = currMountLocation;
                            m_lastClearRslt = decDelta;
                            m_lastStatus = wxString::Format(_("Clearing North backlash, step %d (up to limit of %d)"), m_stepCount, MAX_CLEARING_STEPS);
                            Debug.Write(wxString::Format("BLT: %s, LastDecDelta = %0.2f px\n", m_lastStatus, decDelta));
                            break;
                        }
                    }
                }
                else
                {
                    m_lastStatus = _("Could not clear North backlash - test failed");
                    m_Rslt = MEASUREMENT_INVALID;
                    throw ERROR_INFO("BLT: Could not clear N backlash");
                }
            }
            if (m_acceptedMoves >= BACKLASH_MIN_COUNT || m_backlashExemption || OutOfRoom(pCamera->FullSize, currentCamLoc.X, currentCamLoc.Y, pFrame->pGuider->GetMaxMovePixels()))    // Ok to go ahead with actual backlash measurement
            {
                m_markerPoint = currMountLocation;            // Marker point at start of big Dec move North
                m_bltState = BLT_STATE_STEP_NORTH;
                double totalBacklashCleared = m_stepCount * m_pulseWidth;
                // Want to move the mount North at >=500 ms, regardless of image scale. But reduce pulse width if it would exceed 80% of the tracking rectangle -
                // need to leave some room for seeing deflections and dec drift
                m_pulseWidth = wxMax((int)NORTH_PULSE_SIZE, m_scope->GetCalibrationDuration());
                m_pulseWidth = wxMin(m_pulseWidth, (int)floor(0.7 * (double)pFrame->pGuider->GetMaxMovePixels() / m_lastDecGuideRate));
                m_stepCount = 0;
                // Move 50% more than the backlash we cleared or >=8 secs, whichever is greater.  We want to leave plenty of room
                // for giving South moves time to clear backlash and actually get moving
                m_northPulseCount = wxMax((MAX_NORTH_PULSES + m_pulseWidth - 1) / m_pulseWidth,
                                          totalBacklashCleared * 1.5 / m_pulseWidth);  // Up to 8 secs

                Debug.Write(wxString::Format("BLT: Starting North moves at Dec=%0.2f\n", currMountLocation.Y));
                // falling through to start moving North
            }

        case BLT_STATE_STEP_NORTH:
            if (m_stepCount < m_northPulseCount && !OutOfRoom(pCamera->FullSize, currentCamLoc.X, currentCamLoc.Y, pFrame->pGuider->GetMaxMovePixels()))
            {
                m_lastStatus = wxString::Format(_("Moving North for %d ms, step %d / %d"), m_pulseWidth, m_stepCount + 1, m_northPulseCount);
                Debug.Write(wxString::Format("BLT: %s, DecLoc = %0.2f\n", m_lastStatus, currMountLocation.Y));
                m_northBLSteps.push_back(currMountLocation.Y);
                pFrame->ScheduleCalibrationMove(m_scope, NORTH, m_pulseWidth);
                m_stepCount++;
                break;
            }
            else
            {
                // Either got finished or ran out of room
                Debug.Write(wxString::Format("BLT: North pulses ended at Dec location %0.2f, DecDelta=%0.2f px\n", currMountLocation.Y, decDelta));
                m_northBLSteps.push_back(currMountLocation.Y);
                if (m_stepCount < m_northPulseCount)
                {
                    if (m_stepCount < 0.5 * m_northPulseCount)
                    {
                        pFrame->Alert(_("Star too close to edge for accurate measurement of backlash. Choose a star farther from the edge."));
                        m_Rslt = MEASUREMENT_INVALID;
                    }
                    Debug.Write("BLT: North pulses truncated, too close to frame edge\n");
                }
                m_northRate = fabs(decDelta / (m_stepCount * m_pulseWidth));
                m_northPulseCount = m_stepCount;
                m_stepCount = 0;
                m_bltState = BLT_STATE_STEP_SOUTH;
                // falling through to moving back South
            }

        case BLT_STATE_STEP_SOUTH:
            if (m_stepCount < m_northPulseCount)
            {
                m_lastStatus = wxString::Format(_("Moving South for %d ms, step %d / %d"), m_pulseWidth, m_stepCount + 1, m_northPulseCount);
                Debug.Write(wxString::Format("BLT: %s, DecLoc = %0.2f\n", m_lastStatus, currMountLocation.Y));
                m_southBLSteps.push_back(currMountLocation.Y);
                pFrame->ScheduleCalibrationMove(m_scope, SOUTH, m_pulseWidth);
                m_stepCount++;
                break;
            }
            // Now see where we ended up - fall through to testing this correction
            Debug.Write(wxString::Format("BLT: South pulses ended at Dec location %0.2f\n", currMountLocation.Y));
            m_southBLSteps.push_back(currMountLocation.Y);
            m_endSouth = currMountLocation;
            m_bltState = BLT_STATE_TEST_CORRECTION;
            m_stepCount = 0;
            // fall through

        case BLT_STATE_TEST_CORRECTION:
            if (m_stepCount == 0)
            {
                // decDelta contains the nominal backlash amount
                m_backlashResultPx = fabs(decDelta);
                m_backlashResultMs = (int)(m_backlashResultPx / m_northRate);          // our north rate is probably better than the calibration rate
                if (m_Rslt == MEASUREMENT_VALID)
                {
                    if (m_backlashResultMs >= 0.8 * m_northPulseCount * m_pulseWidth)
                        m_Rslt = MEASUREMENT_IMPAIRED;      // May not have moved far enough north for accurate measurement
                }
                Debug.Write(wxString::Format("BLT: Backlash amount is %0.2f px, %d ms\n", m_backlashResultPx, m_backlashResultMs));
                // Don't try this refinement if the clearing pulse will cause us to lose the star
                if (m_backlashResultPx < pFrame->pGuider->GetMaxMovePixels())
                {
                    m_lastStatus = wxString::Format(_("Issuing test backlash correction of %d ms"), m_backlashResultMs);
                    Debug.Write(m_lastStatus + "\n");
                    // This should put us back roughly to where we issued the big North pulse unless the backlash is very large
                    pFrame->ScheduleCalibrationMove(m_scope, SOUTH, m_backlashResultMs);
                    m_stepCount++;
                }
                else
                {
                    int maxFrameMove = (int)floor((double)pFrame->pGuider->GetMaxMovePixels() / m_northRate);
                    Debug.Write(wxString::Format("BLT: Clearing pulse is very large, issuing max S move of %d\n", maxFrameMove));
                    pFrame->ScheduleCalibrationMove(m_scope, SOUTH, maxFrameMove);       // One more pulse to cycle the state machine
                    m_bltState = BLT_STATE_RESTORE;
                }
                break;
            }
            // See how close we came, maybe fine-tune a bit
            Debug.Write(wxString::Format("BLT: Trial backlash pulse resulted in net DecDelta = %0.2f px, Dec Location %0.2f\n", decDelta, currMountLocation.Y));
            if (fabs(decDelta) > TRIAL_TOLERANCE)
            {
                double pulse_delta = fabs(currMountLocation.Y - m_endSouth.Y);
                if ((m_endSouth.Y - m_markerPoint.Y) * decDelta < 0)                // Sign change, went too far
                {
                    m_backlashResultMs *= m_backlashResultPx / pulse_delta;
                    Debug.Write(wxString::Format("BLT: Trial backlash resulted in overshoot - adjusting pulse size by %0.2f\n", m_backlashResultPx / pulse_delta));
                }
                else
                {
                    double corr_factor = (m_backlashResultPx / pulse_delta - 1.0) * 0.5 + 1.0;          // apply 50% of the correction to avoid over-shoot
                    //m_backlashResultMs *= corr_factor;
                    Debug.Write(wxString::Format("BLT: Trial backlash resulted in under-correction - under-shot by %0.2f\n", corr_factor));
                }
            }
            else
                Debug.Write("BLT: Initial backlash pulse resulted in final delta of < 2 px\n");

            m_bltState = BLT_STATE_RESTORE;
            m_stepCount = 0;
            // fall through

        case BLT_STATE_RESTORE:
            // We could be a considerable distance from where we started, so get back close to the starting point without losing the star
            if (m_stepCount == 0)
            {
                Debug.Write(wxString::Format("BLT: Starting Dec position at %0.2f, Ending Dec position at %0.2f\n", m_markerPoint.Y, currMountLocation.Y));
                amt = fabs(currMountLocation.Y - m_startingPoint.Y);
                if (amt > pFrame->pGuider->GetMaxMovePixels())
                {
                    m_restoreCount = (int)floor((amt / m_northRate) / m_pulseWidth);
                    Debug.Write(wxString::Format("BLT: Final restore distance is %0.1f px, approx %d steps\n", amt, m_restoreCount));
                    m_stepCount = 0;
                }
                else
                    m_bltState = BLT_STATE_WRAPUP;
            }
            if (m_stepCount < m_restoreCount)
            {

                pFrame->ScheduleCalibrationMove(m_scope, SOUTH, m_pulseWidth);
                m_stepCount++;
                m_lastStatus = _("Restoring star position");
                Debug.Write(wxString::Format("BLT: Issuing restore pulse count %d of %d ms\n", m_stepCount, m_pulseWidth));
                break;
            }
            m_bltState = BLT_STATE_WRAPUP;
            // fall through

        case BLT_STATE_WRAPUP:
            m_lastStatus = _("Measurement complete");
            CleanUp();
            m_bltState = BLT_STATE_COMPLETED;
            break;

        case BLT_STATE_COMPLETED:
            break;

        case BLT_STATE_ABORTED:
            m_lastStatus = _("Measurement halted");
            Debug.Write("BLT: measurement process halted by user or by error\n");
            CleanUp();
            break;
        }                       // end of switch on state
    }
    catch (const wxString& msg)
    {
        Debug.Write(wxString::Format("BLT: Exception thrown in logical state %d\n", (int)m_bltState));
        m_bltState = BLT_STATE_ABORTED;
        m_lastStatus = wxString::Format(_("Measurement encountered an error: %s"), msg);
        Debug.Write("BLT: " + m_lastStatus + "\n");
        CleanUp();
    }
}
Ejemplo n.º 13
0
wxBitmap BacklashGraph::CreateGraph(int bmpWidth, int bmpHeight)
{
    wxMemoryDC dc;
    wxBitmap bmp(bmpWidth, bmpHeight, -1);
    wxColour decColor = pFrame->pGraphLog->GetDecOrDyColor();
    wxColour idealColor("WHITE");
    wxPen axisPen("GREY", 3, wxCROSS_HATCH);
    wxPen decPen(decColor, 3, wxSOLID);
    wxPen idealPen(idealColor, 3, wxSOLID);
    wxBrush decBrush(decColor, wxSOLID);
    wxBrush idealBrush(idealColor, wxSOLID);
    //double fakeNorthPoints[] =
    //{152.04, 164.77, 176.34, 188.5, 200.25, 212.36, 224.21, 236.89, 248.62, 260.25, 271.34, 283.54, 294.79, 307.56, 319.22, 330.87, 343.37, 355.75, 367.52, 379.7, 391.22, 403.89, 415.34, 427.09, 439.41, 450.36, 462.6};
    //double fakeSouthPoints[] =
    //{474.84, 474.9, 464.01, 451.83, 438.08, 426, 414.68, 401.15, 390.39, 377.22, 366.17, 353.45, 340.75, 328.31, 316.93, 304.55, 292.42, 280.45, 269.03, 255.02, 243.76, 231.53, 219.43, 207.35, 195.22, 183.06, 169.47};
    //std::vector <double> northSteps(fakeNorthPoints, fakeNorthPoints + 27);
    //std::vector <double> southSteps(fakeSouthPoints, fakeSouthPoints + 27);
    std::vector <double> northSteps = m_BLT->GetNorthSteps();
    std::vector <double> southSteps = m_BLT->GetSouthSteps();

    double xScaleFactor;
    double yScaleFactor;
    int xOrigin;
    int yOrigin;
    int ptRadius;
    int graphWindowWidth;
    int graphWindowHeight;
    int numNorth;
    double northInc;
    int numSouth;

    // Find the max excursion from the origin in order to scale the points to fit the bitmap
    double maxDec = -9999.0;
    double minDec = 9999.0;
    for (auto it = northSteps.begin(); it != northSteps.end(); ++it)
    {
        maxDec = wxMax(maxDec, *it);
        minDec = wxMin(minDec, *it);
    }

    for (auto it = southSteps.begin(); it != southSteps.end(); ++it)
    {
        maxDec = wxMax(maxDec, *it);
        minDec = wxMin(minDec, *it);
    }

    graphWindowWidth = bmpWidth;
    graphWindowHeight = 0.7 * bmpHeight;
    yScaleFactor = (graphWindowHeight) / (maxDec - minDec + 1);
    xScaleFactor = (graphWindowWidth) / (northSteps.size() + southSteps.size());

    // Since we get mount coordinates, north steps will always be in ascending order
    numNorth = northSteps.size();
    northInc = (northSteps.at(numNorth - 1) - northSteps.at(0)) / numNorth;
    numSouth = southSteps.size();       // Should be same as numNorth but be careful

    dc.SelectObject(bmp);
    dc.SetBackground(*wxBLACK_BRUSH);

    dc.SetFont(wxFont(12, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL));
    dc.Clear();

    // Bottom and top labels
    dc.SetTextForeground(idealColor);
    dc.DrawText(_("Ideal"), 0.7 * graphWindowWidth, bmpHeight - 25);
    dc.SetTextForeground(decColor);
    dc.DrawText(_("Measured"), 0.2 * graphWindowWidth, bmpHeight - 25);
    dc.DrawText(_("North"), 0.1 * graphWindowWidth, 10);
    dc.DrawText(_("South"), 0.8 * graphWindowWidth, 10);
    // Draw the axes
    dc.SetPen(axisPen);
    xOrigin = graphWindowWidth / 2;
    yOrigin = graphWindowHeight + 40;           // Leave room at the top for labels and such
    dc.DrawLine(0, yOrigin, graphWindowWidth, yOrigin);    // x
    dc.DrawLine(xOrigin, yOrigin, xOrigin, 0);             // y

    // Draw the north steps
    dc.SetPen(decPen);
    dc.SetBrush(decBrush);
    ptRadius = 2;

    for (int i = 0; i < numNorth; i++)
    {
        wxPoint where = wxPoint(i * xScaleFactor, round(yOrigin - (northSteps.at(i) - minDec) * yScaleFactor));
        dc.DrawCircle(wxPoint(i * xScaleFactor, round(yOrigin - (northSteps.at(i) - minDec) * yScaleFactor)), ptRadius);
    }

    // Draw the south steps
    for (int i = 0; i < numSouth; i++)
    {
        dc.DrawCircle(wxPoint((i + numNorth) * xScaleFactor, round(yOrigin - (southSteps.at(i) - minDec) * yScaleFactor)), ptRadius);
    }

    // Now show an ideal south recovery line
    dc.SetPen(idealPen);
    dc.SetBrush(idealBrush);

    double peakSouth = southSteps.at(0);
    for (int i = 1; i <= numNorth; i++)
    {
        wxPoint where = wxPoint((i + numNorth)* xScaleFactor, round(yOrigin - (peakSouth - i * northInc - minDec) * yScaleFactor));
        dc.DrawCircle(where, ptRadius);
    }

    dc.SelectObject(wxNullBitmap);
    return bmp;
}
Ejemplo n.º 14
0
void BacklashComp::_TrackBLCResults(double yDistance, double minMove, double yRate)
{
    assert(m_justCompensated); // caller checks this

    // The previous Dec correction included a BLC

    // Record the history even if residual error is zero. Sign convention has nothing to do with N or S direction - only whether we
    // needed more correction (+) or less (-)
    GUIDE_DIRECTION dir = yDistance > 0.0 ? DOWN : UP;
    yDistance = fabs(yDistance);
    double miss;
    if (dir == m_lastDirection)
        miss = yDistance;            // + => we needed more of the same, under-shoot
    else
        miss = -yDistance;           // over-shoot
    minMove = fmax(minMove, 0);         // Algo w/ no min-move returns -1
    if (m_residualOffsets.GetCount() == HISTORY_SIZE)
    {
        m_residualOffsets.RemoveAt(0);
    }
    m_residualOffsets.Add(miss);

    if (yDistance >= minMove)           // Don't adjust for a residual error < min_move_equivalent
    {
        // Compute the average residual error
        int numPoints = m_residualOffsets.GetCount();
        double avgMiss = 0.;
        for (int inx = 0; inx < numPoints; inx++)
            avgMiss += m_residualOffsets.Item(inx);
        avgMiss = avgMiss / numPoints;

        if (abs(avgMiss) > minMove)                        // Don't make micro-adjustments
        {
            double corr = (int)floor(fabs(avgMiss / yRate) + 0.5);
            int nominalBLC;
            int newBLC;
            if (miss >= 0)                                  // We under-shot the target
            {
                if (avgMiss > 0)
                    nominalBLC = m_pulseWidth + corr;
                else
                    nominalBLC = m_pulseWidth;              // Need more evidence of under-shooting
                // Don't increase by more than 10% or go above ceiling
                newBLC = ROUND(fmin(m_pulseWidth * 1.1, wxMin(m_adjustmentCeiling, nominalBLC)));
            }
            else
            {                                              // we over-shot the target
                if (avgMiss < 0)
                    nominalBLC = m_pulseWidth - corr;
                else
                    nominalBLC = m_pulseWidth;            // Need more evidence of over-shooting
                // Don't decrease by more than 20% or go below zero
                newBLC = ROUND(fmax(0.8 * m_pulseWidth, wxMax(0, nominalBLC)));
            }

            if (newBLC != m_pulseWidth && numPoints > 2)
                m_residualOffsets.RemoveAt(0);               // Don't let initial big deflection dominate adjustments
            if (newBLC != m_pulseWidth)
            {
                Debug.Write(wxString::Format("BLC: Adjustment from %d to %d based on avg residual of %.1f px\n", m_pulseWidth, newBLC, avgMiss));
                pConfig->Profile.SetInt("/" + m_pMount->GetMountClassName() + "/DecBacklashPulse", newBLC);
                SetCompValues(newBLC, true);
            }

        }
    }

    m_justCompensated = false;
}
Ejemplo n.º 15
0
float Camera::clampPitch(float p_pitch)
{
    float rotationLimit = (89.0f * XM_PI) / 180.0f;
    return wxMin(rotationLimit, wxMax(-rotationLimit, p_pitch));
}
Ejemplo n.º 16
0
wxStreamError wxBackingFileImpl::ReadAt(wxFileOffset pos,
                                        void *buffer,
                                        size_t *size)
{
    size_t reqestedSize = *size;
    *size = 0;

    // size1 is the number of bytes it will read directly from the backing
    // file. size2 is any remaining bytes not yet backed, these are returned
    // from the buffer or read from the parent stream.
    size_t size1, size2;

    if (pos + reqestedSize <= m_filelen + size_t(0)) {
        size1 = reqestedSize;
        size2 = 0;
    } else if (pos < m_filelen) {
        size1 = size_t(m_filelen - pos);
        size2 = reqestedSize - size1;
    } else {
        size1 = 0;
        size2 = reqestedSize;
    }

    if (pos < 0)
        return wxSTREAM_READ_ERROR;

    // read the backing file
    if (size1) {
        if (m_file.Seek(pos) == wxBadSeek)
            return wxSTREAM_READ_ERROR;

        ssize_t n = m_file.Read(buffer, size1);
        if (n > 0) {
            *size = n;
            pos += n;
        }

        if (*size < size1)
            return wxSTREAM_READ_ERROR;
    }

    // read from the buffer or parent stream
    if (size2)
    {
        while (*size < reqestedSize)
        {
            // if pos is further ahead than the parent has been read so far,
            // then read forward in the parent stream
            while (pos - m_filelen + size_t(0) >= m_buflen)
            {
                // if the parent is small enough, don't use a backing file
                // just the buffer memory
                if (!m_stream && m_filelen == 0)
                    return m_parenterror;

                // before refilling the buffer write out the current buffer
                // to the backing file if there is anything in it
                if (m_buflen)
                {
                    if (!m_file.IsOpened())
                        if (!wxCreateTempFile(m_prefix, &m_file, &m_filename))
                            return wxSTREAM_READ_ERROR;

                    if (m_file.Seek(m_filelen) == wxBadSeek)
                        return wxSTREAM_READ_ERROR;

                    size_t count = m_file.Write(m_buf, m_buflen);
                    m_filelen += count;

                    if (count < m_buflen) {
                        delete m_stream;
                        m_stream = NULL;
                        if (count > 0) {
                            delete[] m_buf;
                            m_buf = NULL;
                            m_buflen = 0;
                        }
                        m_parenterror = wxSTREAM_READ_ERROR;
                        return m_parenterror;
                    }

                    m_buflen = 0;

                    if (!m_stream) {
                        delete[] m_buf;
                        m_buf = NULL;
                    }
                }

                if (!m_stream)
                    return m_parenterror;

                // refill buffer
                m_buflen = m_stream->Read(m_buf, m_bufsize).LastRead();

                if (m_buflen < m_bufsize) {
                    m_parenterror = m_stream->GetLastError();
                    if (m_parenterror == wxSTREAM_NO_ERROR)
                        m_parenterror = wxSTREAM_EOF;
                    delete m_stream;
                    m_stream = NULL;
                }
            }

            // copy to the user's buffer
            size_t start = size_t(pos - m_filelen);
            size_t len = wxMin(m_buflen - start, reqestedSize - *size);

            memcpy((char*)buffer + *size, m_buf + start, len);
            *size += len;
            pos += len;
        }
    }

    return wxSTREAM_NO_ERROR;
}
Ejemplo n.º 17
0
wxObject* wxsGrid::OnBuildPreview( wxWindow* parent, long flags )
{
    wxGrid* preview = new wxGrid( parent, GetId(), Pos(parent), Size(parent), Style() );

    if ( GetPropertiesFlags() & flSource )
    {
        if ( m_ColsCount>=0 && m_RowsCount>=0 && (m_ColsCount>0 || m_RowsCount>0) )
        {
            preview->CreateGrid( m_RowsCount, m_ColsCount );
            SetupWindow( preview, flags );

            preview->EnableEditing( !m_ReadOnly);
            preview->EnableGridLines( m_GridLines );

            if ( m_LabelRowHeight > 0 ) preview->SetColLabelSize( m_LabelRowHeight );
            if ( m_LabelColWidth  > 0 ) preview->SetRowLabelSize( m_LabelColWidth );

            if ( m_DefaultRowSize > 0 ) preview->SetDefaultRowSize( m_DefaultRowSize, true );
            if ( m_DefaultColSize > 0 ) preview->SetDefaultColSize( m_DefaultColSize, true );

            wxColour cc = m_LabelTextColour.GetColour();
            if ( cc.IsOk() )
            {
                preview->SetLabelTextColour(cc);
            }

            wxFont labelfont = m_LabelFont.BuildFont();
            if ( labelfont.IsOk() )
            {
                preview->SetLabelFont( labelfont );
            }

            int n = wxMin( (int)m_ColLabels.GetCount(), m_ColsCount );
            for ( int i=0; i<n; i++ )
            {
                preview->SetColLabelValue( i, m_ColLabels[i] );
            }

            n = wxMin( (int)m_RowLabels.GetCount(), m_RowsCount );
            for( int i=0; i<n; i++ )
            {
                preview->SetRowLabelValue( i, m_RowLabels[i] );
            }

            n = (int)m_CellText.GetCount();
            int i = 0;
            for ( int j=0; j<m_RowsCount && i<n; j++ )
            {
                for ( int k=0; k<m_ColsCount && i<n; k++, i++ )
                {
                    preview->SetCellValue( j, k, m_CellText[i] );
                }
            }

            wxFont cellfont = preview->GetFont();
            if ( cellfont.IsOk() )
            {
                preview->SetDefaultCellFont(cellfont);
            }

            cc = preview->GetForegroundColour();
            preview->SetDefaultCellTextColour(cc);

        }
    }

    return preview;
}
Ejemplo n.º 18
0
void Envelope::Paste(double t0, Envelope *e)
{
   bool pointsAdded = false;

   if (e->mEnv.Count() == 0 && this->mEnv.Count() == 0 && e->mDefaultValue == this->mDefaultValue)
   {
      // msmeyer: The envelope is empty and has the same default value, so
      // there is nothing that must be inserted, just return. This avoids
      // the creation of unnecessary duplicate control points
      // MJS: but the envelope does get longer
      mTrackLen += e->mTrackLen;
      return;
   }
   if (this->mEnv.Count() != 0)
   {
      // inserting a clip with a possibly empty envelope into one with an envelope
      // so add end points to e, in case they are not there
      double leftval  = e->GetValue(0+e->mOffset);
      double rightval = e->GetValue(e->mTrackLen+e->mOffset);
      e->Insert(0, leftval);
      e->Insert(e->mTrackLen, rightval);
      pointsAdded = true;  // we need to delete them later so's not to corrupt 'e' for later use
   }
   
   t0 = wxMin(t0 - mOffset, mTrackLen);   // t0 now has origin of zero
   double deltat = e->mTrackLen;

   unsigned int i;
   unsigned int pos = 0;
   bool someToShift = false;
   bool atStart = false;
   bool beforeStart = false;
   bool atEnd = false;
   bool afterEnd = false;
   bool onPoint = false;
   unsigned int len = mEnv.Count();

   // get values to perform framing of the insertion 
   double splitval = GetValue(t0 + mOffset);

   if(len != 0) {   // Not case 10: there are point/s in the envelope

/*
Cases:
(see discussions on audacity-devel around 19/8/7 - 23/8/7 and beyond, "Envelopes and 'Join'")
1  9     11  2    3 5  7   8   6 4   13              12
0-----0--0---0    -----0---0------       --(0)----

1   The insert point is at the beginning of the current env, and it is a control point.
2   The insert point is at the end of the current env, and it is a control point.
3   The insert point is at the beginning of the current env, and it is not a control point.
4   The insert point is at the end of the current env, and it is not a control point.
5   The insert point is not at a control point, and there is space either side.
6   As 5.
7   The insert point is at a control point, and there is space either side.
8   Same as 7.
9   Same as 5.
10  There are no points in the current envelope (commonly called by the 'undo' stuff, and not in the diagrams).
11  As 7.
12  Insert beyond the RH end of the current envelope (should not happen, at the moment)
13  Insert beyond the LH end of the current envelope (should not happen, at the moment)
*/

      // See if existing points need shifting to the right, and what Case we are in
      for (i = 0; i < len; i++) {
         if (mEnv[i]->t > t0)
            someToShift = true;
         else {
            pos = i; // last point not moved
            if ( fabs(mEnv[i]->t - t0) - 1/500000.0 < 0.0 ) // close enough to a point
               onPoint = true;
         }
      }

      // In theses statement, remember we subtracted mOffset from t0
      if( t0 < mTrackEpsilon )
         atStart = true;
      if( (mTrackLen - t0) < mTrackEpsilon )
         atEnd = true;
      if(0 > t0)
         beforeStart = true;  // Case 13
      if(mTrackLen < t0)
         afterEnd = true;  // Case 12

      // Now test for the various Cases, and try to do the right thing
      if(atStart) {   // insertion at the beginning
         if(onPoint) {  // first env point is at LH end
            mEnv[0]->t +=mTrackEpsilon;   // Case 1: move it R slightly to avoid duplicate point
            someToShift = true;  // there is now, even if there wasn't before
            //wxLogDebug(wxT("Case 1"));
         }
         else {
            Insert(t0 + mTrackEpsilon, splitval);   // Case 3: insert a point to maintain the envelope
            someToShift = true;
            //wxLogDebug(wxT("Case 3"));
         }
      }
      else {
         if(atEnd) { // insertion at the end
            if(onPoint) {  // last env point is at RH end, Case 2: 
               mEnv[0]->t -= mTrackEpsilon;  // move it L slightly to avoid duplicate point
               //wxLogDebug(wxT("Case 2"));
            }
            else {   // Case 4:
               Insert(t0 - mTrackEpsilon, splitval);   // insert a point to maintain the envelope
               //wxLogDebug(wxT("Case 4"));
            }
         }
         else {
            if(onPoint) {  // Case 7: move the point L and insert a new one to the R
               mEnv[pos]->t -= mTrackEpsilon;
               Insert(t0 + mTrackEpsilon, splitval);
               someToShift = true;
               //wxLogDebug(wxT("Case 7"));
            }
            else {
               if( !beforeStart && !afterEnd ) {// Case 5: Insert points to L and R
                  Insert(t0 - mTrackEpsilon, splitval);
                  Insert(t0 + mTrackEpsilon, splitval);
                  someToShift = true;
                  //wxLogDebug(wxT("Case 5"));
               }
               else {
                  if( beforeStart ) {  // Case 13:
                     //wxLogDebug(wxT("Case 13"));
                  }
                  else {   // Case 12:
                     //wxLogDebug(wxT("Case 12"));
                  }
               }
            }
         }
      }

      // Now shift existing points to the right, if required
      if(someToShift) {
         len = mEnv.Count();  // it may well have changed
         for (i = 0; i < len; i++)
            if (mEnv[i]->t > t0)
               mEnv[i]->t += deltat;
      }
      mTrackLen += deltat;
   }
   else {   // Case 10:
      mTrackLen = e->mTrackLen;
      mOffset = e->mOffset;
      //wxLogDebug(wxT("Case 10: mTrackLen %f mOffset %f t0 %f"), mTrackLen, mOffset, t0);
   }

   // Copy points from inside the selection
   len = e->mEnv.Count();
   for (i = 0; i < len; i++)
      pos=Insert(t0 + e->mEnv[i]->t, e->mEnv[i]->val);

/*   if(len != 0)
      for (i = 0; i < mEnv.Count(); i++)
         wxLogDebug(wxT("Fixed i %d when %.18f val %f"),i,mEnv[i]->t,mEnv[i]->val); */

   if(pointsAdded)
      while(e->mEnv.Count() != 0)
         e->Delete(0);  // they were not there when we entered this
}
Ejemplo n.º 19
0
bool CWindowStateManager::Restore(unsigned int optionId)
{
	if (wxGetKeyState(WXK_SHIFT) && wxGetKeyState(WXK_ALT) && wxGetKeyState(WXK_CONTROL))
	{
		m_pWindow->CenterOnScreen(wxBOTH);
		return false;
	}

#if wxUSE_DISPLAY
	int min_x = 1000000000;
	int min_y = 1000000000;
	int max_x = 0;
	int max_y = 0;

	// Get bounding rectangle of virtual screen
	for (unsigned int i = 0; i < wxDisplay::GetCount(); i++)
	{
		wxDisplay display(i);
		wxRect rect = display.GetGeometry();
		min_x = wxMin(min_x, rect.GetLeft());
		min_y = wxMin(min_y, rect.GetTop());
		max_x = wxMax(max_x, rect.GetRight());
		max_y = wxMax(max_y, rect.GetBottom());
	}
#else
	int min_x = 0;
	int min_y = 0;
	int max_x = 1000000000;
	int max_y = 1000000000;
#endif

	// Fields:
	// - maximized (1 or 0)
	// - x position
	// - y position
	// - width
	// - height
	const wxString layout = COptions::Get()->GetOption(optionId);
	wxStringTokenizer tokens(layout, _T(" "));
	int count = tokens.CountTokens();
	if (count != 5)
	{
		m_pWindow->CenterOnScreen(wxBOTH);
		return false;
	}
	
	long values[5];
	for (int i = 0; i < count; i++)
	{
		wxString token = tokens.GetNextToken();
		if (!token.ToLong(values + i))
		{
			m_pWindow->CenterOnScreen(wxBOTH);
			return false;
		}
	}

	// Make sure position is (somewhat) sane
	int pos_x = wxMin(max_x - 30, values[1]);
	int pos_y = wxMin(max_y - 30, values[2]);
	int client_width = values[3];
	int client_height = values[4];

	if (pos_x + client_width - 30 < min_x)
		pos_x = min_x;
	if (pos_y + client_height - 30 < min_y)
		pos_y = min_y;

	if (values[0])
	{
		// We need to move so it appears on the proper display on multi-monitor systems
		m_pWindow->Move(pos_x, pos_y);

		// We need to call SetClientSize here too. Since window isn't yet shown here, Maximize
		// doesn't actually resize the window till it is shown

		// The slight off-size is needed to ensure the client sizes gets changed at least once.
		// Otherwise all the splitters would have default size still.
		m_pWindow->SetClientSize(client_width + 1, client_height);

		// A 2nd call is neccessary, for some reason the first call
		// doesn't fully set the height properly at least under wxMSW
		m_pWindow->SetClientSize(client_width, client_height);

		m_pWindow->Maximize();
	}
	else
	{
		m_pWindow->Move(pos_x, pos_y);

		// The slight off-size is needed to ensure the client sizes gets changed at least once.
		// Otherwise all the splitters would have default size still.
		m_pWindow->SetClientSize(client_width + 1, client_height);

		// A 2nd call is neccessary, for some reason the first call
		// doesn't fully set the height properly at least under wxMSW
		m_pWindow->SetClientSize(client_width, client_height);
	}

	return true;
}
Ejemplo n.º 20
0
void GutterCtrl::OnMouseLeftDown(wxMouseEvent& event) {
	//wxLogDebug("OnMouseLeftDown");
	//wxASSERT(m_editorCtrl);
	wxASSERT(m_currentSel == -1);
	Lines& lines = m_editorCtrl.m_lines;

	// Get Mouse location
	const int x = event.GetX();
	const int y = event.GetY() + m_editorCtrl.scrollPos;

	// Handle bookmarks
	if (m_showBookmarks && x < (int)m_numberX) {
		// Find out which line was clicked on
		Lines& lines = m_editorCtrl.m_lines;
		if ((int)y < lines.GetHeight()) {
			const unsigned int line_id = lines.GetLineFromYPos(y);
			m_editorCtrl.AddBookmark(line_id, true /*toggle*/);
			DrawGutter(); // Redraw gutter to show bookmarks
			return;
		}
	}

	// Handle folding
	if (m_showFolds && x > (int)m_foldStartX) {
		ClickOnFold(y);
		return;
	}

	bool hasSelection = false;
	interval sel(0, 0);
	if (event.ShiftDown() && lines.IsSelected()) {
		sel = lines.GetSelections()[lines.GetLastSelection()];
		hasSelection = true;
	}

	// If not multiselecting or extending, remove previous selections
	if (!event.ControlDown()) {
		lines.RemoveAllSelections();
	}

	// Find out which line was clicked on
	if (y < lines.GetHeight()) {
		const unsigned int line_id = lines.GetLineFromYPos(y);

		// Select the line
		if (!lines.isLineVirtual(line_id)) {
			int startpos = lines.GetLineStartpos(line_id);
			int endpos = lines.GetLineEndpos(line_id, false);

			if (hasSelection) {
				startpos = wxMin(startpos, (int)sel.start);
				endpos = wxMax(endpos, (int)sel.end);
			}

			m_currentSel = lines.AddSelection(startpos, endpos);
			lines.SetPos(endpos);

			m_sel_startline = m_sel_endline = line_id;
		}
		m_sel_startoutside = false;
	}
	else {
		const unsigned int linecount = lines.GetLineCount();
		m_sel_startline = m_sel_endline = linecount ? linecount-1 : 0;
		m_sel_startoutside = true;

		if (hasSelection) {
			m_currentSel = lines.AddSelection(sel.start, lines.GetLength());
			lines.SetPos(lines.GetLength());
		}
	}

	// Make sure we capure all mouse events
	// this is released in OnMouseLeftUp()
	CaptureMouse();

	// Redraw the editCtrl to show new selection
	m_editorCtrl.DrawLayout();
}
Ejemplo n.º 21
0
void pgsRegexGen::pgsRegex::set_second(const long & second)
{
	long first = m_first;
	m_first = wxMin(first, second);
	m_second = wxMax(first, second);
}
Ejemplo n.º 22
0
void GutterCtrl::OnMouseMotion(wxMouseEvent& event) {
	Lines& lines = m_editorCtrl.m_lines;

	// Get Mouse location
	const int y = event.GetY() + m_editorCtrl.scrollPos;

	if (event.LeftIsDown() && HasCapture()) {
		// Find out what is under mouse
		unsigned int line_id;
		if (y < 0) line_id = 0;
		else if (y < lines.GetHeight()) {
			line_id = lines.GetLineFromYPos(y);
		}
		else {
			if (m_sel_startoutside && m_currentSel != -1) {
				// Make sure we remove current selection
				m_currentSel = lines.UpdateSelection(m_currentSel, 0, 0);
				lines.SetPos(lines.GetLength());
				m_editorCtrl.DrawLayout();
				return;
			}

			const unsigned int linecount = lines.GetLineCount();
			line_id = linecount ? linecount-1 : 0;
		}

		// Select the lines
		if (line_id != m_sel_endline) {
			m_sel_endline = line_id;

			int sel_start = lines.GetLineStartpos(wxMin(m_sel_startline, m_sel_endline));
			int sel_end = lines.GetLineEndpos(wxMax(m_sel_startline, m_sel_endline), false);

			if (sel_start == sel_end) {
				lines.RemoveAllSelections();
				m_currentSel = -1;
			}
			else {
				// Update the lines selection info
				if (m_currentSel == -1) {
					m_currentSel = lines.AddSelection(sel_start, sel_end);
				}
				else {
					m_currentSel = lines.UpdateSelection(m_currentSel, sel_start, sel_end);
				}
				lines.SetPos(m_sel_endline < m_sel_startline ? sel_start : sel_end);
			}

			m_editorCtrl.MakeCaretVisible(); // also ensures scrolling if outside window
			m_editorCtrl.DrawLayout();
		}
	}
	else if (event.GetX() > (int)m_foldStartX && y >= 0 && y < lines.GetHeight()) {
		const unsigned int line_id = lines.GetLineFromYPos(y);

		vector<EditorCtrl::cxFold*> foldStack = m_editorCtrl.GetFoldStack(line_id);
		if (!foldStack.empty()) {
			m_currentFold = foldStack.back();
			DrawGutter(); // Redraw gutter to show highlights
			return;
		}
	}

	if (m_currentFold) {
		m_currentFold = NULL;
		DrawGutter(); // Redraw gutter to remove highlights
	}
}
Ejemplo n.º 23
0
static int RangeCheck(int thisval)
{
    return wxMin(wxMax(thisval, 0), (int) ProfileWizard::STATE_DONE);
}
Ejemplo n.º 24
0
void wxSheetCellStringRendererRefData::DoDraw(wxSheet& sheet,
        const wxSheetCellAttr& attr,
        wxDC& dc,
        const wxRect& rectCell,
        const wxSheetCoords& coords,
        bool isSelected)
{
    wxRect rect = rectCell;
    rect.Inflate(-1);

    int align = attr.GetAlignment();
    int orient = attr.GetOrientation();

    wxString value( sheet.GetCellValue(coords) );
    int best_width = DoGetBestSize(sheet, attr, dc, value).GetWidth();
    wxSheetCoords cellSpan(sheet.GetCellSpan(coords)); // shouldn't get here if <=0
    int cell_rows = cellSpan.m_row;
    int cell_cols = cellSpan.m_col;

    bool is_grid_cell = coords.IsGridCell();
    // no overflow for row/col/corner labels
    bool overflow = is_grid_cell && (orient == wxSHEET_AttrOrientHoriz) ? attr.GetOverflow() : false;
    int overflowCols = 0;
    int num_cols = sheet.GetNumberCols();
    // this is the right col which includes overflow
    int rightCol = coords.m_col + cell_cols - 1;

    // Check if this cell should overflow to right and for how many cells
    if (overflow)
    {
        bool is_editing = sheet.IsCellEditControlShown();
        wxSheetCoords editorCell = is_editing ? sheet.GetEditControlCoords() : wxNullSheetCoords;
        int row = coords.GetRow(), col = coords.GetCol();
        wxSheetCoords ownerCell;
        if ((best_width > rectCell.width) && (col < num_cols-1) && sheet.GetTable())
        {
            wxSheetCoords cell;
            for (cell.m_col = col+cell_cols; cell.m_col < num_cols; cell.m_col++)
            {
                bool is_empty = true;
                for (cell.m_row = row; cell.m_row < row+cell_rows; cell.m_row++)
                {
                    // check w/ anchor cell for spanned cell block
                    ownerCell = sheet.GetCellOwner(cell);
                    if ( sheet.GetTable()->HasValue(ownerCell) ||
                            (ownerCell == editorCell) )
                    {
                        is_empty = false;
                        break;
                    }
                }

                if (is_empty)
                    rect.width += sheet.GetColWidth(cell.m_col);
                else
                {
                    cell.m_col--;
                    break;
                }

                if (rect.width >= best_width)
                    break;
            }
            // this may extend out of sheet
            overflowCols = cell.m_col - col - cell_cols + 1;
            rightCol = wxMin(coords.m_col+cell_cols-1+overflowCols, num_cols - 1);
        }

        // redraw overflow cells individually for proper selection hilight
        if (overflowCols > 0)
        {
            // if overflowed then it's left aligned (yes I know ALIGN_LEFT=0)
            align &= ~wxSHEET_AttrAlignHoriz_Mask;
            align |= wxSHEET_AttrAlignLeft;

            wxRect clip(rect);
            clip.x += rectCell.width;

            int col_width;
            wxSheetCoords cell(coords);
            // draw each cell individually since it may be selected or not
            for (cell.m_col = col+cell_cols; cell.m_col <= rightCol; cell.m_col++)
            {
                col_width = sheet.GetColWidth(cell.m_col);
                clip.width = col_width - 1;
                dc.DestroyClippingRegion();
                dc.SetClippingRegion(clip);
                SetTextColoursAndFont(sheet, attr, dc, sheet.IsCellSelected(cell));
                sheet.DrawTextRectangle(dc, value, rect, align, orient);
                clip.x += col_width - 1;
            }

            rect = rectCell;
            rect.Inflate(-1);
            rect.width++;
            dc.DestroyClippingRegion();
        }
    }

    // Draw the text
    SetTextColoursAndFont(sheet, attr, dc, isSelected);
    sheet.DrawTextRectangle(dc, value, rect, align, orient);

    if (attr.GetOverflowMarker())
    {
        // Draw a marker to show that the contents has been clipped off
        int cellRight = sheet.GetColRight(rightCol);
        if (cellRight - rect.x < best_width)
        {
            int bmpWidth   = s_overflowBitmap.GetWidth();
            int bmpHeight  = s_overflowBitmap.GetHeight();
            int cellWidth  = sheet.GetColWidth(rightCol);
            int cellHeight = sheet.GetRowHeight(coords.m_row);

            if ((bmpWidth < cellWidth-3) && (bmpHeight < cellHeight-3))
            {
                int cellTop = sheet.GetRowTop(coords.m_row);

                int x = cellRight - bmpWidth - 2;
                int y = cellTop + (cellHeight - bmpHeight)/2;
                wxRect r(x-2, cellTop, bmpWidth+4-1, cellHeight-1);
                wxSheetCellAttr rightAttr(attr);
                if (overflowCols > 0)
                {
                    wxSheetCoords clipCell(coords.m_row, rightCol);
                    isSelected = sheet.IsCellSelected(clipCell);
                    rightAttr = sheet.GetAttr(clipCell);
                }

                // clear background for bitmap
                wxSheetCellRendererRefData::Draw(sheet, rightAttr, dc, r, coords, isSelected);
                dc.DrawBitmap( s_overflowBitmap, x, y, true );
            }
        }
    }
}
Ejemplo n.º 25
0
 virtual wxSize GetAdjustedSize( int minWidth,
                                 int WXUNUSED(prefHeight),
                                 int maxHeight )
 {
     return wxSize(wxMax(300,minWidth),wxMin(250,maxHeight));
 }
Ejemplo n.º 26
0
void wxSheetCellBoolRendererRefData::Draw(wxSheet& sheet,
        const wxSheetCellAttr& attr,
        wxDC& dc, const wxRect& rect,
        const wxSheetCoords& coords,
        bool isSelected)
{
    wxSheetCellRendererRefData::Draw(sheet, attr, dc, rect, coords, isSelected);

    // draw a check mark in the centre (ignoring alignment - TODO)
    wxSize size = GetBestSize(sheet, attr, dc, coords);

    // don't draw outside the cell
    wxCoord minSize = wxMin(rect.width, rect.height) - 1;
    if ((size.x >= minSize) || (size.y >= minSize))
        size.x = size.y = minSize - 2; // leave (at least) 1 pixel margin

    // draw a border around checkmark
    int align = attr.GetAlignment();

    wxRect rectBorder(rect.GetPosition(), size);

    if ((align & wxALIGN_RIGHT) != 0)
        rectBorder.x += rect.width - size.x - 2;
    else if ((align & wxALIGN_CENTRE_HORIZONTAL) != 0)
        rectBorder.x += rect.width/2 - size.x/2;
    else // wxALIGN_LEFT
        rectBorder.x += 2;

    if ((align & wxALIGN_BOTTOM) != 0)
        rectBorder.y += rect.height - size.y - 2;
    else if ((align & wxALIGN_CENTRE_VERTICAL) != 0)
        rectBorder.y += rect.height/2 - size.y/2;
    else // wxALIGN_TOP
        rectBorder.y += 2;

    bool value = false;
    if ( sheet.GetTable() && sheet.GetTable()->CanGetValueAs(coords, wxSHEET_VALUE_BOOL) )
        value = sheet.GetTable()->GetValueAsBool(coords);
    else
    {
        wxString strValue( sheet.GetCellValue(coords) );
        value = !( strValue.IsEmpty() || (strValue == wxT("0")) ||
                   (strValue.Lower() == wxT("f")) || (strValue.Lower() == wxT("false")));
    }

    if ( value )
    {
        wxRect rectMark = rectBorder;
#ifdef __WXMSW__
        // MSW DrawCheckMark() is weird (and should probably be changed...)
        rectMark.Inflate(-wxSHEET_CHECKMARK_MARGIN/2);
        rectMark.x++;
        rectMark.y++;
#else // !MSW
        rectMark.Inflate(-wxSHEET_CHECKMARK_MARGIN);
#endif // MSW/!MSW

        dc.SetTextForeground(attr.GetForegroundColour());
        dc.DrawCheckMark(rectMark);
    }

    dc.SetBrush(*wxTRANSPARENT_BRUSH);
    dc.SetPen(wxPen(attr.GetForegroundColour(), 1, wxSOLID));
    dc.DrawRectangle(rectBorder);
}
Ejemplo n.º 27
0
void wxHtmlTableCell::Layout(int w)
{
    ComputeMinMaxWidths();

    wxHtmlCell::Layout(w);

    /*

    WIDTH ADJUSTING :

    */

    if (m_WidthFloatUnits == wxHTML_UNITS_PERCENT)
    {
        if (m_WidthFloat < 0)
        {
            if (m_WidthFloat < -100)
                m_WidthFloat = -100;
            m_Width = (100 + m_WidthFloat) * w / 100;
        }
        else
        {
            if (m_WidthFloat > 100)
                m_WidthFloat = 100;
            m_Width = m_WidthFloat * w / 100;
        }
    }
    else
    {
        if (m_WidthFloat < 0) m_Width = w + m_WidthFloat;
        else m_Width = m_WidthFloat;
    }


    /*

    LAYOUT :

    */

    /* 1.  setup columns widths:

           The algorithm tries to keep the table size less than w if possible.
       */
    {
        int wpix = m_Width - (m_NumCols + 1) * m_Spacing - 2 * m_Border;  // Available space for cell content
        int i, j;

        // 1a. setup fixed-width columns:
        for (i = 0; i < m_NumCols; i++)
            if (m_ColsInfo[i].units == wxHTML_UNITS_PIXELS)
            {
                m_ColsInfo[i].pixwidth = wxMax(m_ColsInfo[i].width,
                                               m_ColsInfo[i].minWidth);
                wpix -= m_ColsInfo[i].pixwidth;
            }

        // 1b. Calculate maximum possible width if line wrapping would be disabled
        // Recalculate total width if m_WidthFloat is zero to keep tables as small
        // as possible.
        int maxWidth = 0;
        for (i = 0; i < m_NumCols; i++)
            if (m_ColsInfo[i].width == 0)
            {
                maxWidth += m_ColsInfo[i].maxWidth;
            }

        if (!m_WidthFloat)
        {
            // Recalculate table width since no table width was initially given
            int newWidth = m_Width - wpix +  maxWidth;

            // Make sure that floating-width columns will have the right size.
            // Calculate sum of all floating-width columns
            int percentage = 0;
            for (i = 0; i < m_NumCols; i++)
                if ((m_ColsInfo[i].units == wxHTML_UNITS_PERCENT) && (m_ColsInfo[i].width != 0))
                    percentage += m_ColsInfo[i].width;

            if (percentage >= 100)
                newWidth = w;
            else
                newWidth = newWidth * 100 / (100 - percentage);

            newWidth = wxMin(newWidth, w - (m_NumCols + 1) * m_Spacing - 2 * m_Border);
            wpix -= m_Width - newWidth;
            m_Width = newWidth;
        }


        // 1c. setup floating-width columns:
        int wtemp = wpix;
        for (i = 0; i < m_NumCols; i++)
            if ((m_ColsInfo[i].units == wxHTML_UNITS_PERCENT) && (m_ColsInfo[i].width != 0))
            {
                m_ColsInfo[i].pixwidth = wxMin(m_ColsInfo[i].width, 100) * wpix / 100;

                // Make sure to leave enough space for the other columns
                int minRequired = m_Border;
                for (j = 0; j < m_NumCols; j++)
                {
                    if ((m_ColsInfo[j].units == wxHTML_UNITS_PERCENT && j > i) ||
                        !m_ColsInfo[j].width)
                        minRequired += m_ColsInfo[j].minWidth;
                }
                m_ColsInfo[i].pixwidth = wxMax(wxMin(wtemp - minRequired, m_ColsInfo[i].pixwidth), m_ColsInfo[i].minWidth);

                wtemp -= m_ColsInfo[i].pixwidth;
            }
       wpix = wtemp; // minimum cells width

        // 1d. setup default columns (no width specification supplied):
        // The algorithm assigns calculates the maximum possible width if line
        // wrapping would be disabled and assigns column width as a fraction
        // based upon the maximum width of a column
        // FIXME: I'm not sure if this algorithm is conform to HTML standard,
        //        though it seems to be much better than the old one

        for (i = j = 0; i < m_NumCols; i++)
            if (m_ColsInfo[i].width == 0) j++;
        if (wpix < m_Border)
            wpix = m_Border;

        // Assign widths
        for (i = 0; i < m_NumCols; i++)
            if (m_ColsInfo[i].width == 0)
            {
                // Assign with, make sure not to drop below minWidth
                if (maxWidth)
                    m_ColsInfo[i].pixwidth = (int)(wpix * (m_ColsInfo[i].maxWidth / (float)maxWidth) + 0.5);
                else
                    m_ColsInfo[i].pixwidth = wpix / j;

                // Make sure to leave enough space for the other columns
                int minRequired = 0;
                int r;
                for (r = i + 1; r < m_NumCols; r++)
                {
                    if (!m_ColsInfo[r].width)
                        minRequired += m_ColsInfo[r].minWidth;
                }
                m_ColsInfo[i].pixwidth = wxMax(wxMin(wpix - minRequired, m_ColsInfo[i].pixwidth), m_ColsInfo[i].minWidth);

                if (maxWidth)
                {
                    if (m_ColsInfo[i].pixwidth > (wpix * (m_ColsInfo[i].maxWidth / (float)maxWidth) + 0.5))
                    {
                        int diff = (int)(m_ColsInfo[i].pixwidth - (wpix * m_ColsInfo[i].maxWidth / (float)maxWidth + 0.5));
                        maxWidth += diff - m_ColsInfo[i].maxWidth;
                    }
                    else
                        maxWidth -= m_ColsInfo[i].maxWidth;
                }
                wpix -= m_ColsInfo[i].pixwidth;
            }
    }

    /* 2.  compute positions of columns: */
    {
        int wpos = m_Spacing + m_Border;
        for (int i = 0; i < m_NumCols; i++)
        {
            m_ColsInfo[i].leftpos = wpos;
            wpos += m_ColsInfo[i].pixwidth + m_Spacing;
        }

        // add the remaining space to the last column
        if (m_NumCols > 0 && wpos < m_Width - m_Border)
            m_ColsInfo[m_NumCols-1].pixwidth += m_Width - wpos - m_Border;
    }

    /* 3.  sub-layout all cells: */
    {
        int *ypos = new int[m_NumRows + 1];

        int actcol, actrow;
        int fullwid;
        wxHtmlContainerCell *actcell;

        ypos[0] = m_Spacing + m_Border;
        for (actrow = 1; actrow <= m_NumRows; actrow++) ypos[actrow] = -1;
        for (actrow = 0; actrow < m_NumRows; actrow++)
        {
            if (ypos[actrow] == -1) ypos[actrow] = ypos[actrow-1];
            // 3a. sub-layout and detect max height:

            for (actcol = 0; actcol < m_NumCols; actcol++) {
                if (m_CellInfo[actrow][actcol].flag != cellUsed) continue;
                actcell = m_CellInfo[actrow][actcol].cont;
                fullwid = 0;
                for (int i = actcol; i < m_CellInfo[actrow][actcol].colspan + actcol; i++)
                    fullwid += m_ColsInfo[i].pixwidth;
                fullwid += (m_CellInfo[actrow][actcol].colspan - 1) * m_Spacing;
                actcell->SetMinHeight(m_CellInfo[actrow][actcol].minheight, m_CellInfo[actrow][actcol].valign);
                actcell->Layout(fullwid);

                if (ypos[actrow] + actcell->GetHeight() + m_CellInfo[actrow][actcol].rowspan * m_Spacing > ypos[actrow + m_CellInfo[actrow][actcol].rowspan])
                    ypos[actrow + m_CellInfo[actrow][actcol].rowspan] =
                            ypos[actrow] + actcell->GetHeight() + m_CellInfo[actrow][actcol].rowspan * m_Spacing;
            }
        }

        for (actrow = 0; actrow < m_NumRows; actrow++)
        {
            // 3b. place cells in row & let'em all have same height:

            for (actcol = 0; actcol < m_NumCols; actcol++)
            {
                if (m_CellInfo[actrow][actcol].flag != cellUsed) continue;
                actcell = m_CellInfo[actrow][actcol].cont;
                actcell->SetMinHeight(
                                 ypos[actrow + m_CellInfo[actrow][actcol].rowspan] - ypos[actrow] -  m_Spacing,
                                 m_CellInfo[actrow][actcol].valign);
                fullwid = 0;
                for (int i = actcol; i < m_CellInfo[actrow][actcol].colspan + actcol; i++)
                    fullwid += m_ColsInfo[i].pixwidth;
                fullwid += (m_CellInfo[actrow][actcol].colspan - 1) * m_Spacing;
                actcell->Layout(fullwid);
                actcell->SetPos(m_ColsInfo[actcol].leftpos, ypos[actrow]);
            }
        }
        m_Height = ypos[m_NumRows] + m_Border;
        delete[] ypos;
    }

    /* 4. adjust table's width if it was too small: */
    if (m_NumCols > 0)
    {
        int twidth = m_ColsInfo[m_NumCols-1].leftpos +
                     m_ColsInfo[m_NumCols-1].pixwidth + m_Spacing + m_Border;
        if (twidth > m_Width)
            m_Width = twidth;
    }
}
Ejemplo n.º 28
0
//+++-S-cf-------------------------------------------------------------------
//  NAME:       Draw()
//  DESC:       Draw Bar chart
//  PARAMETERS: CHART_HPAINT hp, 
//              CHART_HRECT hr
//  RETURN:     None
//----------------------------------------------------------------------E-+++
void wxPie3DChartPoints::Draw(
    CHART_HPAINT hp, 
    CHART_HRECT hr
)
{
    
    //-----------------------------------------------------------------------
    // Get sizes
    //-----------------------------------------------------------------------
    wxChartSizes *sizes = GetSizes();

    //-----------------------------------------------------------------------
    // Fit Ellisse in window
    //-----------------------------------------------------------------------
    int r = (int)wxMin( (int)hr->w / 2, 
        (int)(hr->h - 2 * sizes->GetSizeHeight() * ELLISSE_H) / 2 );
         
    if ( r > 0 )
    {
        int iNodes = GetCount();

        if ( iNodes > 0 )
        {
            int iData;
            int ValTot;         
            int iDatas = GetCount();
            for ( iData = 0, ValTot = 0; iData < iDatas; ++ iData )
                ValTot += static_cast<int>(GetYVal( iData ));

            hp->SetPen( *wxBLACK_PEN );

            double percent;
            double grad, grad1;
            double rad;
            int deep;
            int x, y, w, h;

			// Calc Size of Rectangle which hold Ellisse
            w = (int)floor(r * ELLISSE_W);
			h = (int)floor(r * ELLISSE_H);

			// Top corner left hand side
            x = hr->x + hr->w/2 - w/2;
            y = hr->y + hr->h/2 - h;
                        
            // Shadow Deep
            deep = (int)floor( SHADOW_DEEP * GetZoom() );
                        
			//---------------------------------------------------------------
			// Draw shadow part of chart
			//---------------------------------------------------------------      

			hp->DrawEllipticArc( 
				x, 
				y + deep, // Shadow Deep
				w, 
				h, 
				175, // Draw half Ellisse
				360);
			hp->DrawEllipticArc( 
				x, 
				y + deep, // Shadow Deep
				w, 
				h, 
				0, // Draw half Ellisse
				5);

			// left hand side line
			rad = DegToRad( 180 );
			
			hp->DrawLine( 
                EllipsePoint( w, h, x, y, rad ).x,
                EllipsePoint( w, h, x, y, rad ).y,
                EllipsePoint( w, h, x, y, rad ).x,
                EllipsePoint( w, h, x, y + deep, rad ).y + 1
            );

			// right hand side line
			rad = DegToRad( 360 );

            hp->DrawLine( 
                EllipsePoint( w, h, x, y, rad ).x,
                EllipsePoint( w, h, x, y, rad ).y,
                EllipsePoint( w, h, x, y, rad ).x,
                EllipsePoint( w - 180, h, x, y + deep, rad ).y
            );

			grad = 0;
			//int count = 0;
            for ( iData = 0; iData < iDatas; ++ iData )
            {
                hp->SetPen( *wxBLACK_PEN );
                hp->SetBrush( wxBrush(GetColor(iData), wxSOLID) );

                // Calc radiants
                percent = (double)(GetYVal(iData) * 100) / (double)ValTot;
                grad1    = grad + (double)(percent * 360) / (double)100;
                rad     = DegToRad( grad );
                
                hp->DrawEllipticArc( x, y, w, h, grad, grad1);

                //-----------------------------------------------------------
                // Fill the shadow with right color
                //-----------------------------------------------------------
                if ( grad1 > 180 )
                {
					//if (++count > 3)
					//	return;

                    // set colors to draw
                    hp->SetPen( 
                        wxPen(wxChartColors::GetDarkColor(
                            GetColor(iData), 15)) 
                    );
                    hp->SetBrush( 
                        wxBrush(wxChartColors::GetDarkColor(
                            GetColor(iData), 15), 
                        wxSOLID) 
                    );
                    
                    // Avoid redraw line
                    if ( grad1 < 360 )
                    {
                        hp->DrawLine( 
                            EllipsePoint( w, h, x, y, DegToRad( grad1 ) ).x,
                            EllipsePoint( w, h, x, y, DegToRad( grad1 ) ).y - 1,
                            EllipsePoint( w, h, x, y, DegToRad( grad1 ) ).x,
                            EllipsePoint( w, h, x, y + deep, 
                                DegToRad( grad1 ) ).y + 1
                        );
                    }
                    hp->FloodFill(
                        EllipsePoint( w, h, x, y, 
                            DegToRad( grad1 ) ).x - 3, // just inside
                        (int)floor(EllipsePoint( w, h, x, y, 
                            DegToRad( grad1 ) ).y + (double)deep/2), // middle
                        *wxWHITE
                    );
				}
                                
                //-----------------------------------------------------------
                // Only draw Label if user wants it
                //-----------------------------------------------------------
                if (!m_ShowLabel)
                    continue;

                wxString lbl; 
                wxLabel wxLbl;
                
                LABEL_POSITION p;
                if ( grad < 90 ||
                    grad > 270 )
                    p = RIGHT;
                else
                    p = LEFT;
                if ( grad  > 180 )
                    p = (LABEL_POSITION)( p | DOWN );
                else
                    p = (LABEL_POSITION)( p | UP );

                switch ( GetDisplayTag() )
                {
                case XVALUE:
                    lbl.Printf( wxT("%d"), static_cast<int>(GetXVal(iData)) );
                    wxLbl.Draw( hp, 
                        EllipsePoint( w, h, x, y, DegToRad( grad ) ).x, 
                        EllipsePoint( w, h, x, y, DegToRad( grad ) ).y, 
                        GetColor(iData), lbl, p );
                    break;
                case YVALUE:
                    lbl.Printf( wxT("%d"), static_cast<int>(GetYVal(iData)) );
                    wxLbl.Draw( hp, 
                        EllipsePoint( w, h, x, y, DegToRad( grad ) ).x, 
                        EllipsePoint( w, h, x, y, DegToRad( grad ) ).y, 
                        GetColor(iData), lbl, p );
                    break;
                case XVALUE_FLOAT:
                    lbl.Printf( wxT("%4.1f"), GetXVal(iData) );
                    wxLbl.Draw( hp, 
                                EllipsePoint( w, h, x, y, DegToRad( grad ) ).x, 
                                EllipsePoint( w, h, x, y, DegToRad( grad ) ).y, 
                                GetColor(iData), lbl, p );
                    break;
                case YVALUE_FLOAT:
                    lbl.Printf( wxT("%4.1f"), GetYVal(iData) );
                    wxLbl.Draw( hp, 
                                EllipsePoint( w, h, x, y, DegToRad( grad ) ).x, 
                                EllipsePoint( w, h, x, y, DegToRad( grad ) ).y, 
                                GetColor(iData), lbl, p );
                    break;
                    case NAME:
                    lbl = GetName(iData).c_str();
                    wxLbl.Draw( hp, 
                        EllipsePoint( w, h, x, y, DegToRad( grad ) ).x, 
                        EllipsePoint( w, h, x, y, DegToRad( grad ) ).y, 
                        GetColor(iData), lbl, p );
                    break;
                default:
                    break;            
                }

                grad = grad1;

            }

        }
    }
}
Ejemplo n.º 29
0
void GribRequestSetting::ApplyRequestConfig( unsigned rs, unsigned it, unsigned tr )
{
    //some useful  strings
    const wxString res[][RESOLUTIONS] = {
        {_T("0.25"), _T("0.5"), _T("1.0"), _T("2.0")},
        {_T("0.2"), _T("0.8"), _T("1.6"), wxEmptyString},
        {_T("0.05"), _T("0.25"), _T("1.0"), wxEmptyString}
    };

    IsZYGRIB = m_pMailTo->GetCurrentSelection() == ZYGRIB;
    if(IsZYGRIB) m_pModel->SetSelection(GFS);                       //Model is always GFS when Zygrib selected
    IsGFS = m_pModel->GetCurrentSelection() == GFS;
    bool IsRTOFS = m_pModel->GetCurrentSelection() == RTOFS;

    //populate resolution choice
    m_pResolution->Clear();
    for( int i = 0; i < RESOLUTIONS; i++ ) {
        if( res[m_pModel->GetCurrentSelection()][i] != wxEmptyString )
            m_pResolution->Append(res[m_pModel->GetCurrentSelection()][i]);
    }
     m_pResolution->SetSelection(rs);

    unsigned l;
     //populate time interval choice
    l = IsGFS ? 3 : IsRTOFS ? 12 : 6;
    m_pInterval->Clear();
    for( unsigned i=l; i<25; i*=2)
        m_pInterval->Append( wxString::Format(_T("%d"), i));
    m_pInterval->SetSelection(wxMin(it,m_pInterval->GetCount()-1));

    //populate time range choice
    l = IsZYGRIB ? 8 : IsGFS ? 16 : IsRTOFS ? 6 : 3;
    m_pTimeRange->Clear();
    for( unsigned i=2; i<l+1; i++)
        m_pTimeRange->Append( wxString::Format(_T("%d"), i));
    m_pTimeRange->SetSelection( wxMin(l-2, tr));

    m_pModel->Enable(!IsZYGRIB);
    m_pWind->SetValue( !IsRTOFS );
    m_pPress->SetValue( !IsRTOFS );
    m_pWaves->SetValue( m_RequestConfigBase.GetChar(8) == 'X' && IsGFS );
    m_pWaves->Enable( IsGFS && m_pTimeRange->GetCurrentSelection() < 7 );      //gfs & time range less than 8 days
    m_pRainfall->SetValue( m_RequestConfigBase.GetChar(9) == 'X' && IsGFS );
    m_pRainfall->Enable( IsGFS );
    m_pCloudCover->SetValue( m_RequestConfigBase.GetChar(10) == 'X' && IsGFS );
    m_pCloudCover->Enable( IsGFS );
    m_pAirTemp->SetValue( m_RequestConfigBase.GetChar(11) == 'X' && IsGFS );
    m_pAirTemp->Enable( IsGFS );
    m_pSeaTemp->SetValue( (m_RequestConfigBase.GetChar(12) == 'X' && (!IsZYGRIB && IsGFS)) || IsRTOFS );
    m_pSeaTemp->Enable( !IsZYGRIB && IsGFS );
    m_pWindGust->SetValue( m_RequestConfigBase.GetChar(14) == 'X' && IsGFS);
    m_pWindGust->Enable( IsGFS );
    m_pCAPE->SetValue( m_RequestConfigBase.GetChar(15) == 'X' && IsGFS );
    m_pCAPE->Enable( IsGFS );

    m_pAltitudeData->SetValue( IsGFS ? m_RequestConfigBase.GetChar(17) == 'X' : false );        //altitude data zigrib + saildocs only GFS
    m_pAltitudeData->Enable( IsGFS );
    m_p850hpa->SetValue( IsZYGRIB ? m_RequestConfigBase.GetChar(18) == 'X' : false );           //only zygrib
    m_p850hpa->Enable( IsZYGRIB );
    m_p700hpa->SetValue(  IsZYGRIB ? m_RequestConfigBase.GetChar(19) == 'X' : false );          //only zigrib
    m_p700hpa->Enable( IsZYGRIB );
    m_p500hpa->SetValue(  IsGFS ? m_RequestConfigBase.GetChar(20) == 'X' : false );             //zigrib + saildocs only GFS
    m_p300hpa->SetValue(  IsZYGRIB ? m_RequestConfigBase.GetChar(21) == 'X' : false  );         //only zigrib
    m_p300hpa->Enable( IsZYGRIB );

    m_pCurrent->SetValue( IsRTOFS );
    m_pCurrent->Enable( false );

    //show parameters only if necessary
    m_cMovingGribEnabled->Show(!IsZYGRIB);                                  //show/hide Moving settings
    m_fgMovingParams->ShowItems( m_cMovingGribEnabled->IsChecked() && m_cMovingGribEnabled->IsShown() );

    m_fgLog->ShowItems(IsZYGRIB);                                           //show/hide zigrib login

    m_pWModel->Show(IsZYGRIB && m_pWaves->IsChecked());                     //show/hide waves model

    m_fgAltitudeData->ShowItems(m_pAltitudeData->IsChecked());              //show/hide altitude params
}
Ejemplo n.º 30
0
bool wxMatrix2D::LoadFile( const wxString &filename, const wxArrayInt *cols )
{
    if (filename.IsNull()) return false;

    // valid separators for data
//  const char comma = 44;  // comma
    const char tab = 9;     // tab
    const char space = 32;  // space
//  const char cr = 13;     // carrage return

    wxFile loadfile;
    loadfile.Open( filename, wxFile::read );

    if (!loadfile.IsOpened()) return false;

    m_file_comments.Clear();
//  m_file_comments_positions.Clear();

    wxFileInputStream filestream( loadfile );
    wxTextInputStream textstream( filestream );

    int sizeof_data = 4000;
    double *data = (double*)malloc(sizeof_data*sizeof(double));
    if (data == (double*)NULL) return false;

    wxString line_str, num_str;

    int i, a, b, pos;
    int num_cols = 0;
    int num_rows = 0;
    int num_points = 0;
    int num_lines = 0;
    double point;

    bool fail = false;


    while ( !filestream.Eof() && !fail )
    {
        ++num_lines;

        line_str = textstream.ReadLine();
        if ( filestream.Eof() ) break;

        line_str.Trim(false);
        line_str.Trim(true);


        if (line_str.Left(1) == wxT("#"))
        {
            m_file_comments.Add( line_str );
            //m_file_comments_positions.Add(num_lines);
        }
        else
        {
            ++num_rows;

            // do this once to figure out how many columns of data there is unless already given
            if ( num_cols < 1 )
            {
                for (i = 0; i < 10000; ++i)
                {
                    line_str.Trim(false);
                    a = line_str.Find(space);
                    b = line_str.Find(tab);

                    if ( (a != -1) && (b != -1) ) pos = wxMin( a, b );
                    else if ( a != -1 ) pos = a;
                    else pos = b;

                    if ( pos != -1 ) num_str = line_str.Left( pos );
                    else num_str = line_str;

                    if ( num_str.ToDouble(&point) )
                    {
                        printf("i%d pts%d cols%d rows%d pos%d pt%lf \n", i, num_points, num_cols, num_rows, pos, point); fflush(stdout);
                        //data[i] = point;
                        ++num_cols;
                        line_str = line_str.Right( line_str.Len() - num_str.Len() );
                        ++num_points;
                    }
                    else
                    {
                        i = 10000;
                        break;
                    }
                }
            }
            else
            {
                if ( num_points > sizeof_data - num_cols*2 )
                {
                    data = (double*)realloc( data, sizeof_data+1000 );
                }
                for (i = 0; i < num_cols; ++i)
                {
                    line_str.Trim(false);
                    a = line_str.Find(space);
                    b = line_str.Find(tab);

                    if ( (a != -1) && (b != -1) ) pos = wxMin( a, b );
                    else if ( a != -1 ) pos = a;
                    else pos = b;

                    if ( pos != -1 ) num_str = line_str.Left( pos );
                    else num_str = line_str;

                    if ( num_str.ToDouble(&point) )
                    {
                        printf("i%d pts%d cols%d rows%d pos%d pt%lf \n", i, num_points, num_cols, num_rows, pos, point); fflush(stdout);
                        //data[numpoints*numcolumns + i] = point;
                        line_str = line_str.Right( line_str.Len() - num_str.Len() );
                        ++num_points;
                    }
                    else
                    {
                        // if not just a blank line then data is wrong
                        if (i != 0)
                        {
                            fail = true;
                            wxMessageBox(wxT("# for comments\n7   4\n33  25\n..."),
                                         wxT("Invalid data file format"), wxOK);
                        }
                        i = num_cols;
                        break;
                    }
                }
            }
        }
    }

    // not static
    data = (double*)realloc( data, (num_points+1)*sizeof(double) );
    Create( num_cols, num_rows, data, false );
    loadfile.Close();
    return true;
}