Example #1
0
/**
 * Function ClipAreaPolygon
 * Process an area that has been modified, by clipping its polygon against itself.
 * This may change the number and order of copper areas in the net.
 * @param aNewZonesList = a PICKED_ITEMS_LIST * where to store new areas pickers (useful in
 *                        undo commands) can be NULL
 * @param aCurrArea = the zone to process
 * @param bMessageBoxInt == true, shows message when clipping occurs.
 * @param  bMessageBoxArc == true, shows message when clipping can't be done due to arcs.
 * @param bRetainArcs = true to handle arcs (not really used in KiCad)
 * @return:
 *  -1 if arcs intersect other sides, so polygon can't be clipped
 *   0 if no intersecting sides
 *   1 if intersecting sides
 * Also sets areas->utility1 flags if areas are modified
 */
int BOARD::ClipAreaPolygon( PICKED_ITEMS_LIST * aNewZonesList,
                            ZONE_CONTAINER* aCurrArea,
                            bool bMessageBoxArc, bool bMessageBoxInt, bool bRetainArcs )
{
    CPolyLine* curr_polygon = aCurrArea->m_Poly;
    int        test = TestAreaPolygon( aCurrArea ); // this sets utility2 flag

    if( test == -1 && !bRetainArcs )
        test = 1;

    if( test == -1 )
    {
        // arc intersections, don't clip unless bRetainArcs == false
        if( bMessageBoxArc && bDontShowSelfIntersectionArcsWarning == false )
        {
            wxString str;
            str.Printf( wxT( "Area %08lX of net \"%s\" has arcs intersecting other sides.\n" ),
                        aCurrArea->GetTimeStamp(), GetChars( aCurrArea->m_Netname ) );
            str += wxT( "This may cause problems with other editing operations,\n" );
            str += wxT( "such as adding cutouts. It can't be fixed automatically.\n" );
            str += wxT( "Manual correction is recommended." );
            wxMessageBox( str );
        }

        return -1;  // arcs intersect with other sides, error
    }

    // mark all areas as unmodified except this one
    for( unsigned ia = 0; ia < m_ZoneDescriptorList.size(); ia++ )
        m_ZoneDescriptorList[ia]->utility = 0;

    aCurrArea->utility = 1;

    if( test == 1 )
    {
        // non-arc intersections, clip the polygon
        if( bMessageBoxInt && bDontShowSelfIntersectionWarning == false )
        {
            wxString str;
            str.Printf( wxT( "Area %08lX of net \"%s\" is self-intersecting and will be clipped.\n" ),
                        aCurrArea->GetTimeStamp(), GetChars( aCurrArea->m_Netname ) );
            str += wxT( "This may result in splitting the area.\n" );
            str += wxT( "If the area is complex, this may take a few seconds." );
            wxMessageBox( str );

//          bDontShowSelfIntersectionWarning = dlg.bDontShowBoxState;
        }
    }

//** TODO test for cutouts outside of area
//**    if( test == 1 )
    {
        std::vector<CPolyLine*>* pa = new std::vector<CPolyLine*>;
        curr_polygon->UnHatch();
        int n_poly = aCurrArea->m_Poly->NormalizeAreaOutlines( pa, bRetainArcs );

        // i.e if clipping has created some polygons, we must add these new copper areas.
        if( n_poly > 1 )
        {
            ZONE_CONTAINER* NewArea;

            for( int ip = 1; ip < n_poly; ip++ )
            {
                // create new copper area and copy poly into it
                CPolyLine* new_p = (*pa)[ip - 1];
                NewArea = AddArea( aNewZonesList, aCurrArea->GetNet(), aCurrArea->GetLayer(),
                                   wxPoint(0, 0), CPolyLine::NO_HATCH );

                // remove the poly that was automatically created for the new area
                // and replace it with a poly from NormalizeAreaOutlines
                delete NewArea->m_Poly;
                NewArea->m_Poly = new_p;
                NewArea->m_Poly->Hatch();
                NewArea->utility = 1;
            }
        }

        curr_polygon->Hatch();
        delete pa;
    }

    return test;
}
Example #2
0
void ExportMultipleDatasetsSelect(wxWindow* pWnd, wxVector<IGxDataset*> &paDatasets)
{
    wxCHECK_RET(paDatasets.size() > 1, wxT("The input dataset array is empty"));

    wxGxContainerDialog dlg(pWnd, wxID_ANY, _("Select output"));
    dlg.SetAllFilters(false);
    dlg.ShowExportFormats(true);

    wxGxObject* pGxSrcObj = dynamic_cast<wxGxObject*>(paDatasets[0]);
    wxGISEnumDatasetType eType = paDatasets[0]->GetType();
    int eSubType = paDatasets[0]->GetSubType();
    bool bDefaultSet = false;
    int eDefaulSubType = 0;

    if (eType == enumGISFeatureDataset)
    {
        for (size_t i = enumVecUnknown + 1; i < enumVecMAX; ++i)
        {
            wxGISEnumVectorDatasetType eCurrentSubType = (wxGISEnumVectorDatasetType)i;
            if (eCurrentSubType != eSubType && IsFileDataset(enumGISFeatureDataset, eCurrentSubType))
            {
                if (bDefaultSet)
                {
                    dlg.AddFilter(new wxGxFeatureDatasetFilter(eCurrentSubType), false);
                }
                else
                {
                    dlg.AddFilter(new wxGxFeatureDatasetFilter(eCurrentSubType), true);
                    bDefaultSet = true;
                    eDefaulSubType = eCurrentSubType;
                }
            }
        }

        if (eSubType != enumVecPostGIS)
        {
            dlg.AddFilter(new wxGxFeatureDatasetFilter(enumVecPostGIS), false);
        }
    }
    else if (eType == enumGISRasterDataset)
    {
        //for (size_t i = enumRasterUnknown + 1; i < enumRasterMAX; ++i)
        //{
        //    wxGISEnumRasterDatasetType eCurrentSubType = (wxGISEnumRasterDatasetType)i;
        //    if (eCurrentSubType != eSubType && IsFileDataset(enumGISRasterDataset, eCurrentSubType))
        //    {
        //        if (bDefaultSet)
        //        {
        //            dlg.AddFilter(new wxGxRasterDatasetFilter(eCurrentSubType), false);
        //        }
        //        else
        //        {
        //            dlg.AddFilter(new wxGxRasterDatasetFilter(eCurrentSubType), true);
        //            bDefaultSet = true;
        //            eDefaulSubType = eCurrentSubType;
        //        }
        //    }
        //}

        //if (eSubType != enumRasterPostGIS)
        //{
        //    dlg.AddFilter(new wxGxRasterDatasetFilter(enumRasterPostGIS), false);
        //}
    }
    else if (eType == enumGISTableDataset)
    {
        for (size_t i = enumTableUnknown + 1; i < enumTableMAX; ++i)
        {
            wxGISEnumTableDatasetType eCurrentSubType = (wxGISEnumTableDatasetType)i;
            if (eCurrentSubType != eSubType && IsFileDataset(enumGISTableDataset, eCurrentSubType))
            {
                if (bDefaultSet)
                {
                    dlg.AddFilter(new wxGxTableDatasetFilter(eCurrentSubType), false);
                }
                else
                {
                    dlg.AddFilter(new wxGxTableDatasetFilter(eCurrentSubType), true);
                    bDefaultSet = true;
                    eDefaulSubType = eCurrentSubType;
                }
            }
        }

        if (eSubType != enumTablePostgres)
        {
            dlg.AddFilter(new wxGxTableDatasetFilter(enumTablePostgres), false);
        }
    }


    dlg.AddShowFilter(new wxGxFolderFilter());
    dlg.AddShowFilter(new wxGxRemoteDBSchemaFilter());
    dlg.ShowCreateButton(true);

    wxGxObject* pGxParentObj = pGxSrcObj->GetParent();
    wxString sStartLoc;

    if (pGxParentObj)
    {
        while (NULL != pGxParentObj)
        {
            wxGxObjectContainer* pGxCont = wxDynamicCast(pGxParentObj, wxGxObjectContainer);
            if (NULL != pGxCont && pGxCont->CanCreate(enumGISFeatureDataset, eDefaulSubType))
            {
                break;
            }
            else
            {
                pGxParentObj = pGxParentObj->GetParent();
            }
        }
        if (pGxParentObj)
        {
            sStartLoc = pGxParentObj->GetFullName();
        }
    }

    wxGISAppConfig oConfig = GetConfig();
    if (oConfig.IsOk())
    {
        if (eType == enumGISFeatureDataset)
        {
            sStartLoc = oConfig.Read(enumGISHKCU, dlg.GetAppName() + wxT("/lastpath/expm_vector_ds/path"), sStartLoc);
        }
        else if (eType == enumGISRasterDataset)
        {
            sStartLoc = oConfig.Read(enumGISHKCU, dlg.GetAppName() + wxT("/lastpath/expm_raster_ds/path"), sStartLoc);
        }
        else if (eType == enumGISTableDataset)
        {
            sStartLoc = oConfig.Read(enumGISHKCU, dlg.GetAppName() + wxT("/lastpath/expm_table_ds/path"), sStartLoc);
        }
    }

    if (!sStartLoc.IsEmpty())
        dlg.SetStartingLocation(sStartLoc);

    if (dlg.ShowModal() == wxID_OK)
    {
        wxGxObjectFilter* pFilter = dlg.GetCurrentFilter();
        if (NULL == pFilter)
        {
            wxMessageBox(_("Unexpected error"), _("Error"), wxCENTRE | wxOK | wxICON_ERROR, pWnd);
            wxLogError(_("Null wxGxObjectFilter returned"));
            return;
        }

        CPLString sPath = dlg.GetPath();
        wxString sCatalogPath = dlg.GetLocation()->GetFullName();

        if (oConfig.IsOk())
        {
            if (eType == enumGISFeatureDataset)
            {
                oConfig.Write(enumGISHKCU, dlg.GetAppName() + wxT("/lastpath/expm_vector_ds/path"), sCatalogPath);
            }
            else if (eType == enumGISRasterDataset)
            {
                oConfig.Write(enumGISHKCU, dlg.GetAppName() + wxT("/lastpath/expm_raster_ds/path"), sCatalogPath);
            }
            else if (eType == enumGISTableDataset)
            {
                oConfig.Write(enumGISHKCU, dlg.GetAppName() + wxT("/lastpath/expm_table_ds/path"), sCatalogPath);
            }
        }

        //TODO: Now we create the copies (new names) instead of overwrite, but should show table with exist names and new names. If user set the same name - overwrite
        // |----------------|------------------|
        // |    dataset1    |  dataset1 (1)    |
        // |    dataset2    |  dataset2 (1)    |
        // |    dataset3    |  dataset3 (2)    |
        // |----------------|------------------|

        wxVector<EXPORTED_DATASET> paExportDatasets;
        for (size_t i = 0; i < paDatasets.size(); ++i)
        {
            wxGxObject* pGxSrcDatasetObj = dynamic_cast<wxGxObject*>(paDatasets[i]);
            if (NULL == pGxSrcDatasetObj)
            {
                continue;
            }
            wxString sNewName = CheckUniqName(sPath, pGxSrcDatasetObj->GetBaseName(), pFilter->GetExt());
            EXPORTED_DATASET ds = { sNewName, paDatasets[i] };
            paExportDatasets.push_back(ds);
        }

        if (eType == enumGISFeatureDataset)
        {
            ExportMultipleVectorDatasets(pWnd, sPath, pFilter, paExportDatasets);
        }
        else if (eType == enumGISRasterDataset)
        {
            ExportMultipleRasterDatasets(pWnd, sPath, pFilter, paExportDatasets);
        }
        else if (eType == enumGISTableDataset)
        {
            ExportMultipleTableDatasets(pWnd, sPath, pFilter, paExportDatasets);
        }
    }
}
Example #3
0
void ExportMultipleVectorDatasets(wxWindow* pWnd, const CPLString &sPath, wxGxObjectFilter* const pFilter, wxVector<EXPORTED_DATASET> &paDatasets)
{
    wxCHECK_RET(pWnd && pFilter && paDatasets.size() > 1, wxT("The input pointer is NULL or datasets array is empty"));

    wxGISProgressDlg ProgressDlg(_("Exporting..."), _("Begin operation..."), 100, pWnd);
    ProgressDlg.SetAddPercentToMessage(false);
    ProgressDlg.ShowProgress(true);

    for (size_t i = 0; i < paDatasets.size(); ++i)
    {
        ProgressDlg.SetTitle(wxString::Format(_("Proceed %ld of %ld..."), i + 1, paDatasets.size()));
        wxGISDataset* pDataset = paDatasets[i].pDSet->GetDataset(false, &ProgressDlg);
        wxVector<wxGISFeatureDataset*> apFeatureDatasets;
        if (pDataset->GetSubsetsCount() == 0)
        {
            wxGISFeatureDataset* pFeatureDataset = wxDynamicCast(pDataset, wxGISFeatureDataset);
            if (NULL != pFeatureDataset)
            {
                pFeatureDataset->Reference();
                apFeatureDatasets.push_back(pFeatureDataset);
            }
        }
        else
        {
            for (size_t j = 0; j < pDataset->GetSubsetsCount(); ++j)
            {
                wxGISFeatureDataset* pFeatureDataset = wxDynamicCast(pDataset->GetSubset(j), wxGISFeatureDataset);
                if (NULL != pFeatureDataset)
                {
                    pFeatureDataset->Reference();
                    apFeatureDatasets.push_back(pFeatureDataset);
                }
            }
        }

        if (apFeatureDatasets.size() == 0)
        {
            wxMessageBox(_("The dataset is empty"), _("Error"), wxCENTRE | wxICON_ERROR | wxOK, pWnd);
            wxLogError(_("wxGISFeatureDataset pointer is null returned"));
            return;
        }

        for (size_t j = 0; j < apFeatureDatasets.size(); ++j)
        {
            if(!ProgressDlg.Continue())
                break;
            if (!apFeatureDatasets[j]->IsOpened())
            {
                if (!apFeatureDatasets[j]->Open(0, TRUE, false, &ProgressDlg))
                {
                    wxMessageBox(ProgressDlg.GetLastMessage(), _("Error"), wxCENTRE | wxICON_ERROR | wxOK, pWnd);
                    wxLogError(ProgressDlg.GetLastMessage());
                    wsDELETE(apFeatureDatasets[j]);
                    continue;
                }
            }

            if (!ExportFormat(apFeatureDatasets[j], sPath, paDatasets[i].sName, pFilter, wxGISNullSpatialFilter, NULL, NULL, true, static_cast<ITrackCancel*>(&ProgressDlg)))
            {
                wxMessageBox(ProgressDlg.GetLastMessage(), _("Error"), wxCENTRE | wxICON_ERROR | wxOK, pWnd);
                wxLogError(ProgressDlg.GetLastMessage());
                wsDELETE(apFeatureDatasets[j]);
                continue;
            }
            wsDELETE(apFeatureDatasets[j]);
        }
    }

    if (ProgressDlg.GetWarningCount() > 0 && ProgressDlg.Continue())
    {
        ShowMessageDialog(pWnd, ProgressDlg.GetWarnings());
    }
}
Example #4
0
/* init board, route traces*/
void PCB_EDIT_FRAME::Autoroute( wxDC* DC, int mode )
{
    int      start, stop;
    MODULE*  Module = NULL;
    D_PAD*   Pad    = NULL;
    int      autoroute_net_code = -1;
    wxString msg;

    if( GetBoard()->GetCopperLayerCount() > 1 )
    {
        Route_Layer_TOP    = GetScreen()->m_Route_Layer_TOP;
        Route_Layer_BOTTOM = GetScreen()->m_Route_Layer_BOTTOM;
    }
    else
    {
        Route_Layer_TOP = Route_Layer_BOTTOM = LAYER_N_BACK;
    }

    switch( mode )
    {
    case ROUTE_NET:
        if( GetScreen()->GetCurItem() )
        {
            switch( GetScreen()->GetCurItem()->Type() )
            {
            case PCB_PAD_T:
                Pad = (D_PAD*) GetScreen()->GetCurItem();
                autoroute_net_code = Pad->GetNet();
                break;

            default:
                break;
            }
        }
        if( autoroute_net_code <= 0 )
        {
            wxMessageBox( _( "Net not selected" ) );
            return;
        }
        break;

    case ROUTE_MODULE:
        Module = (MODULE*) GetScreen()->GetCurItem();
        if( (Module == NULL) || (Module->Type() != PCB_MODULE_T) )
        {
            wxMessageBox( _( "Module not selected" ) );
            return;
        }
        break;

    case ROUTE_PAD:
        Pad = (D_PAD*) GetScreen()->GetCurItem();

        if( (Pad == NULL)  || (Pad->Type() != PCB_PAD_T) )
        {
            wxMessageBox( _( "Pad not selected" ) );
            return;
        }

        break;
    }

    if( (GetBoard()->m_Status_Pcb & LISTE_RATSNEST_ITEM_OK ) == 0 )
        Compile_Ratsnest( DC, true );

    /* Set the flag on the ratsnest to CH_ROUTE_REQ. */
    for( unsigned ii = 0; ii < GetBoard()->GetRatsnestsCount(); ii++ )
    {
        RATSNEST_ITEM* ptmp = &GetBoard()->m_FullRatsnest[ii];
        ptmp->m_Status &= ~CH_ROUTE_REQ;

        switch( mode )
        {
        case ROUTE_ALL:
            ptmp->m_Status |= CH_ROUTE_REQ;
            break;

        case ROUTE_NET:
            if( autoroute_net_code == ptmp->GetNet() )
                ptmp->m_Status |= CH_ROUTE_REQ;
            break;

        case ROUTE_MODULE:
        {
            D_PAD* pt_pad = (D_PAD*) Module->m_Pads;
            for( ; pt_pad != NULL; pt_pad = pt_pad->Next() )
            {
                if( ptmp->m_PadStart == pt_pad )
                    ptmp->m_Status |= CH_ROUTE_REQ;

                if( ptmp->m_PadEnd == pt_pad )
                    ptmp->m_Status |= CH_ROUTE_REQ;
            }

            break;
        }

        case ROUTE_PAD:
            if( ( ptmp->m_PadStart == Pad ) || ( ptmp->m_PadEnd == Pad ) )
                ptmp->m_Status |= CH_ROUTE_REQ;

            break;
        }
    }

    start = time( NULL );

    /* Calculation of no fixed routing to 5 mils and more. */
    RoutingMatrix.m_GridRouting = (int)GetScreen()->GetGridSize().x;

    if( RoutingMatrix.m_GridRouting < (5*IU_PER_MILS) )
        RoutingMatrix.m_GridRouting = 5*IU_PER_MILS;


    /* Calculated ncol and nrow, matrix size for routing. */
    RoutingMatrix.ComputeMatrixSize( GetBoard() );

    m_messagePanel->EraseMsgBox();

    /* Map the board */
    RoutingMatrix.m_RoutingLayersCount = 1;

    if( Route_Layer_TOP != Route_Layer_BOTTOM )
        RoutingMatrix.m_RoutingLayersCount = 2;

    if( RoutingMatrix.InitRoutingMatrix() < 0 )
    {
        wxMessageBox( _( "No memory for autorouting" ) );
        RoutingMatrix.UnInitRoutingMatrix();  /* Free memory. */
        return;
    }

    SetStatusText( _( "Place Cells" ) );
    PlaceCells( GetBoard(), -1, FORCE_PADS );

    /* Construction of the track list for router. */
    RoutingMatrix.m_RouteCount = Build_Work( GetBoard() );

    // DisplayRoutingMatrix( m_canvas, DC );

    Solve( DC, RoutingMatrix.m_RoutingLayersCount );

    /* Free memory. */
    FreeQueue();
    InitWork();             /* Free memory for the list of router connections. */
    RoutingMatrix.UnInitRoutingMatrix();
    stop = time( NULL ) - start;
    msg.Printf( wxT( "time = %d second%s" ), stop, ( stop == 1 ) ? wxT( "" ) : wxT( "s" ) );
    SetStatusText( msg );
}
Example #5
0
//------------------------------------------------------------------------------
void OutputTree::OnCompareNumericColumns(wxCommandEvent &event)
{
   #ifdef DEBUG_COMPARE
   MessageInterface::ShowMessage("OutputTree::OnCompareNumericColumns() entered\n");
   #endif
   
   ReportFile *theReport =
      (ReportFile*) theGuiInterpreter->GetConfiguredObject(theSubscriberName.c_str());
   
   if (!theReport)
   {
      MessageInterface::ShowMessage
         ("OutputTree::OnCompareNumericColumns() The ReportFile: %s is NULL.\n",
          theSubscriberName.WX_TO_C_STRING);
      return;
   }
   
   std::string basefilename = theReport->GetFullPathFileName();
   StringArray colTitles = theReport->GetRefObjectNameArray(Gmat::PARAMETER);
   wxString filename1 =
      wxFileSelector("Choose a file to open", "", "", "report|eph|txt",
                     "Report files (*.report)|*.report|"
                     "Text files (*.txt)|*.txt|"
                     "Text ephemeris files (*.eph)|*.eph|"
                     "All files (*.*)|*.*");
   
   if (filename1.empty())
      return;
   
   Real tol = GmatFileUtil::COMPARE_TOLERANCE;
   wxString tolStr;
   tolStr.Printf("%e", tol);
   tolStr = wxGetTextFromUser("Enter absolute tolerance to be used in flagging: ",
                              "Tolerance", tolStr, this);
   
   if (!tolStr.ToDouble(&tol))
   {
      wxMessageBox("Entered Invalid Tolerance", "Error", wxOK, this);
      return;
   }
    
   StringArray output =
      GmatFileUtil::CompareNumericColumns(1, basefilename.c_str(), filename1.c_str(), "", "",
                                          tol);
   
   ViewTextFrame *compWindow = GmatAppData::Instance()->GetCompareWindow();
   if (compWindow == NULL)
   {
      compWindow = 
         new ViewTextFrame(GmatAppData::Instance()->GetMainFrame(),
                           _T("Compare Utility"), 50, 50, 800, 500, "Permanent");
      GmatAppData::Instance()->SetCompareWindow(compWindow);
      wxString msg;
      msg.Printf(_T("GMAT Build Date: %s %s\n\n"),  __DATE__, __TIME__);  
      compWindow->AppendText(msg);
   }
   
   compWindow->Show(true);
   
   for (unsigned int i=0; i<output.size(); i++)
   {
      compWindow->AppendText(wxString(output[i].c_str()));
      MessageInterface::ShowMessage(output[i].c_str());
   }
}
Example #6
0
void NyqBench::OnFindDialog(wxFindDialogEvent & e)
{
    wxEventType type = e.GetEventType();

    if (type == wxEVT_COMMAND_FIND_CLOSE) {
        wxFindReplaceDialog *dlg = e.GetDialog();

        dlg->Destroy();

        int flags = mFindData.GetFlags();

        gPrefs->Write(wxT("NyqBench/Find/Down"), (flags & wxFR_DOWN) != 0);
        gPrefs->Write(wxT("NyqBench/Find/Word"), (flags & wxFR_WHOLEWORD) != 0);
        gPrefs->Write(wxT("NyqBench/Find/Case"), (flags & wxFR_MATCHCASE) != 0);

        mFindDlg = NULL;
        mFindText = NULL;

        return;
    }

    wxString text = mFindText->GetValue();

#if defined(__WXMSW__)
    // We cheat on Windows.  We know that the Windows text control
    // uses CRLF for line endings and if we don't account for that,
    // the selection positions will be off.
    //
    // Not sure why I thought I needed this, but it appears not to
    // be.  Leaving just in case.
    //
    // text.Replace(wxT("\n"), wxT("\r\n"));
#endif

    size_t startpos = mFindText->GetInsertionPoint();
    size_t len = mFindText->GetLastPosition();
    size_t pos;

    wxString find = e.GetFindString();
    bool down = (e.GetFlags() & wxFR_DOWN) != 0;
    bool mixed = (e.GetFlags() & wxFR_MATCHCASE) != 0;

    if (!mixed) {
        text.MakeUpper();
        find.MakeUpper();
    }

    if (down) {
        pos = text.find(find, startpos);
        if (type == wxEVT_COMMAND_FIND_NEXT && pos == startpos && pos < len) {
            pos = text.find(find, startpos + 1);
        }
    }
    else {
        pos = text.rfind(find, startpos);
        if (type == wxEVT_COMMAND_FIND_NEXT && pos == startpos && pos > 0) {
            pos = text.rfind(find, startpos - 1);
        }
    }

    if (pos == wxString::npos) {
        wxMessageBox(_("No matches found"),
                     _("Nyquist Effect Workbench"),
                     wxOK | wxCENTER,
                     e.GetDialog());

        return;
    }

    mFindText->SetInsertionPoint((long)pos);

#if defined(__WXGTK__)
    // GTK's selection and intertion pointer interact where the insertion
    // pointer winds up after the second parameter, so we reverse them to
    // force the pointer at the beginning of the selection.  Doing so
    // allows reverse find to work properly.
    mFindText->SetSelection((long)(pos + find.Length()), (long)pos);
#else
    mFindText->SetSelection((long)pos, (long)(pos + find.Length()));
#endif

#if defined(__WXMAC__)
    // Doing this coaxes the text control to update the selection.  Without
    // it the selection doesn't appear to change if the found string is within
    // the currently displayed text, i.e., no reposition is needed.
    mFindText->Show(false);
    mFindText->Show(true);
#endif
}
/**
 * \brief
 */
bool NewClassDlg::ValidateInput()
{
    // validate the class name
    if(!IsValidCppIndetifier(m_textClassName->GetValue())) {
        wxString msg;
        msg << wxT("'") << m_textClassName->GetValue() << _("' is not a valid C++ qualifier");
        wxMessageBox(msg, _("CodeLite"), wxOK | wxICON_WARNING);
        return false;
    }

    // validate the namespace
    if(!m_textCtrlNamespace->GetValue().IsEmpty()) {
        wxArrayString namespacesList;
        this->GetNamespacesList(namespacesList);
        // validate each namespace
        for(unsigned int i = 0; i < namespacesList.Count(); i++) {
            if(!IsValidCppIndetifier(namespacesList[i])) {
                wxString msg;
                msg << wxT("'") << namespacesList[i] << _("' is not a valid C++ qualifier");
                wxMessageBox(msg, _("CodeLite"), wxOK | wxICON_WARNING);
                return false;
            }
        }
    }

    // validate the path of the class
    wxString path(m_textCtrlGenFilePath->GetValue());
    if(!wxDir::Exists(path)) {
        wxString msg;
        msg << wxT("'") << path << _("': directory does not exist");
        wxMessageBox(msg, _("CodeLite"), wxOK | wxICON_WARNING);
        return false;
    }

    if(GetClassFile().IsEmpty()) {
        wxMessageBox(_("Empty file name"), _("CodeLite"), wxOK | wxICON_WARNING);
        return false;
    }

    wxString cpp_file;
    cpp_file << GetClassPath() << wxFileName::GetPathSeparator() << GetClassFile() << wxT(".cpp");
    if(wxFileName::FileExists(cpp_file)) {
        if(wxMessageBox(
               wxString::Format(_("A file with this name: '%s' already exists, continue anyway?"), cpp_file.GetData()),
               _("CodeLite"),
               wxYES_NO | wxICON_WARNING) == wxNO) {
            return false;
        }
    }
    wxString h_file;
    h_file << GetClassPath() << wxFileName::GetPathSeparator() << GetClassFile() << wxT(".h");
    if(wxFileName::FileExists(h_file)) {
        if(wxMessageBox(
               wxString::Format(_("A file with this name: '%s' already exists, continue anyway?"), h_file.GetData()),
               _("CodeLite"),
               wxYES_NO | wxICON_WARNING) == wxNO) {
            return false;
        }
    }

    if(GetVirtualDirectoryPath().IsEmpty()) {
        wxMessageBox(_("Please select a virtual directory"), _("CodeLite"), wxOK | wxICON_WARNING);
        return false;
    }
    return true;
}
void MyFrame::OnAbout(wxCommandEvent& event)
{
	wxMessageBox("This is a wxWidgets app for testing OneDrive Cloud.",
		"About OneDriveTest", wxOK | wxICON_INFORMATION);
}
bool ROSMain_features() {
	CoSLAM& coSLAM = MyApp::coSLAM;
	/////////////////////////1.GPU initilization/////////////////////////
	//initialization for CG;
	glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
	glutCreateWindow(" ");
	glutHideWindow();

	glewInit();

	V3D_GPU::Cg_ProgramBase::initializeCg();

	//////////////////////////2.read video information//////////////////
	try {
//		for(int c = 0; c < coSLAM.numCams; c++){
//			coSLAM.slam[c].videoReader = &MyApp::aviReader[c];
//		}

		coSLAM.init(false);
		MyApp::bInitSucc = true;
		logInfo("Loading video sequences.. OK!\n");
	} catch (SL_Exception& e) {
		logInfo(e.what());
#ifdef WIN32
		wxMessageBox(e.what());
#endif
		return 0;
	}

	//notify the GUI thread to create GUIs
	MyApp::broadcastCreateGUI();

	//wait for the accomplishment of creating GUIs
	MyApp::waitCreateGUI();

	for (int i = 0; i < coSLAM.numCams; i++){
		MyApp::videoWnd[i]->setSLAMData(i, &coSLAM);
		vector<float> reprojErrStatic, reprojErrDynamic;
		vector<int> frameNumber;
		MyApp::s_reprojErrDynamic.push_back(reprojErrStatic);
		MyApp::s_reprojErrStatic.push_back(reprojErrDynamic);
		MyApp::s_frameNumber.push_back(frameNumber);
	}


	MyApp::modelWnd1->setSLAMData(&coSLAM);
	MyApp::modelWnd2->setSLAMData(&coSLAM);
	MyApp::broadcastCreateGUI();

	//for measuring the timings
	Timings timingsPerStep;
	Timings timingsReadFrame;
	Timings timingsNewMapPonits;

	/* start the SLAM process*/
	try {
		coSLAM.readFrame();
		//copy the data to buffers for display
		updateDisplayData();
		//initialise the map points
		for (int i = 0; i < coSLAM.numCams; i++) {
			printf("slam[%d].m_camPos.size(): %d\n", i, coSLAM.slam[i].m_camPos.size());
		}
//		tic();
//		coSLAM.initMap();
//		toc();
		cout <<"debug\n";

//		redis->setPose(1, 2, 3.6);

		while (!MyApp::bExit){
			pthread_mutex_lock(&MyApp::_mutexImg);
			if (!coSLAM.grabReadFrame())
				pthread_cond_wait(&MyApp::_condImg, &MyApp::_mutexImg);
			pthread_mutex_unlock(&MyApp::_mutexImg);

//			//copy the data to buffers for display
			updateDisplayData();
			//printf("current frame: %d\n", coSLAM.curFrame);
			if (MyApp::bStartInit){
				MyApp::publishMapInit();
				printf("Start initializing map...\n");
				coSLAM.curFrame = 0;
				//initialise the map points
				if (coSLAM.initMap()){

					// Need this in real test
					coSLAM.calibGlobal2Cam();
//					return 0;

					for (int i = 0; i < coSLAM.numCams; i++)
						coSLAM.state[i] = SLAM_STATE_NORMAL;
					printf("Init map success!\n");
					break;
				}
				else{
					MyApp::bStartInit = false;
					MyApp::publishMapInit();
				}
			}
		}
		updateDisplayData();
//		coSLAM.pause();

		for (int i = 0; i < coSLAM.numCams; i++) {
			printf("slam[%d].m_camPos.size(): %d\n", i, coSLAM.slam[i].m_camPos.size());
			coSLAM.state[i] = SLAM_STATE_NORMAL;
		}

//		return 0;
//		coSLAM.pause();

		int endFrame = SLAMParam::nTotalFrame - SLAMParam::nSkipFrame
				- SLAMParam::nInitFrame - 10;
//		int endFrame = 500;

//		endFrame = 1500;

		int i = 0;
		// init estimation flag
		bool bEstPose[SLAM_MAX_NUM];
		for (int i = 0; i < SLAM_MAX_NUM; i++){
			bEstPose[i] = false;
		}

		vector<double> tmStepVec;


		vector<double> poseSent[SLAM_MAX_NUM];
//		vector<double> rosTime;

		while (!MyApp::bExit) {
//			while (MyApp::bStop) {/*stop*/
//			}

//			if (MyApp::_mergeable){
//				if (MyApp::_imgReady[0] && MyApp::_imgReady[1]){
//					coSLAM.grabReadFrame();
//					MyApp::_imgAvailableForMerge = true;
//				}
//				else
//					continue;
//			}

			i++;
			TimeMeasurer tmPerStep;
			tmPerStep.tic();


			if (!receiveFeatures){
				coSLAM.grabReadFrame();
				coSLAM.featureTracking();
			}
			else{
				coSLAM.featureReceiving();
				coSLAM.virtualReadFrame();
			}
			for (int i = 0; i < coSLAM.numCams; i++){
			cv::Mat cvImg(coSLAM.slam[i].m_img.rows, coSLAM.slam[i].m_img.cols, CV_8UC1,
								coSLAM.slam[i].m_img.data);
			MyApp::s_camFrames[i].push_back(cvImg.clone());
			CamPoseItem* cam = coSLAM.slam[i].m_camPos.current();
			double ts = cam->ts;
			MyApp::s_camFramesTS[i].push_back(ts);
			}

			if(!coSLAM.poseUpdate(bEstPose))
				break;
			//Use redis to send over the poses


//			for (int i = 0; i < coSLAM.numCams; i++){
//				double org[3];
////				getCamCenter(coSLAM.slam[i].m_camPos.current(), org);
//				coSLAM.transformCamPose2Global(coSLAM.slam[i].m_camPos.current(), org);
//
//				MyApp::redis[i]->setPose(org[0], org[1], org[2]);
//
//				double ts = coSLAM.slam[i].m_camPos.current()->ts;
//				poseSent[i].push_back(ts);
//				poseSent[i].push_back(org[0]);
//				poseSent[i].push_back(org[1]);
//				poseSent[i].push_back(org[2]);
//				rosTime.push_back(ts);
//			}
//			if (MyApp::bStartMove){
//				MyApp::redis_start->setCommand("go");
//				MyApp::bStartMove = false;
//			}

			//coSLAM.pause();
			coSLAM.cameraGrouping();
			//existing 3D to 2D points robust
			coSLAM.activeMapPointsRegister(Const::PIXEL_ERR_VAR);

			TimeMeasurer tmNewMapPoints;
			tmNewMapPoints.tic();

			if (receiveFeatures){
				coSLAM.genNewMapPoints_new();
				if (MyApp::_mergeable)
					MyApp::triggerClients();
			}
			else
			{
				bool merge = false;
				coSLAM.genNewMapPoints(merge);
			}
//
//			coSLAM.m_tmNewMapPoints = tmNewMapPoints.toc();
//			cout << "coSLAM.m_tmNewMapPoints" << coSLAM.m_tmNewMapPoints << endl;

			//point registration
			coSLAM.currentMapPointsRegister(Const::PIXEL_ERR_VAR,
					i % 50 == 0 ? true : false);

			coSLAM.storeDynamicPoints();

			updateDisplayData();
			redrawAllViews();

//			Sleep(50);

			if (i % 500 == 0) {
				//coSLAM.releaseFeatPts(coSLAM.curFrame - 500);
				coSLAM.releaseKeyPoseImgs(coSLAM.curFrame - 500);
				coSLAM.m_lastReleaseFrm = coSLAM.curFrame;
			}

			coSLAM.m_tmPerStep = tmPerStep.toc();
			tmStepVec.push_back(coSLAM.m_tmPerStep);

			//Send pose
			for (int i = 0; i < coSLAM.numCams; i++)
			{
				if (coSLAM.slam[i].m_camPos.size() > 0){

					double org[3], rpy[3];
					CamPoseItem* cam = coSLAM.slam[i].m_camPos.current();
					double ts = cam->ts;
					getCamCenter(cam, org);
					coSLAM.transformCamPose2Global(cam, org, rpy);

					double targetPos[3];
					targetPos[0] = targetPos[1] = targetPos[2] = 0;
					double theta = 0;
					if(coSLAM.dynObjPresent){
						coSLAM.transformTargetPos2Global(cam->currDynPos, targetPos);
						//printf("targetPos: %lf %lf %lf\n", targetPos[0], targetPos[1], targetPos[2]);
						coSLAM.slam[i].projectTargetToCam(cam, cam->currDynPos);
						theta = atan2(coSLAM.slam[i]._targetPosInCam[0], coSLAM.slam[i]._targetPosInCam[2]);
//							double H = targetPos[2] * 2;
//							double Z = coSLAM.slam[i]._targetPosInCam[2];
						MyApp::redis[i]->setPoseTarget(ts, 1, theta, org[0], org[1], rpy[2], targetPos[0], targetPos[1], 0.9);
//						MyApp::redis_dynObj->setDynObj(ts, targetPos[0], targetPos[1], 0.9);
//						printf("currDynPos: %lf %lf %lf\n", cam->currDynPos[0], cam->currDynPos[1], cam->currDynPos[2]);
					}
					else
						MyApp::redis[i]->setPoseTarget(ts, 0, theta, org[0], org[1], rpy[2], targetPos[0], targetPos[1], 0.9);

					MyApp::redis_dynObj->setDynObj(ts, 0.5, 2, 0.9);

					printf("targetPos: %lf %lf %lf\n", targetPos[0], targetPos[1], targetPos[2]);
					printf("org[2]: %lf %lf %lf\n", org[0], org[1], rpy[2]);
				}
			}
		}

		cout << " the result is saved at " << MyApp::timeStr << endl;
		coSLAM.exportResults(MyApp::timeStr);

		FILE* fid = fopen("/home/rui/coslamTime.txt","w");
		for (int i = 0; i < tmStepVec.size(); i++){
			fprintf(fid, "%lf\n", tmStepVec[i]);
		}
		fclose(fid);

//		FILE* fid = fopen("slam_timing.txt","w");
//		for (int i = 0; i < tmStepVec.size(); i++)
//			fprintf(fid, "%f\n", tmStepVec[i]);
//		fclose(fid);
//
//		fid = fopen("poseSent0.txt","w");
//		for (int i = 0; i < poseSent[0].size(); i = i + 4)
//			fprintf(fid, "%lf %lf %lf %lf\n", poseSent[0][i],
//					poseSent[0][i+1], poseSent[0][i+2], poseSent[0][i+3]);
//		fclose(fid);
//
//		fid = fopen("poseSent1.txt","w");
//		for (int i = 0; i < poseSent[1].size(); i = i + 4)
//			fprintf(fid, "%lf %lf %lf %lf\n", poseSent[1][i],
//					poseSent[1][i+1], poseSent[1][i+2], poseSent[1][i+3]);
//		fclose(fid);
//
//		FILE* fid = fopen("rosTime.txt","w");
//		for (int i = 0; i < rosTime.size(); i = i + coSLAM.numCams + 1){
//			for (int j = 0; j <= coSLAM.numCams; j++){
//				fprintf(fid, "%lf ", rosTime[i+j]);
//			}
//			fprintf(fid, "\n");
//		}
//		fclose(fid);

		logInfo("slam finished\n");
	} catch (SL_Exception& e) {
		logInfo(e.what());
	} catch (std::exception& e) {
#ifdef WIN32
		wxMessageBox(e.what());
#endif
		logInfo("%s\n", e.what());
		logInfo("slam failed!\n");
#ifdef WIN32
		wxMessageBox(e.what());
#endif
	}

	logInfo("\nslam stopped!\n");
	return 0;
}
Example #10
0
void QMakePlugin::OnNewQmakeBasedProject(wxCommandEvent& event)
{
    wxUnusedVar(event);
    if(m_conf->GetAllConfigurations().IsEmpty()) {
        wxMessageBox(_("There is no qmake defined, please define one from 'Plugins -> Qmake -> Settings'"),
                     _("CodeLite"), wxOK | wxICON_WARNING | wxCENTER, m_mgr->GetTheApp()->GetTopWindow());
        return;
    }

    NewQtProjDlg dlg(m_mgr->GetTheApp()->GetTopWindow(), m_conf, m_mgr);
    if(dlg.ShowModal() == wxID_OK) {
        wxString kind = dlg.GetProjectKind();
        wxString name = dlg.GetProjectName();
        wxString path = dlg.GetProjectPath();
        wxString configRelease = wxT("0000");
        wxString config = wxT("0000");
        wxString templateFile = m_mgr->GetStartupDirectory();
        wxString type = wxEmptyString;
        wxString qmakeSettings = dlg.GetQmake();
        wxString qmake;
        wxString content;

        if(kind == wxT("Static Library")) {

            type = PROJECT_TYPE_STATIC_LIBRARY;

        } else if(kind == wxT("Dynamic Library")) {

            type = PROJECT_TYPE_DYNAMIC_LIBRARY;

        } else if(kind == wxT("Console")) {

            type = PROJECT_TYPE_EXECUTABLE;
            configRelease = wxT("0017CONFIG += console");
            config = wxT("0023CONFIG += console debug");

        } else {

            type = PROJECT_TYPE_EXECUTABLE;
            config = wxT("0015CONFIG += debug");
            configRelease = wxT("0000");
        }

        wxString filename(m_mgr->GetStartupDirectory() + wxT("/templates/qmake/qmake.project"));
        if(!ReadFileWithConversion(filename, content)) { return; }

        // prepend the string lenght
        qmake = wxString::Format(wxT("%04d%s"), qmakeSettings.Length(), qmakeSettings.c_str());

        content.Replace(wxT("$(TYPE)"), type);
        content.Replace(wxT("$(NAME)"), name);
        content.Replace(wxT("$(CONFIG)"), config);
        content.Replace(wxT("$(RELEASE_CONFIG)"), configRelease);
        content.Replace(wxT("$(QMAKE)"), qmake);

        // save the file to the disk
        {
            DirSaver ds;
            if(!wxSetWorkingDirectory(path)) {
                wxMessageBox(_("Invalid project path!"), _("CodeLite"), wxOK | wxCENTER | wxICON_WARNING);
                return;
            }

            if(dlg.GetCreateDirectory()) {
                wxMkdir(name);
                wxSetWorkingDirectory(name);
            }

            if(!WriteFileWithBackup(name + wxT(".project"), content, false)) {
                wxMessageBox(wxString::Format(_("Failed to create .project file '%s'"),
                                              wxString(name + wxT(".project")).c_str()),
                             _("CodeLite"), wxOK | wxCENTER | wxICON_WARNING);
                return;
            }

            path = wxGetCwd();
            path << wxFileName::GetPathSeparator() << name << wxT(".project");

            m_mgr->AddProject(path);
        }
    }
}
bool PCB_EDIT_FRAME::OnRightClick( const wxPoint& aMousePos, wxMenu* aPopMenu )
{
    wxString    msg;
    STATUS_FLAGS flags = 0;
    bool        trackFound = false; // Flag set to true,
                                    // if a track is being the cursor, to avoid
                                    // to display menus relative to tracks twice
    bool        blockActive  = !GetScreen()->m_BlockLocate.IsIdle();

    wxClientDC  dc( m_canvas );

    BOARD_ITEM* item = GetCurItem();

    m_canvas->SetCanStartBlock( -1 );    // Avoid to start a block command when clicking on menu

    // If a command or a block is in progress:
    // Put the Cancel command (if needed) and the End command

    if( blockActive )
    {
        createPopUpBlockMenu( aPopMenu );
        aPopMenu->AppendSeparator();
        return true;
    }

    m_canvas->CrossHairOff( &dc );

    if( GetToolId() != ID_NO_TOOL_SELECTED )
    {
        if( item && item->GetFlags() )
        {
            AddMenuItem( aPopMenu, ID_POPUP_CANCEL_CURRENT_COMMAND, _( "Cancel" ),
                         KiBitmap( cancel_xpm ) );
        }
        else
        {
            AddMenuItem( aPopMenu, ID_POPUP_CLOSE_CURRENT_TOOL,
                         _( "End Tool" ), KiBitmap( cursor_xpm ) );
        }

        aPopMenu->AppendSeparator();
    }
    else
    {
        if( item && item->GetFlags() )
        {
            AddMenuItem( aPopMenu, ID_POPUP_CANCEL_CURRENT_COMMAND,
                         _( "Cancel" ), KiBitmap( cancel_xpm ) );
            aPopMenu->AppendSeparator();
        }
    }

    // Select a proper item

    wxPoint cursorPos = GetCrossHairPosition();
    wxPoint selectPos = m_Collector->GetRefPos();

    selectPos = GetNearestGridPosition( selectPos );

    /*  We can reselect another item only if there are no item being edited
     * because ALL moving functions use GetCurItem(), therefore GetCurItem()
     * must return the same item during moving. We know an item is moving
     * if( item && (item->m_Flags != 0)) is true and after calling
     * PcbGeneralLocateAndDisplay(), GetCurItem() is any arbitrary BOARD_ITEM,
     * not the current item being edited. In such case we cannot call
     * PcbGeneralLocateAndDisplay().
     */
    if( !item || (item->GetFlags() == 0) )
    {
        // show the "item selector" menu if no item selected or
        // if there is a selected item but the mouse has moved
        // (therefore a new item is perhaps under the cursor)
        if( !item || cursorPos != selectPos )
        {
            m_canvas->SetAbortRequest( false );
            item = PcbGeneralLocateAndDisplay();

            if( m_canvas->GetAbortRequest() )
            {
                m_canvas->CrossHairOn( &dc );
                return false;
            }
        }
    }

    item = GetCurItem();

    if( item )
        flags = item->GetFlags();
    else
        flags = 0;

    // Add the context menu, which depends on the picked item:
    if( item )
    {
        switch( item->Type() )
        {
        case PCB_MODULE_T:
            createPopUpMenuForFootprints( (MODULE*) item, aPopMenu );

            if( m_mainToolBar->GetToolToggled( ID_TOOLBARH_PCB_MODE_MODULE ) )
            {
                aPopMenu->AppendSeparator();

                if( !( (MODULE*) item )->IsLocked() )
                {
                    msg = AddHotkeyName( _("Lock Module" ), g_Board_Editor_Hokeys_Descr,
                                         HK_LOCK_UNLOCK_FOOTPRINT );
                    AddMenuItem( aPopMenu, ID_POPUP_PCB_AUTOPLACE_FIXE_MODULE, msg,
                                 KiBitmap( locked_xpm ) );
                }
                else
                {
                    msg = AddHotkeyName( _( "Unlock Module" ), g_Board_Editor_Hokeys_Descr,
                                         HK_LOCK_UNLOCK_FOOTPRINT );
                    AddMenuItem( aPopMenu, ID_POPUP_PCB_AUTOPLACE_FREE_MODULE, msg,
                                 KiBitmap( unlocked_xpm ) );
                }

                if( !flags )
                    aPopMenu->Append( ID_POPUP_PCB_AUTOPLACE_CURRENT_MODULE,
                                      _( "Automatically Place Module" ) );
            }

            if( m_mainToolBar->GetToolToggled( ID_TOOLBARH_PCB_MODE_TRACKS ) )
            {
                if( !flags )
                    aPopMenu->Append( ID_POPUP_PCB_AUTOROUTE_MODULE,
                                      _( "Automatically Route Module" ) );
            }
            break;

        case PCB_PAD_T:
            createPopUpMenuForFpPads( (D_PAD*) item, aPopMenu );
            break;

        case PCB_MODULE_TEXT_T:
            createPopUpMenuForFpTexts( (TEXTE_MODULE*) item, aPopMenu );
            break;

        case PCB_LINE_T:  // Some graphic items on technical layers
            if( (flags & IS_NEW) )
            {
                AddMenuItem( aPopMenu, ID_POPUP_PCB_STOP_CURRENT_DRAWING,
                             _( "End Drawing" ), KiBitmap( apply_xpm ) );
            }

            if( !flags )
            {
                msg = AddHotkeyName( _( "Move Drawing" ), g_Board_Editor_Hokeys_Descr,
                                     HK_MOVE_ITEM );
                AddMenuItem( aPopMenu, ID_POPUP_PCB_MOVE_DRAWING_REQUEST,
                             msg, KiBitmap( move_xpm ) );
                AddMenuItem( aPopMenu, ID_POPUP_PCB_EDIT_DRAWING, _( "Edit Drawing" ),
                             KiBitmap( edit_xpm ) );
                AddMenuItem( aPopMenu, ID_POPUP_PCB_DELETE_DRAWING,
                             _( "Delete Drawing" ), KiBitmap( delete_xpm ) );

                if( !IsCopperLayer( item->GetLayer() ) )
                    AddMenuItem( aPopMenu, ID_POPUP_PCB_DELETE_DRAWING_LAYER,
                                 _( "Delete All Drawings on Layer" ), KiBitmap( delete_xpm ) );
            }

            break;

        case PCB_ZONE_T:      // Item used to fill a zone
            AddMenuItem( aPopMenu, ID_POPUP_PCB_DELETE_ZONE,
                         _( "Delete Zone Filling" ), KiBitmap( delete_xpm ) );
            break;

        case PCB_ZONE_AREA_T:    // Item used to handle a zone area (outlines, holes ...)
            if( flags & IS_NEW )
            {
                AddMenuItem( aPopMenu, ID_POPUP_PCB_STOP_CURRENT_EDGE_ZONE,
                             _( "Close Zone Outline" ), KiBitmap( apply_xpm ) );
                AddMenuItem( aPopMenu, ID_POPUP_PCB_DELETE_ZONE_LAST_CREATED_CORNER,
                             _( "Delete Last Corner" ), KiBitmap( delete_xpm ) );
            }
            else
            {
                createPopUpMenuForZones( (ZONE_CONTAINER*) item, aPopMenu );
            }

            break;

        case PCB_TEXT_T:
            createPopUpMenuForTexts( (TEXTE_PCB*) item, aPopMenu );
            break;

        case PCB_TRACE_T:
        case PCB_VIA_T:
            trackFound = true;
            createPopupMenuForTracks( (TRACK*) item, aPopMenu );
            break;

        case PCB_MARKER_T:
            createPopUpMenuForMarkers( (MARKER_PCB*) item, aPopMenu );
            break;

        case PCB_DIMENSION_T:
            if( !flags )
            {
                msg = AddHotkeyName( _( "Edit Dimension" ), g_Board_Editor_Hokeys_Descr,
                                     HK_EDIT_ITEM );
                AddMenuItem( aPopMenu, ID_POPUP_PCB_EDIT_DIMENSION, msg, KiBitmap( edit_xpm ) );
                msg = AddHotkeyName( _( "Move Dimension Text" ), g_Board_Editor_Hokeys_Descr,
                                     HK_MOVE_ITEM );
                AddMenuItem( aPopMenu, ID_POPUP_PCB_MOVE_TEXT_DIMENSION_REQUEST,
                             msg, KiBitmap( move_text_xpm ) );
                msg = AddHotkeyName( _( "Delete Dimension" ), g_Board_Editor_Hokeys_Descr,
                                     HK_DELETE );
                AddMenuItem( aPopMenu, ID_POPUP_PCB_DELETE_DIMENSION,
                             msg, KiBitmap( delete_xpm ) );
            }
            break;

        case PCB_TARGET_T:
            if( !flags )
            {
                msg = AddHotkeyName( _( "Move Target" ), g_Board_Editor_Hokeys_Descr,
                                     HK_MOVE_ITEM );
                AddMenuItem( aPopMenu, ID_POPUP_PCB_MOVE_MIRE_REQUEST, msg, KiBitmap( move_xpm ) );
                msg = AddHotkeyName( _( "Edit Target" ), g_Board_Editor_Hokeys_Descr,
                                     HK_EDIT_ITEM );
                AddMenuItem( aPopMenu, ID_POPUP_PCB_EDIT_MIRE, msg, KiBitmap( edit_xpm ) );
                msg = AddHotkeyName( _( "Delete Target" ), g_Board_Editor_Hokeys_Descr, HK_DELETE );
                AddMenuItem( aPopMenu, ID_POPUP_PCB_DELETE_MIRE,
                             msg, KiBitmap( delete_xpm ) );
            }

            break;

        case PCB_MODULE_EDGE_T:
        case SCREEN_T:
        case TYPE_NOT_INIT:
        case PCB_T:
            msg.Printf( wxT( "PCB_EDIT_FRAME::OnRightClick() Error: unexpected DrawType %d" ),
                        item->Type() );
            wxMessageBox( msg );
            SetCurItem( NULL );
            break;

        default:
            msg.Printf( wxT( "PCB_EDIT_FRAME::OnRightClick() Error: unknown DrawType %d" ),
                        item->Type() );
            wxMessageBox( msg );

            // Attempt to clear error (but should no occurs )
            if( item->Type() >= MAX_STRUCT_TYPE_ID )
                SetCurItem( NULL );

            break;
        }

       aPopMenu->AppendSeparator();
    }

    if( !flags )
    {
        msg = AddHotkeyName( _( "Get and Move Footprint" ),
                             g_Board_Editor_Hokeys_Descr, HK_GET_AND_MOVE_FOOTPRINT );
        AddMenuItem( aPopMenu, ID_POPUP_PCB_GET_AND_MOVE_MODULE_REQUEST,
                     msg, KiBitmap( move_module_xpm ) );
    }

    // Display context sensitive commands:
    switch(  GetToolId() )
    {
    case ID_PCB_ZONES_BUTT:
        if(  GetBoard()->m_ZoneDescriptorList.size() > 0 )
        {
            aPopMenu->AppendSeparator();
            AddMenuItem( aPopMenu, ID_POPUP_PCB_FILL_ALL_ZONES,
                         _( "Fill or Refill All Zones" ), KiBitmap( fill_zone_xpm ) );
            AddMenuItem( aPopMenu, ID_POPUP_PCB_REMOVE_FILLED_AREAS_IN_ALL_ZONES,
                         _( "Remove Filled Areas in All Zones" ), KiBitmap( zone_unfill_xpm ) );
            aPopMenu->AppendSeparator();
        }

        AddMenuItem( aPopMenu, ID_POPUP_PCB_SELECT_LAYER,
                     _( "Select Working Layer" ), KiBitmap( select_w_layer_xpm ) );
        aPopMenu->AppendSeparator();
        break;

    case ID_PCB_KEEPOUT_AREA_BUTT:
        AddMenuItem( aPopMenu, ID_POPUP_PCB_SELECT_LAYER,
                     _( "Select Working Layer" ), KiBitmap( select_w_layer_xpm ) );
        aPopMenu->AppendSeparator();
        break;

    case ID_TRACK_BUTT:
        if ( ! trackFound )   // This menu is already added when a track is located
        {
            aPopMenu->AppendSeparator();
            msg = AddHotkeyName( _( "Begin Track" ),
                                 g_Board_Editor_Hokeys_Descr, HK_ADD_NEW_TRACK );
            AddMenuItem( aPopMenu, ID_POPUP_PCB_BEGIN_TRACK,
                         msg, KiBitmap( add_tracks_xpm ) );

            AddMenuItem( aPopMenu, Append_Track_Width_List( GetBoard() ),
                         ID_POPUP_PCB_SELECT_WIDTH, _( "Select Track Width" ),
                         KiBitmap( width_track_xpm ) );

            AddMenuItem( aPopMenu, ID_POPUP_PCB_SELECT_CU_LAYER,
                         _( "Select Working Layer" ), KiBitmap( select_w_layer_xpm ) );
            AddMenuItem( aPopMenu, ID_POPUP_PCB_SELECT_LAYER_PAIR,
                         _( "Select Layer Pair for Vias" ), KiBitmap( select_layer_pair_xpm ) );
            aPopMenu->AppendSeparator();
        }
        break;

    case ID_PCB_CIRCLE_BUTT:
    case ID_PCB_ARC_BUTT:
    case ID_PCB_ADD_TEXT_BUTT:
    case ID_PCB_ADD_LINE_BUTT:
    case ID_PCB_DIMENSION_BUTT:
        AddMenuItem( aPopMenu, ID_POPUP_PCB_SELECT_NO_CU_LAYER,
                      _( "Select Working Layer" ), KiBitmap( select_w_layer_xpm ) );
        aPopMenu->AppendSeparator();
        break;

    case ID_PCB_MODULE_BUTT:
        if( !flags )
        {
            AddMenuItem( aPopMenu, ID_POPUP_PCB_DISPLAY_FOOTPRINT_DOC,
                         _( "Footprint Documentation" ), KiBitmap( book_xpm ) );
            aPopMenu->AppendSeparator();
        }
        break;

    case ID_NO_TOOL_SELECTED:
        if( m_mainToolBar->GetToolToggled( ID_TOOLBARH_PCB_MODE_MODULE ) )
        {
            wxMenu* commands = new wxMenu;
            AddMenuItem( aPopMenu, commands, ID_POPUP_PCB_AUTOPLACE_COMMANDS,
                         _( "Global Spread and Place" ), KiBitmap( move_xpm ) );
            AddMenuItem( commands, ID_POPUP_PCB_AUTOPLACE_FREE_ALL_MODULES,
                         _( "Unlock All Footprints" ), KiBitmap( unlocked_xpm ) );
            AddMenuItem( commands, ID_POPUP_PCB_AUTOPLACE_FIXE_ALL_MODULES,
                         _( "Lock All Footprints" ), KiBitmap( locked_xpm ) );
            commands->AppendSeparator();
            AddMenuItem( commands, ID_POPUP_PCB_SPREAD_ALL_MODULES,
                         _( "Spread out All Footprints" ), KiBitmap( move_xpm ) );
            commands->Append( ID_POPUP_PCB_SPREAD_NEW_MODULES,
                              _( "Spread out Footprints not Already on Board" ) );
            commands->AppendSeparator();
            commands->Append( ID_POPUP_PCB_AUTOPLACE_ALL_MODULES,
                              _( "Automatically Place All Footprints" ) );
            commands->Append( ID_POPUP_PCB_AUTOPLACE_NEW_MODULES,
                              _( "Automatically Place New Footprints" ) );
            commands->Append( ID_POPUP_PCB_AUTOPLACE_NEXT_MODULE,
                              _( "Automatically Place Next Footprints" ) );
            commands->AppendSeparator();
            AddMenuItem( commands, ID_POPUP_PCB_REORIENT_ALL_MODULES,
                         _( "Orient All Footprints" ), KiBitmap( rotate_module_pos_xpm ) );
            aPopMenu->AppendSeparator();
        }

        if( m_mainToolBar->GetToolToggled( ID_TOOLBARH_PCB_MODE_TRACKS ) )
        {
            wxMenu* commands = new wxMenu;
            aPopMenu->Append( ID_POPUP_PCB_AUTOROUTE_COMMANDS, _( "Autoroute" ), commands );
            AddMenuItem( commands, ID_POPUP_PCB_SELECT_LAYER_PAIR,
                         _( "Select Layer Pair" ), KiBitmap( select_layer_pair_xpm ) );
            commands->AppendSeparator();
            commands->Append( ID_POPUP_PCB_AUTOROUTE_ALL_MODULES,
                              _( "Automatically Route All Modules" ) );
            commands->AppendSeparator();
            commands->Append( ID_POPUP_PCB_AUTOROUTE_RESET_UNROUTED, _( "Reset Unrouted" ) );
            aPopMenu->AppendSeparator();
        }

        if( !trackFound )
        {
            msg = AddHotkeyName( _( "Begin Track" ), g_Board_Editor_Hokeys_Descr, HK_ADD_NEW_TRACK );
            AddMenuItem( aPopMenu, ID_POPUP_PCB_BEGIN_TRACK, msg, KiBitmap( add_tracks_xpm ) );

            AddMenuItem( aPopMenu, Append_Track_Width_List( GetBoard() ),
                         ID_POPUP_PCB_SELECT_WIDTH, _( "Select Track Width" ),
                         KiBitmap( width_track_xpm ) );

            AddMenuItem( aPopMenu, ID_POPUP_PCB_SELECT_LAYER,
                         _( "Select Working Layer" ), KiBitmap( select_w_layer_xpm ) );
            aPopMenu->AppendSeparator();
        }
        break;
    }

    m_canvas->CrossHairOn( &dc );
    return true;
}
void PCB_EDIT_FRAME::Process_Config( wxCommandEvent& event )
{
    int         id = event.GetId();
    wxFileName  fn;

    switch( id )
    {
    case ID_MENU_PCB_SHOW_HIDE_LAYERS_MANAGER_DIALOG:
        m_show_layer_manager_tools = ! m_show_layer_manager_tools;
        m_auimgr.GetPane( wxT( "m_LayersManagerToolBar" ) ).Show( m_show_layer_manager_tools );
        m_auimgr.Update();

        GetMenuBar()->SetLabel( ID_MENU_PCB_SHOW_HIDE_LAYERS_MANAGER_DIALOG,
                                m_show_layer_manager_tools ?
                                _("Hide &Layers Manager" ) : _("Show &Layers Manager" ));
        break;

    case ID_MENU_PCB_SHOW_HIDE_MUWAVE_TOOLBAR:
        m_show_microwave_tools  = ! m_show_microwave_tools;
        m_auimgr.GetPane( wxT( "m_microWaveToolBar" ) ).Show( m_show_microwave_tools );
        m_auimgr.Update();

        GetMenuBar()->SetLabel( ID_MENU_PCB_SHOW_HIDE_MUWAVE_TOOLBAR,
                                m_show_microwave_tools ?
                                _( "Hide Microwave Toolbar" ): _( "Show Microwave Toolbar" ));
        break;


    case ID_PCB_LAYERS_SETUP:
        if( InvokeLayerSetup( this, GetBoard() ) )
        {
            LAYER_ID cur_layer = GetActiveLayer();

            // If after showing the dialog the user has removed the active layer,
            // then select a new active layer (front copper layer).
            if( !GetBoard()->GetEnabledLayers()[ cur_layer ] )
                cur_layer = F_Cu;

            SetActiveLayer( cur_layer );

            OnModify();
            ReCreateLayerBox();
            ReFillLayerWidget();

            if( IsGalCanvasActive() )
                static_cast<PCB_DRAW_PANEL_GAL*>( GetGalCanvas() )->SyncLayersVisibility( GetBoard() );
        }
        break;

    case ID_PCB_LIB_WIZARD:
    case ID_PCB_LIB_TABLE_EDIT:
    {
        bool tableChanged = false;
        int r = 0;

        if( id == ID_PCB_LIB_TABLE_EDIT )
            r = InvokePcbLibTableEditor( this, &GFootprintTable, Prj().PcbFootprintLibs() );
        else
            r = InvokeFootprintWizard( this, &GFootprintTable, Prj().PcbFootprintLibs() );

        if( r & 1 )
        {
            try
            {
                FILE_OUTPUTFORMATTER sf( FP_LIB_TABLE::GetGlobalTableFileName() );

                GFootprintTable.Format( &sf, 0 );
                tableChanged = true;
            }
            catch( const IO_ERROR& ioe )
            {
                wxString msg = wxString::Format( _(
                                                     "Error occurred saving the global footprint library "
                                                     "table:\n\n%s" ),
                                                 GetChars( ioe.errorText.GetData() )
                                               );
                wxMessageBox( msg, _( "File Save Error" ), wxOK | wxICON_ERROR );
            }
        }

        // If no board file is defined, do not save the project specific library table.  It
        // is kept in memory and created in the path when the new board is saved.
        if( (r & 2) && !GetBoard()->GetFileName().IsEmpty() )
        {
            wxString    tblName   = Prj().FootprintLibTblName();

            try
            {
                Prj().PcbFootprintLibs()->Save( tblName );
                tableChanged = true;
            }
            catch( const IO_ERROR& ioe )
            {
                wxString msg = wxString::Format( _(
                                                     "Error occurred saving project specific footprint library "
                                                     "table:\n\n%s" ),
                                                 GetChars( ioe.errorText )
                                               );
                wxMessageBox( msg, _( "File Save Error" ), wxOK | wxICON_ERROR );
            }
        }

        FOOTPRINT_VIEWER_FRAME* viewer;

        if( tableChanged && (viewer = (FOOTPRINT_VIEWER_FRAME*)Kiway().Player( FRAME_PCB_MODULE_VIEWER, false )) != NULL )
        {
            viewer->ReCreateLibraryList();
        }
    }
    break;

    case ID_PCB_MASK_CLEARANCE:
    {
        DIALOG_PADS_MASK_CLEARANCE dlg( this );

        if( dlg.ShowModal() == 1 && IsGalCanvasActive() )
        {
            for( MODULE* module = GetBoard()->m_Modules; module; module = module->Next() )
                module->ViewUpdate();

            GetGalCanvas()->Refresh();
        }
    }
    break;

    case wxID_PREFERENCES:
    {
        DIALOG_GENERALOPTIONS dlg( this );
        dlg.ShowModal();
    }
    break;

    case ID_PCB_PAD_SETUP:
        InstallPadOptionsFrame( NULL );
        break;

    case ID_CONFIG_SAVE:
        SaveProjectSettings( true );
        break;

    case ID_CONFIG_READ:
    {
        fn = GetBoard()->GetFileName();
        fn.SetExt( ProjectFileExtension );

        wxFileDialog dlg( this, _( "Read Project File" ), fn.GetPath(),
                          fn.GetFullName(), ProjectFileWildcard,
                          wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_CHANGE_DIR );

        if( dlg.ShowModal() == wxID_CANCEL )
            break;

        if( !wxFileExists( dlg.GetPath() ) )
        {
            wxString msg = wxString::Format( _(
                                                 "File %s not found" ),
                                             GetChars( dlg.GetPath() )
                                           );
            DisplayError( this, msg );
            break;
        }

        wxString pro_file = dlg.GetPath();

        Prj().ConfigLoad( Kiface().KifaceSearch(), GROUP_PCB, GetProjectFileParameters(), pro_file );
    }
    break;

    // Hotkey IDs
    case ID_PREFERENCES_HOTKEY_EXPORT_CONFIG:
        ExportHotkeyConfigToFile( g_Board_Editor_Hokeys_Descr, wxT( "pcbnew" ) );
        break;

    case ID_PREFERENCES_HOTKEY_IMPORT_CONFIG:
        ImportHotkeyConfigFromFile( g_Board_Editor_Hokeys_Descr, wxT( "pcbnew" ) );
        break;

    case ID_PREFERENCES_HOTKEY_SHOW_EDITOR:
        InstallHotkeyFrame( this, g_Board_Editor_Hokeys_Descr );
        break;

    case ID_PREFERENCES_HOTKEY_SHOW_CURRENT_LIST:
        // Display current hotkey list for Pcbnew.
        DisplayHotkeyList( this, g_Board_Editor_Hokeys_Descr );
        break;

    // Macros IDs
    case ID_PREFRENCES_MACROS_SAVE:
        SaveMacros();
        break;

    case ID_PREFRENCES_MACROS_READ:
        ReadMacros();
        break;

    default:
        DisplayError( this, wxT( "PCB_EDIT_FRAME::Process_Config error" ) );
    }
}
bool HDRMergeOptionsDialog::BuildCommandLineArgument()
{
    int selection=m_mode->GetSelection();
    m_cmd.Clear();
    bool correct_input=true;
    double i = 0;
    wxString errorstring(_("Invalid input\n"));
    switch(selection)
    {
        case 0:
            m_cmd.Append(wxT("-m avg"));
            if(m_option_c->IsChecked())
                m_cmd.Append(wxT(" -c"));
            break;
        case 1:
            m_cmd.Append(wxT("-m avg_slow"));
            break;
        case 2:
            m_cmd.Append(wxT("-m khan"));
            if(m_khan_iter->GetValue())
            {
                m_cmd.Append(wxString::Format(wxT(" -i %d"),m_khan_iter->GetValue()));
            }
            else
            {
                correct_input=false;
                errorstring.Append(wxString::Format(_("Input \"%s\" for %s is not a valid number\n"),
                    m_khan_iter->GetValue(),_("Iteration")));
            };
            if(m_khan_sigma->GetValue().ToDouble(&i))
            {
                //change locale for correct numeric output
                char * p = setlocale(LC_NUMERIC,NULL);
                char * old_locale = strdup(p);
                setlocale(LC_NUMERIC,"C");
                m_cmd.Append(wxString::Format(wxT(" -s %f"),i));
                //reset locale
                setlocale(LC_NUMERIC,old_locale);
                free(old_locale);
            }
            else
            {
                correct_input=false;
                errorstring.Append(wxString::Format(_("Input \"%s\" for %s is not a valid number\n"),
                    m_khan_iter->GetValue(),_("Sigma")));
            };
            if(m_option_khan_af->IsChecked() || m_option_khan_ag->IsChecked() || 
                m_option_khan_am->IsChecked())
            {
                m_cmd.Append(wxT(" -a "));
                if(m_option_khan_af->IsChecked())
                    m_cmd.Append(wxT("f"));
                if(m_option_khan_ag->IsChecked())
                    m_cmd.Append(wxT("g"));
                if(m_option_khan_am->IsChecked())
                    m_cmd.Append(wxT("m"));
            }
            break;
    };
    if(!correct_input)
        wxMessageBox(errorstring,_("Wrong input"),wxOK | wxICON_INFORMATION);
    return correct_input;
};
Example #14
0
/**
 * Function CombineAllAreasInNet
 * Checks all copper areas in net for intersections, combining them if found
 * @param aDeletedList = a PICKED_ITEMS_LIST * where to store deleted areas (useful in
 *                       undo commands can be NULL
 * @param aNetCode = net to consider
 * @param bMessageBox : if true display warning message box
 * @param bUseUtility : if true, don't check areas if both utility flags are 0
 * Sets utility flag = 1 for any areas modified
 * If an area has self-intersecting arcs, doesn't try to combine it
 */
int BOARD::CombineAllAreasInNet( PICKED_ITEMS_LIST* aDeletedList, int aNetCode,
                                 bool bMessageBox, bool bUseUtility )
{
    if( m_ZoneDescriptorList.size() <= 1 )
        return 0;

    // start by testing all area polygons to set utility2 flags
    for( unsigned ia = 0; ia < m_ZoneDescriptorList.size(); ia++ )
        if( m_ZoneDescriptorList[ia]->GetNet() == aNetCode )
            TestAreaPolygon( m_ZoneDescriptorList[ia] );

    // now loop through all combinations
    for( unsigned ia1 = 0; ia1 < m_ZoneDescriptorList.size() - 1; ia1++ )
    {
        ZONE_CONTAINER* curr_area = m_ZoneDescriptorList[ia1];
        if( curr_area->GetNet() != aNetCode )
            continue;

        // legal polygon
        CRect b1 = curr_area->m_Poly->GetCornerBounds();
        bool  mod_ia1 = false;

        for( unsigned ia2 = m_ZoneDescriptorList.size() - 1; ia2 > ia1; ia2-- )
        {
            ZONE_CONTAINER* area2 = m_ZoneDescriptorList[ia2];

            if( area2->GetNet() != aNetCode )
                continue;
            if( curr_area->GetPriority() != area2->GetPriority() )
                continue;

            if( curr_area->GetLayer() == area2->GetLayer()
                && curr_area->utility2 != -1 && area2->utility2 != -1 )
            {
                CRect b2 = area2->m_Poly->GetCornerBounds();
                if( !( b1.left > b2.right || b1.right < b2.left
                       || b1.bottom > b2.top || b1.top < b2.bottom ) )
                {
                    // check area2 against curr_area
                    if( curr_area->utility || area2->utility || bUseUtility == false )
                    {
                        int ret = TestAreaIntersection( curr_area, area2 );

                        if( ret == 1 )
                            ret = CombineAreas( aDeletedList, curr_area, area2 );

                        if( ret == 1 )
                        {
                            mod_ia1 = true;
                        }
                        else if( ret == 2 )
                        {
                            if( bMessageBox && bDontShowIntersectionArcsWarning == false )
                            {
                                wxString str;
                                str.Printf( wxT( "Areas %d and %d of net \"%s\" intersect, but some of the intersecting sides are arcs.\n" ),
                                            ia1 + 1,
                                            ia2 + 1,
                                            GetChars( curr_area->m_Netname ) );
                                str += wxT( "Therefore, these areas can't be combined." );
                                wxMessageBox( str );
                            }
                        }
                    }
                }
            }
        }

        if( mod_ia1 )
            ia1--;     // if modified, we need to check it again
    }

    return 0;
}
Example #15
0
void ParamEdit::ParamInsertUpdateError(wxString error) {
	wxMessageBox(_("Error while editing network set: ") + error, _("Editing network set error"),
		wxOK | wxICON_ERROR, this);
}
Example #16
0
bool SimpleFTP::UploadFile(std::string file, std::string folder, std::string newfilename, bool backup, bool binary, wxWindow* parent)
{
    static log4cpp::Category &logger_base = log4cpp::Category::getInstance(std::string("log_base"));
    if (!IsConnected()) return false;

    if (newfilename == "") newfilename = file;

    ftp.ChDir(folder);

    if (binary)
    {
        ftp.SetBinary();
    }
    else
    {
        ftp.SetAscii();
    }

    wxProgressDialog progress("FTP Upload", wxString(file.c_str()), 100, parent, wxPD_CAN_ABORT | wxPD_APP_MODAL | wxPD_AUTO_HIDE);
    progress.Show();

    bool cancelled = false;

    progress.Update(0, wxEmptyString, &cancelled);

    wxFileName fn(wxString(file.c_str()));
    wxString ext = fn.GetExt();
    if (ext != "") ext = "." + ext;
    wxString basefile = fn.GetName() + ext;
    wxFileName fnnew(wxString(newfilename.c_str()));
    wxString extnew = fnnew.GetExt();
    if (extnew != "") extnew = "." + extnew;
    wxString basefilenew = fnnew.GetName() + extnew;

    wxLogNull logNo; //kludge: avoid "error 0" message from wxWidgets

    //logger_base.info("FTP current directory %s.", (const char *)ftp.Pwd().c_str());

    if (backup)
    {
        int size = ftp.GetFileSize((folder + "/" + basefile).c_str());
        if (size == -1)
        {
            // file not there so no need to backup
        }
        else
        {
            wxDateTime dt = wxDateTime::Now();
            wxString tgtfile = wxString((folder + "/" + basefilenew).c_str()) + "_" + dt.Format("%Y%m%d_%H%M%S");
            logger_base.info("FTP Backing up file %s to %s.", (const char *)(folder + "/" + basefilenew).c_str(), (const char *)tgtfile.c_str());
            ftp.Rename((folder + "/" + basefilenew).c_str(), tgtfile);
            if (!cancelled)
            {
                cancelled = progress.WasCancelled();
            }
        }
    }

    wxFile in;
    in.Open(wxString(file.c_str()));
    if (in.IsOpened())
    {
        logger_base.info("FTP Uploading file %s to %s.", (const char *)file.c_str(), (const char *)(folder + "/" + basefilenew).c_str());
        wxFileOffset length = in.Length();
        wxFileOffset done = 0;
        wxSocketOutputStream *out = dynamic_cast<wxSocketOutputStream*>(ftp.GetOutputStream((folder + "/" + basefilenew).c_str()));
        wxSocketBase sock;
        MySocketOutputStream sout(sock, (MySocketOutputStream*)out);
        if (out)
        {
            uint8_t buffer[8192]; // 8KB at a time
            int lastDone = 0;
            while (!in.Eof() && !cancelled)
            {
                ssize_t read = in.Read(&buffer[0], sizeof(buffer));
                done += read;

                int bufPos = 0;
                while (read) {
                    out->Write(&buffer[bufPos], read);
                    ssize_t written = out->LastWrite();
                    bufPos += written;
                    read -= written;
                }
                ssize_t donePct = done * 100;
                donePct = donePct / length;
                if (donePct != lastDone) {
                    lastDone = donePct;
                    cancelled = !progress.Update(donePct, wxEmptyString, &cancelled);
                    wxYield();
                }
            }
            if (in.Eof())
            {
                progress.Update(100, wxEmptyString, &cancelled);
                logger_base.info("   FTP Upload of file %s done.", (const char *)file.c_str());
            }
            else
            {
                progress.Update(100, wxEmptyString, &cancelled);
                logger_base.warn("   FTP Upload of file %s cancelled.", (const char *)file.c_str());
            }
            in.Close();
            out->Close();
            delete out;
            if (ftp.GetFileSize((folder + "/" + basefilenew).c_str()) != length)
            {
                logger_base.warn("   FTP Upload of file %s failed. Source size (%d) != Destination Size (%d)", (const char *)file.c_str(), length, ftp.GetFileSize((folder + "/" + basefile).c_str()));
            }
        }
        else
        {
            wxMessageBox("FTP Upload of file failed to create the target file.");
            progress.Update(100, wxEmptyString, &cancelled);
            logger_base.error("   FTP Upload of file %s failed as file %s could not be created on FPP.", (const char *)file.c_str(), (const char *)(folder + "/" + basefilenew).c_str());
        }
    }
    else
    {
        wxMessageBox("FTP Upload of file failed to open the file.");
        progress.Update(100, wxEmptyString, &cancelled);
        logger_base.error("   FTP Upload of file %s failed as file could not be opened.", (const char *)file.c_str());
    }

    if (!cancelled)
    {
        cancelled = progress.WasCancelled();
    }

    return cancelled;
}
bool DIALOG_TEXT_PROPERTIES::TransferDataToWindow()
{
    if( m_SingleLineText->IsShown() )
    {
        m_SingleLineText->SetValue( m_edaText->GetText() );

        if( m_modText && m_modText->GetType() == TEXTE_MODULE::TEXT_is_REFERENCE )
            SelectReferenceNumber( static_cast<wxTextEntry*>( m_SingleLineText ) );
        else
            m_SingleLineText->SetSelection( -1, -1 );
    }
    else if( m_MultiLineText->IsShown() )
    {
        m_MultiLineText->SetValue( m_edaText->GetText() );
        m_MultiLineText->SetSelection( -1, -1 );
    }
    else if (m_DimensionText->IsShown() )
    {
        m_DimensionText->SetValue( m_edaText->GetText() );
        m_DimensionText->SetSelection( -1, -1 );

        DIMENSION* dimension = (DIMENSION*) m_item;
        EDA_UNITS_T units;
        bool useMils;
        dimension->GetUnits( units, useMils );

        m_DimensionUnitsOpt->SetSelection( units == MILLIMETRES ? 2 : useMils ? 1 : 0 );
    }

    if( m_item->Type() == PCB_MODULE_TEXT_T && m_modText )
    {
        MODULE*  module = dynamic_cast<MODULE*>( m_modText->GetParent() );
        wxString msg;

        if( module )
        {
            msg.Printf( _("Footprint %s (%s), %s, rotated %.1f deg"),
                        module->GetReference(),
                        module->GetValue(),
                        module->IsFlipped() ? _( "back side (mirrored)" ) : _( "front side" ),
                        module->GetOrientation() / 10.0 );
        }

        m_statusLine->SetLabel( msg );
    }
    else
    {
        m_statusLine->Show( false );
    }

    if( m_LayerSelectionCtrl->SetLayerSelection( m_item->GetLayer() ) < 0 )
    {
        wxMessageBox( _( "This item was on a non-existing or forbidden layer.\n"
                         "It has been moved to the first allowed layer." ) );
        m_LayerSelectionCtrl->SetSelection( 0 );
    }

    m_textWidth.SetValue( m_edaText->GetTextSize().x );
    m_textHeight.SetValue( m_edaText->GetTextSize().y );
    m_thickness.SetValue( m_edaText->GetThickness() );
    m_posX.SetValue( m_edaText->GetTextPos().x );
    m_posY.SetValue( m_edaText->GetTextPos().y );

    m_Visible->SetValue( m_edaText->IsVisible() );
    m_Italic->SetValue( m_edaText->IsItalic() );
    EDA_TEXT_HJUSTIFY_T hJustify = m_edaText->GetHorizJustify();
    m_JustifyChoice->SetSelection( (int) hJustify + 1 );
    m_OrientValue = m_edaText->GetTextAngleDegrees();
    m_Mirrored->SetValue( m_edaText->IsMirrored() );

    if( m_modText )
        m_KeepUpright->SetValue( m_modText->IsKeepUpright() );

    return DIALOG_TEXT_PROPERTIES_BASE::TransferDataToWindow();
}
void DIALOG_MODEDIT_FP_BODY_ITEM_PROPERTIES::initDlg()
{
    SetFocus();
    m_StandardButtonsSizerOK->SetDefault();

    // Set unit symbol
    wxStaticText * texts_unit[] =
    {
        m_StartPointXUnit,
        m_StartPointYUnit,
        m_EndPointXUnit,
        m_EndPointYUnit,
        m_ThicknessTextUnit,
        m_DefaulThicknessTextUnit,
        NULL
    };

    for( int ii = 0; ; ii++ )
    {
        if( texts_unit[ii] == NULL )
            break;

        texts_unit[ii]->SetLabel( GetAbbreviatedUnitsLabel() );
    }

    wxString msg;

    // Change texts according to the segment shape:
    switch ( m_item->GetShape() )
    {
    case S_CIRCLE:
        m_StartPointXLabel->SetLabel(_("Center X"));
        m_StartPointYLabel->SetLabel(_("Center Y"));
        m_EndPointXLabel->SetLabel(_("Point X"));
        m_EndPointYLabel->SetLabel(_("Point Y"));
        m_Angle_Text->Show(false);
        m_Angle_Ctrl->Show(false);
        m_AngleUnit->Show(false);
        break;

    case S_ARC:
        m_StartPointXLabel->SetLabel(_("Center X"));
        m_StartPointYLabel->SetLabel(_("Center Y"));
        m_EndPointXLabel->SetLabel(_("Start Point X"));
        m_EndPointYLabel->SetLabel(_("Start Point Y"));

        // Here the angle is a double, but the UI is still working
        // with integers
        msg << int( m_item->GetAngle() );
        m_Angle_Ctrl->SetValue(msg);
        break;

    default:
        m_Angle_Text->Show(false);
        m_Angle_Ctrl->Show(false);
        m_AngleUnit->Show(false);
        break;
    }

    PutValueInLocalUnits( *m_Center_StartXCtrl, m_item->GetStart().x );

    PutValueInLocalUnits( *m_Center_StartYCtrl, m_item->GetStart().y );

    PutValueInLocalUnits( *m_EndX_Radius_Ctrl, m_item->GetEnd().x );

    PutValueInLocalUnits( *m_EndY_Ctrl, m_item->GetEnd().y );

    PutValueInLocalUnits( *m_ThicknessCtrl, m_item->GetWidth() );

    PutValueInLocalUnits( *m_DefaultThicknessCtrl, m_brdSettings.m_ModuleSegmentWidth );

    // Configure the layers list selector
    m_LayerSelectionCtrl->SetLayersHotkeys( false );
    m_LayerSelectionCtrl->SetLayerSet( LSET::InternalCuMask().set( Edge_Cuts ) );
    m_LayerSelectionCtrl->SetBoardFrame( m_parent );
    m_LayerSelectionCtrl->Resync();

    if( m_LayerSelectionCtrl->SetLayerSelection( m_item->GetLayer() ) < 0 )
    {
        wxMessageBox( _( "This item has an illegal layer id.\n"
                        "Now, forced on the front silk screen layer. Please, fix it" ) );
        m_LayerSelectionCtrl->SetLayerSelection( F_SilkS );
    }
}
Example #19
0
bool wxMacPrinter::Print(wxWindow *parent, wxPrintout *printout, bool prompt)
{
    sm_abortIt = false;
    sm_abortWindow = NULL;

    if (!printout)
    {
        sm_lastError = wxPRINTER_ERROR;
        return false;
    }

    if (m_printDialogData.GetMinPage() < 1)
        m_printDialogData.SetMinPage(1);
    if (m_printDialogData.GetMaxPage() < 1)
        m_printDialogData.SetMaxPage(9999);

    // Create a suitable device context
    wxPrinterDC *dc = NULL;
    if (prompt)
    {
        wxMacPrintDialog dialog(parent, & m_printDialogData);
        if (dialog.ShowModal() == wxID_OK)
        {
            dc = wxDynamicCast(dialog.GetPrintDC(), wxPrinterDC);
            wxASSERT(dc);
            m_printDialogData = dialog.GetPrintDialogData();
        }
    }
    else
    {
        dc = new wxPrinterDC( m_printDialogData.GetPrintData() ) ;
    }

    // May have pressed cancel.
    if (!dc || !dc->IsOk())
    {
        delete dc;
        return false;
    }

    // on the mac we have always pixels as addressing mode with 72 dpi
    printout->SetPPIScreen(72, 72);

    PMResolution res;
    PMPrinter printer;
    wxOSXPrintData* nativeData = (wxOSXPrintData*)
          (m_printDialogData.GetPrintData().GetNativeData());

    if (PMSessionGetCurrentPrinter(nativeData->GetPrintSession(), &printer) == noErr)
    {
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
        if ( PMPrinterGetOutputResolution != NULL )
        {
            if (PMPrinterGetOutputResolution( printer, nativeData->GetPrintSettings(), &res) == -9589 /* kPMKeyNotFound */ )
            {
                res.hRes = res.vRes = 300;
            }
        }
        else
#endif
        {
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
            PMPrinterGetPrinterResolution(printer, kPMCurrentValue, &res);
#endif
        }
    }
    printout->SetPPIPrinter(int(res.hRes), int(res.vRes));

    // Set printout parameters
    printout->SetDC(dc);

    int w, h;
    dc->GetSize(&w, &h);
    printout->SetPageSizePixels((int)w, (int)h);
    printout->SetPaperRectPixels(dc->GetPaperRect());
    wxCoord mw, mh;
    dc->GetSizeMM(&mw, &mh);
    printout->SetPageSizeMM((int)mw, (int)mh);

    // Create an abort window
    wxBeginBusyCursor();

    printout->OnPreparePrinting();

    // Get some parameters from the printout, if defined
    int fromPage, toPage;
    int minPage, maxPage;
    printout->GetPageInfo(&minPage, &maxPage, &fromPage, &toPage);

    if (maxPage == 0)
    {
        sm_lastError = wxPRINTER_ERROR;
        return false;
    }

    // Only set min and max, because from and to will be
    // set by the user
    m_printDialogData.SetMinPage(minPage);
    m_printDialogData.SetMaxPage(maxPage);

    printout->OnBeginPrinting();

    bool keepGoing = true;

    if (!printout->OnBeginDocument(m_printDialogData.GetFromPage(), m_printDialogData.GetToPage()))
    {
            wxEndBusyCursor();
            wxMessageBox(wxT("Could not start printing."), wxT("Print Error"), wxOK, parent);
    }

    int pn;
    for (pn = m_printDialogData.GetFromPage();
        keepGoing && (pn <= m_printDialogData.GetToPage()) && printout->HasPage(pn);
        pn++)
    {
        if (sm_abortIt)
        {
                break;
        }
        else
        {
                dc->StartPage();
                keepGoing = printout->OnPrintPage(pn);
                dc->EndPage();
        }
    }
    printout->OnEndDocument();

    printout->OnEndPrinting();

    if (sm_abortWindow)
    {
        sm_abortWindow->Show(false);
        wxDELETE(sm_abortWindow);
    }

    wxEndBusyCursor();

    delete dc;

    return true;
}
Example #20
0
void CQuickconnectBar::OnQuickconnect(wxCommandEvent& event)
{
	CState* pState = CContextManager::Get()->GetCurrentContext();
	if (!pState || !pState->m_pEngine)
	{
		wxMessageBox(_("FTP Engine not initialized, can't connect"), _("FileZilla Error"), wxICON_EXCLAMATION);
		return;
	}

	wxString host = m_pHost->GetValue();
	wxString user = m_pUser->GetValue();
	wxString pass = m_pPass->GetValue();
	wxString port = m_pPort->GetValue();
	
	CServer server;

	wxString error;

	CServerPath path;
	if (!server.ParseUrl(host, port, user, pass, error, path))
	{
		wxString msg = _("Could not parse server address:");
		msg += _T("\n");
		msg += error;
		wxMessageBox(msg, _("Syntax error"), wxICON_EXCLAMATION);
		return;
	}

	host = server.FormatHost(true);
	ServerProtocol protocol = server.GetProtocol();
	switch (protocol)
	{
	case FTP:
	case UNKNOWN:
		if (CServer::GetProtocolFromPort(server.GetPort()) != FTP &&
			CServer::GetProtocolFromPort(server.GetPort()) != UNKNOWN)
			host = _T("ftp://") + host;
		break;
	default:
		{
			const wxString prefix = server.GetPrefixFromProtocol(protocol);
			if (prefix != _T(""))
				host = prefix + _T("://") + host;
		}
		break;
	}
	
	m_pHost->SetValue(host);
	if (server.GetPort() != server.GetDefaultPort(server.GetProtocol()))
		m_pPort->SetValue(wxString::Format(_T("%d"), server.GetPort()));
	else
		m_pPort->SetValue(_T(""));

	m_pUser->SetValue(server.GetUser());
	m_pPass->SetValue(server.GetPass());

	if (protocol == HTTP || protocol == HTTPS)
	{
		wxString error = _("Invalid protocol specified. Valid protocols are:\nftp:// for normal FTP,\nsftp:// for SSH file transfer protocol,\nftps:// for FTP over SSL (implicit) and\nftpes:// for FTP over SSL (explicit).");
		wxMessageBox(error, _("Syntax error"), wxICON_EXCLAMATION);
		return;
	}

	if (event.GetId() == 1)
		server.SetBypassProxy(true);

	if (!m_pMainFrame->ConnectToServer(server, path))
		return;

	CRecentServerList::SetMostRecentServer(server);
}
Example #21
0
/**
 * Function Export_IDF3
 * generates IDFv3 compliant board (*.emn) and library (*.emp)
 * files representing the user's PCB design.
 */
bool Export_IDF3( BOARD* aPcb, const wxString& aFullFileName, bool aUseThou,
                  double aXRef, double aYRef )
{
    IDF3_BOARD idfBoard( IDF3::CAD_ELEC );

    SetLocaleTo_C_standard();

    bool ok = true;
    double scale = MM_PER_IU;   // we must scale internal units to mm for IDF
    IDF3::IDF_UNIT idfUnit;

    if( aUseThou )
    {
        idfUnit = IDF3::UNIT_THOU;
        idfBoard.SetUserPrecision( 1 );
    }
    else
    {
        idfUnit = IDF3::UNIT_MM;
        idfBoard.SetUserPrecision( 5 );
    }

    wxFileName brdName = aPcb->GetFileName();

    idfBoard.SetUserScale( scale );
    idfBoard.SetBoardThickness( aPcb->GetDesignSettings().GetBoardThickness() * scale );
    idfBoard.SetBoardName( TO_UTF8( brdName.GetFullName() ) );
    idfBoard.SetBoardVersion( 0 );
    idfBoard.SetLibraryVersion( 0 );

    std::ostringstream ostr;
    ostr << "KiCad " << TO_UTF8( GetBuildVersion() );
    idfBoard.SetIDFSource( ostr.str() );

    try
    {
        // set up the board reference point
        idfBoard.SetUserOffset( -aXRef, aYRef );

        // Export the board outline
        idf_export_outline( aPcb, idfBoard );

        // Output the drill holes and module (library) data.
        for( MODULE* module = aPcb->m_Modules; module != 0; module = module->Next() )
            idf_export_module( aPcb, module, idfBoard );

        if( !idfBoard.WriteFile( aFullFileName, idfUnit, false ) )
        {
            wxString msg;
            msg << _( "IDF Export Failed:\n" ) << FROM_UTF8( idfBoard.GetError().c_str() );
            wxMessageBox( msg );

            ok = false;
        }
    }
    catch( const IO_ERROR& ioe )
    {
        wxString msg;
        msg << _( "IDF Export Failed:\n" ) << ioe.errorText;
        wxMessageBox( msg );

        ok = false;
    }
    catch( const std::exception& e )
    {
        wxString msg;
        msg << _( "IDF Export Failed:\n" ) << FROM_UTF8( e.what() );
        wxMessageBox( msg );
        ok = false;
    }

    SetLocaleTo_Default();

    return ok;
}
Example #22
0
void VAutoDialog::OnNotifyCameraShoot (wxCommandEvent& ev)
{
	bool accidentalStop = false;
	CameraNotifier::CameraShootAction shootAction = (CameraNotifier::CameraShootAction) ev.GetInt ();
//	wxLogDebug (wxString::Format("Camera notification arrived: %d", shootAction));

	switch (shootAction) {
		case CameraNotifier::SHOOT_NOTIFY_TIME: 
			{
				SetStatusText (ev.GetString ());
				return;
			}
			break;
		case CameraNotifier::SHOOT_STOP_NORMALLY:
//			ObservationLog::Instance().SetStatus (wxT("OK"));
//			ObservationLog::Instance().Flush ();
			break;
		case CameraNotifier::SHOOT_TIMEOUT:
			m_camera->AbortShooting ();
//			ObservationLog::Instance().SetStatus (LOG_STATUS_TIMEOUT);
//			ObservationLog::Instance().Flush ();
			wxMessageBox (_("The camera is not stop shooting before timeout expired."), _("Shooting"), wxICON_EXCLAMATION | wxOK, this);
			accidentalStop = true;
			break;
		case CameraNotifier::SHOOT_ABORT:
//			ObservationLog::Instance().SetStatus (wxT("Failed:abort"));
//			ObservationLog::Instance().Flush ();
			wxMessageBox (_("The exposition stopped by the user."), _("Shooting"), wxICON_EXCLAMATION | wxOK, this);
			accidentalStop = true;
			break;
		}

	if (!m_Auto) {

		if (m_HasPlan)
			NextPlanTarget ();
		SetState (STATE_READY);
		DoDisableControls (false);
		m_MoveButton->SetFocus ();

		}

	else {

		if (!NextPlanTarget ()) {

			// TODO: A plan file-t töröljük az utolsó target után?

			m_Auto = false;
			SetState (STATE_READY);
			DoDisableControls (false);
			m_MoveButton->SetFocus ();

			}

		else {

			if (!DoMove ()) {

				m_Auto = false;
				SetState (STATE_READY);
				DoDisableControls (false);
				m_MoveButton->SetFocus ();

				}

			}

		}
}
Example #23
0
void CLocalTreeView::OnMenuDelete(wxCommandEvent& event)
{
	if (!m_contextMenuItem.IsOk())
		return;

	wxString path = GetDirFromItem(m_contextMenuItem);

	if (!m_pState->LocalDirHasParent(path) || !m_pState->LocalDirIsWriteable(path))
		return;

#ifdef __WXMSW__
	if (path.Len() == 3 && path.Mid(1) == _T(":\\"))
		return;
#endif

	// Under Windows use SHFileOperation to delete files and directories.
	// Under other systems, we have to recurse into subdirectories manually
	// to delete all contents.

#ifdef __WXMSW__
	// SHFileOperation accepts a list of null-terminated strings. Go through all
	// items to get the required buffer length

	if (path.Last() == wxFileName::GetPathSeparator())
		path.RemoveLast();

	int len = path.Len() + 2;

	// Allocate memory
	wxChar* pBuffer = new wxChar[len];
	_tcscpy(pBuffer, path);
	pBuffer[len - 1] = 0;

	// Now we can delete the files in the buffer
	SHFILEOPSTRUCT op;
	memset(&op, 0, sizeof(op));
	op.hwnd = (HWND)GetHandle();
	op.wFunc = FO_DELETE;
	op.pFrom = pBuffer;

	// Move to trash if shift is not pressed, else delete
	op.fFlags = wxGetKeyState(WXK_SHIFT) ? 0 : FOF_ALLOWUNDO;

	SHFileOperation(&op);

	delete [] pBuffer;
#else
	if (wxMessageBox(_("Really delete all selected files and/or directories?"), _("Confirmation needed"), wxICON_QUESTION | wxYES_NO, this) != wxYES)
		return;

	// Remember the directories to delete and the directories to visit
	std::list<wxString> dirsToDelete;
	std::list<wxString> dirsToVisit;

	if (path.Last() != wxFileName::GetPathSeparator())
		path += wxFileName::GetPathSeparator();

	dirsToVisit.push_back(path);
	dirsToDelete.push_front(path);

	// Process any subdirs which still have to be visited
	while (!dirsToVisit.empty())
	{
		wxString filename = dirsToVisit.front();
		dirsToVisit.pop_front();
		wxDir dir;
		if (!dir.Open(filename))
			continue;

		wxString file;
		for (bool found = dir.GetFirst(&file); found; found = dir.GetNext(&file))
		{
			if (file == _T(""))
			{
				wxGetApp().DisplayEncodingWarning();
				continue;
			}
			if (wxFileName::DirExists(filename + file))
			{
				wxString subDir = filename + file + wxFileName::GetPathSeparator();
				dirsToVisit.push_back(subDir);
				dirsToDelete.push_front(subDir);
			}
			else
				wxRemoveFile(filename + file);
		}
	}

	// Delete the now empty directories
	for (std::list<wxString>::const_iterator iter = dirsToDelete.begin(); iter != dirsToDelete.end(); iter++)
		wxRmdir(*iter);

#endif

	wxTreeItemId item = GetSelection();
	while (item && item != m_contextMenuItem)
		item = GetItemParent(item);

	if (!item)
	{
		if (GetItemParent(m_contextMenuItem) == GetSelection())
			m_pState->RefreshLocal();
		else
			Refresh();
		return;
	}

	if (path.Last() == wxFileName::GetPathSeparator())
		path.RemoveLast();
	int pos = path.Find(wxFileName::GetPathSeparator(), true);
	if (pos < 1)
		path = _T("/");
	else
		path = path.Left(pos);

	m_pState->SetLocalDir(path);
	Refresh();
}
Example #24
0
	virtual void Task()
	{
		for(uint i=0; i<cores; i++)
		{
			while(done[i] == false) Sleep(1);
		}

		ConLog.Write("Saving dump is started!");
		const uint length_for_core = prog_dial.GetMaxValue(0);
		const uint length = length_for_core * cores;
		prog_dial.Close();

		wxArrayLong max;
		max.Add(length);
		MTProgressDialog& prog_dial2 = 
			*new MTProgressDialog(NULL, wxDefaultSize, "Saving", "Loading...", max, 1);

		wxFile fd;
		fd.Open(patch, wxFile::write);

		const u32 shdr_count = ElfType64 ? shdr_arr_64->GetCount() : shdr_arr_32->GetCount();

		for(uint sh=0, counter=0; sh<shdr_count; ++sh)
		{
			const u64 sh_size = ElfType64 ? (*shdr_arr_64)[sh].sh_size : (*shdr_arr_32)[sh].sh_size;

			if(!sh_size) continue;
			const uint c_sh_size = sh_size / 4;

			fd.Write(wxString::Format("Start of section header %d (instructions count: %d)\n", sh, c_sh_size));

			for(uint i=0, c=0, v=0; i<c_sh_size; i++, c++, counter++)
			{
				if(c >= cores)
				{
					c = 0;
					v++;
				}

				prog_dial2.Update(0, counter, wxString::Format("Saving data to file: %d of %d", counter, length));

				if(v >= arr[c][sh].GetCount()) continue;

				fd.Write("\t");
				fd.Write(arr[c][sh][v]);
			}

			fd.Write(wxString::Format("End of section header %d\n\n", sh));
		}
		
		ConLog.Write("CleanUp dump saving!");

		for(uint c=0; c<cores; ++c)
		{
			for(uint sh=0; sh<shdr_count; ++sh) arr[c][sh].Empty();
		}

		delete[] arr;

		//safe_delete(shdr_arr);
		delete l_elf32;
		delete l_elf64;

		prog_dial2.Close();
		fd.Close();

		wxMessageBox("Dumping done.", "rpcs3 message");

		Emu.Stop();
	}
Example #25
0
void LabelDialog::OnExport(wxCommandEvent & WXUNUSED(event))
{
   int cnt = mData.size();

   // Silly user (could just disable the button, but that's a hassle ;-))
   if (cnt == 0) {
      wxMessageBox(_("No labels to export."));
      return;
   }

   // Extract the actual name.
   wxString fName = mTrackNames[mTrackNames.GetCount() - 1].AfterFirst(wxT('-')).Mid(1);

   fName = FileSelector(_("Export Labels As:"),
      wxEmptyString,
      fName.c_str(),
      wxT("txt"),
      wxT("*.txt"),
      wxFD_SAVE | wxFD_OVERWRITE_PROMPT | wxRESIZE_BORDER,
      this);

   if (fName == wxT(""))
      return;

   // Move existing files out of the way.  Otherwise wxTextFile will
   // append to (rather than replace) the current file.

   if (wxFileExists(fName)) {
#ifdef __WXGTK__
      wxString safetyFileName = fName + wxT("~");
#else
      wxString safetyFileName = fName + wxT(".bak");
#endif

      if (wxFileExists(safetyFileName))
         wxRemoveFile(safetyFileName);

      wxRename(fName, safetyFileName);
   }

   wxTextFile f(fName);
#ifdef __WXMAC__
   wxFile{}.Create(fName);
#else
   f.Create();
#endif
   f.Open();
   if (!f.IsOpened()) {
      wxMessageBox(_("Couldn't write to file: ") + fName);
      return;
   }

   // Transfer our collection to a temporary label track
   auto lt = mFactory.NewLabelTrack();
   int i;

   for (i = 0; i < cnt; i++) {
      RowData &rd = mData[i];

      lt->AddLabel(rd.selectedRegion, rd.title);
   }

   // Export them and clean
   lt->Export(f);

#ifdef __WXMAC__
   f.Write(wxTextFileType_Mac);
#else
   f.Write();
#endif
   f.Close();
}
/* MapEditorConfigDialog::onBtnNewMap
 * Called when the 'New Map' button is clicked
 *******************************************************************/
void MapEditorConfigDialog::onBtnNewMap(wxCommandEvent& e)
{
    // Get selected game/port index
    int sel_port = choice_port_config->GetSelection() - 1;
    if (sel_port >= 0)
        sel_port = ports_list[sel_port];
    int sel_game = choice_game_config->GetSelection();

    // Create new map dialog
    NewMapDialog dlg(this, sel_game, sel_port, maps, archive);

    // Show it
    dlg.SetInitialSize(wxSize(250, -1));
    dlg.CenterOnParent();
    if (dlg.ShowModal() == wxID_OK)
    {
        string mapname = dlg.getMapName();
        if (mapname.IsEmpty())
            return;

        // Check the map name isn't already taken
        for (unsigned a = 0; a < maps.size(); a++)
        {
            if (S_CMPNOCASE(maps[a].name, mapname))
            {
                wxMessageBox("Map " + mapname + " already exists", "Error");
                return;
            }
        }

        // Get selected map format
        int map_format = MAP_DOOM;
        for (uint8_t map_type = 0; map_type < MAP_UNKNOWN; map_type++)
            if (dlg.getMapFormat() == MAP_TYPE_NAMES[map_type])
            {
                map_format = map_type;
                break;
            }

        // Check archive type
        if (archive->getType() == ARCHIVE_WAD)
        {
            // Create new (empty) map at the end of the wad
            ArchiveEntry* head = archive->addNewEntry(mapname);
            ArchiveEntry* end = NULL;

            if (map_format == MAP_UDMF)
            {
                // UDMF
                archive->addNewEntry("TEXTMAP");
                end = archive->addNewEntry("ENDMAP");
            }
            else
            {
                // Doom(64) / Hexen
                archive->addNewEntry("THINGS");
                archive->addNewEntry("LINEDEFS");
                archive->addNewEntry("SIDEDEFS");
                archive->addNewEntry("VERTEXES");
                end = archive->addNewEntry("SECTORS");

                // Hexen
                if (map_format == MAP_HEXEN)
                    end = archive->addNewEntry("BEHAVIOR");
            }

            // Refresh map list
            populateMapList();
            list_maps->selectItem(list_maps->GetItemCount()-1);
        }
        else if (archive->getType() == ARCHIVE_ZIP
                 || archive->getType() == ARCHIVE_FOLDER)
        {
            // Create new wad archive for the map
            Archive* wad = new WadArchive();

            // Create new (empty) map at the end of the wad
            ArchiveEntry* head = wad->addNewEntry(mapname);
            ArchiveEntry* end = NULL;

            if (map_format == MAP_UDMF)
            {
                // UDMF
                wad->addNewEntry("TEXTMAP");
                end = wad->addNewEntry("ENDMAP");
            }
            else
            {
                // Doom(64) / Hexen
                wad->addNewEntry("THINGS");
                wad->addNewEntry("LINEDEFS");
                wad->addNewEntry("SIDEDEFS");
                wad->addNewEntry("VERTEXES");
                end = wad->addNewEntry("SECTORS");

                // Hexen
                if (map_format == MAP_HEXEN)
                    end = wad->addNewEntry("BEHAVIOR");
                // Doom 64
                else if (map_format == MAP_DOOM64)
                {
                    wad->addNewEntry("LIGHTS");
                    end = wad->addNewEntry("MACROS");
                }
            }

            // Add new map entry to the maps dir
            //ArchiveEntry* mapentry = archive->addNewEntry(mapname+".wad", 0xFFFFFFFF, archive->createDir("maps"));
            ArchiveEntry* mapentry = archive->addNewEntry(mapname + ".wad", "maps");
            MemChunk mc;
            wad->write(mc);
            mapentry->importMemChunk(mc);

            // Clean up
            delete wad;

            // Refresh map list
            populateMapList();
            list_maps->selectItem(list_maps->GetItemCount()-1);
        }
    }
}
Example #27
0
void ExportSingleDatasetSelect(wxWindow* pWnd, IGxDataset* const pGxDataset)
{
    wxCHECK_RET(pGxDataset, wxT("The input pointer (IGxDataset*) is NULL"));


    wxGxObject* pGxSrcObj = dynamic_cast<wxGxObject*>(pGxDataset);
    wxString sName = pGxSrcObj->GetName();
    sName = ClearExt(sName);

    wxGxObjectDialog dlg(pWnd, wxID_ANY, _("Select output"));
    dlg.SetName(sName);
    dlg.SetAllowMultiSelect(false);
    dlg.SetAllFilters(false);


    wxGISEnumDatasetType eType = pGxDataset->GetType();
    int eSubType = pGxDataset->GetSubType();
    bool bDefaultSet = false;
    int eDefaulSubType = 0;

    if (eType == enumGISFeatureDataset)
    {
        for (size_t i = enumVecUnknown + 1; i < enumVecMAX; ++i)
        {
            wxGISEnumVectorDatasetType eCurrentSubType = (wxGISEnumVectorDatasetType)i;
            if (eCurrentSubType != eSubType && IsFileDataset(enumGISFeatureDataset, eCurrentSubType))
            {
                if (bDefaultSet)
                {
                    dlg.AddFilter(new wxGxFeatureDatasetFilter(eCurrentSubType), false);
                }
                else
                {
                    dlg.AddFilter(new wxGxFeatureDatasetFilter(eCurrentSubType), true);
                    bDefaultSet = true;
                    eDefaulSubType = eCurrentSubType;
                }
            }
        }

        if (eSubType != enumVecPostGIS)
        {
            dlg.AddFilter(new wxGxFeatureDatasetFilter(enumVecPostGIS), false);
        }
    }
    else if (eType == enumGISRasterDataset)
    {
        //for (size_t i = enumRasterUnknown + 1; i < enumRasterMAX; ++i)
        //{
        //    wxGISEnumRasterDatasetType eCurrentSubType = (wxGISEnumRasterDatasetType)i;
        //    if (eCurrentSubType != eSubType && IsFileDataset(enumGISRasterDataset, eCurrentSubType))
        //    {
        //        if (bDefaultSet)
        //        {
        //            dlg.AddFilter(new wxGxRasterDatasetFilter(eCurrentSubType), false);
        //        }
        //        else
        //        {
        //            dlg.AddFilter(new wxGxRasterDatasetFilter(eCurrentSubType), true);
        //            bDefaultSet = true;
        //            eDefaulSubType = eCurrentSubType;
        //        }
        //    }
        //}

        //if (eSubType != enumRasterPostGIS)
        //{
        //    dlg.AddFilter(new wxGxRasterDatasetFilter(enumRasterPostGIS), false);
        //}
    }
    else if (eType == enumGISTableDataset)
    {
        for (size_t i = enumTableUnknown + 1; i < enumTableMAX; ++i)
        {
            wxGISEnumTableDatasetType eCurrentSubType = (wxGISEnumTableDatasetType)i;
            if (eCurrentSubType != eSubType && IsFileDataset(enumGISTableDataset, eCurrentSubType))
            {
                if (bDefaultSet)
                {
                    dlg.AddFilter(new wxGxTableDatasetFilter(eCurrentSubType), false);
                }
                else
                {
                    dlg.AddFilter(new wxGxTableDatasetFilter(eCurrentSubType), true);
                    bDefaultSet = true;
                    eDefaulSubType = eCurrentSubType;
                }
            }
        }

        if (eSubType != enumTablePostgres)
        {
            dlg.AddFilter(new wxGxTableDatasetFilter(enumTablePostgres), false);
        }
    }

    dlg.SetButtonCaption(_("Export"));
    dlg.SetOverwritePrompt(true);

    wxGxObject* pGxParentObj = pGxSrcObj->GetParent();
    wxString sStartLoc;

    if (pGxParentObj)
    {
        while (NULL != pGxParentObj)
        {
            wxGxObjectContainer* pGxCont = wxDynamicCast(pGxParentObj, wxGxObjectContainer);
            if (NULL != pGxCont && pGxCont->CanCreate(enumGISFeatureDataset, eDefaulSubType))
            {
                break;
            }
            else
            {
                pGxParentObj = pGxParentObj->GetParent();
            }
        }
        if (pGxParentObj)
        {
            sStartLoc = pGxParentObj->GetFullName();
        }
    }

    wxGISAppConfig oConfig = GetConfig();
    if (oConfig.IsOk())
    {
        if (eType == enumGISFeatureDataset)
        {
            sStartLoc = oConfig.Read(enumGISHKCU, dlg.GetAppName() + wxT("/lastpath/exp_vector_ds/path"), sStartLoc);
        }
        else if (eType == enumGISRasterDataset)
        {
            sStartLoc = oConfig.Read(enumGISHKCU, dlg.GetAppName() + wxT("/lastpath/exp_raster_ds/path"), sStartLoc);
        }
        else if (eType == enumGISTableDataset)
        {
            sStartLoc = oConfig.Read(enumGISHKCU, dlg.GetAppName() + wxT("/lastpath/exp_table_ds/path"), sStartLoc);
        }
    }

    if (!sStartLoc.IsEmpty())
        dlg.SetStartingLocation(sStartLoc);
    if (dlg.ShowModalSave() == wxID_OK)
    {

        wxGxObjectFilter* pFilter = dlg.GetCurrentFilter();
        if (NULL == pFilter)
        {
            wxMessageBox(_("Unexpected error"), _("Error"), wxCENTRE | wxOK | wxICON_ERROR, pWnd);
            wxLogError(_("Null wxGxObjectFilter returned"));
            return;
        }

        CPLString sPath = dlg.GetPath();
        wxString sCatalogPath = dlg.GetLocation()->GetFullName();
        wxFileName oFName(dlg.GetName());
        wxString sName = oFName.GetName();

        if (oConfig.IsOk())
        {
            if (eType == enumGISFeatureDataset)
            {
                oConfig.Write(enumGISHKCU, dlg.GetAppName() + wxT("/lastpath/exp_vector_ds/path"), sCatalogPath);
            }
            else if (eType == enumGISRasterDataset)
            {
                oConfig.Write(enumGISHKCU, dlg.GetAppName() + wxT("/lastpath/exp_raster_ds/path"), sCatalogPath);
            }
            else if (eType == enumGISTableDataset)
            {
                oConfig.Write(enumGISHKCU, dlg.GetAppName() + wxT("/lastpath/exp_table_ds/path"), sCatalogPath);
            }
        }

        if (eType == enumGISFeatureDataset)
        {
            ExportSingleVectorDataset(pWnd, sPath, sName, pFilter, pGxDataset);
        }
        else if (eType == enumGISRasterDataset)
        {
            ExportSingleRasterDataset(pWnd, sPath, sName, pFilter, pGxDataset);
        }
        else if (eType == enumGISTableDataset)
        {
            ExportSingleTableDataset(pWnd, sPath, sName, pFilter, pGxDataset);
        }
    }
}
Example #28
0
void hamguiFrame::OnAbout(wxCommandEvent &event)
{
    wxString msg = wxbuildinfo(long_f);
    wxMessageBox(msg, _("Welcome to..."));
}
		void LoadXMLFileImp( T& doc, bool condenseWhiteSpace, const wxString& path, U* declaration )
	{
		if ( NULL == declaration )
		{
			// Ask user to all wxFB to convert the file to UTF-8 and add the XML declaration
			wxString msg = _("This xml file has no declaration.\n");
			msg 		+= _("Would you like wxFormBuilder to backup the file and convert it to UTF-8\?\n");
			msg			+= _("You will be prompted for an encoding.\n\n");
			msg			+= _("Path: ");
			msg			+= path;
			int result = wxMessageBox( msg, _("Missing Declaration"), wxICON_QUESTION | wxYES_NO | wxYES_DEFAULT, wxTheApp->GetTopWindow() );
			if ( wxNO == result )
			{
				// User declined, give up
				THROW_WXFBEX( _("Missing Declaration on XML File: ") << path );
			}

			// User accepted, convert the file
			wxFontEncoding chosenEncoding = StringUtils::GetEncodingFromUser( _("Please choose the original encoding.") );
			if ( wxFONTENCODING_MAX == chosenEncoding )
			{
				THROW_WXFBEX( _("Missing Declaration on XML File: ") << path );
			}

			ConvertAndAddDeclaration( path, chosenEncoding );

			// Reload
			LoadXMLFile( doc, condenseWhiteSpace, path );
			return;
		}

		// The file will have a declaration at this point
		wxString version = _WXSTR( declaration->Version() );
		if ( version.empty() )
		{
			version = wxT("1.0");
		}

		wxString standalone = _WXSTR( declaration->Standalone() );
		if ( standalone.empty() )
		{
			standalone = wxT("yes");
		}

		wxString encodingName = _WXSTR( declaration->Encoding() );
		if ( encodingName.empty() )
		{
			// Ask user to all wxFB to convert the file to UTF-8 and add the XML declaration
			wxString msg = _("This xml file has no encoding specified.\n");
			msg 		+= _("Would you like wxFormBuilder to backup the file and convert it to UTF-8\?\n");
			msg			+= _("You will be prompted for an encoding.\n\n");
			msg			+= _("Path: ");
			msg			+= path;
			if ( wxNO == wxMessageBox( msg, _("Unknown Encoding"), wxICON_QUESTION | wxYES_NO | wxYES_DEFAULT, wxTheApp->GetTopWindow() ) )
			{
				// User declined, give up
				THROW_WXFBEX( _("Unknown Encoding for XML File: ") << path );
			}

			// User accepted, convert the file
			wxFontEncoding chosenEncoding = StringUtils::GetEncodingFromUser( _("Please choose the original encoding.") );
			if ( wxFONTENCODING_MAX == chosenEncoding )
			{
				THROW_WXFBEX( _("Unknown Encoding for XML File: ") << path );
			}
			ConvertAndChangeDeclaration( path, version, standalone, chosenEncoding );

			// Reload
			LoadXMLFile( doc, condenseWhiteSpace, path );
			return;
		}

		// The file will have an encoding at this point
		wxFontEncoding encoding = wxFontMapperBase::GetEncodingFromName( encodingName.MakeLower() );
		if ( wxFONTENCODING_UTF8 == encoding )
		{
			// This is what we want
			return;
		}
		else if ( wxFONTENCODING_MAX == encoding )
		{
			wxString msg = wxString::Format( _("The encoding of this xml file is not supported.\n\nFile: %s\nEncoding: %s\nSupported Encodings:\n\n%s"),
							path.c_str(),
							encodingName.c_str(),
							StringUtils::GetSupportedEncodings().c_str() );
			wxMessageBox( msg, wxString::Format( _("Unsupported Encoding: %s"), encodingName.c_str() ) );
			THROW_WXFBEX( _("Unsupported encoding for XML File: ") << path );
		}
		else
		{
			// Ask user to all wxFB to convert the file to UTF-8 and add the XML declaration
			wxString msg = wxString::Format( _("This xml file has specified encoding %s. wxFormBuilder only works with UTF-8.\n"),
							wxFontMapper::GetEncodingDescription( encoding ).c_str() );
			msg 		+= _("Would you like wxFormBuilder to backup the file and convert it to UTF-8\?\n\n");
			msg			+= _("Path: ");
			msg			+= path;
			if ( wxNO == wxMessageBox( msg, _("Not UTF-8"), wxICON_QUESTION | wxYES_NO | wxYES_DEFAULT, wxTheApp->GetTopWindow() ) )
			{
				// User declined, give up
				THROW_WXFBEX( _("Wrong Encoding for XML File: ") << path );
			}

			// User accepted, convert the file
			ConvertAndChangeDeclaration( path, version, standalone, encoding );

			// Reload
			LoadXMLFile( doc, condenseWhiteSpace, path );
			return;
		}
	}
Example #30
0
void ecResolveConflictsDialog::OnContinue(wxCommandEvent& event)
{
    // Ensure we have the current conflict check array
    int i;
    for (i = 0; i < m_conflictsCtrl->GetItemCount(); i++)
    {
        if (m_conflictsCtrl->GetItemState(i, wxLIST_STATE_SELECTED) & wxLIST_STATE_SELECTED)
            RemoveConflictSolutions((CdlConflict) m_conflictsCtrl->GetItemData(i));
    }

    // Dismiss the window
    EndModal(wxID_OK);

    std::list<CdlConflict>::const_iterator conf_i;

    for (conf_i= m_conflicts.begin (); conf_i != m_conflicts.end (); conf_i++) // for each conflict
    {
        CdlConflict conflict=*conf_i;
        //int nSolutions=conflict->get_solution().size();
        SolutionInfo &info=Info(conflict);
        int nIndex=0;
        const std::vector<std::pair<CdlValuable, CdlValue> >&Solution=conflict->get_solution();
        for (std::vector<std::pair<CdlValuable, CdlValue> >::const_iterator soln_i = Solution.begin();soln_i != Solution.end(); soln_i++) {
            if(SolutionInfo::CHECKED==info.arItem[nIndex++]){
                CdlValuable valuable  = soln_i->first;
                CdlValue value=soln_i->second;
                CdlValueFlavor flavor = valuable->get_flavor();
                const wxString strName(valuable->get_name().c_str());
                const wxString strValue(value.get_value().c_str());
                bool rc = TRUE;
                wxString str;
                try
                {
                    switch(flavor)
                    {
                    case CdlValueFlavor_None :
                        str = wxT("set CdlValueFlavor_None");
                        rc = FALSE;
                        break;
                    case CdlValueFlavor_Bool :
                        str.Printf(_("%s %s\n"), (const wxChar*) (value.is_enabled()?_("disable"):_("enable")), (const wxChar*) strName);
                        valuable->set_enabled (m_Transaction, value.is_enabled(), CdlValueSource_User);
                        break;
                    case CdlValueFlavor_BoolData :
                        {
                            bool bEnabled=value.is_enabled();
                            str.Printf(_("%s %s and set value to %s\n"), (const wxChar*) (bEnabled? _("disable"):_("enable")), (const wxChar*) strName, (const wxChar*) strValue);
                            // Surely this is wrong - we don't want to set the same value, we want to
                            // set a NEW value.
                            // CdlSimpleValue simple_value = valuable->get_simple_value ();
                            //valuable->set_enabled_and_value (m_Transaction, bEnabled, simple_value, CdlValueSource_User);
                            valuable->set_enabled_and_value (m_Transaction, bEnabled, ecUtils::UnicodeToStdStr (strValue), CdlValueSource_User);
                        }
                        break;
                    case CdlValueFlavor_Data :
                        str.Printf(_("set %s to %s\n"), (const wxChar*) strName, (const wxChar*) strValue);
                        valuable->set_value (m_Transaction, ecUtils::UnicodeToStdStr (strValue), CdlValueSource_User);
                        break;
                    }
                }
                catch(...)
                {
                    rc = FALSE;
                }
                if(rc)
                {
                    wxGetApp().GetConfigToolDoc()->Modify(TRUE);
                } else
                {
                    wxString msg;
                    msg.Printf(_("Failed to %s\n"), (const wxChar*) str);
                    wxMessageBox(msg, wxGetApp().GetSettings().GetAppName(), wxICON_EXCLAMATION|wxOK);
                }
            }
        }
    }
}