Пример #1
0
void PCB_EDIT_FRAME::Start_DragTrackSegmentAndKeepSlope( TRACK* track, wxDC*  DC )
{
    TRACK* TrackToStartPoint = NULL;
    TRACK* TrackToEndPoint   = NULL;
    bool   error = false;

    if( !track )
        return;

    // TODO: Use cleanup functions to merge collinear segments if track
    // is connected to a collinear segment.

    s_StartSegmentPresent = s_EndSegmentPresent = true;

    if( ( track->start == NULL ) || ( track->start->Type() == PCB_TRACE_T ) )
        TrackToStartPoint = track->GetTrack( GetBoard()->m_Track, NULL, ENDPOINT_START, true, false );

    //  Test if more than one segment is connected to this point
    if( TrackToStartPoint )
    {
        TrackToStartPoint->SetState( BUSY, true );

        if( ( TrackToStartPoint->Type() == PCB_VIA_T )
           || track->GetTrack( GetBoard()->m_Track, NULL, ENDPOINT_START, true, false ) )
            error = true;

        TrackToStartPoint->SetState( BUSY, false );
    }

    if( ( track->end == NULL ) || ( track->end->Type() == PCB_TRACE_T ) )
        TrackToEndPoint = track->GetTrack( GetBoard()->m_Track, NULL, ENDPOINT_END, true, false );

    //  Test if more than one segment is connected to this point
    if( TrackToEndPoint )
    {
        TrackToEndPoint->SetState( BUSY, true );

        if( (TrackToEndPoint->Type() == PCB_VIA_T)
           || track->GetTrack( GetBoard()->m_Track, NULL, ENDPOINT_END, true, false ) )
            error = true;

        TrackToEndPoint->SetState( BUSY, false );
    }

    if( error )
    {
        DisplayError( this,
                      _( "Unable to drag this segment: too many segments connected" ) );
        return;
    }

    if( !TrackToStartPoint || ( TrackToStartPoint->Type() != PCB_TRACE_T ) )
        s_StartSegmentPresent = false;

    if( !TrackToEndPoint || ( TrackToEndPoint->Type() != PCB_TRACE_T ) )
        s_EndSegmentPresent = false;

    // Change high light net: the new one will be highlighted
    GetBoard()->PushHighLight();

    if( GetBoard()->IsHighLightNetON() )
        HighLight( DC );

    EraseDragList();

    track->SetFlags( IS_DRAGGED );

    if( TrackToStartPoint )
    {
        STATUS_FLAGS flag = STARTPOINT;

        if( track->GetStart() != TrackToStartPoint->GetStart() )
            flag = ENDPOINT;

        AddSegmentToDragList( flag, TrackToStartPoint );
        track->SetFlags( STARTPOINT );
    }

    if( TrackToEndPoint )
    {
        STATUS_FLAGS flag = STARTPOINT;

        if( track->GetEnd() != TrackToEndPoint->GetStart() )
            flag = ENDPOINT;

        AddSegmentToDragList( flag, TrackToEndPoint );
        track->SetFlags( ENDPOINT );
    }

    AddSegmentToDragList( track->GetFlags(), track );

    UndrawAndMarkSegmentsToDrag( m_canvas, DC );


    PosInit   = GetCrossHairPosition();
    s_LastPos = GetCrossHairPosition();
    m_canvas->SetMouseCapture( Show_Drag_Track_Segment_With_Cte_Slope, Abort_MoveTrack );

    GetBoard()->SetHighLightNet( track->GetNetCode() );
    GetBoard()->HighLightON();
    GetBoard()->DrawHighLight( m_canvas, DC, GetBoard()->GetHighLightNetCode() );

    // Prepare the Undo command
    ITEM_PICKER picker( NULL, UR_CHANGED );

    for( unsigned ii = 0; ii < g_DragSegmentList.size(); ii++ )
    {
        TRACK* draggedtrack = g_DragSegmentList[ii].m_Track;
        picker.SetItem( draggedtrack);
        picker.SetLink ( draggedtrack->Clone() );
        s_ItemsListPicker.PushItem( picker );
        draggedtrack = (TRACK*) picker.GetLink();
        draggedtrack->SetStatus( 0 );
        draggedtrack->ClearFlags();
    }

    if( !InitialiseDragParameters() )
    {
        DisplayError( this, _( "Unable to drag this segment: two collinear segments" ) );
        m_canvas->SetMouseCaptureCallback( NULL );
        Abort_MoveTrack( m_canvas, DC );
        return;
    }
}
void main ()
{
	HANDLE hOutputReadTmp,hOutputRead,hOutputWrite;
	HANDLE hInputWriteTmp,hInputRead,hInputWrite;
	HANDLE hErrorWrite;
	HANDLE hThread;
	DWORD ThreadId;
	SECURITY_ATTRIBUTES sa;


	// Set up the security attributes struct.
	sa.nLength= sizeof(SECURITY_ATTRIBUTES);
	sa.lpSecurityDescriptor = NULL;
	sa.bInheritHandle = TRUE;


	// Create the child output pipe.
	if (!CreatePipe(&hOutputReadTmp,&hOutputWrite,&sa,0))
		DisplayError("CreatePipe");


	// Create a duplicate of the output write handle for the std error
	// write handle. This is necessary in case the child application
	// closes one of its std output handles.
	if (!DuplicateHandle(GetCurrentProcess(),hOutputWrite,
		GetCurrentProcess(),&hErrorWrite,0,
		TRUE,DUPLICATE_SAME_ACCESS))
		DisplayError("DuplicateHandle");


	// Create the child input pipe.
	if (!CreatePipe(&hInputRead,&hInputWriteTmp,&sa,0))
		DisplayError("CreatePipe");


	// Create new output read handle and the input write handles. Set
	// the Properties to FALSE. Otherwise, the child inherits the
	// properties and, as a result, non-closeable handles to the pipes
	// are created.
	if (!DuplicateHandle(GetCurrentProcess(),hOutputReadTmp,
		GetCurrentProcess(),
		&hOutputRead, // Address of new handle.
		0,FALSE, // Make it uninheritable.
		DUPLICATE_SAME_ACCESS))
		DisplayError("DupliateHandle");

	if (!DuplicateHandle(GetCurrentProcess(),hInputWriteTmp,
		GetCurrentProcess(),
		&hInputWrite, // Address of new handle.
		0,FALSE, // Make it uninheritable.
		DUPLICATE_SAME_ACCESS))
		DisplayError("DupliateHandle");


	// Close inheritable copies of the handles you do not want to be
	// inherited.
	if (!CloseHandle(hOutputReadTmp)) DisplayError("CloseHandle");
	if (!CloseHandle(hInputWriteTmp)) DisplayError("CloseHandle");


	// Get std input handle so you can close it and force the ReadFile to
	// fail when you want the input thread to exit.
	if ( (hStdIn = GetStdHandle(STD_INPUT_HANDLE)) ==
		INVALID_HANDLE_VALUE )
		DisplayError("GetStdHandle");

	PrepAndLaunchRedirectedChild(hOutputWrite,hInputRead,hErrorWrite);


	// Close pipe handles (do not continue to modify the parent).
	// You need to make sure that no handles to the write end of the
	// output pipe are maintained in this process or else the pipe will
	// not close when the child process exits and the ReadFile will hang.
	if (!CloseHandle(hOutputWrite)) DisplayError("CloseHandle");
	if (!CloseHandle(hInputRead )) DisplayError("CloseHandle");
	if (!CloseHandle(hErrorWrite)) DisplayError("CloseHandle");


	// Launch the thread that gets the input and sends it to the child.
	hThread = CreateThread(NULL,0,GetAndSendInputThread,
		(LPVOID)hInputWrite,0,&ThreadId);
	if (hThread == NULL) DisplayError("CreateThread");


	// Read the child's output.
	ReadAndHandleOutput(hOutputRead);
	// Redirection is complete


	// Force the read on the input to return by closing the stdin handle.
	Sleep(5000);
	if (!CloseHandle(hStdIn)) DisplayError("CloseHandle");
	printf("closed hStdIn\n");


	// Tell the thread to exit and wait for thread to die.
	bRunThread = FALSE;

	if (WaitForSingleObject(hThread,INFINITE) == WAIT_FAILED)
		DisplayError("WaitForSingleObject");

	if (!CloseHandle(hOutputRead)) DisplayError("CloseHandle");
	if (!CloseHandle(hInputWrite)) DisplayError("CloseHandle");
}
Пример #3
0
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_3DSHAPELIB_WIZARD:
#ifdef BUILD_GITHUB_PLUGIN
        Invoke3DShapeLibsDownloaderWizard( this );
#endif
        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" ) );
    }
}
Пример #4
0
void PCB_EDIT_FRAME::Files_io_from_id( int id )
{
    wxString   msg;

    // If an edition is in progress, stop it.
    // For something else than save, get rid of current tool.
    if( id == ID_SAVE_BOARD )
        m_canvas->EndMouseCapture( -1, m_canvas->GetDefaultCursor() );
    else
        m_canvas->EndMouseCapture( ID_NO_TOOL_SELECTED, m_canvas->GetDefaultCursor() );

    switch( id )
    {
    case ID_LOAD_FILE:
        {
            // LoadOnePcbFile( GetBoard()->GetFileName(), append=false, aForceFileDialog=true );

            int         open_ctl;
            wxString    fileName = Prj().AbsolutePath( GetBoard()->GetFileName() );

            if( !AskLoadBoardFileName( this, &open_ctl, &fileName ) )
                return;

            OpenProjectFiles( std::vector<wxString>( 1, fileName ), open_ctl );
        }
        break;

    case ID_MENU_READ_BOARD_BACKUP_FILE:
    case ID_MENU_RECOVER_BOARD_AUTOSAVE:
        {
            wxFileName currfn = Prj().AbsolutePath( GetBoard()->GetFileName() );
            wxFileName fn = currfn;

            if( id == ID_MENU_RECOVER_BOARD_AUTOSAVE )
            {
                wxString rec_name = wxString( autosavePrefix ) + fn.GetName();
                fn.SetName( rec_name );
            }
            else
            {
                wxString backup_ext = fn.GetExt()+ backupSuffix;
                fn.SetExt( backup_ext );
            }

            if( !fn.FileExists() )
            {
                msg.Printf( _( "Recovery file '%s' not found." ),
                            GetChars( fn.GetFullPath() ) );
                DisplayInfoMessage( this, msg );
                break;
            }

            msg.Printf( _( "OK to load recovery or backup file '%s'" ),
                            GetChars(fn.GetFullPath() ) );

            if( !IsOK( this, msg ) )
                break;

            GetScreen()->ClrModify();    // do not prompt the user for changes

            // LoadOnePcbFile( fn.GetFullPath(), aAppend=false, aForceFileDialog=false );
            OpenProjectFiles( std::vector<wxString>( 1, fn.GetFullPath() ) );

            // Re-set the name since name or extension was changed
            GetBoard()->SetFileName( currfn.GetFullPath() );
            UpdateTitle();
        }
        break;

    case ID_APPEND_FILE:
        {
            int         open_ctl;
            wxString    fileName;

            if( !AskLoadBoardFileName( this, &open_ctl, &fileName, true ) )
                break;

            AppendBoardFile( fileName, open_ctl );

            m_canvas->Refresh();
        }
        break;

    case ID_NEW_BOARD:
    {
        if( !Clear_Pcb( true ) )
            break;

        wxFileName fn( wxStandardPaths::Get().GetDocumentsDir(), wxT( "noname" ),
                       ProjectFileExtension );

        Prj().SetProjectFullName( fn.GetFullPath() );

        fn.SetExt( PcbFileExtension );

        GetBoard()->SetFileName( fn.GetFullPath() );
        UpdateTitle();
        ReCreateLayerBox();
        break;
    }

    case ID_SAVE_BOARD:
        if( ! GetBoard()->GetFileName().IsEmpty() )
        {
            SavePcbFile( Prj().AbsolutePath( GetBoard()->GetFileName() ) );
            break;
        }
    // Fall through
    case ID_COPY_BOARD_AS:
    case ID_SAVE_BOARD_AS:
        {
            wxString    pro_dir = wxPathOnly( Prj().GetProjectFullName() );
            wxFileName  fn( pro_dir, _( "noname" ), KiCadPcbFileExtension );
            wxString    filename = fn.GetFullPath();

            if( AskSaveBoardFileName( this, &filename ) )
            {
                if( id == ID_COPY_BOARD_AS )
                    SavePcbCopy( filename );
                else
                    SavePcbFile( filename, NO_BACKUP_FILE );
            }
        }
        break;

    default:
        DisplayError( this, wxT( "File_io Internal Error" ) );
        break;
    }
}
Пример #5
0
bool PCB_EDIT_FRAME::SavePcbFile( const wxString& aFileName, bool aCreateBackupFile )
{
    // please, keep it simple.  prompting goes elsewhere.

    wxFileName  pcbFileName = aFileName;

    if( pcbFileName.GetExt() == LegacyPcbFileExtension )
        pcbFileName.SetExt( KiCadPcbFileExtension );

    if( !IsWritable( pcbFileName ) )
    {
        wxString msg = wxString::Format( _(
            "No access rights to write to file '%s'" ),
            GetChars( pcbFileName.GetFullPath() )
            );

        DisplayError( this, msg );
        return false;
    }

    wxString backupFileName;

    // aCreateBackupFile == false is mainly used to write autosave files
    // or new files in save as... command
    if( aCreateBackupFile )
    {
        backupFileName = create_backup_file( aFileName );
    }

    GetBoard()->m_Status_Pcb &= ~CONNEXION_OK;

    GetBoard()->SynchronizeNetsAndNetClasses();

    // Select default Netclass before writing file.
    // Useful to save default values in headers
    SetCurrentNetClass( NETCLASS::Default );

    ClearMsgPanel();

    wxString    upperTxt;
    wxString    lowerTxt;

    try
    {
        PLUGIN::RELEASER    pi( IO_MGR::PluginFind( IO_MGR::KICAD ) );

        wxASSERT( pcbFileName.IsAbsolute() );

        pi->Save( pcbFileName.GetFullPath(), GetBoard(), NULL );
    }
    catch( const IO_ERROR& ioe )
    {
        wxString msg = wxString::Format( _(
                "Error saving board file '%s'.\n%s" ),
                GetChars( pcbFileName.GetFullPath() ),
                GetChars( ioe.errorText )
                );
        DisplayError( this, msg );

        lowerTxt.Printf( _( "Failed to create '%s'" ), GetChars( pcbFileName.GetFullPath() ) );

        AppendMsgPanel( upperTxt, lowerTxt, CYAN );

        return false;
    }

    GetBoard()->SetFileName( pcbFileName.GetFullPath() );
    UpdateTitle();

    // Put the saved file in File History, unless aCreateBackupFile
    // is false.
    // aCreateBackupFile == false is mainly used to write autosave files
    // and not need to have an autosave file in file history
    if( aCreateBackupFile )
        UpdateFileHistory( GetBoard()->GetFileName() );

    // Delete auto save file on successful save.
    wxFileName autoSaveFileName = pcbFileName;

    autoSaveFileName.SetName( wxString( autosavePrefix ) + pcbFileName.GetName() );

    if( autoSaveFileName.FileExists() )
        wxRemoveFile( autoSaveFileName.GetFullPath() );

    if( !!backupFileName )
        upperTxt.Printf( _( "Backup file: '%s'" ), GetChars( backupFileName ) );

    lowerTxt.Printf( _( "Wrote board file: '%s'" ), GetChars( pcbFileName.GetFullPath() ) );

    AppendMsgPanel( upperTxt, lowerTxt, CYAN );

    GetScreen()->ClrModify();
    GetScreen()->ClrSave();
    return true;
}
/* Called on events (popup menus) relative to automove and autoplace footprints
 */
void PCB_EDIT_FRAME::OnPlaceOrRouteFootprints( wxCommandEvent& event )
{
    int        id = event.GetId();

    if( m_mainToolBar == NULL )
        return;

    INSTALL_UNBUFFERED_DC( dc, m_canvas );

    switch( id )
    {
    case ID_POPUP_PCB_AUTOROUTE_SELECT_LAYERS:
        return;

    case ID_POPUP_PCB_AUTOPLACE_FIXE_MODULE:
        LockModule( (MODULE*) GetScreen()->GetCurItem(), true );
        return;

    case ID_POPUP_PCB_AUTOPLACE_FREE_MODULE:
        LockModule( (MODULE*) GetScreen()->GetCurItem(), false );
        return;

    case ID_POPUP_PCB_AUTOPLACE_FREE_ALL_MODULES:
        LockModule( NULL, false );
        return;

    case ID_POPUP_PCB_AUTOPLACE_FIXE_ALL_MODULES:
        LockModule( NULL, true );
        return;

    case ID_POPUP_CANCEL_CURRENT_COMMAND:
        if( m_canvas->IsMouseCaptured() )
        {
            m_canvas->CallEndMouseCapture( &dc );
        }

        break;

    default:   // Abort a current command (if any)
        m_canvas->EndMouseCapture( ID_NO_TOOL_SELECTED, m_canvas->GetDefaultCursor() );
        break;
    }

    // Erase ratsnest if needed
    if( GetBoard()->IsElementVisible(RATSNEST_VISIBLE) )
        DrawGeneralRatsnest( &dc );

    GetBoard()->m_Status_Pcb |= DO_NOT_SHOW_GENERAL_RASTNEST;

    switch( id )
    {
    case ID_POPUP_PCB_AUTOPLACE_CURRENT_MODULE:
        AutoPlaceModule( (MODULE*) GetScreen()->GetCurItem(), PLACE_1_MODULE, &dc );
        break;

    case ID_POPUP_PCB_AUTOPLACE_ALL_MODULES:
        AutoPlaceModule( NULL, PLACE_ALL, &dc );
        break;

    case ID_POPUP_PCB_AUTOPLACE_NEW_MODULES:
        AutoPlaceModule( NULL, PLACE_OUT_OF_BOARD, &dc );
        break;

    case ID_POPUP_PCB_AUTOPLACE_NEXT_MODULE:
        AutoPlaceModule( NULL, PLACE_INCREMENTAL, &dc );
        break;

    case ID_POPUP_PCB_SPREAD_ALL_MODULES:
        if( !IsOK( this,
                   _("Not locked footprints inside the board will be moved. OK?") ) )
            break;
        // Fall through
    case ID_POPUP_PCB_SPREAD_NEW_MODULES:
        if( GetBoard()->m_Modules == NULL )
        {
            DisplayError( this, _( "No footprint found!" ) );
            return;
        }
        else
        {
            MODULE* footprint = GetBoard()->m_Modules;
            std::vector<MODULE*> footprintList;
            for( ; footprint != NULL; footprint = footprint->Next() )
                footprintList.push_back( footprint );

            SpreadFootprints( &footprintList, id == ID_POPUP_PCB_SPREAD_NEW_MODULES, true );
        }
        break;

    case ID_POPUP_PCB_AUTOROUTE_ALL_MODULES:
        Autoroute( &dc, ROUTE_ALL );
        break;

    case ID_POPUP_PCB_AUTOROUTE_MODULE:
        Autoroute( &dc, ROUTE_MODULE );
        break;

    case ID_POPUP_PCB_AUTOROUTE_PAD:
        Autoroute( &dc, ROUTE_PAD );
        break;

    case ID_POPUP_PCB_AUTOROUTE_NET:
        Autoroute( &dc, ROUTE_NET );
        break;

    case ID_POPUP_PCB_AUTOROUTE_RESET_UNROUTED:
        Reset_Noroutable( &dc );
        break;

    default:
        wxMessageBox( wxT( "OnPlaceOrRouteFootprints command error" ) );
        break;
    }

    GetBoard()->m_Status_Pcb &= ~DO_NOT_SHOW_GENERAL_RASTNEST;
    Compile_Ratsnest( &dc, true );
}
Пример #7
0
int PCB_EDIT_FRAME::Begin_Zone( wxDC* DC )
{
    ZONE_SETTINGS zoneInfo = GetZoneSettings();

    // verify if s_CurrentZone exists (could be deleted since last selection) :
    int ii;
    for( ii = 0; ii < GetBoard()->GetAreaCount(); ii++ )
    {
        if( s_CurrentZone == GetBoard()->GetArea( ii ) )
            break;
    }

    if( ii >= GetBoard()->GetAreaCount() ) // Not found: could be deleted since last selection
    {
        s_AddCutoutToCurrentZone = false;
        s_CurrentZone = NULL;
    }

    // If no zone contour in progress, a new zone is being created:
    if( !GetBoard()->m_CurrentZoneContour )
    {
        if( GetToolId() == ID_PCB_KEEPOUT_AREA_BUTT &&
            getActiveLayer() >= FIRST_NON_COPPER_LAYER )
        {
            DisplayError( this,
                          _( "Error: a keepout area is allowed only on copper layers" ) );
            return 0;
        }
        else
            GetBoard()->m_CurrentZoneContour = new ZONE_CONTAINER( GetBoard() );
    }

    ZONE_CONTAINER* zone = GetBoard()->m_CurrentZoneContour;

    if( zone->GetNumCorners() == 0 )    // Start a new contour: init zone params (net, layer ...)
    {
        if( !s_CurrentZone )            // A new outline is created, from scratch
        {
            ZONE_EDIT_T edited;

            // Init zone params to reasonable values
            zone->SetLayer( getActiveLayer() );

            // Prompt user for parameters:
            m_canvas->SetIgnoreMouseEvents( true );

            if( zone->IsOnCopperLayer() )
            {
                // Put a zone on a copper layer
                if( GetBoard()->GetHighLightNetCode() > 0 )
                {
                    zoneInfo.m_NetcodeSelection = GetBoard()->GetHighLightNetCode();

                    zone->SetNet( zoneInfo.m_NetcodeSelection );
                    zone->SetNetNameFromNetCode( );
                }
                double tmp = ZONE_THERMAL_RELIEF_GAP_MIL;
                wxGetApp().GetSettings()->Read( ZONE_THERMAL_RELIEF_GAP_STRING_KEY, &tmp );
                zoneInfo.m_ThermalReliefGap = KiROUND( tmp * IU_PER_MILS);

                tmp = ZONE_THERMAL_RELIEF_COPPER_WIDTH_MIL;
                wxGetApp().GetSettings()->Read( ZONE_THERMAL_RELIEF_COPPER_WIDTH_STRING_KEY,
                                                &tmp );
                zoneInfo.m_ThermalReliefCopperBridge = KiROUND( tmp * IU_PER_MILS );

                tmp = ZONE_CLEARANCE_MIL;
                wxGetApp().GetSettings()->Read( ZONE_CLEARANCE_WIDTH_STRING_KEY,
                                                &tmp );
                zoneInfo.m_ZoneClearance = KiROUND( tmp * IU_PER_MILS );

                tmp = ZONE_THICKNESS_MIL;
                wxGetApp().GetSettings()->Read( ZONE_MIN_THICKNESS_WIDTH_STRING_KEY,
                                                &tmp );
                zoneInfo.m_ZoneMinThickness = KiROUND( tmp * IU_PER_MILS );

                zoneInfo.m_CurrentZone_Layer = zone->GetLayer();

                if( GetToolId() == ID_PCB_KEEPOUT_AREA_BUTT )
                {
                    zoneInfo.SetIsKeepout( true );
                    // Netcode and netname are irrelevant,
                    // so ensure they are cleared
                    zone->SetNet( 0 );
                    zone->SetNetName( wxEmptyString );
                    edited = InvokeKeepoutAreaEditor( this, &zoneInfo );
                }
                else
                {
                    zoneInfo.SetIsKeepout( false );
                    edited = InvokeCopperZonesEditor( this, &zoneInfo );
                }
            }
            else   // Put a zone on a non copper layer (technical layer)
            {
                zoneInfo.SetIsKeepout( false );
                zoneInfo.m_NetcodeSelection = 0;     // No net for non copper zones
                edited = InvokeNonCopperZonesEditor( this, zone, &zoneInfo );
            }

            m_canvas->MoveCursorToCrossHair();
            m_canvas->SetIgnoreMouseEvents( false );

            if( edited == ZONE_ABORT )
                return 0;

            // Switch active layer to the selected zone layer
            setActiveLayer( zoneInfo.m_CurrentZone_Layer );

            SetZoneSettings( zoneInfo );
        }
        else
        {
            // Start a new contour: init zone params (net and layer) from an existing
            // zone (add cutout or similar zone)

            zoneInfo.m_CurrentZone_Layer = s_CurrentZone->GetLayer();
            setActiveLayer( s_CurrentZone->GetLayer() );

            zoneInfo << *s_CurrentZone;

            SetZoneSettings( zoneInfo );
        }

        // Show the Net for zones on copper layers
        if( zoneInfo.m_CurrentZone_Layer < FIRST_NON_COPPER_LAYER &&
            ! zoneInfo.GetIsKeepout() )
        {
            if( s_CurrentZone )
            {
                zoneInfo.m_NetcodeSelection = s_CurrentZone->GetNet();
                GetBoard()->SetZoneSettings( zoneInfo );
            }

            if( GetBoard()->IsHighLightNetON() )
            {
                HighLight( DC );    // Remove old highlight selection
            }

            GetBoard()->SetHighLightNet( zoneInfo.m_NetcodeSelection );
            HighLight( DC );
        }

        if( !s_AddCutoutToCurrentZone )
            s_CurrentZone = NULL; // the zone is used only once ("add similar zone" command)
    }

    // if first segment
    if( zone->GetNumCorners() == 0 )
    {
        zone->SetFlags( IS_NEW );
        zone->SetTimeStamp( GetNewTimeStamp() );

        zoneInfo.ExportSetting( *zone );

        zone->Outline()->Start( zoneInfo.m_CurrentZone_Layer,
                                GetCrossHairPosition().x,
                                GetCrossHairPosition().y,
                                zone->GetHatchStyle() );

        zone->AppendCorner( GetCrossHairPosition() );

        if( g_Drc_On && (m_drc->Drc( zone, 0 ) == BAD_DRC) && zone->IsOnCopperLayer() )
        {
            zone->ClearFlags();
            zone->RemoveAllContours();

            // use the form of SetCurItem() which does not write to the msg panel,
            // SCREEN::SetCurItem(), so the DRC error remains on screen.
            // PCB_EDIT_FRAME::SetCurItem() calls DisplayInfo().
            GetScreen()->SetCurItem( NULL );
            DisplayError( this,
                          _( "DRC error: this start point is inside or too close an other area" ) );
            return 0;
        }

        SetCurItem( zone );
        m_canvas->SetMouseCapture( Show_New_Edge_While_Move_Mouse, Abort_Zone_Create_Outline );
    }
    else    // edge in progress:
    {
        ii = zone->GetNumCorners() - 1;

        // edge in progress : the current corner coordinate was set
        // by Show_New_Edge_While_Move_Mouse
        if( zone->GetCornerPosition( ii - 1 ) != zone->GetCornerPosition( ii ) )
        {
            if( !g_Drc_On || !zone->IsOnCopperLayer() || ( m_drc->Drc( zone, ii - 1 ) == OK_DRC ) )
            {
                // Ok, we can add a new corner
                if( m_canvas->IsMouseCaptured() )
                    m_canvas->CallMouseCapture( DC, wxPoint(0,0), false );
                zone->AppendCorner( GetCrossHairPosition() );
                SetCurItem( zone );     // calls DisplayInfo().
                if( m_canvas->IsMouseCaptured() )
                    m_canvas->CallMouseCapture( DC, wxPoint(0,0), false );
            }
        }
    }

    return zone->GetNumCorners();
}
Пример #8
0
void WinEDA_PcbFrame::OnLeftClick(wxDC * DC, const wxPoint& MousePos)
/********************************************************************/
/* Traite les commandes declenchée par le bouton gauche de la souris,
	quand un outil est deja selectionné
*/
{
    EDA_BaseStruct * DrawStruct = CURRENT_ITEM;

    if ( (m_ID_current_state == 0) || ( DrawStruct && DrawStruct->m_Flags ))
    {
        DrawPanel->m_AutoPAN_Request = FALSE;
        if ( DrawStruct && DrawStruct->m_Flags ) // Commande "POPUP" en cours
        {
            switch (DrawStruct->m_StructType )
            {
            case TYPETRACK:
            case TYPEVIA:
                if ( CURRENT_ITEM->m_Flags & IS_DRAGGED )
                {
                    PlaceDraggedTrackSegment((TRACK *)DrawStruct, DC);
                    return;
                }
                break;

            case TYPETEXTE:
                Place_Texte_Pcb((TEXTE_PCB *)DrawStruct, DC);
                return;
                break;

            case TYPETEXTEMODULE:
                PlaceTexteModule( (TEXTE_MODULE *) DrawStruct, DC);
                return;
                break;

            case TYPEPAD:
                PlacePad((D_PAD *)DrawStruct, DC);
                return;
                break;

            case TYPEMODULE:
                Place_Module((MODULE *)DrawStruct, DC);
                return;
                break;

            case TYPEMIRE:
                Place_Mire((MIREPCB *)DrawStruct, DC);
                return;
                break;

            case TYPEDRAWSEGMENT:
                if (m_ID_current_state == 0)
                {
                    Place_DrawItem( (DRAWSEGMENT * )DrawStruct, DC);
                    return;
                }
                break;

            default:
                if (m_ID_current_state == 0)
                {
                    DisplayError(this,
                                 wxT("WinEDA_PcbFrame::OnLeftClick() err: m_Flags != 0") );
                    return;
                }
            }
        }
        else
        {
            DrawStruct = PcbGeneralLocateAndDisplay();
        }
    }

    switch ( m_ID_current_state )
    {
    case ID_MAIN_MENUBAR:
    case 0:
        break;

    case ID_NO_SELECT_BUTT:
        break;


    case ID_PCB_MUWAVE_TOOL_SELF_CMD:
    case ID_PCB_MUWAVE_TOOL_GAP_CMD:
    case ID_PCB_MUWAVE_TOOL_STUB_CMD:
    case ID_PCB_MUWAVE_TOOL_STUB_ARC_CMD:
    case ID_PCB_MUWAVE_TOOL_FUNCTION_SHAPE_CMD:
        MuWaveCommand(DC, MousePos);
        break;


    case ID_PCB_HIGHLIGHT_BUTT:
    {
        int netcode = Select_High_Light(DC);
        if ( netcode < 0 ) Affiche_Infos_Status_Pcb(this);
        else Affiche_Infos_Equipot(netcode, this);
    }
    break;

    case ID_PCB_SHOW_1_RATSNEST_BUTT:
        DrawStruct = PcbGeneralLocateAndDisplay();
        Show_1_Ratsnest(DrawStruct, DC);
        break;

    case ID_PCB_MIRE_BUTT:
        if ( (DrawStruct == NULL) || (DrawStruct->m_Flags == 0) )
        {
            GetScreen()->m_CurrentItem = Create_Mire( DC );
            DrawPanel->MouseToCursorSchema();
        }
        else if (DrawStruct->m_StructType == TYPEMIRE )
        {
            Place_Mire((MIREPCB *)DrawStruct, DC);
        }
        else DisplayError(this, wxT("Internal err: Struct not TYPEMIRE"));
        break;

    case ID_PCB_CIRCLE_BUTT:
    case ID_PCB_ARC_BUTT:
    case ID_LINE_COMMENT_BUTT:
    {
        int shape = S_SEGMENT;
        if ( m_ID_current_state == ID_PCB_CIRCLE_BUTT) shape = S_CIRCLE;
        if ( m_ID_current_state == ID_PCB_ARC_BUTT) shape = S_ARC;

        if ( GetScreen()->m_Active_Layer <= CMP_N )
        {
            DisplayError(this, _("Graphic not autorized on Copper layers"));
            break;
        }
        if ( (DrawStruct == NULL) || (DrawStruct->m_Flags == 0) )
        {
            GetScreen()->m_CurrentItem = DrawStruct =
                                             Begin_DrawSegment(NULL, shape, DC);
            DrawPanel->m_AutoPAN_Request = TRUE;
        }
        else if (DrawStruct &&
                 (DrawStruct->m_StructType == TYPEDRAWSEGMENT) &&
                 (DrawStruct->m_Flags & IS_NEW) )
        {
            GetScreen()->m_CurrentItem = DrawStruct =
                                             Begin_DrawSegment((DRAWSEGMENT *)DrawStruct, shape, DC);
            DrawPanel->m_AutoPAN_Request = TRUE;
        }
        break;
    }

    case ID_TRACK_BUTT:
        if ( GetScreen()->m_Active_Layer > CMP_N )
        {
            DisplayError(this, _("Tracks on Copper layers only "));
            break;
        }

        if ( (DrawStruct == NULL) || (DrawStruct->m_Flags == 0) )
        {
            GetScreen()->m_CurrentItem = DrawStruct =
                                             Begin_Route(NULL, DC);
            if ( DrawStruct ) DrawPanel->m_AutoPAN_Request = TRUE;
        }
        else if (DrawStruct &&
//					(DrawStruct->m_StructType == TYPETRACK) &&
                 (DrawStruct->m_Flags & IS_NEW) )
        {
            TRACK * track = Begin_Route((TRACK *) DrawStruct, DC);
            if ( track )	// c'est a dire si OK
                GetScreen()->m_CurrentItem = DrawStruct = track;
            DrawPanel->m_AutoPAN_Request = TRUE;
        }
        break;


    case ID_PCB_ZONES_BUTT:
        if ( (DrawStruct == NULL) || (DrawStruct->m_Flags == 0) )
        {
            GetScreen()->m_CurrentItem = DrawStruct =
                                             Begin_Zone();
        }
        else if (DrawStruct &&
                 (DrawStruct->m_StructType == TYPEEDGEZONE) &&
                 (DrawStruct->m_Flags & IS_NEW) )
        {
            GetScreen()->m_CurrentItem = DrawStruct =
                                             Begin_Zone();
        }
        else DisplayError(this, wxT("Edit: zone internal error"));
        break;

    case ID_TEXT_COMMENT_BUTT:
        if ( (DrawStruct == NULL) || (DrawStruct->m_Flags == 0) )
        {
            GetScreen()->m_CurrentItem = Create_Texte_Pcb( DC );
            DrawPanel->MouseToCursorSchema();
            DrawPanel->m_AutoPAN_Request = TRUE;
        }
        else if (DrawStruct->m_StructType == TYPETEXTE )
        {
            Place_Texte_Pcb((TEXTE_PCB *)DrawStruct, DC);
            DrawPanel->m_AutoPAN_Request = FALSE;
        }
        else DisplayError(this, wxT("Internal err: Struct not TYPETEXTE"));
        break;

    case ID_COMPONENT_BUTT:
        if ( (DrawStruct == NULL) || (DrawStruct->m_Flags == 0) )
        {
            DrawPanel->MouseToCursorSchema();
            GetScreen()->m_CurrentItem = DrawStruct =
                                             Load_Module_From_Library(wxEmptyString, DC);
            if ( DrawStruct )
                StartMove_Module((MODULE *)DrawStruct, DC);
        }
        else if (DrawStruct->m_StructType == TYPEMODULE )
        {
            Place_Module((MODULE *)DrawStruct, DC);
            DrawPanel->m_AutoPAN_Request = FALSE;
        }
        else DisplayError(this, wxT("Internal err: Struct not TYPEMODULE"));
        break;

    case ID_PCB_COTATION_BUTT:
        if ( GetScreen()->m_Active_Layer <= CMP_N )
        {
            DisplayError(this, _("Cotation not autorized on Copper layers"));
            break;
        }
        if ( (DrawStruct == NULL) || (DrawStruct->m_Flags == 0) )
        {
            GetScreen()->m_CurrentItem = DrawStruct =
                                             Begin_Cotation(NULL, DC);
            DrawPanel->m_AutoPAN_Request = TRUE;
        }
        else if (DrawStruct &&
                 (DrawStruct->m_StructType == TYPECOTATION) &&
                 (DrawStruct->m_Flags & IS_NEW) )
        {
            GetScreen()->m_CurrentItem = DrawStruct =
                                             Begin_Cotation((COTATION * )DrawStruct, DC);
            DrawPanel->m_AutoPAN_Request = TRUE;
        }
        else DisplayError(this, wxT("Internal err: Struct not COTATION"));
        break;

    case ID_PCB_DELETE_ITEM_BUTT:
        if ( !DrawStruct || (DrawStruct->m_Flags == 0) )
        {
            DrawStruct = PcbGeneralLocateAndDisplay();
            if ( DrawStruct && (DrawStruct->m_Flags == 0) )
            {
                RemoveStruct(DrawStruct, DC);
                GetScreen()->m_CurrentItem = DrawStruct = NULL;
            }
        }
        break;

    case ID_PCB_PLACE_OFFSET_COORD_BUTT:
        GetScreen()->Trace_Curseur(DrawPanel, DC);
        DrawPanel->m_Draw_Auxiliary_Axe(DC, GR_XOR);
        m_Auxiliary_Axe_Position = GetScreen()->m_Curseur;
        DrawPanel->m_Draw_Auxiliary_Axe( DC, GR_COPY);
        GetScreen()->Trace_Curseur(DrawPanel, DC);
        break;

    default :
        DrawPanel->SetCursor(wxCURSOR_ARROW);
        DisplayError(this, wxT("WinEDA_PcbFrame::OnLeftClick() id error"));
        SetToolID(0, wxCURSOR_ARROW,wxEmptyString);
        break;
    }
}
Пример #9
0
void WinEDA_PcbFrame::Process_Special_Functions(wxCommandEvent& event)
/*********************************************************************/
/* Traite les selections d'outils et les commandes appelees du menu POPUP
*/
{
    int id = event.GetId();
    wxPoint pos;
    wxClientDC dc(DrawPanel);
    int itmp;

    DrawPanel->PrepareGraphicContext(&dc);

    wxGetMousePosition(&pos.x, &pos.y);

    pos.y += 20;

    switch ( id )	// Arret eventuel de la commande de déplacement en cours
    {
    case wxID_CUT:
    case wxID_COPY:
    case ID_AUX_TOOLBAR_PCB_TRACK_WIDTH:
    case ID_AUX_TOOLBAR_PCB_VIA_SIZE:
    case ID_ON_GRID_SELECT:
    case ID_ON_ZOOM_SELECT:
    case ID_PCB_USER_GRID_SETUP:
    case ID_TOOLBARH_PCB_SELECT_LAYER:
    case ID_POPUP_PCB_ROTATE_TEXTEPCB:
    case ID_POPUP_PCB_EDIT_TEXTEPCB:
    case ID_POPUP_PCB_EDIT_MIRE:
    case ID_POPUP_PCB_ROTATE_TEXTMODULE:
    case ID_POPUP_PCB_ROTATE_MODULE_CLOCKWISE:
    case ID_POPUP_PCB_ROTATE_MODULE_COUNTERCLOCKWISE:
    case ID_POPUP_PCB_CHANGE_SIDE_MODULE:
    case ID_POPUP_PCB_EDIT_MODULE:
    case ID_POPUP_PCB_EDIT_TEXTMODULE:
    case ID_POPUP_PCB_STOP_CURRENT_DRAWING:
    case ID_POPUP_PCB_END_TRACK:
    case ID_POPUP_PCB_PLACE_VIA:
    case ID_POPUP_PCB_IMPORT_PAD_SETTINGS:
    case ID_POPUP_PCB_EXPORT_PAD_SETTINGS:
    case ID_POPUP_PCB_GLOBAL_IMPORT_PAD_SETTINGS:
    case ID_POPUP_PCB_STOP_CURRENT_EDGE_ZONE:
    case ID_POPUP_PCB_DELETE_EDGE_ZONE:
    case ID_POPUP_PCB_DELETE_ZONE_LIMIT:
    case ID_POPUP_PCB_EDIT_ZONE:
    case ID_POPUP_PCB_DELETE_ZONE:
    case ID_POPUP_PCB_DELETE_TRACKSEG:
    case ID_POPUP_PCB_DELETE_TRACK:
    case ID_POPUP_PCB_DELETE_TRACKNET:
    case ID_POPUP_PCB_FILL_ZONE:
    case ID_POPUP_PCB_SELECT_NET_ZONE:
    case ID_POPUP_PCB_SELECT_LAYER:
    case ID_POPUP_PCB_SELECT_CU_LAYER:
    case ID_POPUP_PCB_SELECT_LAYER_PAIR:
    case ID_POPUP_PCB_SELECT_NO_CU_LAYER:
    case ID_POPUP_PCB_SELECT_WIDTH:
    case ID_POPUP_PCB_SELECT_WIDTH1:
    case ID_POPUP_PCB_SELECT_WIDTH2:
    case ID_POPUP_PCB_SELECT_WIDTH3:
    case ID_POPUP_PCB_SELECT_WIDTH4:
    case ID_POPUP_PCB_SELECT_WIDTH5:
    case ID_POPUP_PCB_SELECT_WIDTH6:
    case ID_POPUP_PCB_SELECT_WIDTH7:
    case ID_POPUP_PCB_SELECT_WIDTH8:
    case ID_POPUP_PCB_SELECT_VIASIZE:
    case ID_POPUP_PCB_SELECT_VIASIZE1:
    case ID_POPUP_PCB_SELECT_VIASIZE2:
    case ID_POPUP_PCB_SELECT_VIASIZE3:
    case ID_POPUP_PCB_SELECT_VIASIZE4:
    case ID_POPUP_PCB_SELECT_VIASIZE5:
    case ID_POPUP_PCB_SELECT_VIASIZE6:
    case ID_POPUP_PCB_SELECT_VIASIZE7:
    case ID_POPUP_PCB_SELECT_VIASIZE8:
    case ID_POPUP_PCB_MOVE_TRACK_NODE:
    case ID_POPUP_PCB_PLACE_MOVED_TRACK_NODE:
    case ID_POPUP_PCB_BREAK_TRACK:
    case ID_POPUP_PCB_EDIT_NET:
    case ID_POPUP_PCB_EDIT_TRACK:
    case ID_POPUP_PCB_EDIT_TRACKSEG:
    case ID_POPUP_PCB_LOCK_ON_TRACKSEG:
    case ID_POPUP_PCB_LOCK_OFF_TRACKSEG:
    case ID_POPUP_PCB_LOCK_ON_TRACK:
    case ID_POPUP_PCB_LOCK_OFF_TRACK:
    case ID_POPUP_PCB_LOCK_ON_NET:
    case ID_POPUP_PCB_LOCK_OFF_NET:
    case ID_POPUP_DELETE_BLOCK:
    case ID_POPUP_PLACE_BLOCK:
    case ID_POPUP_ZOOM_BLOCK:
    case ID_POPUP_INVERT_BLOCK:
    case ID_POPUP_ROTATE_BLOCK:
    case ID_POPUP_COPY_BLOCK:
    case ID_POPUP_PCB_VIA_EDITING:
    case ID_POPUP_PCB_VIA_HOLE_TO_DEFAULT:
    case ID_POPUP_PCB_VIA_HOLE_TO_VALUE:
    case ID_POPUP_PCB_VIA_HOLE_ENTER_VALUE:
    case ID_POPUP_PCB_VIA_HOLE_EXPORT:
    case ID_POPUP_PCB_VIA_HOLE_RESET_TO_DEFAULT:
    case ID_POPUP_PCB_VIA_HOLE_EXPORT_TO_OTHERS:
        break;

    case ID_POPUP_CANCEL_CURRENT_COMMAND:
        if( GetScreen()->ManageCurseur &&
                GetScreen()->ForceCloseManageCurseur )
        {
            GetScreen()->ForceCloseManageCurseur(this, &dc);
        }
        /* ne devrait pas etre execute, sauf bug */
        if (m_CurrentScreen->BlockLocate.m_Command != BLOCK_IDLE)
        {
            m_CurrentScreen->BlockLocate.m_Command = BLOCK_IDLE;
            m_CurrentScreen->BlockLocate.m_State = STATE_NO_BLOCK;
            m_CurrentScreen->BlockLocate.m_BlockDrawStruct = NULL;
        }
        if (m_ID_current_state == 0 )
            SetToolID(0, wxCURSOR_ARROW,wxEmptyString);
        else SetCursor(DrawPanel->m_PanelCursor = DrawPanel->m_PanelDefaultCursor);
        break;

    default:	// Arret de la commande de déplacement en cours
        if( GetScreen()->ManageCurseur &&
                GetScreen()->ForceCloseManageCurseur )
        {
            GetScreen()->ForceCloseManageCurseur(this, &dc);
        }
        SetToolID(0, wxCURSOR_ARROW,wxEmptyString);
        break;
    }

    switch ( id )	// Traitement des commandes
    {
    case ID_EXIT :
        Close(TRUE);
        break;

    case ID_OPEN_MODULE_EDITOR:
        if (m_Parent->m_ModuleEditFrame == NULL )
        {
            m_Parent->m_ModuleEditFrame = new WinEDA_ModuleEditFrame(this,
                    m_Parent,_("Module Editor"),
                    wxPoint(-1, -1), wxSize(600,400) );
            m_Parent->m_ModuleEditFrame->Show(TRUE);
            m_Parent->m_ModuleEditFrame->Zoom_Automatique(TRUE);
        }
        else m_Parent->m_ModuleEditFrame->Iconize(FALSE);
        break;

    case ID_NEW_PROJECT:
    case ID_LOAD_PROJECT:
        Files_io(event);
        break;

    case ID_PCB_GLOBAL_DELETE:
        InstallPcbGlobalDeleteFrame(pos);
        break;

    case ID_POPUP_PLACE_BLOCK:
        GetScreen()->BlockLocate.m_Command = BLOCK_MOVE;
        DrawPanel->m_AutoPAN_Request = FALSE;
        HandleBlockPlace(&dc);
        break;

    case ID_POPUP_COPY_BLOCK:
        GetScreen()->BlockLocate.m_Command = BLOCK_COPY;
        m_CurrentScreen->BlockLocate.SetMessageBlock(this);
        DrawPanel->m_AutoPAN_Request = FALSE;
        HandleBlockPlace(&dc);
        break;

    case ID_POPUP_ZOOM_BLOCK:
        GetScreen()->BlockLocate.m_Command = BLOCK_ZOOM;
        m_CurrentScreen->BlockLocate.SetMessageBlock(this);
        m_CurrentScreen->BlockLocate.SetMessageBlock(this);
        HandleBlockEnd(&dc);
        break;

    case ID_POPUP_DELETE_BLOCK:
        GetScreen()->BlockLocate.m_Command = BLOCK_DELETE;
        m_CurrentScreen->BlockLocate.SetMessageBlock(this);
        HandleBlockEnd(&dc);
        break;

    case ID_POPUP_ROTATE_BLOCK:
        GetScreen()->BlockLocate.m_Command = BLOCK_ROTATE;
        m_CurrentScreen->BlockLocate.SetMessageBlock(this);
        HandleBlockEnd(&dc);
        break;

    case ID_POPUP_INVERT_BLOCK:
        GetScreen()->BlockLocate.m_Command = BLOCK_INVERT;
        m_CurrentScreen->BlockLocate.SetMessageBlock(this);
        HandleBlockEnd(&dc);
        break;

    case ID_UNDO_BUTT:
        UnDeleteItem(&dc);
        break;

    case ID_DRC_CONTROL:
        Install_Test_DRC_Frame(&dc);
        break;

    case ID_GET_NETLIST:
        InstallNetlistFrame(&dc, wxPoint(-1,-1));
        break;

    case ID_GET_TOOLS:
//			InstallToolsFrame(this, wxPoint(-1,-1) );
        break;

    case ID_FIND_ITEMS:
        InstallFindFrame(pos, &dc);
        break;

    case ID_TRACK_BUTT:
        SetToolID( id, wxCURSOR_PENCIL, _("Add Tracks"));
        DisplayTrackSettings();
        if ( (m_Pcb->m_Status_Pcb & LISTE_CHEVELU_OK) == 0)
        {
            Compile_Ratsnest( &dc, TRUE );
        }
        break;

    case ID_PCB_ZONES_BUTT:
        SetToolID( id, wxCURSOR_PENCIL, _("Add Zones"));
        if ( ! DisplayOpt.DisplayZones )
            DisplayInfo(this, _("Warning: Display Zone is OFF!!!") );
        DelLimitesZone(&dc, TRUE);
        if( ! g_HightLigt_Status && (g_HightLigth_NetCode > 0 ) )
            Hight_Light(&dc);
        break;

    case ID_PCB_MIRE_BUTT:
        SetToolID( id, wxCURSOR_PENCIL, _("Add Mire"));
        break;

    case ID_PCB_PLACE_OFFSET_COORD_BUTT:
        SetToolID( id, wxCURSOR_PENCIL, _("Adjust Zero"));
        break;

    case ID_LINE_COMMENT_BUTT:
    case ID_PCB_ARC_BUTT:
    case ID_PCB_CIRCLE_BUTT:
        SetToolID( id, wxCURSOR_PENCIL, _("Add Graphic"));
        break;

    case ID_TEXT_COMMENT_BUTT:
        SetToolID( id, wxCURSOR_PENCIL, _("Add Text"));
        break;

    case ID_COMPONENT_BUTT:
        SetToolID( id, wxCURSOR_HAND, _("Add Modules"));
        break;

    case ID_PCB_COTATION_BUTT:
        SetToolID( id, wxCURSOR_PENCIL, _("Add Cotation"));
        break;

    case ID_NO_SELECT_BUTT:
        SetToolID( 0, wxCURSOR_ARROW, wxEmptyString);
        break;

    case ID_PCB_HIGHLIGHT_BUTT:
        SetToolID( id, wxCURSOR_HAND, _("Net Highlight"));
        break;

    case ID_PCB_SHOW_1_RATSNEST_BUTT:
        SetToolID( id, wxCURSOR_HAND, _("Local Ratsnest"));
        if ( (m_Pcb->m_Status_Pcb & LISTE_CHEVELU_OK) == 0)
            Compile_Ratsnest( &dc, TRUE );
        break;

    case ID_POPUP_CLOSE_CURRENT_TOOL:
        SetToolID( 0, wxCURSOR_ARROW, wxEmptyString);
        break;


    case ID_POPUP_CANCEL_CURRENT_COMMAND:
        break;

    case ID_POPUP_END_LINE:
        DrawPanel->MouseToCursorSchema();
//			EndSegment(&dc);
        break;

    case ID_POPUP_PCB_EDIT_TRACK:
        if ( CURRENT_ITEM == NULL) break;
        Edit_Track_Width(&dc, (TRACK *) CURRENT_ITEM);
        DrawPanel->MouseToCursorSchema();
        GetScreen()->SetModify();
        break;

    case ID_POPUP_PCB_EDIT_TRACKSEG:
        if ( CURRENT_ITEM == NULL) break;
        Edit_TrackSegm_Width(&dc, (TRACK *) CURRENT_ITEM);
        DrawPanel->MouseToCursorSchema();
        GetScreen()->SetModify();
        break;

    case ID_POPUP_PCB_EDIT_NET:
        if ( CURRENT_ITEM == NULL) break;
        Edit_Net_Width(&dc, ((TRACK *) CURRENT_ITEM)->m_NetCode);
        DrawPanel->MouseToCursorSchema();
        GetScreen()->SetModify();
        break;

    case ID_POPUP_PCB_EDIT_ALL_VIAS_AND_TRACK_SIZE:
    case ID_POPUP_PCB_EDIT_ALL_VIAS_SIZE:
    case ID_POPUP_PCB_EDIT_ALL_TRACK_SIZE:
        if ( CURRENT_ITEM == NULL) break;
        {
            bool resize_vias = TRUE, resize_track = TRUE;
            if( id == ID_POPUP_PCB_EDIT_ALL_VIAS_SIZE) resize_track = FALSE;
            if( id == ID_POPUP_PCB_EDIT_ALL_TRACK_SIZE) resize_vias = FALSE;
            if ( Resize_Pistes_Vias(&dc, resize_track, resize_vias)) GetScreen()->SetModify();
        }
        DrawPanel->MouseToCursorSchema();
        break;

    case ID_POPUP_PCB_END_TRACK:
        DrawPanel->MouseToCursorSchema();
        End_Route( (TRACK *) CURRENT_ITEM, &dc);
        break;

    case ID_POPUP_PCB_PLACE_MOVED_TRACK_NODE:
        DrawPanel->MouseToCursorSchema();
        if ( CURRENT_ITEM->m_Flags & IS_DRAGGED )
        {
            PlaceDraggedTrackSegment((TRACK *) CURRENT_ITEM, &dc);
        }
        break;

    case ID_POPUP_PCB_PLACE_VIA:
        DrawPanel->MouseToCursorSchema();
        if ( CURRENT_ITEM->m_Flags & IS_DRAGGED )
        {
            PlaceDraggedTrackSegment((TRACK *) CURRENT_ITEM, &dc);
        }
        else
        {
            Other_Layer_Route( (TRACK *) CURRENT_ITEM, &dc);
            if ( DisplayOpt.ContrastModeDisplay )
                GetScreen()->SetRefreshReq();
        }
        break;


    case ID_POPUP_PCB_DELETE_TRACKSEG:
        DrawPanel->MouseToCursorSchema();
        GetScreen()->m_CurrentItem = Delete_Segment(&dc, (TRACK*)CURRENT_ITEM);
        GetScreen()->SetModify();
        break;

    case ID_POPUP_PCB_DELETE_TRACK:
        DrawPanel->MouseToCursorSchema();
        Delete_Track(&dc, (TRACK*)CURRENT_ITEM);
        GetScreen()->m_CurrentItem = NULL;
        GetScreen()->SetModify();
        break;

    case ID_POPUP_PCB_DELETE_TRACKNET:
        DrawPanel->MouseToCursorSchema();
        Delete_net(&dc, (TRACK*)CURRENT_ITEM);
        GetScreen()->m_CurrentItem = NULL;
        GetScreen()->SetModify();
        break;

    case ID_POPUP_PCB_LOCK_ON_TRACKSEG:
        Attribut_Segment((TRACK*)CURRENT_ITEM, &dc, TRUE);
        break;

    case ID_POPUP_PCB_LOCK_OFF_TRACKSEG:
        Attribut_Segment((TRACK*)CURRENT_ITEM, &dc, FALSE);
        break;

    case ID_POPUP_PCB_LOCK_ON_TRACK:
        Attribut_Track((TRACK*)CURRENT_ITEM, &dc, TRUE);
        break;

    case ID_POPUP_PCB_LOCK_OFF_TRACK:
        Attribut_Track((TRACK*)CURRENT_ITEM, &dc, FALSE);
        break;

    case ID_POPUP_PCB_LOCK_ON_NET:
        Attribut_net(&dc, ((TRACK*)CURRENT_ITEM)->m_NetCode, TRUE);
        break;

    case ID_POPUP_PCB_LOCK_OFF_NET:
        Attribut_net(&dc, ((TRACK*)CURRENT_ITEM)->m_NetCode, FALSE);
        break;

    case ID_POPUP_PCB_SETFLAGS_TRACK_MNU:
        break;

    case ID_POPUP_PCB_DELETE_ZONE:
        DrawPanel->MouseToCursorSchema();
        if ( CURRENT_ITEM == NULL) break;
        Delete_Zone(&dc, (SEGZONE*)CURRENT_ITEM);
        GetScreen()->m_CurrentItem = NULL;
        break;

    case ID_POPUP_PCB_EDIT_ZONE:
        DrawPanel->MouseToCursorSchema();
        if ( CURRENT_ITEM == NULL) break;
        Edit_Zone_Width(&dc, (SEGZONE*)CURRENT_ITEM);
        break;

    case ID_POPUP_PCB_DELETE_ZONE_LIMIT:
        DrawPanel->MouseToCursorSchema();
        DelLimitesZone(&dc, TRUE);
        break;

    case ID_PCB_DELETE_ITEM_BUTT:
        SetToolID( id, wxCURSOR_BULLSEYE, _("Delete item"));
        break;

    case ID_POPUP_PCB_MOVE_TEXTEPCB_REQUEST:
        Process_Move_Item(this, CURRENT_ITEM, &dc);
        DrawPanel->m_AutoPAN_Request = TRUE;
        break;

    case ID_POPUP_PCB_DRAG_MODULE_REQUEST:
        g_Drag_Pistes_On = TRUE;
    case ID_POPUP_PCB_MOVE_MODULE_REQUEST:
        // If the current Item is a pad, text module ...: Get the parent
        if ( CURRENT_ITEM->m_StructType != TYPEMODULE )
            CURRENT_ITEM = (MODULE *) CURRENT_ITEM->m_Parent;
        if ( !CURRENT_ITEM || CURRENT_ITEM->m_StructType != TYPEMODULE )
        {
            g_Drag_Pistes_On = FALSE;
            break;
        }
        DrawPanel->MouseToCursorSchema();
        StartMove_Module( (MODULE*)CURRENT_ITEM, &dc);
        break;

    case ID_POPUP_PCB_DELETE_MODULE:
        DrawPanel->MouseToCursorSchema();
        // If the current Item is a pad, text module ...: Get the parent
        if ( CURRENT_ITEM->m_StructType != TYPEMODULE )
            CURRENT_ITEM = (MODULE *) CURRENT_ITEM->m_Parent;
        if ( !CURRENT_ITEM || CURRENT_ITEM->m_StructType != TYPEMODULE )
            break;
        if ( Delete_Module((MODULE*) CURRENT_ITEM, &dc) )
        {
            GetScreen()->m_CurrentItem = NULL;
        }
        break;

    case ID_POPUP_PCB_ROTATE_MODULE_COUNTERCLOCKWISE:
        DrawPanel->MouseToCursorSchema();
        // If the current Item is a pad, text module ...: Get the parent
        if ( CURRENT_ITEM->m_StructType != TYPEMODULE )
            CURRENT_ITEM = (MODULE *) CURRENT_ITEM->m_Parent;
        if ( !CURRENT_ITEM || CURRENT_ITEM->m_StructType != TYPEMODULE )
            break;
        Rotate_Module(&dc, (MODULE*)CURRENT_ITEM, -900, TRUE);
        break;

    case ID_POPUP_PCB_ROTATE_MODULE_CLOCKWISE:
        DrawPanel->MouseToCursorSchema();
        // If the current Item is a pad, text module ...: Get the parent
        if ( CURRENT_ITEM->m_StructType != TYPEMODULE )
            CURRENT_ITEM = (MODULE *) CURRENT_ITEM->m_Parent;
        if ( !CURRENT_ITEM || CURRENT_ITEM->m_StructType != TYPEMODULE )
            break;
        Rotate_Module(&dc, (MODULE*)CURRENT_ITEM, 900, TRUE);
        break;

    case ID_POPUP_PCB_CHANGE_SIDE_MODULE:
        DrawPanel->MouseToCursorSchema();
        // If the current Item is a pad, text module ...: Get the parent
        if ( CURRENT_ITEM->m_StructType != TYPEMODULE )
            CURRENT_ITEM = (MODULE *) CURRENT_ITEM->m_Parent;
        if ( !CURRENT_ITEM || CURRENT_ITEM->m_StructType != TYPEMODULE )
            break;
        Change_Side_Module((MODULE *) CURRENT_ITEM, &dc);
        break;

    case ID_POPUP_PCB_EDIT_MODULE:
        // If the current Item is a pad, text module ...: Get the parent
        if ( CURRENT_ITEM->m_StructType != TYPEMODULE )
            CURRENT_ITEM = (MODULE *) CURRENT_ITEM->m_Parent;
        if ( !CURRENT_ITEM || CURRENT_ITEM->m_StructType != TYPEMODULE )
            break;
        InstallModuleOptionsFrame((MODULE *)CURRENT_ITEM,
                                  &dc, pos);
        DrawPanel->MouseToCursorSchema();
        break;

    case ID_POPUP_PCB_DRAG_PAD_REQUEST:
        g_Drag_Pistes_On = TRUE;
    case ID_POPUP_PCB_MOVE_PAD_REQUEST:
        DrawPanel->MouseToCursorSchema();
        StartMovePad((D_PAD *)CURRENT_ITEM, &dc);
        break;

    case ID_POPUP_PCB_EDIT_PAD:
        InstallPadOptionsFrame((D_PAD *)CURRENT_ITEM,
                               &dc, pos);
        DrawPanel->MouseToCursorSchema();
        break;

    case ID_POPUP_PCB_IMPORT_PAD_SETTINGS:
        DrawPanel->MouseToCursorSchema();
        Import_Pad_Settings((D_PAD *)CURRENT_ITEM, &dc);
        break;

    case ID_POPUP_PCB_GLOBAL_IMPORT_PAD_SETTINGS:
        DrawPanel->MouseToCursorSchema();
        Global_Import_Pad_Settings((D_PAD *)CURRENT_ITEM, &dc);
        break;

    case ID_POPUP_PCB_EXPORT_PAD_SETTINGS:
        DrawPanel->MouseToCursorSchema();
        Export_Pad_Settings((D_PAD *)CURRENT_ITEM);
        break;


    case ID_POPUP_PCB_DELETE_PAD:
        DeletePad((D_PAD *)CURRENT_ITEM, &dc);
        GetScreen()->m_CurrentItem = NULL;
        DrawPanel->MouseToCursorSchema();
        break;

    case ID_POPUP_PCB_EDIT_TEXTMODULE:
        InstallTextModOptionsFrame((TEXTE_MODULE *)CURRENT_ITEM,
                                   &dc, pos);
        DrawPanel->MouseToCursorSchema();
        break;

    case ID_POPUP_PCB_MOVE_TEXTMODULE_REQUEST:
        DrawPanel->MouseToCursorSchema();
        StartMoveTexteModule( (TEXTE_MODULE *) CURRENT_ITEM,
                              &dc);
        break;

    case ID_POPUP_PCB_ROTATE_TEXTMODULE:
        RotateTextModule((TEXTE_MODULE *)CURRENT_ITEM,
                         &dc);
        DrawPanel->MouseToCursorSchema();
        break;

    case ID_POPUP_PCB_DELETE_TEXTMODULE:
        DeleteTextModule((TEXTE_MODULE *)CURRENT_ITEM,
                         &dc);
        GetScreen()->m_CurrentItem = NULL;
        DrawPanel->MouseToCursorSchema();
        break;

    case ID_POPUP_PCB_SELECT_LAYER:
        itmp = SelectLayer(GetScreen()->m_Active_Layer, -1, -1);
        if ( itmp >= 0 ) GetScreen()->m_Active_Layer = itmp;
        DrawPanel->MouseToCursorSchema();
        break;

    case ID_POPUP_PCB_SELECT_NO_CU_LAYER:
        itmp = SelectLayer(GetScreen()->m_Active_Layer, CMP_N+1, -1);
        if ( itmp >= 0 ) GetScreen()->m_Active_Layer = itmp;
        DrawPanel->MouseToCursorSchema();
        break;

    case ID_POPUP_PCB_SELECT_CU_LAYER:
        itmp = SelectLayer(GetScreen()->m_Active_Layer, -1, CMP_N);
        if ( itmp >= 0 ) GetScreen()->m_Active_Layer = itmp;
        break;

    case ID_POPUP_PCB_SELECT_LAYER_PAIR:
        SelectLayerPair();
        DrawPanel->MouseToCursorSchema();
        break;

    case ID_TOOLBARH_PCB_SELECT_LAYER:
        itmp = m_SelLayerBox->GetChoice();
        GetScreen()->m_Active_Layer = (int)((size_t) m_SelLayerBox->GetClientData(itmp));
        if ( DisplayOpt.ContrastModeDisplay ) DrawPanel->Refresh(TRUE);
        break;

    case ID_POPUP_PCB_EDIT_TEXTEPCB:
        InstallTextPCBOptionsFrame((TEXTE_PCB *)CURRENT_ITEM,
                                   &dc, pos);
        DrawPanel->MouseToCursorSchema();
        break;

    case ID_POPUP_PCB_ROTATE_TEXTEPCB:
        Rotate_Texte_Pcb((TEXTE_PCB *)CURRENT_ITEM, &dc);
        DrawPanel->MouseToCursorSchema();
        break;

    case ID_POPUP_PCB_DELETE_TEXTEPCB:
        Delete_Texte_Pcb((TEXTE_PCB *)CURRENT_ITEM, &dc);
        DrawPanel->MouseToCursorSchema();
        break;

    case ID_POPUP_PCB_MOVE_MIRE_REQUEST:
        StartMove_Mire((MIREPCB *)CURRENT_ITEM, &dc);
        DrawPanel->MouseToCursorSchema();
        break;

    case ID_POPUP_PCB_EDIT_MIRE:
        InstallMireOptionsFrame((MIREPCB *)CURRENT_ITEM, &dc, pos);
        DrawPanel->MouseToCursorSchema();
        break;

    case ID_POPUP_PCB_DELETE_MIRE:
        DrawPanel->MouseToCursorSchema();
        Delete_Mire((MIREPCB *)CURRENT_ITEM, &dc);
        GetScreen()->m_CurrentItem = NULL;
        break;

    case ID_POPUP_PCB_DELETE_COTATION:
        DrawPanel->MouseToCursorSchema();
        Delete_Cotation((COTATION*)CURRENT_ITEM, &dc);
        GetScreen()->m_CurrentItem = NULL;
        break;

    case ID_POPUP_PCB_EDIT_COTATION:
        Install_Edit_Cotation((COTATION*)CURRENT_ITEM, &dc, pos);
        DrawPanel->MouseToCursorSchema();
        break;

    case ID_POPUP_PCB_DELETE_DRAWING:
        Delete_Segment_Edge((DRAWSEGMENT *)CURRENT_ITEM, &dc);
        DrawPanel->MouseToCursorSchema();
        break;

    case ID_POPUP_PCB_DELETE_DRAWING_LAYER:
        Delete_Drawings_All_Layer((DRAWSEGMENT *)CURRENT_ITEM, &dc);
        GetScreen()->m_CurrentItem = NULL;
        DrawPanel->MouseToCursorSchema();
        break;

    case ID_POPUP_PCB_EDIT_DRAWING:
        Drawing_SetNewWidth((DRAWSEGMENT *)CURRENT_ITEM, &dc);
        DrawPanel->MouseToCursorSchema();
        break;

    case ID_POPUP_PCB_MOVE_DRAWING_REQUEST:
        DrawPanel->MouseToCursorSchema();
        Start_Move_DrawItem((DRAWSEGMENT *)CURRENT_ITEM, &dc);
        break;

    case ID_POPUP_PCB_STOP_CURRENT_DRAWING:
        DrawPanel->MouseToCursorSchema();
        if ( CURRENT_ITEM && (CURRENT_ITEM->m_Flags & IS_NEW) )
        {
            End_Edge( (DRAWSEGMENT *)CURRENT_ITEM, &dc);
            GetScreen()->m_CurrentItem = NULL;
        }
        break;

    case ID_POPUP_PCB_STOP_CURRENT_EDGE_ZONE:
        DrawPanel->MouseToCursorSchema();
        if ( CURRENT_ITEM && (CURRENT_ITEM->m_Flags & IS_NEW) )
        {
            End_Zone(&dc);
            GetScreen()->m_CurrentItem = NULL;
        }
        break;

    case ID_POPUP_PCB_DELETE_EDGE_ZONE:
        DrawPanel->MouseToCursorSchema();
        if ( CURRENT_ITEM && (CURRENT_ITEM->m_Flags & IS_NEW) )
        {
            GetScreen()->m_CurrentItem = Del_SegmEdgeZone(&dc,
                                         (EDGE_ZONE *) CURRENT_ITEM);
        }
        break;

    case ID_POPUP_PCB_FILL_ZONE:
        DrawPanel->MouseToCursorSchema();
        Fill_Zone(&dc);
        break;

    case ID_POPUP_PCB_SELECT_NET_ZONE:
        DrawPanel->MouseToCursorSchema();
        CaptureNetName(&dc);
        break;

    case ID_POPUP_PCB_SELECT_WIDTH:
        break;

    case ID_AUX_TOOLBAR_PCB_TRACK_WIDTH:
    {
        int ii = m_SelTrackWidthBox->GetChoice();
        g_DesignSettings.m_CurrentTrackWidth = g_DesignSettings.m_TrackWidhtHistory[ii];
        DisplayTrackSettings();
        m_SelTrackWidthBox_Changed = FALSE;
        m_SelViaSizeBox_Changed = FALSE;
    }
    break;
    case ID_POPUP_PCB_SELECT_WIDTH1:
    case ID_POPUP_PCB_SELECT_WIDTH2:
    case ID_POPUP_PCB_SELECT_WIDTH3:
    case ID_POPUP_PCB_SELECT_WIDTH4:
    case ID_POPUP_PCB_SELECT_WIDTH5:
    case ID_POPUP_PCB_SELECT_WIDTH6:
    case ID_POPUP_PCB_SELECT_WIDTH7:
    case ID_POPUP_PCB_SELECT_WIDTH8:
        DrawPanel->MouseToCursorSchema();
        {
            int ii = id - ID_POPUP_PCB_SELECT_WIDTH1;
            g_DesignSettings.m_CurrentTrackWidth = g_DesignSettings.m_TrackWidhtHistory[ii];
            DisplayTrackSettings();
        }
        break;

    case ID_POPUP_PCB_SELECT_VIASIZE:
        break;

    case ID_AUX_TOOLBAR_PCB_VIA_SIZE:
    {
        int ii = m_SelViaSizeBox->GetChoice();
        g_DesignSettings.m_CurrentViaSize = g_DesignSettings.m_ViaSizeHistory[ii];
        DisplayTrackSettings();
        m_SelTrackWidthBox_Changed = FALSE;
        m_SelViaSizeBox_Changed = FALSE;
    }
    break;

    case ID_POPUP_PCB_SELECT_VIASIZE1:
    case ID_POPUP_PCB_SELECT_VIASIZE2:
    case ID_POPUP_PCB_SELECT_VIASIZE3:
    case ID_POPUP_PCB_SELECT_VIASIZE4:
    case ID_POPUP_PCB_SELECT_VIASIZE5:
    case ID_POPUP_PCB_SELECT_VIASIZE6:
    case ID_POPUP_PCB_SELECT_VIASIZE7:
    case ID_POPUP_PCB_SELECT_VIASIZE8:
    case ID_POPUP_PCB_VIA_EDITING:
    case ID_POPUP_PCB_VIA_HOLE_TO_DEFAULT:
    case ID_POPUP_PCB_VIA_HOLE_TO_VALUE:
    case ID_POPUP_PCB_VIA_HOLE_ENTER_VALUE:
    case ID_POPUP_PCB_VIA_HOLE_EXPORT:
    case ID_POPUP_PCB_VIA_HOLE_RESET_TO_DEFAULT:
    case ID_POPUP_PCB_VIA_HOLE_EXPORT_TO_OTHERS:
        Via_Edit_Control(&dc, id, (SEGVIA *) GetScreen()->m_CurrentItem);
        break;

    case ID_POPUP_PCB_MOVE_TRACK_NODE:
        DrawPanel->MouseToCursorSchema();
        Start_MoveOneTrackSegment((TRACK *) GetScreen()->m_CurrentItem,
                                  &dc, TRUE);
        break;

    case ID_POPUP_PCB_BREAK_TRACK:
        DrawPanel->MouseToCursorSchema();
        {
            TRACK * track = (TRACK *) GetScreen()->m_CurrentItem;
            wxPoint pos = GetScreen()->m_Curseur;
            track->Draw(DrawPanel, &dc, GR_XOR);
            TRACK * newtrack = CreateLockPoint(&pos.x, &pos.y, track, NULL);
            track->Draw(DrawPanel, &dc, GR_XOR);
            newtrack->Draw(DrawPanel, &dc, GR_XOR);
        }
        break;

    case ID_MENU_PCB_CLEAN:
        Clean_Pcb(&dc);
        break;

    case ID_MENU_PCB_SWAP_LAYERS:
        Swap_Layers(event);
        break;

    case ID_POPUP_PCB_AUTOROUTE_GET_AUTOROUTER:
        GlobalRoute(&dc);
        break;

    case ID_POPUP_PCB_AUTOROUTE_GET_AUTOROUTER_DATA:
        ReadAutoroutedTracks(&dc);
        break;

    case ID_PCB_USER_GRID_SETUP:
        InstallGridFrame(pos);
        break;

    case ID_POPUP_PCB_DISPLAY_FOOTPRINT_DOC:
    {
        wxString msg = FindKicadHelpPath();
        msg += EDA_Appl->m_EDA_CommonConfig->Read(wxT("module_doc_file"),
                wxT("pcbnew/footprints.pdf"));
        GetAssociatedDocument(this, wxEmptyString, msg);
    }
    break;

    case ID_MENU_ARCHIVE_NEW_MODULES:
        Archive_Modules(wxEmptyString, TRUE);
        break;

    case ID_MENU_ARCHIVE_ALL_MODULES:
        Archive_Modules(wxEmptyString, FALSE);
        break;

    default:
    {
        DisplayError(this, wxT("WinEDA_PcbFrame::Process_Special_Functions() id error"));
        break;
    }
    }

    SetToolbars();
}
Пример #10
0
int RegisterUnregisterVPinMAME(HWND hWnd, int fRegister)
{
	HRESULT hr;
	HMODULE hModule;

	// so now let's see if we can load vpinmame.dll
	hModule = LoadLibrary("vpinmame.dll");
	if ( !hModule ) {
		DisplayError(hWnd, GetLastError(), "The 'vpinmame.dll' file can't be loaded.", "Be sure to have this file in the current directory!");
		return 0;
	}

	char szModuleFilename[MAX_PATH];
	GetModuleFileName(hModule, szModuleFilename, sizeof szModuleFilename);

	char szVersion[256];
	GetVersionResourceEntry(szModuleFilename, TEXT("ProductVersion"), szVersion, sizeof szVersion);

	char szMsg[256];
	if ( fRegister )
		wsprintf(szMsg, "You have selected to install version %s of Visual PinMAME! \nAre you ready to proceed?", szVersion);
	else
		wsprintf(szMsg, "You have selected to uninstall version %s of Visual PinMAME! \nAre you ready to proceed?", szVersion);	

	if ( MessageBox(hWnd, szMsg, g_szCaption, MB_ICONQUESTION|MB_YESNO)==IDNO ) {
		if ( fRegister )
			MessageBox(hWnd, "Installation aborted!", g_szCaption, MB_ICONEXCLAMATION|MB_OK);
		else
			MessageBox(hWnd, "UnInstallation aborted!\nVisual PinMAME is still installed on your system", g_szCaption, MB_ICONEXCLAMATION|MB_OK);
		FreeLibrary(hModule);
		return 0;
	}

	if ( fRegister ) {
		typedef HRESULT DLLREGISTERSERVER(void);

		DLLREGISTERSERVER* DllRegisterServer = (DLLREGISTERSERVER*) GetProcAddress(hModule, "DllRegisterServer");
		if ( !DllRegisterServer ) {
			DisplayError(hWnd, GetLastError(), "Can't find the registering function (DllRegisterServer) in the vpinmame.dll.", "Please check if you have a valid vpinmame.dll!");
			FreeLibrary(hModule);
			return 0;
		}

		hr = (*DllRegisterServer)();
		if ( FAILED(hr) ) {
			DisplayError(hWnd, hr, "Unable to register the class object!", "Please check if you have a valid vpinmame.dll!");
			FreeLibrary(hModule);
			return 0;
		}
		FreeLibrary(hModule);

		// load the class one time to check if it's working
		IUnknown *pUnknown;
		CLSID ClsID;

		hr = CLSIDFromProgID(OLESTR("VPinMAME.Controller"), &ClsID);
		if ( FAILED(hr) ) {
			DisplayError(hWnd, hr, "Class couldn't be found. Registering failed");
			return 0;
		}

		hr = CoCreateInstance(ClsID, NULL, CLSCTX_INPROC_SERVER, IID_IUnknown, (void**) &pUnknown);
		if ( FAILED(hr) ) {
			DisplayError(hWnd, hr, "Can't create the Controller class");
			return 0;
		}
		
		pUnknown->Release();
	}
	else {
		typedef HRESULT DLLUNREGISTERSERVER(void);

		DLLUNREGISTERSERVER* DllUnregisterServer = (DLLUNREGISTERSERVER*) GetProcAddress(hModule, "DllUnregisterServer");
		if ( !DllUnregisterServer ) {
			DisplayError(hWnd, GetLastError(), "Can't find the unregistering function (DllUnegisterServer) in the vpinmame.dll.", "Please check if you have a valid vpinmame.dll!");
			FreeLibrary(hModule);
			return 0;
		}

		hr = (*DllUnregisterServer)();
		if ( FAILED(hr) ) {
			DisplayError(hWnd, hr, "Unable to unregister the class object!", "Please check if you have a valid vpinmame.dll!");
			FreeLibrary(hModule);
			return 0;
		}
		
		FreeLibrary(hModule);
	}

	if ( !fRegister ) {
		if ( MessageBox(hWnd, "Do you want also delete all registry entrys Visual PinMAME has made?", g_szCaption, MB_ICONQUESTION|MB_YESNO)==IDYES ) 
			RegDeleteKeyEx(HKEY_CURRENT_USER, "Software\\Freeware\\Visual PinMame");
	}

	return 1;
}
Пример #11
0
void WinEDA_PcbFrame::OnLeftDClick(wxDC * DC, const wxPoint& MousePos)
/********************************************************************************/
/* Appelé sur un double click:
	pour un élément editable (textes, composant):
		appel de l'editeur correspondant.
	pour une connexion en cours:
		termine la connexion
*/
{
    EDA_BaseStruct * DrawStruct = CURRENT_ITEM;
    wxPoint pos = GetPosition();
    wxClientDC dc(DrawPanel);

    DrawPanel->PrepareGraphicContext(&dc);

    switch ( m_ID_current_state )
    {
    case 0:
        if ( (DrawStruct == NULL) || (DrawStruct->m_Flags == 0) )
        {
            DrawStruct = PcbGeneralLocateAndDisplay();
        }

        if ( (DrawStruct == NULL) || (DrawStruct->m_Flags != 0) )
            break;

        // Element localisé
        GetScreen()->m_CurrentItem = DrawStruct;
        switch ( DrawStruct->m_StructType )
        {
        case TYPETRACK:
        case TYPEVIA:
            if (DrawStruct->m_Flags & IS_NEW)
            {
                End_Route( (TRACK *) DrawStruct, DC);
                DrawPanel->m_AutoPAN_Request = FALSE;
            }
            else if (DrawStruct->m_Flags == 0)
            {
                Edit_TrackSegm_Width(DC,
                                     (TRACK *) DrawStruct);
            }
            break;

        case TYPETEXTE:
            InstallTextPCBOptionsFrame((TEXTE_PCB *)DrawStruct,
                                       DC, ((TEXTE_PCB *)DrawStruct)->m_Pos);
            DrawPanel->MouseToCursorSchema();
            break;

        case TYPEPAD:
            InstallPadOptionsFrame(
                (D_PAD *)DrawStruct, &dc, pos);
            DrawPanel->MouseToCursorSchema();
            break;

        case TYPEMODULE:
            InstallModuleOptionsFrame((MODULE *)DrawStruct,
                                      &dc, pos);
            DrawPanel->MouseToCursorSchema();
            break;

        case TYPEMIRE:
            InstallMireOptionsFrame( (MIREPCB *)DrawStruct, &dc, pos);
            DrawPanel->MouseToCursorSchema();
            break;

        case TYPETEXTEMODULE:
            InstallTextModOptionsFrame((TEXTE_MODULE *)DrawStruct,
                                       &dc, pos);
            DrawPanel->MouseToCursorSchema();
            break;

        case TYPEDRAWSEGMENT:
            break;

        default:
            break;
        }
        break;	// end case 0

    case ID_TRACK_BUTT:
        if ( DrawStruct && (DrawStruct->m_Flags & IS_NEW) )
        {
            End_Route( (TRACK *) DrawStruct, DC);
            DrawPanel->m_AutoPAN_Request = FALSE;
        }
        break;

    case ID_PCB_ZONES_BUTT:
        End_Zone(DC);
        DrawPanel->m_AutoPAN_Request = FALSE;
        GetScreen()->m_CurrentItem = NULL;
        break;

    case ID_LINE_COMMENT_BUTT:
    case ID_PCB_ARC_BUTT:
    case ID_PCB_CIRCLE_BUTT:
        if ( DrawStruct == NULL ) break;
        if ( DrawStruct->m_StructType != TYPEDRAWSEGMENT )
        {
            DisplayError(this, wxT("DrawStruct Type error"));
            DrawPanel->m_AutoPAN_Request = FALSE;
            break;
        }
        if ( (DrawStruct->m_Flags & IS_NEW) )
        {
            End_Edge( (DRAWSEGMENT *) DrawStruct, &dc);
            DrawPanel->m_AutoPAN_Request = FALSE;
            GetScreen()->m_CurrentItem = NULL;
        }
        break;

    }
}
Пример #12
0
int DisplayDialogs(HWND hWnd, int nDialog)
{
	// Let's make a little bit COM
	HRESULT hr;
	IUnknown *pUnknown;
	CLSID ClsID;

	hr = CLSIDFromProgID(OLESTR("VPinMAME.Controller"), &ClsID);
	if ( FAILED(hr) ) {
		DisplayError(hWnd, hr, "Class couldn't be found. Maybe it isn't registered");
		return 0;
	}

	hr = CoCreateInstance(ClsID, NULL, CLSCTX_INPROC_SERVER, IID_IUnknown, (void**) &pUnknown);
	if ( FAILED(hr) ) {
		DisplayError(hWnd, hr, "Can't create the Controller class! \nPlease check that you have installed Visual PinMAME properly!");
		return 0;
	}

	// Don't want to include the header files for the class, so let's using IDispatch
	IDispatch *pDispatch;
	
	hr = pUnknown->QueryInterface(IID_IDispatch, (void**) &pDispatch);
	if ( FAILED(hr) ) {
		DisplayError(hWnd, hr, "Can't get the dispatch interface");
		pUnknown->Release();
		return 0;
	}

	OLECHAR *pszName[3] = {L"ShowPathesDialog", L"ShowOptsDialog", L"ShowAboutDialog"};
	DISPID dispid;

	hr = pDispatch->GetIDsOfNames(IID_NULL, &pszName[nDialog], 1, LOCALE_SYSTEM_DEFAULT, &dispid);
	if ( FAILED(hr) ) {
		DisplayError(hWnd, hr, "Can't get the dispatch interface");
		pDispatch->Release();
		pUnknown->Release();
		return 0;
	}
	
	VARIANT varParam;
	varParam.vt   = VT_I4;
	varParam.lVal = (long) hWnd;

	DISPPARAMS DispParams = {&varParam,NULL,1,0};
	EXCEPINFO ExcepInfo;
	hr = pDispatch->Invoke(dispid, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_METHOD, &DispParams, NULL, &ExcepInfo, NULL);

	if ( FAILED(hr) ) {
		if ( hr==DISP_E_EXCEPTION )
			// actually we call the ONLY UNICODE function in Windows 9x
			MessageBoxW(0, ExcepInfo.bstrDescription, L"Error from the VPinMAME.Controller interface", MB_ICONERROR|MB_OK);
		else 
			DisplayError(hWnd, hr, "Can't get the dispatch interface");

		pDispatch->Release();
		pUnknown->Release();
		return 0;
	}

	pDispatch->Release();
	pUnknown->Release();

	return 1;
}
Пример #13
0
void DeleteStructure( EDA_BaseStruct * PtStruct )
/**************************************************/
/* Supprime de la liste chainee la stucture pointee par GenericStructure
	et libere la memoire correspondante
*/
{
EDA_BaseStruct *PtNext, *PtBack;
int IsDeleted;
int typestruct;
char Line[256];

	if( PtStruct == NULL) return ;

	typestruct = (int)PtStruct->m_StructType;
	IsDeleted = PtStruct->GetState(DELETED);

	PtNext = PtStruct->Pnext;
	PtBack = PtStruct->Pback;

	switch( typestruct )
		{
		case TYPE_NOT_INIT:
			DisplayError(NULL, "DeleteStruct: Type Structure Non Initialise");
			break;

		 case PCB_EQUIPOT_STRUCT_TYPE:
			#undef Struct
			#define Struct ((EQUIPOT*)PtStruct)
			Struct->UnLink();
			delete Struct;
			break;

		 case TYPEMODULE:
			#undef Struct
			#define Struct ((MODULE*)PtStruct)
			Struct->UnLink();
			delete Struct;
			break;


		 case TYPEPAD:
			#undef Struct
			#define Struct ((D_PAD*)PtStruct)
			Struct->UnLink();
			delete Struct;
			break;

		case TYPECOTATION:
			#undef Struct
			#define Struct ((COTATION*)PtStruct)
			Struct->UnLink();
			delete Struct;
			break;

		case TYPEMIRE:
			#undef Struct
			#define Struct ((MIREPCB*)PtStruct)
			Struct->UnLink();
			delete Struct;
			break;

		case TYPEDRAWSEGMENT:
			#undef Struct
			#define Struct ((DRAWSEGMENT*)PtStruct)
			Struct->UnLink();
			delete Struct;
			break;

		 case TYPETEXTE:
			#undef Struct
			#define Struct ((TEXTE_PCB*)PtStruct)
			Struct->UnLink();
			delete Struct;
			break;


		 case TYPETEXTEMODULE:
			#undef Struct
			#define Struct ((TEXTE_MODULE*)PtStruct)
			Struct->UnLink();
			delete Struct;
			break;

		 case TYPEEDGEMODULE:
			#undef Struct
			#define Struct ((EDGE_MODULE*)PtStruct)
			Struct->UnLink();
			delete Struct;
			break;

		case TYPETRACK:
			#undef Struct
			#define Struct ((TRACK*)PtStruct)
			Struct->UnLink();
			delete Struct;
			break;

		case TYPEVIA:
			#undef Struct
			#define Struct ((SEGVIA*)PtStruct)
			Struct->UnLink();
			delete Struct;
			break;

		case TYPEZONE:
			#undef Struct
			#define Struct ((SEGZONE*)PtStruct)
			Struct->UnLink();
			delete Struct;
			break;

		 case TYPEMARQUEUR:
			#undef Struct
			#define Struct ((MARQUEUR*)PtStruct)
			Struct->UnLink();
			delete Struct;
			break;

		case TYPEPCB:

		default:
			sprintf(Line," DeleteStructure: Type %d Inattendu",
										PtStruct->m_StructType);
			DisplayError(NULL, Line);
			break;
		}
}
Пример #14
0
LRESULT CALLBACK
EditTagsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
  static HANDLE hwndText;
  static int sizeX, sizeY;
  int len, newSizeX, newSizeY;
  char *str;
  RECT rect;
  MINMAXINFO *mmi;
  int err;
  
  switch (message) {
  case WM_INITDIALOG: /* message: initialize dialog box */
    /* Initialize the dialog items */
    Translate(hDlg, DLG_EditTags);
   hwndText = memo = GetDlgItem(hDlg, OPT_TagsText);
    SendMessage(hwndText, WM_SETFONT, 
      (WPARAM)font[boardSize][EDITTAGS_FONT]->hf, MAKELPARAM(FALSE, 0));
    SetDlgItemText(hDlg, OPT_TagsText, editTagsText);
    EnableWindow(GetDlgItem(hDlg, OPT_TagsCancel), canEditTags);
    EnableWindow(GetDlgItem(hDlg, OPT_EditTags), !canEditTags || bookUp);
    SendMessage(hwndText, EM_SETREADONLY, !canEditTags, 0);
    if (bookUp) {
      SetDlgItemText(hDlg, OPT_EditTags, _("&Play Move"));
      SetWindowText(hDlg, _("Edit Book"));
      SetFocus(hwndText);
    } else
    if (canEditTags) {
      SetWindowText(hDlg, _("Edit Tags"));
      SetFocus(hwndText);
    } else {
      SetWindowText(hDlg, _("Tags"));
      SetFocus(GetDlgItem(hDlg, IDOK));
    }
    if (!editTagsDialog) {
      editTagsDialog = hDlg;
      GetClientRect(hDlg, &rect);
      sizeX = rect.right;
      sizeY = rect.bottom;
      SendDlgItemMessage( hDlg, OPT_TagsText, EM_SETEVENTMASK, 0, ENM_MOUSEEVENTS );
      if (wpTags.x != CW_USEDEFAULT && wpTags.y != CW_USEDEFAULT &&
	  wpTags.width != CW_USEDEFAULT && wpTags.height != CW_USEDEFAULT) {
	WINDOWPLACEMENT wp;
	EnsureOnScreen(&wpTags.x, &wpTags.y, 0, 0);
	wp.length = sizeof(WINDOWPLACEMENT);
	wp.flags = 0;
	wp.showCmd = SW_SHOW;
	wp.ptMaxPosition.x = wp.ptMaxPosition.y = 0;
	wp.rcNormalPosition.left = wpTags.x;
	wp.rcNormalPosition.right = wpTags.x + wpTags.width;
	wp.rcNormalPosition.top = wpTags.y;
	wp.rcNormalPosition.bottom = wpTags.y + wpTags.height;
	SetWindowPlacement(hDlg, &wp);

	GetClientRect(hDlg, &rect);
	newSizeX = rect.right;
	newSizeY = rect.bottom;
        ResizeEditPlusButtons(hDlg, hwndText, sizeX, sizeY,
			      newSizeX, newSizeY);
	sizeX = newSizeX;
	sizeY = newSizeY;
      }
    }
    return FALSE;
    
  case WM_COMMAND:
    switch (LOWORD(wParam)) {
    case IDOK:
    case OPT_TagsSave:
      if (canEditTags) {
	char *p, *q;
	/* Read changed options from the dialog box */
	len = GetWindowTextLength(hwndText);
	str = (char *) malloc(len + 1);
	GetWindowText(hwndText, str, len + 1);
	p = q = str;
	while (*q) {
	  if (*q == '\r')
	    q++;
	  else
	    *p++ = *q++;
	}
	*p = NULLCHAR; err = 0;
        if(resPtr) *resPtr = strdup(str); else
	if(bookUp) SaveToBook(str), DisplayBook(currentMove); else
	err = ReplaceTags(str, &gameInfo);
	if (err) DisplayError(_("Error replacing tags."), err);

	free(str);
      }
      if(LOWORD(wParam) == IDOK) TagsPopDown();
      return TRUE;
      
    case IDCANCEL:
    case OPT_TagsCancel:
      TagsPopDown();
      return TRUE;
      
    case OPT_EditTags:
      if(bookUp) addToBookFlag = !addToBookFlag; else
      EditTagsEvent();
      return TRUE;

    default:
      break;
    }
    break;

  case WM_NOTIFY: // [HGM] vari: cloned from whistory.c
        if( wParam == OPT_TagsText ) {
            MSGFILTER * lpMF = (MSGFILTER *) lParam;

            if( lpMF->msg == WM_RBUTTONDOWN ) {
                POINTL pt;
                LRESULT index;

                pt.x = LOWORD( lpMF->lParam );
                pt.y = HIWORD( lpMF->lParam );

                index = SendDlgItemMessage( hDlg, OPT_TagsText, EM_CHARFROMPOS, 0, (LPARAM) &pt );

		hwndText = GetDlgItem(hDlg, OPT_TagsText); // cloned from above
		len = GetWindowTextLength(hwndText);
		str = (char *) malloc(len + 1);
		GetWindowText(hwndText, str, len + 1);
		if(bookUp) PlayBookMove(str, index);
		free(str);

                /* Zap the message for good: apparently, returning non-zero is not enough */
                lpMF->msg = WM_USER;

                return TRUE;
            }
        }
        break;

  case WM_SIZE:
    newSizeX = LOWORD(lParam);
    newSizeY = HIWORD(lParam);
    ResizeEditPlusButtons(hDlg, hwndText, sizeX, sizeY, newSizeX, newSizeY);
    sizeX = newSizeX;
    sizeY = newSizeY;
    break;

  case WM_GETMINMAXINFO:
    /* Prevent resizing window too small */
    mmi = (MINMAXINFO *) lParam;
    mmi->ptMinTrackSize.x = 100;
    mmi->ptMinTrackSize.y = 100;
    break;
  }
  return FALSE;
}
Пример #15
0
EDA_BaseStruct * WinEDA_SchematicFrame::FindSchematicItem(
			const wxString & pattern, int SearchType)
/************************************************************************/
/* Find a string in schematic.
	Search is made in current sheet (SearchType = 0),
	or the whole hierarchy (SearchType = 1),
	or for the next item  (SearchType = 2).
	Mouse cursor is put on item
*/
{
SCH_SCREEN * Screen, * FirstScreen = NULL;
EDA_BaseStruct *DrawList = NULL, *FirstStruct = NULL, *Struct = NULL;
int NotFound, StartCount, ii, jj;
wxPoint firstpos, pos;
static int FindAll;
wxSize size = DrawPanel->GetClientSize();
wxPoint curpos;
bool force_recadre = FALSE;
wxString msg, WildText;
	
	g_LastSearchIsMarker = FALSE;
	
	Screen = ScreenSch;
	if( SearchType == 0 )
	{
		s_OldStringFound = pattern;
		Screen = (SCH_SCREEN*) m_CurrentScreen; FindAll = FALSE;
	}
	
	if( SearchType == 1 )
	{
		s_OldStringFound = pattern;
		FindAll = TRUE;
	}

	if(  SearchType != 2  ) ItemsCount = 0;

	WildText = s_OldStringFound;
	NotFound = 1; StartCount = 0;
	
	for ( ; Screen != NULL; Screen = Screen->Next() )
	{
		DrawList = Screen->EEDrawList;
		while ( DrawList )
		{
			switch (DrawList->m_StructType)
			{
				case DRAW_LIB_ITEM_STRUCT_TYPE :
					#undef STRUCT
					#define STRUCT ((EDA_SchComponentStruct*)DrawList)
					if( WildCompareString( WildText, STRUCT->m_Field[REFERENCE].m_Text, FALSE ) )
					{
						NotFound = 0;
						pos = STRUCT->m_Field[REFERENCE].m_Pos;
						break;
					}
					if( WildCompareString( WildText, STRUCT->m_Field[VALUE].m_Text, FALSE ) )
					{
						NotFound = 0;
						pos = STRUCT->m_Field[VALUE].m_Pos;
					}
					break;

				case DRAW_LABEL_STRUCT_TYPE :
				case DRAW_GLOBAL_LABEL_STRUCT_TYPE :
				case DRAW_TEXT_STRUCT_TYPE :
					#undef STRUCT
					#define STRUCT ((DrawTextStruct*)DrawList)
					if( WildCompareString( WildText, STRUCT->m_Text, FALSE ) )
					{
						NotFound = 0;
						pos = STRUCT->m_Pos;
					}
					break;

				default:
					break;
			}

			if(NotFound == 0)	/* Element trouve */
			{
				if ( FirstScreen == NULL )	/* 1er element trouve */
				{
					FirstScreen = Screen; firstpos = pos;
					FirstStruct = DrawList;
				}

				StartCount++;
				if( ItemsCount >= StartCount )
				{
					NotFound = 1;	/* Continue recherche de l'element suivant */
				}
				else
				{
					Struct = DrawList; ItemsCount++; break ;
				}
			}
			if( NotFound == 0 ) break;
			DrawList = DrawList->Pnext;
		}
		if( NotFound == 0 ) break;
		if( FindAll == FALSE ) break;
	}

	if( NotFound && FirstScreen )
	{
		NotFound = 0; Screen = FirstScreen; Struct = FirstStruct;
		pos = firstpos; ItemsCount = 1;
	}

	if( NotFound == 0)
	{
		if ( Screen != GetScreen() )
		{
			Screen->SetZoom(GetScreen()->GetZoom() );
			m_CurrentScreen = ActiveScreen = Screen;
			force_recadre = TRUE;
		}

		/* Si la struct localisee est du type DRAW_LIB_ITEM_STRUCT_TYPE,
			Les coordonnes sont a recalculer en fonction de la matrice
			d'orientation */
		if( Struct->m_StructType == DRAW_LIB_ITEM_STRUCT_TYPE )
		{
			#undef STRUCT
			#define STRUCT ((EDA_SchComponentStruct*)Struct)
			pos.x -= STRUCT->m_Pos.x; pos.y -= STRUCT->m_Pos.y;
			ii = STRUCT->m_Transform[0][0] * pos.x + STRUCT->m_Transform[0][1] * pos.y;
			jj = STRUCT->m_Transform[1][0] * pos.x + STRUCT->m_Transform[1][1] * pos.y;
			pos.x = ii + STRUCT->m_Pos.x; pos.y = jj + STRUCT->m_Pos.y;
		}

		Screen->m_Curseur = pos;
		curpos = DrawPanel->CursorScreenPosition();
		DrawPanel->GetViewStart(&m_CurrentScreen->m_StartVisu.x,
								&m_CurrentScreen->m_StartVisu.y);

		// calcul des coord curseur avec origine = screen
		curpos.x -= m_CurrentScreen->m_StartVisu.x;
		curpos.y -= m_CurrentScreen->m_StartVisu.y;

		/* Il y a peut-etre necessite de recadrer le dessin: */
		if( (curpos.x <= 0) || (curpos.x >= size.x-1) ||
			(curpos.y <= 0) || (curpos.y >= size.y) || force_recadre )
		{
			Recadre_Trace(TRUE);
		}
		else
		{
			GRMouseWarp(DrawPanel, curpos );
		}

		msg = WildText + _(" Found in ") + Screen->m_FileName;
		Affiche_Message(msg);
	}

	else
	{
		Affiche_Message(wxEmptyString);
		msg = WildText + _(" Not Found");
		DisplayError(this,msg, 10);
	}
	
	return DrawList;
}
Пример #16
0
void EDIT_TOOL::remove( BOARD_ITEM* aItem )
{
    BOARD* board = getModel<BOARD>();

    switch( aItem->Type() )
    {
    case PCB_MODULE_T:
    {
        MODULE* module = static_cast<MODULE*>( aItem );
        module->ClearFlags();
        module->RunOnChildren( boost::bind( &KIGFX::VIEW::Remove, getView(), _1 ) );

        // Module itself is deleted after the switch scope is finished
        // list of pads is rebuild by BOARD::BuildListOfNets()

        // Clear flags to indicate, that the ratsnest, list of nets & pads are not valid anymore
        board->m_Status_Pcb = 0;
    }
    break;

    // Default removal procedure
    case PCB_MODULE_TEXT_T:
    {
        TEXTE_MODULE* text = static_cast<TEXTE_MODULE*>( aItem );

        switch( text->GetType() )
        {
            case TEXTE_MODULE::TEXT_is_REFERENCE:
                DisplayError( getEditFrame<PCB_BASE_FRAME>(), _( "Cannot delete component reference." ) );
                return;

            case TEXTE_MODULE::TEXT_is_VALUE:
                DisplayError( getEditFrame<PCB_BASE_FRAME>(), _( "Cannot delete component value." ) );
                return;

            case TEXTE_MODULE::TEXT_is_DIVERS:    // suppress warnings
                break;
        }

        if( m_editModules )
        {
            MODULE* module = static_cast<MODULE*>( aItem->GetParent() );
            module->SetLastEditTime();
            board->m_Status_Pcb = 0; // it is done in the legacy view
            aItem->DeleteStructure();
        }

        return;
    }

    case PCB_PAD_T:
    case PCB_MODULE_EDGE_T:
    {
        MODULE* module = static_cast<MODULE*>( aItem->GetParent() );
        module->SetLastEditTime();

        board->m_Status_Pcb = 0; // it is done in the legacy view


        if( !m_editModules )
        {
            getView()->Remove( aItem );
            board->Remove( aItem );
        }

        aItem->DeleteStructure();

        return;
    }

    case PCB_LINE_T:                // a segment not on copper layers
    case PCB_TEXT_T:                // a text on a layer
    case PCB_TRACE_T:               // a track segment (segment on a copper layer)
    case PCB_VIA_T:                 // a via (like track segment on a copper layer)
    case PCB_DIMENSION_T:           // a dimension (graphic item)
    case PCB_TARGET_T:              // a target (graphic item)
    case PCB_MARKER_T:              // a marker used to show something
    case PCB_ZONE_T:                // SEG_ZONE items are now deprecated
    case PCB_ZONE_AREA_T:
        break;

    default:                        // other types do not need to (or should not) be handled
        assert( false );
        return;
    }

    getView()->Remove( aItem );
    board->Remove( aItem );
}
Пример #17
0
void WinEDA_FindFrame::LocatePartInLibs(wxCommandEvent& event)
/*************************************************************/
/* Recherche exhaustive d'un composant en librairies, meme non chargees
*/
{
wxString Text, FindList;
const wxChar ** ListNames;
LibraryStruct *Lib = NULL;
EDA_LibComponentStruct * LibEntry;
bool FoundInLib = FALSE;	// True si reference trouvee ailleurs qu'en cache
	
	Text = m_NewTextCtrl->GetData();
	if ( Text.IsEmpty() )
	{
		Close(); return;
	}
	s_OldStringFound = Text;

	int ii, nbitems, NumOfLibs = NumOfLibraries();
	if (NumOfLibs == 0)
		{
		DisplayError(this, _("No libraries are loaded"));
		Close(); return;
		}

	ListNames = GetLibNames();
		
	nbitems = 0;
	for (ii = 0; ii < NumOfLibs; ii++ )	/* Recherche de la librairie */
	{
	bool IsLibCache;
		Lib = FindLibrary(ListNames[ii]);
		if ( Lib == NULL ) break;
		if ( Lib->m_Name.Contains( wxT(".cache")) ) IsLibCache = TRUE;
		else IsLibCache = FALSE;
		LibEntry = (EDA_LibComponentStruct *) PQFirst(&Lib->m_Entries, FALSE);
		while( LibEntry )
		{
			if( WildCompareString(Text, LibEntry->m_Name.m_Text, FALSE) )
			{
				nbitems ++;
				if ( ! IsLibCache ) FoundInLib = TRUE;
				if ( ! FindList.IsEmpty() ) FindList += wxT("\n");
				FindList << _("Found ")
						+ LibEntry->m_Name.m_Text
						+ _(" in lib ") + Lib->m_Name;
			}
		LibEntry = (EDA_LibComponentStruct *) PQNext(Lib->m_Entries, LibEntry, NULL);
		}
	}

	free (ListNames);
	
	if ( ! FoundInLib )
	{
		if ( nbitems ) FindList = wxT("\n") + Text + _(" found only in cache");
		else FindList = Text + _(" not found");
		FindList += _("\nExplore All Libraries?");
		if ( IsOK(this, FindList) )
		{
			FindList.Empty();
			ExploreAllLibraries(Text, FindList);
			if ( FindList.IsEmpty() ) DisplayInfo(this, _("Nothing found") );
			else DisplayInfo(this, FindList);
		}
	}
	else DisplayInfo(this, FindList);
	
	Close();
}
Пример #18
0
/* Insert or add a library to the library list:
 *   The new library is put in list before (insert button) the selection,
 *   or added (add button) to end of list
 * The real list (m_Parent->m_ComponentLibFiles) is not changed, so the change
 * can be canceled
 */
void DIALOG_EESCHEMA_CONFIG::OnAddOrInsertLibClick( wxCommandEvent& event )
{
    int        ii;
    wxString   libfilename;
    wxFileName fn;
    wxArrayInt selections;

    m_ListLibr->GetSelections( selections );

    ii = selections.GetCount();

    if( ii > 0 )
        ii = selections[0];
    else
        ii = 0;

    wxString libpath;
    libpath = m_DefaultLibraryPathslistBox->GetStringSelection();

    if ( libpath.IsEmpty() )
        libpath = wxGetApp().ReturnLastVisitedLibraryPath();

    wxFileDialog FilesDialog( this, _( "Library files:" ), libpath,
                              wxEmptyString, CompLibFileWildcard,
                              wxFD_DEFAULT_STYLE | wxFD_MULTIPLE );

    if( FilesDialog.ShowModal() != wxID_OK )
        return;

    wxArrayString Filenames;
    FilesDialog.GetPaths( Filenames );

    for( unsigned jj = 0; jj < Filenames.GetCount(); jj++ )
    {
        fn = Filenames[jj];

        if ( jj == 0 )
            wxGetApp().SaveLastVisitedLibraryPath( fn.GetPath() );

        /* If the library path is already in the library search paths
         * list, just add the library name to the list.  Otherwise, add
         * the library name with the full or relative path.
         * the relative path, when possible is preferable,
         * because it preserve use of default libraries paths, when the path
         * is a sub path of these default paths
         */
        libfilename = wxGetApp().ReturnFilenameWithRelativePathInLibPath( fn.GetFullPath() );

        // Remove extension:
        fn = libfilename;
        fn.SetExt(wxEmptyString);
        libfilename = fn.GetFullPath();

        //Add or insert new library name, if not already in list
        if( m_ListLibr->FindString( libfilename, fn.IsCaseSensitive() ) == wxNOT_FOUND )
        {
            m_LibListChanged = true;

            if( event.GetId() == ID_ADD_LIB )
                m_ListLibr->Append( libfilename );
            else
                m_ListLibr->Insert( libfilename, ii++ );
        }
        else
        {
            wxString msg = wxT( "<" ) + libfilename + wxT( "> : " ) +
                           _( "Library already in use" );
            DisplayError( this, msg );
        }
    }
}
Пример #19
0
BOOL GL11Window::Create(CONST WindowSettings& settings /*= {}*/)
{
	m_settings = settings;

	CONST auto hInstance{GetModuleHandle(NULL)};
	if (!hInstance)
	{
		DisplayError(TEXT("Failed to retrieve the application handle."), GetLastError());
		return FALSE;
	}

	WNDCLASSEX wndClassEx{};
	ZeroMemory(&wndClassEx, sizeof(WNDCLASSEX));
	wndClassEx.cbSize        = sizeof(WNDCLASSEX);
	wndClassEx.style         = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
	wndClassEx.lpfnWndProc   = WndProc;
	wndClassEx.cbClsExtra    = 0;
	wndClassEx.cbWndExtra    = sizeof(VOID*) + sizeof(INT);
	wndClassEx.hInstance     = hInstance;
	wndClassEx.hIcon         = LoadIcon(NULL, IDI_APPLICATION);
	wndClassEx.hCursor       = LoadCursor(NULL, IDC_ARROW);
	wndClassEx.hbrBackground = NULL;
	wndClassEx.lpszMenuName  = NULL;
	wndClassEx.lpszClassName = TEXT("GL11WindowClass");
	wndClassEx.hIconSm       = NULL;

	if (FAILED(RegisterClassEx(&wndClassEx)))
	{
		DisplayError(TEXT("Failed to register the window class."), GetLastError());
		return FALSE;
	}

	DWORD windowStyle{WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS};
	DWORD windowStyleEx{WS_EX_ACCEPTFILES};

	RECT windowRect{0, 0, m_settings.width, m_settings.height};
	if (FAILED(AdjustWindowRectEx(&windowRect, windowStyle, FALSE, windowStyleEx)))
	{
		DisplayError(TEXT("Failed to adjust the window rect."), GetLastError());
		return FALSE;
	}

	m_settings.x = (GetSystemMetrics(SM_CXSCREEN) / 2) - (m_settings.width / 2);
	m_settings.y = (GetSystemMetrics(SM_CYSCREEN) / 2) - (m_settings.height / 2);

	CONST auto FULL_TITLE{m_settings.title + m_settings.titleEx};
	m_handle = CreateWindowEx(windowStyleEx,
	                          wndClassEx.lpszClassName,
	                          FULL_TITLE.c_str(),
	                          windowStyle,
	                          m_settings.x,
	                          m_settings.y,
	                          windowRect.right - windowRect.left,
	                          windowRect.bottom - windowRect.top,
	                          NULL,
	                          NULL,
	                          hInstance,
	                          this);
	if (!m_handle)
	{
		DisplayError(TEXT("Failed to create the window handle."), GetLastError());
		return FALSE;
	}

	m_deviceContext = GetDC(m_handle);

	// Query a pixel format:
	PIXELFORMATDESCRIPTOR desiredPixelFormat{};
	ZeroMemory(&desiredPixelFormat, sizeof(PIXELFORMATDESCRIPTOR));
	desiredPixelFormat.nSize        = sizeof(PIXELFORMATDESCRIPTOR);
	desiredPixelFormat.nVersion     = 1;
	desiredPixelFormat.dwFlags      = PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL;
	desiredPixelFormat.iPixelType   = PFD_TYPE_RGBA;
	desiredPixelFormat.cColorBits   = 32;
	desiredPixelFormat.cDepthBits   = 24;
	desiredPixelFormat.cStencilBits = 8;
	desiredPixelFormat.iLayerType   = PFD_MAIN_PLANE;

	auto chosenPixelFormat{ChoosePixelFormat(m_deviceContext, &desiredPixelFormat)};
	if (!chosenPixelFormat)
	{
		DisplayError(TEXT("Failed to choose a dummy pixel format."), GetLastError());
		return FALSE;
	}

	if (FAILED(DescribePixelFormat(m_deviceContext,
	                               chosenPixelFormat,
	                               sizeof(PIXELFORMATDESCRIPTOR),
	                               &desiredPixelFormat)))
	{
		DisplayError(TEXT("Failed to fill the pixel format."), GetLastError());
		return FALSE;
	}

	if (FAILED(SetPixelFormat(m_deviceContext, chosenPixelFormat, &desiredPixelFormat)))
	{
		DisplayError(TEXT("Failed to set the pixel format."), GetLastError());
		return FALSE;
	}

	// Create the OpenGL context:
	m_renderingContext = wglCreateContext(m_deviceContext);
	if (!m_renderingContext)
	{
		DisplayError(TEXT("Failed to create the OpenGL context."), GetLastError());
		return FALSE;
	}

	if (FAILED(wglMakeCurrent(m_deviceContext, m_renderingContext)))
	{
		DisplayError(TEXT("Failed to make the OpenGL context current."), GetLastError());
		return FALSE;
	}

	ShowWindow(m_handle, SW_SHOWNORMAL);
	UpdateWindow(m_handle);

	if (!s_firstWindowInitialized)
	{
		s_firstWindowInitialized = TRUE;
		m_isFirstWindow          = TRUE;
	}

	return TRUE;
}
Пример #20
0
void DIALOG_EESCHEMA_CONFIG::OnAddOrInsertPath( wxCommandEvent& event )
{
    wxString path = wxGetApp().ReturnLastVisitedLibraryPath();

    bool select = EDA_DirectorySelector( _( "Default Path for Libraries" ),
                                         path, wxDD_DEFAULT_STYLE,
                                         this, wxDefaultPosition );

    if( !select )
        return;

    if( !wxFileName::DirExists( path ) )    // Should not occurs
        return;

    // Add or insert path if not already in list
    if( m_listUserPaths->FindString( path ) == wxNOT_FOUND )
    {
        int ipos = m_listUserPaths->GetCount();

        if ( event.GetId() == wxID_INSERT_PATH )
        {
            if ( ipos  )
                ipos--;

            int jj = m_listUserPaths->GetSelection();

            if ( jj >= 0 )
                ipos = jj;
        }

        // Ask the user if this is a relative path
       int diag = wxMessageBox( _( "Use a relative path?" ), _( "Path type" ),
                                wxYES_NO | wxICON_QUESTION, this );

        if( diag == wxYES )
        {   // Make it relative
            wxFileName fn = path;
            fn.MakeRelativeTo( wxT(".") );
            path = fn.GetPathWithSep() + fn.GetFullName();
        }

        m_listUserPaths->Insert(path, ipos);
        m_LibPathChanged = true;
        wxGetApp().InsertLibraryPath( path, ipos+1 );

        // Display actual libraries paths:
        wxPathList libpaths = wxGetApp().GetLibraryPathList();
        m_DefaultLibraryPathslistBox->Clear();

        for( unsigned ii = 0; ii < libpaths.GetCount(); ii++ )
        {
            m_DefaultLibraryPathslistBox->Append( libpaths[ii]);
        }
    }
    else
    {
        DisplayError( this, _("Path already in use") );
    }

    wxGetApp().SaveLastVisitedLibraryPath( path );
}
Пример #21
0
bool PCB_EDIT_FRAME::End_Zone( wxDC* DC )
{
    ZONE_CONTAINER* zone = GetBoard()->m_CurrentZoneContour;

    if( !zone )
        return true;

    // Validate the current outline:
    if( zone->GetNumCorners() <= 2 )   // An outline must have 3 corners or more
    {
        Abort_Zone_Create_Outline( m_canvas, DC );
        return true;
    }

    // Remove the last corner if is is at the same location as the prevoius corner
    zone->Outline()->RemoveNullSegments();

    // Validate the current edge:
    int icorner = zone->GetNumCorners() - 1;
    if( zone->IsOnCopperLayer() )
    {
        if( g_Drc_On && m_drc->Drc( zone, icorner - 1 ) == BAD_DRC )  // we can't validate last edge
            return false;

        if( g_Drc_On && m_drc->Drc( zone, icorner ) == BAD_DRC )      // we can't validate the closing edge
        {
            DisplayError( this,
                          _( "DRC error: closing this area creates a drc error with an other area" ) );
            m_canvas->MoveCursorToCrossHair();
            return false;
        }
    }

    zone->ClearFlags();

    zone->DrawWhileCreateOutline( m_canvas, DC, GR_XOR );

    m_canvas->SetMouseCapture( NULL, NULL );

    // Undraw old drawings, because they can have important changes
    LAYER_NUM layer = zone->GetLayer();
    GetBoard()->RedrawAreasOutlines( m_canvas, DC, GR_XOR, layer );
    GetBoard()->RedrawFilledAreas( m_canvas, DC, GR_XOR, layer );

    // Save initial zones configuration, for undo/redo, before adding new zone
    s_AuxiliaryList.ClearListAndDeleteItems();
    s_PickedList.ClearListAndDeleteItems();
    SaveCopyOfZones(s_PickedList, GetBoard(), zone->GetNet(), zone->GetLayer() );

    // Put new zone in list
    if( !s_CurrentZone )
    {
        zone->Outline()->CloseLastContour(); // Close the current corner list
        GetBoard()->Add( zone );
        GetBoard()->m_CurrentZoneContour = NULL;

        // Add this zone in picked list, as new item
        ITEM_PICKER picker( zone, UR_NEW );
        s_PickedList.PushItem( picker );
    }
    else    // Append this outline as a cutout to an existing zone
    {
        for( int ii = 0; ii < zone->GetNumCorners(); ii++ )
        {
            s_CurrentZone->AppendCorner( zone->GetCornerPosition( ii ) );
        }

        s_CurrentZone->Outline()->CloseLastContour(); // Close the current corner list
        zone->RemoveAllContours();      // All corners are copied in s_CurrentZone. Free corner list.
        zone = s_CurrentZone;
    }

    s_AddCutoutToCurrentZone = false;
    s_CurrentZone = NULL;

    GetScreen()->SetCurItem( NULL );       // This outline can be deleted when merging outlines

    // Combine zones if possible :
    GetBoard()->OnAreaPolygonModified( &s_AuxiliaryList, zone );

    // Redraw the real edge zone :
    GetBoard()->RedrawAreasOutlines( m_canvas, DC, GR_OR, layer );
    GetBoard()->RedrawFilledAreas( m_canvas, DC, GR_OR, layer );

    int ii = GetBoard()->GetAreaIndex( zone );   // test if zone exists

    if( ii < 0 )
        zone = NULL;                        // was removed by combining zones

    int error_count = GetBoard()->Test_Drc_Areas_Outlines_To_Areas_Outlines( zone, true );

    if( error_count )
    {
        DisplayError( this, _( "Area: DRC outline error" ) );
    }

    UpdateCopyOfZonesList( s_PickedList, s_AuxiliaryList, GetBoard() );
    SaveCopyInUndoList(s_PickedList, UR_UNSPECIFIED);
    s_PickedList.ClearItemsList(); // s_ItemsListPicker is no more owner of picked items

    OnModify();
    return true;
}
bool FOOTPRINT_EDIT_FRAME::HandleBlockEnd( wxDC* DC )
{
    int  itemsCount    = 0;
    bool nextcmd = false;
    MODULE* currentModule = GetBoard()->m_Modules;

    if( GetScreen()->m_BlockLocate.GetCount() )
    {
        BLOCK_STATE_T   state   = GetScreen()->m_BlockLocate.GetState();
        BLOCK_COMMAND_T command = GetScreen()->m_BlockLocate.GetCommand();

        m_canvas->CallEndMouseCapture( DC );
        GetScreen()->m_BlockLocate.SetState( state );
        GetScreen()->m_BlockLocate.SetCommand( command );
        m_canvas->SetMouseCapture( DrawAndSizingBlockOutlines, AbortBlockCurrentCommand );

        SetCrossHairPosition( wxPoint(  GetScreen()->m_BlockLocate.GetRight(),
                                        GetScreen()->m_BlockLocate.GetBottom() ) );
        m_canvas->MoveCursorToCrossHair();
    }

    switch( GetScreen()->m_BlockLocate.GetCommand() )
    {
    case  BLOCK_IDLE:
        DisplayError( this, wxT( "Error in HandleBlockPLace" ) );
        break;

    case BLOCK_DRAG:        // Drag
    case BLOCK_MOVE:        // Move
    case BLOCK_COPY:        // Copy
        itemsCount = MarkItemsInBloc( currentModule, GetScreen()->m_BlockLocate );

        if( itemsCount )
        {
            nextcmd = true;

            if( m_canvas->IsMouseCaptured() )
            {
                m_canvas->CallMouseCapture( DC, wxDefaultPosition, false );
                m_canvas->SetMouseCaptureCallback( DrawMovingBlockOutlines );
                m_canvas->CallMouseCapture( DC, wxDefaultPosition, false );
            }

            GetScreen()->m_BlockLocate.SetState( STATE_BLOCK_MOVE );
            m_canvas->Refresh( true );
        }

        break;

    case BLOCK_PRESELECT_MOVE:     // Move with preselection list
        nextcmd = true;
        m_canvas->SetMouseCaptureCallback( DrawMovingBlockOutlines );
        GetScreen()->m_BlockLocate.SetState( STATE_BLOCK_MOVE );
        break;

    case BLOCK_DELETE:     // Delete
        itemsCount = MarkItemsInBloc( currentModule, GetScreen()->m_BlockLocate );

        if( itemsCount )
            SaveCopyInUndoList( currentModule, UR_MODEDIT );

        DeleteMarkedItems( currentModule );
        break;

    case BLOCK_SAVE:     // Save
    case BLOCK_PASTE:
        break;

    case BLOCK_ROTATE:
        itemsCount = MarkItemsInBloc( currentModule, GetScreen()->m_BlockLocate );

        if( itemsCount )
            SaveCopyInUndoList( currentModule, UR_MODEDIT );

        RotateMarkedItems( currentModule, GetScreen()->m_BlockLocate.Centre() );
        break;


    case BLOCK_MIRROR_X:
    case BLOCK_MIRROR_Y:
    case BLOCK_FLIP:     // mirror
        itemsCount = MarkItemsInBloc( currentModule, GetScreen()->m_BlockLocate );

        if( itemsCount )
            SaveCopyInUndoList( currentModule, UR_MODEDIT );

        MirrorMarkedItems( currentModule, GetScreen()->m_BlockLocate.Centre() );
        break;

    case BLOCK_ZOOM:     // Window Zoom
        Window_Zoom( GetScreen()->m_BlockLocate );
        break;

    case BLOCK_ABORT:
        break;

    case BLOCK_SELECT_ITEMS_ONLY:
        break;
    }

    if( !nextcmd )
    {
        if( GetScreen()->m_BlockLocate.GetCommand() != BLOCK_SELECT_ITEMS_ONLY )
        {
            ClearMarkItems( currentModule );
        }

        GetScreen()->ClearBlockCommand();
        SetCurItem( NULL );
        m_canvas->EndMouseCapture( GetToolId(), m_canvas->GetCurrentCursor(), wxEmptyString,
                                   false );
        m_canvas->Refresh( true );
    }

    return nextcmd;
}
Пример #23
0
bool PCB_EDIT_FRAME::OpenProjectFiles( const std::vector<wxString>& aFileSet, int aCtl )
{
    // This is for python:
    if( aFileSet.size() != 1 )
    {
        UTF8 msg = StrPrintf( "Pcbnew:%s() takes only a single filename", __func__ );
        DisplayError( this, msg );
        return false;
    }

    wxString fullFileName( aFileSet[0] );

    // We insist on caller sending us an absolute path, if it does not, we say it's a bug.
    wxASSERT_MSG( wxFileName( fullFileName ).IsAbsolute(),
        wxT( "bug in single_top.cpp or project manager." ) );

    if( !LockFile( fullFileName ) )
    {
        wxString msg = wxString::Format( _(
                "PCB file '%s' is already open." ),
                GetChars( fullFileName )
                );
        DisplayError( this, msg );
        return false;
    }

    if( GetScreen()->IsModify() )
    {
        int response = YesNoCancelDialog( this, _(
            "The current board has been modified.  Do you wish to save the changes?" ),
            wxEmptyString,
            _( "Save and Load" ),
            _( "Load Without Saving" )
            );

        if( response == wxID_CANCEL )
            return false;
        else if( response == wxID_YES )
            SavePcbFile( GetBoard()->GetFileName(), CREATE_BACKUP_FILE );
        else
        {
            // response == wxID_NO, fall thru
        }
    }

    wxFileName pro = fullFileName;
    pro.SetExt( ProjectFileExtension );

    bool is_new = !wxFileName::IsFileReadable( fullFileName );

    // If its a non-existent schematic and caller thinks it exists
    if( is_new && !( aCtl & KICTL_CREATE ) )
    {
        // notify user that fullFileName does not exist, ask if user wants to create it.
        wxString ask = wxString::Format( _(
                "Board '%s' does not exist.  Do you wish to create it?" ),
                GetChars( fullFileName )
                );
        if( !IsOK( this, ask ) )
            return false;
    }

    Clear_Pcb( false );     // pass false since we prompted above for a modified board

    IO_MGR::PCB_FILE_T  pluginType = plugin_type( fullFileName, aCtl );

    bool converted =  pluginType != IO_MGR::LEGACY && pluginType != IO_MGR::KICAD;

    if( !converted )
    {
        // PROJECT::SetProjectFullName() is an impactful function.  It should only be
        // called under carefully considered circumstances.

        // The calling code should know not to ask me here to change projects unless
        // it knows what consequences that will have on other KIFACEs running and using
        // this same PROJECT.  It can be very harmful if that calling code is stupid.
        Prj().SetProjectFullName( pro.GetFullPath() );

        // load project settings before BOARD
        LoadProjectSettings();
    }

    if( is_new )
    {
        OnModify();
    }
    else
    {
        BOARD* loadedBoard = 0;   // it will be set to non-NULL if loaded OK

        PLUGIN::RELEASER pi( IO_MGR::PluginFind( pluginType ) );

        try
        {
            PROPERTIES  props;
            char        xbuf[30];
            char        ybuf[30];

            // EAGLE_PLUGIN can use this info to center the BOARD, but it does not yet.
            sprintf( xbuf, "%d", GetPageSizeIU().x );
            sprintf( ybuf, "%d", GetPageSizeIU().y );

            props["page_width"]  = xbuf;
            props["page_height"] = ybuf;

#if USE_INSTRUMENTATION
            // measure the time to load a BOARD.
            unsigned startTime = GetRunningMicroSecs();
#endif

            loadedBoard = pi->Load( fullFileName, NULL, &props );

#if USE_INSTRUMENTATION
            unsigned stopTime = GetRunningMicroSecs();
            printf( "PLUGIN::Load(): %u usecs\n", stopTime - startTime );
#endif
        }
        catch( const IO_ERROR& ioe )
        {
            wxString msg = wxString::Format( _(
                    "Error loading board.\n%s" ),
                    GetChars( ioe.errorText )
                    );
            DisplayError( this, msg );

            return false;
        }

        SetBoard( loadedBoard );

        // we should not ask PLUGINs to do these items:
        loadedBoard->BuildListOfNets();
        loadedBoard->SynchronizeNetsAndNetClasses();

        SetStatusText( wxEmptyString );
        BestZoom();

        // update the layer names in the listbox
        ReCreateLayerBox( false );

        GetScreen()->ClrModify();

        {
            wxFileName fn = fullFileName;
            CheckForAutoSaveFile( fullFileName, fn.GetExt() );
        }

        if( pluginType == IO_MGR::LEGACY &&
            loadedBoard->GetFileFormatVersionAtLoad() < LEGACY_BOARD_FILE_VERSION )
        {
            DisplayInfoMessage( this,
                _(  "This file was created by an older version of Pcbnew.\n"
                    "It will be stored in the new file format when you save this file again." ) );
        }
    }

    {
        wxFileName fn = fullFileName;

        if( converted )
            fn.SetExt( PcbFileExtension );

        wxString fname = fn.GetFullPath();

        fname.Replace( WIN_STRING_DIR_SEP, UNIX_STRING_DIR_SEP );

        GetBoard()->SetFileName( fname );
    }

    UpdateTitle();

    if( !converted )
        UpdateFileHistory( GetBoard()->GetFileName() );

    // Rebuild the new pad list (for drc and ratsnet control ...)
    GetBoard()->m_Status_Pcb = 0;

    // Update info shown by the horizontal toolbars
    SetCurrentNetClass( NETCLASS::Default );
    ReFillLayerWidget();
    ReCreateLayerBox();

    // upate the layer widget to match board visibility states, both layers and render columns.
    syncLayerVisibilities();
    syncLayerWidgetLayer();
    syncRenderStates();

    // Update the tracks / vias available sizes list:
    ReCreateAuxiliaryToolbar();

    // Update the RATSNEST items, which were not loaded at the time
    // BOARD::SetVisibleElements() was called from within any PLUGIN.
    // See case RATSNEST_VISIBLE: in BOARD::SetElementVisibility()
    GetBoard()->SetVisibleElements( GetBoard()->GetVisibleElements() );

    // Display the loaded board:
    Zoom_Automatique( false );

    // Compile ratsnest and displays net info
    {
        wxBusyCursor dummy;    // Displays an Hourglass while building connectivity
        Compile_Ratsnest( NULL, true );
        GetBoard()->GetRatsnest()->ProcessBoard();
    }

    SetMsgPanel( GetBoard() );

    // Refresh the 3D view, if any
    EDA_3D_FRAME* draw3DFrame = Get3DViewerFrame();

    if( draw3DFrame )
        draw3DFrame->NewDisplay();

#if 0 && defined(DEBUG)
    // Output the board object tree to stdout, but please run from command prompt:
    GetBoard()->Show( 0, std::cout );
#endif

    // from EDA_APPL which was first loaded BOARD only:
    {
        /* For an obscure reason the focus is lost after loading a board file
         * when starting up the process.
         * (seems due to the recreation of the layer manager after loading the file)
         * Give focus to main window and Drawpanel
         * must be done for these 2 windows (for an obscure reason ...)
         * Linux specific
         * This is more a workaround than a fix.
         */
        SetFocus();
        GetCanvas()->SetFocus();
    }

    return true;
}
void FOOTPRINT_EDIT_FRAME::HandleBlockPlace( wxDC* DC )
{
    MODULE* currentModule = GetBoard()->m_Modules;

    if( !m_canvas->IsMouseCaptured() )
    {
        DisplayError( this, wxT( "HandleBlockPLace : m_mouseCaptureCallback = NULL" ) );
    }

    GetScreen()->m_BlockLocate.SetState( STATE_BLOCK_STOP );

    switch( GetScreen()->m_BlockLocate.GetCommand() )
    {
    case  BLOCK_IDLE:
        break;

    case BLOCK_DRAG:                // Drag
    case BLOCK_MOVE:                // Move
    case BLOCK_PRESELECT_MOVE:      // Move with preselection list
        GetScreen()->m_BlockLocate.ClearItemsList();
        SaveCopyInUndoList( currentModule, UR_MODEDIT );
        MoveMarkedItems( currentModule, GetScreen()->m_BlockLocate.GetMoveVector() );
        m_canvas->Refresh( true );
        break;

    case BLOCK_COPY:     // Copy
        GetScreen()->m_BlockLocate.ClearItemsList();
        SaveCopyInUndoList( currentModule, UR_MODEDIT );
        CopyMarkedItems( currentModule, GetScreen()->m_BlockLocate.GetMoveVector() );
        break;

    case BLOCK_PASTE:     // Paste
        GetScreen()->m_BlockLocate.ClearItemsList();
        break;

    case BLOCK_MIRROR_X:
    case BLOCK_MIRROR_Y:
    case BLOCK_FLIP:      // Mirror by popup menu, from block move
        SaveCopyInUndoList( currentModule, UR_MODEDIT );
        MirrorMarkedItems( currentModule, GetScreen()->m_BlockLocate.Centre() );
        break;

    case BLOCK_ROTATE:
        SaveCopyInUndoList( currentModule, UR_MODEDIT );
        RotateMarkedItems( currentModule, GetScreen()->m_BlockLocate.Centre() );
        break;

    case BLOCK_ZOOM:        // Handled by HandleBlockEnd
    case BLOCK_DELETE:
    case BLOCK_SAVE:
    case BLOCK_ABORT:
    default:
        break;
    }

    OnModify();

    GetScreen()->m_BlockLocate.SetState( STATE_NO_BLOCK );
    GetScreen()->m_BlockLocate.SetCommand( BLOCK_IDLE );
    SetCurItem( NULL );
    m_canvas->EndMouseCapture( GetToolId(), m_canvas->GetCurrentCursor(), wxEmptyString, false );
    m_canvas->Refresh( true );
}
Пример #25
0
/* work from target back to source, actually laying the traces
 *  Parameters:
 *      start on side target_side, of coordinates row_target, col_target.
 *      arrive on side masque_layer_start, coordinate row_source, col_source
 * The search is done in reverse routing, the point of arrival (target) to
 * the starting point (source)
 * The router.
 *
 * Target_side = symbol (TOP / BOTTOM) of departure
 * = Mask_layer_source mask layers Arrival
 *
 * Returns:
 * 0 if error
 * > 0 if Ok
 */
static int Retrace( PCB_EDIT_FRAME* pcbframe, wxDC* DC,
                    int row_source, int col_source,
                    int row_target, int col_target, int target_side,
                    int current_net_code )
{
    int  r0, c0, s0;
    int  r1, c1, s1;    /* row, col, starting side. */
    int  r2, c2, s2;    /* row, col, ending side. */
    int  x, y = -1;
    long b;

    r1 = row_target;
    c1 = col_target;    /* start point is target ( end point is source )*/
    s1 = target_side;
    r0 = c0 = s0 = ILLEGAL;

    wxASSERT( g_CurrentTrackList.GetCount() == 0 );

    do
    {
        /* find where we came from to get here */
        r2 = r1; c2 = c1; s2 = s1;
        x  = RoutingMatrix.GetDir( r1, c1, s1 );

        switch( x )
        {
        case FROM_NORTH:
            r2++;
            break;

        case FROM_EAST:
            c2++;
            break;

        case FROM_SOUTH:
            r2--;
            break;

        case FROM_WEST:
            c2--;
            break;

        case FROM_NORTHEAST:
            r2++;
            c2++;
            break;

        case FROM_SOUTHEAST:
            r2--;
            c2++;
            break;

        case FROM_SOUTHWEST:
            r2--;
            c2--;
            break;

        case FROM_NORTHWEST:
            r2++;
            c2--;
            break;

        case FROM_OTHERSIDE:
            s2 = 1 - s2;
            break;

        default:
            wxMessageBox( wxT( "Retrace: internal error: no way back" ) );
            return 0;
        }

        if( r0 != ILLEGAL )
            y = RoutingMatrix.GetDir( r0, c0, s0 );

        /* see if target or hole */
        if( ( ( r1 == row_target ) && ( c1 == col_target ) ) || ( s1 != s0 ) )
        {
            int p_dir;

            switch( x )
            {
            case FROM_NORTH:
                p_dir = HOLE_NORTH;
                break;

            case FROM_EAST:
                p_dir = HOLE_EAST;
                break;

            case FROM_SOUTH:
                p_dir = HOLE_SOUTH;
                break;

            case FROM_WEST:
                p_dir = HOLE_WEST;
                break;

            case FROM_NORTHEAST:
                p_dir = HOLE_NORTHEAST;
                break;

            case FROM_SOUTHEAST:
                p_dir = HOLE_SOUTHEAST;
                break;

            case FROM_SOUTHWEST:
                p_dir = HOLE_SOUTHWEST;
                break;

            case FROM_NORTHWEST:
                p_dir = HOLE_NORTHWEST;
                break;

            case FROM_OTHERSIDE:
            default:
                DisplayError( pcbframe, wxT( "Retrace: error 1" ) );
                return 0;
            }

            OrCell_Trace( pcbframe->GetBoard(), r1, c1, s1, p_dir, current_net_code );
        }
        else
        {
            if( ( y == FROM_NORTH || y == FROM_NORTHEAST
                  || y == FROM_EAST || y == FROM_SOUTHEAST
                  || y == FROM_SOUTH || y == FROM_SOUTHWEST
                  || y == FROM_WEST || y == FROM_NORTHWEST )
               && ( x == FROM_NORTH || x == FROM_NORTHEAST
                    || x == FROM_EAST || x == FROM_SOUTHEAST
                    || x == FROM_SOUTH || x == FROM_SOUTHWEST
                    || x == FROM_WEST || x == FROM_NORTHWEST
                    || x == FROM_OTHERSIDE )
               && ( ( b = bit[y - 1][x - 1] ) != 0 ) )
            {
                OrCell_Trace( pcbframe->GetBoard(), r1, c1, s1, b, current_net_code );

                if( b & HOLE )
                    OrCell_Trace( pcbframe->GetBoard(), r2, c2, s2, HOLE, current_net_code );
            }
            else
            {
                wxMessageBox( wxT( "Retrace: error 2" ) );
                return 0;
            }
        }

        if( ( r2 == row_source ) && ( c2 == col_source ) ) /* see if source */
        {
            int p_dir;

            switch( x )
            {
            case FROM_NORTH:
                p_dir = HOLE_SOUTH;
                break;

            case FROM_EAST:
                p_dir = HOLE_WEST;
                break;

            case FROM_SOUTH:
                p_dir = HOLE_NORTH;
                break;

            case FROM_WEST:
                p_dir = HOLE_EAST;
                break;

            case FROM_NORTHEAST:
                p_dir = HOLE_SOUTHWEST;
                break;

            case FROM_SOUTHEAST:
                p_dir = HOLE_NORTHWEST;
                break;

            case FROM_SOUTHWEST:
                p_dir = HOLE_NORTHEAST;
                break;

            case FROM_NORTHWEST:
                p_dir = HOLE_SOUTHEAST;
                break;

            case FROM_OTHERSIDE:
            default:
                wxMessageBox( wxT( "Retrace: error 3" ) );
                return 0;
            }

            OrCell_Trace( pcbframe->GetBoard(), r2, c2, s2, p_dir, current_net_code );
        }

        /* move to next cell */
        r0 = r1;
        c0 = c1;
        s0 = s1;
        r1 = r2;
        c1 = c2;
        s1 = s2;
    } while( !( ( r2 == row_source ) && ( c2 == col_source ) ) );

    AddNewTrace( pcbframe, DC );
    return 1;
}
Пример #26
0
void _fastcall r4300i_SB (void) {
	DWORD Address =  GPR[Opcode.base].UW[0] + (short)Opcode.offset;	
	if (!r4300i_SB_VAddr(Address,GPR[Opcode.rt].UB[0])) {
		DisplayError("SB TLB: %X",Address);
	}
}
Пример #27
0
void PCB_EDIT_FRAME::ReadMacros()
{
    wxFileName fn;

    fn = GetBoard()->GetFileName();
    fn.SetExt( MacrosFileExtension );

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

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

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

    wxXmlDocument xml;

    xml.SetFileEncoding( wxT( "UTF-8" ) );

    if( !xml.Load( dlg.GetFilename() ) )
            return;

    XNODE *macrosNode = (XNODE*) xml.GetRoot()->GetChildren();

    while( macrosNode )
    {
        int number = -1;

        if( macrosNode->GetName() == wxT( "macros" ) )
        {
            number = wxAtoi( macrosNode->GetAttribute( wxT( "number" ), wxT( "-1" ) ) );

            if( number >= 0  && number < 10 )
            {
                m_Macros[number].m_Record.clear();

                XNODE *hotkeyNode = macrosNode->GetChildren();

                while( hotkeyNode )
                {
                    if( hotkeyNode->GetName() == wxT( "hotkey" ) )
                    {
                        int x = wxAtoi( hotkeyNode->GetAttribute( wxT( "x" ), wxT( "0" ) ) );
                        int y = wxAtoi( hotkeyNode->GetAttribute( wxT( "y" ), wxT( "0" ) ) );
                        int hk = wxAtoi( hotkeyNode->GetAttribute( wxT( "hkcode" ), wxT( "0" ) ) );

                        MACROS_RECORD macros_record;
                        macros_record.m_HotkeyCode = hk;
                        macros_record.m_Position.x = x;
                        macros_record.m_Position.y = y;
                        m_Macros[number].m_Record.push_back( macros_record );
                    }

                    hotkeyNode = hotkeyNode->GetNext();
                }
            }
        }

        macrosNode = macrosNode->GetNext();
    }
}
Пример #28
0
EDA_BaseStruct * WinEDA_SchematicFrame::FindMarker(int SearchType)
/*****************************************************************/
/* Search de markers in whole the hierarchy.
	Mouse cursor is put on the marker
	SearchType = 0: searche th first marker, else search next marker
*/
{
SCH_SCREEN * Screen, * FirstScreen = NULL;
EDA_BaseStruct *DrawList, *FirstStruct = NULL, *Struct = NULL;
DrawMarkerStruct * Marker = NULL;
int NotFound, StartCount;
wxPoint firstpos, pos;
wxSize size = DrawPanel->GetClientSize();
wxPoint curpos;
bool force_recadre = FALSE;
wxString msg, WildText;
	
	g_LastSearchIsMarker = TRUE;
	Screen = ScreenSch;
	if( SearchType == 0 ) MarkerCount = 0;

	NotFound = TRUE; StartCount = 0;
	for ( ; Screen != NULL; Screen = Screen->Next() )
	{
		DrawList = Screen->EEDrawList;
		while ( DrawList && NotFound )
		{
			if(DrawList->m_StructType == DRAW_MARKER_STRUCT_TYPE )
			{
			Marker = (DrawMarkerStruct *) DrawList;
				NotFound = FALSE;
				pos = Marker->m_Pos;
				if ( FirstScreen == NULL )	/* First item found */
				{
					FirstScreen = Screen; firstpos = pos;
					FirstStruct = DrawList;
				}
	
				StartCount++;
				if( MarkerCount >= StartCount )
				{
					NotFound = TRUE;	/* Search for the next item */
				}
				else
				{
					Struct = DrawList; MarkerCount++; break ;
				}
			}
			DrawList = DrawList->Pnext;
		}
		if( NotFound == FALSE ) break;
	}

	if( NotFound && FirstScreen )
	{
		NotFound = 0; Screen = FirstScreen; Struct = FirstStruct;
		pos = firstpos; MarkerCount = 1;
	}

	if( NotFound == 0)
	{
		if ( Screen != GetScreen() )
		{
			Screen->SetZoom(GetScreen()->GetZoom() );
			m_CurrentScreen = ActiveScreen = Screen;
			force_recadre = TRUE;
		}

		Screen->m_Curseur = pos;
		curpos = DrawPanel->CursorScreenPosition();
		DrawPanel->GetViewStart(&m_CurrentScreen->m_StartVisu.x,
								&m_CurrentScreen->m_StartVisu.y);

		// calcul des coord curseur avec origine = screen
		curpos.x -= m_CurrentScreen->m_StartVisu.x;
		curpos.y -= m_CurrentScreen->m_StartVisu.y;

		/* Il y a peut-etre necessite de recadrer le dessin: */
		if( (curpos.x <= 0) || (curpos.x >= size.x-1) ||
			(curpos.y <= 0) || (curpos.y >= size.y) || force_recadre )
		{
			Recadre_Trace(TRUE);
		}
		else
		{
			GRMouseWarp(DrawPanel, curpos );
		}

		msg = _("Marker found in ") + Screen->m_FileName;
		Affiche_Message(msg);
	}

	else
	{
		Affiche_Message(wxEmptyString);
		msg = _("Marker Not Found");
		DisplayError(NULL,msg, 10);
	}
	
	return Marker;
}
Пример #29
0
char* system_(char* cmd) {
  HANDLE hOutputReadTmp,hOutputRead,hOutputWrite;
  HANDLE hInputWriteTmp,hInputRead,hInputWrite;
  HANDLE hErrorWrite;
  SECURITY_ATTRIBUTES sa;
  CHAR lpBuffer[256];
  DWORD nBytesRead;
  DWORD ExitCode;
  PROCESS_INFORMATION pi;
  STARTUPINFO si;
  char* ret=q("");
  sa.nLength= sizeof(SECURITY_ATTRIBUTES);
  sa.lpSecurityDescriptor = NULL;
  sa.bInheritHandle = TRUE;
  if (!CreatePipe(&hOutputReadTmp,&hOutputWrite,&sa,0))
    DisplayError("CreatePipe");

  if (!DuplicateHandle(GetCurrentProcess(),hOutputWrite,
                       GetCurrentProcess(),&hErrorWrite,0,
                       TRUE,DUPLICATE_SAME_ACCESS))
    DisplayError("DuplicateHandle");

  if (!CreatePipe(&hInputRead,&hInputWriteTmp,&sa,0))
    DisplayError("CreatePipe");

  if (!DuplicateHandle(GetCurrentProcess(),hOutputReadTmp,
                       GetCurrentProcess(),
                       &hOutputRead,0,FALSE,
                       DUPLICATE_SAME_ACCESS))
    DisplayError("DupliateHandle");

  if (!DuplicateHandle(GetCurrentProcess(),hInputWriteTmp,
                       GetCurrentProcess(),
                       &hInputWrite,0,FALSE,
                       DUPLICATE_SAME_ACCESS))
    DisplayError("DupliateHandle");

  if (!CloseHandle(hOutputReadTmp)) DisplayError("CloseHandle");
  if (!CloseHandle(hInputWriteTmp)) DisplayError("CloseHandle");
  ZeroMemory(&si,sizeof(STARTUPINFO));
  si.cb = sizeof(STARTUPINFO);
  si.dwFlags = STARTF_USESTDHANDLES;
  si.hStdOutput = hOutputWrite;
  si.hStdInput  = hInputRead;
  si.hStdError  = hErrorWrite;
  if (!CreateProcess(NULL,cmd,NULL,NULL,TRUE,0,NULL,NULL,&si,&pi))
    DisplayError("CreateProcess");
  if (!CloseHandle(pi.hThread)) DisplayError("CloseHandle");
  if (!CloseHandle(hOutputWrite)) DisplayError("CloseHandle");
  if (!CloseHandle(hInputRead )) DisplayError("CloseHandle");
  if (!CloseHandle(hErrorWrite)) DisplayError("CloseHandle");
  while(1) {
    if (!ReadFile(hOutputRead,lpBuffer,sizeof(lpBuffer),
                  &nBytesRead,NULL) || !nBytesRead) {
      if (GetLastError() == ERROR_BROKEN_PIPE)
        break;
      else
        DisplayError("ReadFile");
    }
    lpBuffer[nBytesRead]='\0';
    ret=s_cat(ret,q(lpBuffer),NULL);
  }
  if (!CloseHandle(hOutputRead)) DisplayError("CloseHandle");
  if (!CloseHandle(hInputWrite)) DisplayError("CloseHandle");
  if (!GetExitCodeProcess(pi.hProcess,&ExitCode) || ExitCode) {
    s(ret);
    ret=NULL;
  }
  return ret;
}
Пример #30
0
void SetupDSoundBuffers(void) {
	LPDIRECTSOUNDBUFFER lpdsb;
    DSBUFFERDESC        dsPrimaryBuff, dsbdesc;
    WAVEFORMATEX        wfm;
    HRESULT             hr;
	int count;

    if (lpdsbuf) { CloseDLL(); InitiateAudio(AudioInfo);}

    if ( FAILED( hr = DirectSoundCreate( NULL, &lpds, NULL ) ) ) {
        return FALSE;
	}

    if ( FAILED( hr = IDirectSound8_SetCooperativeLevel(lpds, AudioInfo.hwnd, DSSCL_PRIORITY   ))) {
        return FALSE;
	}
    for ( count = 0; count < NUMCAPTUREEVENTS; count++ ) {
        rghEvent[count] = CreateEvent( NULL, FALSE, FALSE, NULL );
        if (rghEvent[count] == NULL ) { return FALSE; }
    }

	memset( &dsPrimaryBuff, 0, sizeof( DSBUFFERDESC ) ); 
    
	dsPrimaryBuff.dwSize        = sizeof( DSBUFFERDESC ); 
    dsPrimaryBuff.dwFlags       = DSBCAPS_PRIMARYBUFFER; 
    dsPrimaryBuff.dwBufferBytes = 0;  
    dsPrimaryBuff.lpwfxFormat   = NULL; 
    memset( &wfm, 0, sizeof( WAVEFORMATEX ) ); 

	wfm.wFormatTag = WAVE_FORMAT_PCM;
	wfm.nChannels = 2;
	wfm.nSamplesPerSec = 44100;
	wfm.wBitsPerSample = 16;
	wfm.nBlockAlign = wfm.wBitsPerSample / 8 * wfm.nChannels;
	wfm.nAvgBytesPerSec = wfm.nSamplesPerSec * wfm.nBlockAlign;

	hr = IDirectSound8_CreateSoundBuffer(lpds,&dsPrimaryBuff, &lpdsb, NULL);
	
	if (SUCCEEDED ( hr ) ) {
		IDirectSoundBuffer8_SetFormat(lpdsb, &wfm );
	    IDirectSoundBuffer8_Play(lpdsb, 0, 0, DSBPLAY_LOOPING );
	}

	wfm.nSamplesPerSec = Frequency;
	wfm.wBitsPerSample = 16;
	wfm.nBlockAlign = wfm.wBitsPerSample / 8 * wfm.nChannels;
	wfm.nAvgBytesPerSec = wfm.nSamplesPerSec * wfm.nBlockAlign;

    memset( &dsbdesc, 0, sizeof( DSBUFFERDESC ) ); 
    dsbdesc.dwSize = sizeof( DSBUFFERDESC ); 
    dsbdesc.dwFlags = DSBCAPS_GLOBALFOCUS | DSBCAPS_CTRLPOSITIONNOTIFY;
    dsbdesc.dwBufferBytes = BufferSize * 3;  
    dsbdesc.lpwfxFormat = &wfm; 

	if ( FAILED( hr = IDirectSound8_CreateSoundBuffer(lpds, &dsbdesc, &lpdsbuf, NULL ) ) ) {
		DisplayError("Failed in creation of Play buffer 1");	
	}
	FillBufferWithSilence( lpdsbuf );

    rgdscbpn[0].dwOffset = ( BufferSize ) - 1;
    rgdscbpn[0].hEventNotify = rghEvent[0];
    rgdscbpn[1].dwOffset = ( BufferSize * 2) - 1;
    rgdscbpn[1].hEventNotify = rghEvent[1];
    rgdscbpn[2].dwOffset = ( BufferSize * 3) - 1;
    rgdscbpn[2].hEventNotify = rghEvent[2];
    rgdscbpn[3].dwOffset = DSBPN_OFFSETSTOP;
    rgdscbpn[3].hEventNotify = rghEvent[3];

    if ( FAILED( hr = IDirectSound8_QueryInterface(lpdsbuf, &IID_IDirectSoundNotify, ( VOID ** )&lpdsNotify ) ) ) {
		DisplayError("IDirectSound8_QueryInterface: Failed\n");
		return;
	}

    // Set capture buffer notifications.
    if ( FAILED( hr = IDirectSoundNotify_SetNotificationPositions(lpdsNotify, NUMCAPTUREEVENTS, rgdscbpn ) ) ) {
		DisplayError("IDirectSoundNotify_SetNotificationPositions: Failed");
		return;
    }

	//AddEffect();
}