Example #1
0
void GameVisualScene::updateOverlays()
{
	str text = StrPrintf("visual frame #%d maxFPS = %.2f\n",game->visualSystem.getCurrentFrameNum(),game->visualSystem.getMaxFPS());
	text    += StrPrintf("physics last step %dms\n",game->physicsSystem.getLastTimeElapsed());
	text    += DebugRegistry::getInstance()->print();
	debugTextOverlay->setCaption(text);
}
Example #2
0
void ConsolePrintWarning(MSGVEC *msgvecP)
{
  TCHAR format[80];
  TCHAR *msgtextP;

  // Print the primary warning message.

  msgtextP = GetMessageText(msgvecP->code);

  StrPrintf (format, msgtextP,
    msgvecP->param[0], msgvecP->param[1], msgvecP->param[2],
    msgvecP->param[3], msgvecP->param[4], msgvecP->param[5],
    msgvecP->param[6], msgvecP->param[7]);

  FPrintf (stderr, _T("\nWarning: %s\n"), format);

  // Print the (optional) secondary warning message.

  if (msgvecP->subcode)
    {
    msgtextP = GetMessageText(msgvecP->subcode);

    StrPrintf (format, msgtextP,
      msgvecP->subparam[0], msgvecP->subparam[1], msgvecP->subparam[2],
      msgvecP->subparam[3], msgvecP->subparam[4], msgvecP->subparam[5],
      msgvecP->subparam[6], msgvecP->subparam[7]);

    FPrintf (stderr, _T("%s\n"), format);
    }
}
// -----------------------------------------------------------------------------------------
// Date time stamp
// -----------------------------------------------------------------------------------------
STRING DateTimeStamp(STRING bszBuffer, UINT32 u32BcharCount)
	{

#ifdef WIN32
	SYSTEMTIME st;

	GetLocalTime(&st);

	return StrPrintf(bszBuffer, u32BcharCount, 
		S("%4d/%02d/%02d %02d:%02d:%02d.%03d"),
		st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
#else
	struct timeval tv;
	struct tm tm;

	gettimeofday(&tv, NULL);
	localtime_r(&tv.tv_sec, &tm);

	return StrPrintf(bszBuffer, u32BcharCount, 
		S("%4d/%02d/%02d %02d:%02d:%02d.%03d"),
		tm.tm_year + 1900, tm.tm_mon, tm.tm_mday, 
		tm.tm_hour, tm.tm_min, tm.tm_sec, tv.tv_usec/1000);
#endif

	} // DateTimeStamp
static std::string GenCADLayerName( int aCuCount, LAYER_ID aId )
{
    if( IsCopperLayer( aId ) )
    {
        if( aId == F_Cu )
            return "TOP";
        else if( aId == B_Cu )
            return "BOTTOM";

        else if( aId <= 14 )
        {
            return StrPrintf(  "INNER%d", aCuCount - aId - 1 );
        }
        else
        {
            return StrPrintf( "LAYER%d", aId );
        }
    }

    else
    {
        const char* txt;

        // using a switch to clearly show mapping & catch out of bounds index.
        switch( aId )
        {
        // Technicals
        case B_Adhes:   txt = "B.Adhes";                break;
        case F_Adhes:   txt = "F.Adhes";                break;
        case B_Paste:   txt = "SOLDERPASTE_BOTTOM";     break;
        case F_Paste:   txt = "SOLDERPASTE_TOP";        break;
        case B_SilkS:   txt = "SILKSCREEN_BOTTOM";      break;
        case F_SilkS:   txt = "SILKSCREEN_TOP";         break;
        case B_Mask:    txt = "SOLDERMASK_BOTTOM";      break;
        case F_Mask:    txt = "SOLDERMASK_TOP";         break;

        // Users
        case Dwgs_User: txt = "Dwgs.User";              break;
        case Cmts_User: txt = "Cmts.User";              break;
        case Eco1_User: txt = "Eco1.User";              break;
        case Eco2_User: txt = "Eco2.User";              break;
        case Edge_Cuts: txt = "Edge.Cuts";              break;
        case Margin:    txt = "Margin";                 break;

        // Footprint
        case F_CrtYd:   txt = "F_CrtYd";                break;
        case B_CrtYd:   txt = "B_CrtYd";                break;
        case F_Fab:     txt = "F_Fab";                  break;
        case B_Fab:     txt = "B_Fab";                  break;

        default:
            wxASSERT_MSG( 0, wxT( "aId UNEXPECTED" ) );
                        txt = "BAD-INDEX!";             break;
        }

        return txt;
    }
};
Example #5
0
const char * pyVaultAgeInfoNode::GetDisplayName() const
{
    if (fNode) {
        char str[MAX_PATH];
        VaultAgeInfoNode access(fNode);
        if (access.GetAgeSequenceNumber() > 0)
            StrPrintf(str, arrsize(str), "%S(%d) %S", access.GetAgeUserDefinedName(), access.GetAgeSequenceNumber(), access.GetAgeInstanceName());
        else
            StrPrintf(str, arrsize(str), "%S %S", access.GetAgeUserDefinedName(), access.GetAgeInstanceName());
        fAgeDispName = str;
    }
    return fAgeDispName.c_str();
}
bool GITHUB_GETLIBLIST::remoteGetJSON( const std::string& aFullURLCommand, wxString* aMsgError )
{
    KICAD_CURL_EASY kcurl;

    wxLogDebug( wxT( "Attempting to download: " ) + aFullURLCommand );

    kcurl.SetURL(aFullURLCommand);
    kcurl.SetUserAgent("KiCad-EDA");
    kcurl.SetHeader("Accept", m_option_string);
    kcurl.SetFollowRedirects(true);

    try
    {
        kcurl.Perform();
        m_image.reserve( kcurl.GetBuffer()->Size );
        m_image.assign( kcurl.GetBuffer()->Payload, kcurl.GetBuffer()->Size );
        return true;
    }
    catch( const IO_ERROR& ioe )
    {
        if( aMsgError )
        {
            UTF8 fmt( _( "Error fetching JSON data from URL '%s'.\nReason: '%s'" ) );
            
            std::string msg = StrPrintf( fmt.c_str(), 
                                         aFullURLCommand.c_str(),
                                         TO_UTF8( ioe.errorText ) );

            *aMsgError = FROM_UTF8( msg.c_str() );
        }
        return false;
    }
}
static std::string fmt_mask( LSET aSet )
{
#if 0
    return aSet.FmtHex();
#else
    return StrPrintf( "%08x", (unsigned) ( aSet & LSET::AllCuMask() ).to_ulong() );
#endif
}
// flipped layer name for Gencad export (to make CAM350 imports correct)
static std::string GenCADLayerNameFlipped( int aCuCount, LAYER_ID aId )
{
    if( 1<= aId && aId <= 14 )
    {
        return StrPrintf(  "INNER%d", 14 - aId );
    }

    return GenCADLayerName( aCuCount, aId );
};
const std::string GENDRILL_WRITER_BASE::layerName( PCB_LAYER_ID aLayer ) const
{
    // Generic names here.
    switch( aLayer )
    {
    case F_Cu:
        return "front";
    case B_Cu:
        return "back";
    default:
        return StrPrintf( "in%d", aLayer );
    }
}
const std::string EXCELLON_WRITER::layerName( LAYER_ID aLayer ) const
{
    // Generic names here.
    switch( aLayer )
    {
    case F_Cu:
        return "front";
    case B_Cu:
        return "back";
    default:
        return StrPrintf( "inner%d", aLayer );
    }
}
Example #11
0
char *GetErrorStr
(
    DWORD errNum,   ///< Error number to get the string version for.
    char *errStr,   ///< Place to store the error string.
    size_t maxLen   ///< Max length that can be written into errStr.
)
{
    if ( FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM, // dwFlags
                        0,                          // lpSource
                        errNum,                     // dwMessageId
                        GetUserDefaultLangID(),     // dwlanguageId
                        errStr,                     // lpBuffer
                        maxLen,                     // nSize
                        NULL ) == 0 )               // arguments
    {
        StrPrintf( errStr, maxLen, "*** Unknown Error: %d ***", errNum );
    }

    return errStr;
                        
} // GetErrorStr
Example #12
0
void CVPCB_MAINFRAME::SendMessageToEESCHEMA()
{
    if( m_netlist.IsEmpty() )
        return;

    int selection = m_compListBox->GetSelection();

    if ( selection < 0 )
        selection = 0;

    if( m_netlist.GetComponent( selection ) == NULL )
        return;

    COMPONENT* component = m_netlist.GetComponent( selection );

    std::string packet = StrPrintf( "$PART: \"%s\"", TO_UTF8( component->GetReference() ) );

    if( Kiface().IsSingle() )
        SendCommand( MSG_TO_SCH, packet.c_str() );
    else
        Kiway().ExpressMail( FRAME_SCH, MAIL_CROSS_PROBE, packet, this );
}
Example #13
0
void KICAD_MANAGER_FRAME::OnImportEagleFiles( wxCommandEvent& event )
{
    // Close other windows.
    if( !Kiway().PlayersClose( false ) )
        return;


    wxString title = _( "Import Eagle Project Files" );
    int style = wxFD_OPEN | wxFD_FILE_MUST_EXIST;
    wxString default_dir = GetMruPath();

    ClearMsg();

    wxFileDialog schdlg( this, title, default_dir, wxEmptyString,
                         EagleFilesWildcard(), style );

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


    wxFileName sch( schdlg.GetPath() );

    sch.SetExt( SchematicFileExtension );

    wxFileName pro = sch;

    pro.SetExt( ProjectFileExtension );

    wxString protitle = _( "KiCad Project Destination" );

    // Don't use wxFileDialog here.  On GTK builds, the default path is returned unless a
    // file is actually selected.
    wxDirDialog prodlg( this, protitle, pro.GetPath(), wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST );

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

    pro.SetPath( prodlg.GetPath() );

    // Check if the project directory is empty
    wxDir directory( pro.GetPath() );

    if( directory.HasFiles() )
    {
        wxString msg = _( "The selected directory is not empty.  We recommend you "
                          "create projects in their own clean directory.\n\nDo you "
                          "want to create a new empty directory for the project?" );

        KIDIALOG dlg( this, msg, _( "Confirmation" ), wxYES_NO | wxICON_WARNING );
        dlg.DoNotShowCheckbox( __FILE__, __LINE__ );

        if( dlg.ShowModal() == wxID_YES )
        {
            // Append a new directory with the same name of the project file
            // and try to create it
            pro.AppendDir( pro.GetName() );

            if( !wxMkdir( pro.GetPath() ) )
                // There was a problem, undo
                pro.RemoveLastDir();
        }
    }

    wxFileName pcb( sch );
    pro.SetExt( ProjectFileExtension );         // enforce extension
    pcb.SetExt( LegacyPcbFileExtension );       // enforce extension

    if( !pro.IsAbsolute() )
        pro.MakeAbsolute();

    SetProjectFileName( pro.GetFullPath() );
    wxString prj_filename = GetProjectFileName();

    if( sch.FileExists() )
    {
        KIWAY_PLAYER* schframe = Kiway().Player( FRAME_SCH, false );

        if( !schframe )
        {
            try     // SCH frame was not available, try to start it
            {
                schframe = Kiway().Player( FRAME_SCH, true );
            }
            catch( const IO_ERROR& err )
            {
                wxMessageBox( _( "Eeschema failed to load:\n" ) + err.What(),
                        _( "KiCad Error" ), wxOK | wxICON_ERROR, this );
                return;
            }
        }

        std::string packet = StrPrintf( "%d\n%s", SCH_IO_MGR::SCH_EAGLE,
                                                  TO_UTF8( sch.GetFullPath() ) );
        schframe->Kiway().ExpressMail( FRAME_SCH, MAIL_IMPORT_FILE, packet, this );

        if( !schframe->IsShown() )      // the frame exists, (created by the dialog field editor)
                                        // but no project loaded.
        {
            schframe->Show( true );
        }

        if( schframe->IsIconized() )
            schframe->Iconize( false );

        schframe->Raise();
    }


    if( pcb.FileExists() )
    {
        KIWAY_PLAYER* pcbframe = Kiway().Player( FRAME_PCB, false );

        if( !pcbframe )
        {
            try     // PCB frame was not available, try to start it
            {
                pcbframe = Kiway().Player( FRAME_PCB, true );
            }
            catch( const IO_ERROR& err )
            {
                wxMessageBox( _( "Pcbnew failed to load:\n" ) + err.What(), _( "KiCad Error" ),
                        wxOK | wxICON_ERROR, this );
                return;
            }
        }

        // a pcb frame can be already existing, but not yet used.
        // this is the case when running the footprint editor, or the footprint viewer first
        // if the frame is not visible, the board is not yet loaded
        if( !pcbframe->IsVisible() )
        {
            pcbframe->Show( true );
        }

        std::string packet = StrPrintf( "%d\n%s", IO_MGR::EAGLE,
                                                  TO_UTF8( pcb.GetFullPath() ) );
        pcbframe->Kiway().ExpressMail( FRAME_PCB, MAIL_IMPORT_FILE, packet, this );

        // On Windows, Raise() does not bring the window on screen, when iconized
        if( pcbframe->IsIconized() )
            pcbframe->Iconize( false );

        pcbframe->Raise();
    }

    ReCreateTreePrj();
    m_active_project = true;
}
Example #14
0
static void PrintFullPath(char* dst, size_t dstChars, const char* shaderName)
{
    StrPrintf(dst, dstChars, "%s_MTL.shd", shaderName);
}
Example #15
0
//============================================================================
static bool SelfPatcherProc (bool * abort, plLauncherInfo *info) {

    bool patched = false;
    s_downloadComplete = false;
    s_patchResult = kNetSuccess;

    NetClientInitialize();
    NetClientSetErrorHandler(NetErrorHandler);

    const char** addrs;
    unsigned count;

    count = GetGateKeeperSrvHostnames(&addrs);

    // Start connecting to the server
    NetCliGateKeeperStartConnect(addrs, count);

    // request a file server ip address
    NetCliGateKeeperFileSrvIpAddressRequest(FileSrvIpAddressCallback, nil, true);

    while(!s_downloadComplete && !*abort) {
        NetClientUpdate();
        AsyncSleep(10);
    }   

    NetCliFileDisconnect();
    NetClientUpdate();

    // Shutdown the client/server networking subsystem
    NetClientDestroy();

    if (s_downloadComplete && !*abort && s_updated && IS_NET_SUCCESS(s_patchResult)) {

        // launch new patcher
        STARTUPINFOW        si;
        PROCESS_INFORMATION pi;
        memset(&si, 0, sizeof(si));
        memset(&pi, 0, sizeof(pi));
        si.cb = sizeof(si);

        wchar_t cmdline[MAX_PATH];
        StrPrintf(cmdline, arrsize(cmdline), L"%s %s", s_newPatcherFile, info->cmdLine);

        // we have only successfully patched if we actually launch the new version of the patcher
        patched = CreateProcessW(
            NULL,
            cmdline,
            NULL,
            NULL,
            FALSE, 
            DETACHED_PROCESS,
            NULL,
            NULL,
            &si,
            &pi
        );
        SetReturnCode(pi.dwProcessId);
        CloseHandle( pi.hThread );
        CloseHandle( pi.hProcess );
        ASSERT(patched);
    }

    return patched;
}
Example #16
0
//
// MsgReceive handler for plasma messages
//
bool plNetClientMgr::MsgReceive( plMessage* msg )
{
    if (plNetLinkingMgr::GetInstance()->MsgReceive( msg ))
        return true;

    plEvalMsg* evalMsg = plEvalMsg::ConvertNoRef(msg);
    if (evalMsg)
    {
        IPlaybackMsgs();

        if ( GetFlagsBit( kNeedToSendAgeLoadedMsg ) )
        {
            SetFlagsBit( kNeedToSendAgeLoadedMsg, false );
            plAgeLoader::GetInstance()->NotifyAgeLoaded( true );
        }

        if ( GetFlagsBit( kNeedToSendInitialAgeStateLoadedMsg ) )
        {
            SetFlagsBit(kNeedToSendInitialAgeStateLoadedMsg, false);
            plInitialAgeStateLoadedMsg* m = new plInitialAgeStateLoadedMsg;
            m->Send();
        }

        return true;
    }

    plGenRefMsg* ref = plGenRefMsg::ConvertNoRef(msg);
    if (ref)
    {
        if( ref->fType == kVaultImage )
        {
            // Ignore, we just use it for reffing, don't care about the actual pointer
            return true;
        }

        hsAssert(ref->fType==kAgeSDLHook, "unknown ref msg context");
        if (ref->GetContext()==plRefMsg::kOnCreate)
        {
            hsAssert(fAgeSDLObjectKey==nil, "already have a ref to age sdl hook");
            fAgeSDLObjectKey = ref->GetRef()->GetKey();
            DebugMsg("Age SDL hook object created, uoid=%s", fAgeSDLObjectKey->GetUoid().StringIze().c_str());
        }
        else
        {
            fAgeSDLObjectKey=nil;
            DebugMsg("Age SDL hook object destroyed");
        }
        return true;
    }

    if (plNetClientMgrMsg * ncmMsg = plNetClientMgrMsg::ConvertNoRef(msg)) {
        if (ncmMsg->type == plNetClientMgrMsg::kCmdDisableNet) {
            SetFlagsBit(kDisableOnNextUpdate);
            hsRefCnt_SafeUnRef(fDisableMsg);
            fDisableMsg = ncmMsg;
            fDisableMsg->Ref();
        }
        return true;
    }
    
    if (plNetCommAuthMsg * authMsg = plNetCommAuthMsg::ConvertNoRef(msg)) {
        if (IS_NET_ERROR(authMsg->result)) {
            char str[256];
            StrPrintf(str, arrsize(str), "Authentication failed: %S", NetErrorToString(authMsg->result));
            QueueDisableNet(true, str);
            return false;   // @@@ TODO: Handle this failure better
        }

        return true;
    }

    if (plNetCommActivePlayerMsg * activePlrMsg = plNetCommActivePlayerMsg::ConvertNoRef(msg)) {
        if (IS_NET_ERROR(activePlrMsg->result)) {
            char str[256];
            StrPrintf(str, arrsize(str), "SetActivePlayer failed: %S", NetErrorToString(activePlrMsg->result));
            QueueDisableNet(true, str);
            return false;   // @@@ TODO: Handle this failure better.
        }
            
        return true;
    }

    plPlayerPageMsg *playerPageMsg = plPlayerPageMsg::ConvertNoRef(msg);
    if(playerPageMsg)
    {
        IHandlePlayerPageMsg(playerPageMsg);
        return true;    // handled
    }

    plLoadCloneMsg* pCloneMsg = plLoadCloneMsg::ConvertNoRef(msg);
    if(pCloneMsg)
    {
        ILoadClone(pCloneMsg);
        return true;    // handled
    }

    // player is petitioning a CCR
    plCCRPetitionMsg* petMsg=plCCRPetitionMsg::ConvertNoRef(msg);
    if (petMsg)
    {
        ISendCCRPetition(petMsg);
        return true;
    }

    // a remote CCR is turning invisible
    plCCRInvisibleMsg* invisMsg=plCCRInvisibleMsg::ConvertNoRef(msg);
    if (invisMsg)
    {
        LogMsg(kLogDebug, "plNetClientMgr::MsgReceive - Got plCCRInvisibleMsg");
        MakeCCRInvisible(invisMsg->fAvKey, invisMsg->fInvisLevel);
        return true;
    }
    
    plCCRBanLinkingMsg* banLinking = plCCRBanLinkingMsg::ConvertNoRef(msg);
    if (banLinking)
    {
        DebugMsg("Setting BanLinking to %d", banLinking->fBan);
        SetFlagsBit(kBanLinking, banLinking->fBan);
        return true;
    }

    plCCRSilencePlayerMsg* silence = plCCRSilencePlayerMsg::ConvertNoRef(msg);
    if (silence)
    {
        DebugMsg("Setting Silence to %d", silence->fSilence);
        SetFlagsBit(kSilencePlayer, silence->fSilence);
        return true;
    }

    plNetVoiceListMsg* voxList = plNetVoiceListMsg::ConvertNoRef(msg);
    if (voxList)
    {
        IHandleNetVoiceListMsg(voxList);
        return true;
    }

    plSynchEnableMsg* synchEnable = plSynchEnableMsg::ConvertNoRef(msg);
    if (synchEnable)
    {
        if (synchEnable->fPush)
        {
            plSynchedObject::PushSynchDisabled(!synchEnable->fEnable);
        }
        else
        {
            plSynchedObject::PopSynchDisabled();
        }
        return true;
    }

    plClientMsg* clientMsg = plClientMsg::ConvertNoRef(msg);
    if (clientMsg && clientMsg->GetClientMsgFlag()==plClientMsg::kInitComplete)
    {
        // add 1 debug object for age sdl
        if (plNetObjectDebugger::GetInstance())
        {
            plNetObjectDebugger::GetInstance()->RemoveDebugObject("AgeSDLHook");    
            plNetObjectDebugger::GetInstance()->AddDebugObject("AgeSDLHook");
        }

        // if we're linking to startup we don't need (or want) a player set
        plString ageName = NetCommGetStartupAge()->ageDatasetName;
        if (ageName.IsEmpty())
            ageName = "StartUp";
        if (ageName.CompareI("StartUp") == 0)
            NetCommSetActivePlayer(0, nullptr);

        plAgeLinkStruct link;
        link.GetAgeInfo()->SetAgeFilename(NetCommGetStartupAge()->ageDatasetName);
        link.SetLinkingRules(plNetCommon::LinkingRules::kOriginalBook);
        plNetLinkingMgr::GetInstance()->LinkToAge(&link);

        return true;
    }
    
    return plNetClientApp::MsgReceive(msg);
}
Example #17
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( "Path is not absolute!" ) );

    std::unique_ptr<wxSingleInstanceChecker> lockFile = ::LockFile( fullFileName );

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

    if( GetScreen()->IsModify() && !GetBoard()->IsEmpty() )
    {
        if( !HandleUnsavedChanges( this, _( "The current PCB has been modified.  Save changes?" ),
            [&]()->bool { return SavePcbFile( GetBoard()->GetFileName(), CREATE_BACKUP_FILE ); } ) )
        {
            return false;
        }
    }

    // Release the lock file, until the new file is actually loaded
    ReleaseFile();

    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( _( "PCB \"%s\" does not exist.  Do you wish to create it?" ),
                                         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_SEXP;

    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 ) );

        // This will rename the file if there is an autosave and the user want to recover
		CheckForAutoSaveFile( fullFileName );

        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 )
        {
            if( ioe.Problem() != wxT( "CANCEL" ) )
            {
                wxString msg = wxString::Format( _( "Error loading board file:\n%s" ), fullFileName );
                DisplayErrorMessage( this, msg, ioe.What() );
            }

            return false;
        }


        // 6.0 TODO: some settings didn't make it into the board file in 5.1 so as not to
        // change the file format.  For 5.1 we must copy them across from the config-initialized
        // board.
        BOARD_DESIGN_SETTINGS& bds = loadedBoard->m_designSettings;
        BOARD_DESIGN_SETTINGS& configBds = GetBoard()->GetDesignSettings();

        bds.m_RequireCourtyards                 = configBds.m_RequireCourtyards;
        bds.m_ProhibitOverlappingCourtyards     = configBds.m_ProhibitOverlappingCourtyards;
        bds.m_HoleToHoleMin                     = configBds.m_HoleToHoleMin;
        bds.m_LineThickness[LAYER_CLASS_OTHERS] = configBds.m_LineThickness[LAYER_CLASS_OTHERS];
        bds.m_TextSize[LAYER_CLASS_OTHERS]      = configBds.m_TextSize[LAYER_CLASS_OTHERS];
        bds.m_TextThickness[LAYER_CLASS_OTHERS] = configBds.m_TextThickness[LAYER_CLASS_OTHERS];
        std::copy( configBds.m_TextItalic,  configBds.m_TextItalic + 4,  bds.m_TextItalic );
        std::copy( configBds.m_TextUpright, configBds.m_TextUpright + 4, bds.m_TextUpright );
        bds.m_DiffPairDimensionsList            = configBds.m_DiffPairDimensionsList;
        bds.m_CopperEdgeClearance               = configBds.m_CopperEdgeClearance;

        SetBoard( loadedBoard );

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

        // If this is a legacy board then we set the copper edge clearance to 1/2 the edge-cut
        // line width (which was a legacy kludge for implementing edge clearances).
        if( bds.m_CopperEdgeClearance == Millimeter2iu( LEGACY_COPPEREDGECLEARANCE ) )
            bds.SetCopperEdgeClearance( inferLegacyEdgeClearance( loadedBoard ) );

        if( loadedBoard->IsModified() )
            OnModify();
        else
            GetScreen()->ClrModify();

        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 );
    }

    // Lock the file newly opened:
    m_file_checker.reset( lockFile.release() );

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

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

    // Select netclass Default as current netclass (it always exists)
    SetCurrentNetClass( NETCLASS::Default );

    // Rebuild list of nets (full ratsnest rebuild)
    Compile_Ratsnest( NULL, true );
    GetBoard()->BuildConnectivity();

    onBoardLoaded();

    // Refresh the 3D view, if any
    EDA_3D_VIEWER* 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;
}
Example #18
0
bool TcpComm::Open
(
    /** Specifies the host and port. The host can be a hostname or a dotted
        IP address. The port (optional) is specified with a colon and may be
        numeric of the name of a service.                                   */
    const char *openStr
)
{
    DWORD   err;
    char    errStr[ 200 ];

    // Initialize 

    if ( !m_initialized )
    {
        WSADATA  wsaData;

        if (( err = WSAStartup( 0x0202, &wsaData )) != 0  )
        {
            LOG_ERROR( "Error initializing Windows Sockets: " << GetErrorStr( err, errStr, sizeof( errStr )));
            return false;
        }
        m_initialized = true;
    }

    char   *endPtr;

    // Extract the hostname and portname.

    char    token[ 200 ];

    char *hostName = NULL;

    // NextToken parses skips leading delimiters

    if ( *openStr == ':' )
    {
        hostName = "";
        openStr++;
    }

    // If it's all digits, then assume it's a port number

    if ( strspn( openStr, "0123456789" ) == strlen( openStr ))
    {
        hostName = "";
    }

    StrTokenizer    tokenizer( openStr, token, sizeof( token ));

    if ( hostName == NULL )
    {
        hostName = tokenizer.NextToken( ":" );
    }

    if ( hostName == NULL )
    {
        if ( m_mode == TcpComm::Server )
        {
            hostName = "";
        }
        else
        {
            LOG_ERROR( "No hostname specified" );
            return false;
        }
    }

    if ( *hostName == '\0' )
    {
        m_sockAddr.sin_addr.S_un.S_addr = htonl( INADDR_ANY );
    }
    else
    {
        // Check to see if the servername is only made up of numbers and dots.

        if ( strspn( hostName, ".0123456789" ) == strlen( hostName ))
        {
            int   seg;
            char *segStr  = hostName;
            char *endPtr;

            // The hostname is only made up of numbers and dots. We'll parse
            // it ourselves.
            //
            // We expect it to be of the form a.b.c.d, where a, b, c, and d are
            // all positive integers in the range 0 thru 255.

            for ( seg = 0; seg < 4; seg++ ) 
            {
                long  longByte = strtol( segStr, &endPtr, 10 );

                if (( longByte < 0 ) || ( longByte > 255 ))
                {
                    LOG_ERROR( "Expecting a positive number between 0 and 255, found: '" << segStr << "'" );
                    return false;
                }
                if (( endPtr == segStr )
                ||  (( *endPtr == '.' ) && ( seg == 3 ))
                ||  (( *endPtr != '.' ) && ( seg <  3 ))) 
                {
                    LOG_ERROR( "Expecting IP address of the form a.b.c.d, found: '" << hostName << "'" );
                    return false;
                }

                m_sockAddr.sin_addr.S_un.S_addr <<= 8; 
				m_sockAddr.sin_addr.S_un.S_addr += (unsigned char)longByte;

                segStr = endPtr + 1;
            }
			m_sockAddr.sin_addr.S_un.S_addr = htonl( m_sockAddr.sin_addr.S_un.S_addr );
        }
        else
        {
            // The server name was specified symbolically, see if we can translate it

            struct hostent      *hostent;

            hostent = gethostbyname( hostName );
            if ( hostent == NULL )
            {
                LOG_ERROR( "Unable to translate hostname '" << hostName << "' into an IP address." );
                return false;
            }
            m_sockAddr.sin_addr.S_un.S_addr = *((long *)hostent->h_addr_list[ 0 ]);
        }
    }

    // Now parse the port (if present)

    const char *portStr = tokenizer.Remainder();

    if ( *portStr == '\0' )
    {
        // No port specified

        m_sockAddr.sin_port = htons( m_defaultPort );
    }
    else
    {
		long	longPort;

        if ( strspn( portStr, "0123456789" ) == strlen( portStr ))
        {
            // The port string is all numeric

            longPort = strtol( portStr, &endPtr, 0 );
            if ( *endPtr != '\0' )
            {
                LOG_ERROR( "Expecting a positive numeric port specifier; Found '" << portStr << "'." );
                return false;
            }
        }
        else
        {
            struct servent *servent;

            servent = getservbyname( portStr, "tcp" );
            if ( servent == NULL )
            {
                LOG_ERROR( "Unable to translate service '" << portStr << "' into a port number." );
                return false;
            }
            longPort = ntohs( servent->s_port );
        }

        if (( longPort <= 0 ) || ( longPort > 65535 ))
        {
            LOG_ERROR( "Expecting port to be between 1 and 65535; Found: " << longPort );
            return false;
        }
        m_sockAddr.sin_port = htons( (short)longPort );
    }
    m_sockAddr.sin_family = AF_INET;

    // We now have an IP address and port number

    // Open a socket

    m_socket = socket( AF_INET, SOCK_STREAM, 0 );
    if ( m_socket == INVALID_SOCKET )
    {
        err = WSAGetLastError();
        LOG_ERROR( "Error calling socket: " << GetErrorStr( err, errStr, sizeof( errStr )));
        return false;
    }

    if ( m_mode == Server )
    {
        // Bind the address to the socket

        if ( bind( m_socket, (struct sockaddr *)&m_sockAddr, sizeof( m_sockAddr )) != 0 )
        {
            err = WSAGetLastError();
            LOG_ERROR( "Error calling bind: " << GetErrorStr( err, errStr, sizeof( errStr )));
            return false;
        }

        // Wait for an incoming connection

        LOG_INFO( "Waiting for incoming TCP/IP connection on port " << ntohs( m_sockAddr.sin_port ) << " ..." );

        int listenSocket = m_socket;

        if ( listen( listenSocket, 1 ) != 0 )
        {
            err = WSAGetLastError();
            LOG_ERROR( "Error calling listen: " << GetErrorStr( err, errStr, sizeof( errStr )));
            return false;
        }

        int addrLen = sizeof( m_remAddr );

        memset( &m_remAddr, 0, sizeof( m_remAddr ));

        m_socket = accept( listenSocket, (struct sockaddr *)&m_remAddr, &addrLen );
        closesocket( listenSocket );

        if ( m_socket == INVALID_SOCKET )
        {
            err = WSAGetLastError();
            LOG_ERROR( "Error calling accept: " << GetErrorStr( err, errStr, sizeof( errStr )));
            return false;
        }

        StrPrintf( m_connectionInfo, sizeof( m_connectionInfo ),
                   "%d.%d.%d.%d:%d",
                   m_remAddr.sin_addr.S_un.S_un_b.s_b1,
                   m_remAddr.sin_addr.S_un.S_un_b.s_b2,
                   m_remAddr.sin_addr.S_un.S_un_b.s_b3,
                   m_remAddr.sin_addr.S_un.S_un_b.s_b4,
                   ntohs( m_remAddr.sin_port ));
        
        LOG_INFO( "Connection received from " << m_connectionInfo
               << " on port " << ntohs( m_sockAddr.sin_port ));
    }
    else
    {
        // Connect to the server

        if ( connect( m_socket, (struct sockaddr *)&m_sockAddr, sizeof( m_sockAddr )) != 0 )
        {
            err = WSAGetLastError();
            LOG_ERROR( "Error calling connect: " << GetErrorStr( err, errStr, sizeof( errStr )));
            return false;
        }

        StrPrintf( m_connectionInfo, sizeof( m_connectionInfo ),
                   "%s (%d.%d.%d.%d:%d)", openStr,
                   m_sockAddr.sin_addr.S_un.S_un_b.s_b1,
                   m_sockAddr.sin_addr.S_un.S_un_b.s_b2,
                   m_sockAddr.sin_addr.S_un.S_un_b.s_b3,
                   m_sockAddr.sin_addr.S_un.S_un_b.s_b4,
                   ntohs( m_sockAddr.sin_port ));

        LOG_INFO( "Connected to " << m_connectionInfo );
    }

    // Create an event which will be signalled when new data arrives

    m_abortEvent = CreateEvent( NULL,   // lpEventAttributes
                                FALSE,  // bManualReset
                                FALSE,  // bInitialState
                                NULL ); // lpName
    
    m_readEvent  = CreateEvent( NULL,   // lpEventAttributes
                                FALSE,  // bManualReset
                                FALSE,  // bInitialState
                                NULL ); // lpName

    // Set things up so the event gets signalled when new data arrives

    if ( WSAEventSelect( m_socket, m_readEvent, FD_READ | FD_CLOSE ) != 0 )
    {
        err = WSAGetLastError();
        LOG_ERROR( "Error calling WSAEventSelect: " << GetErrorStr( err, errStr, sizeof( errStr )));
        return false;
    }

    m_name = openStr;

    return true;
}
Example #19
0
bool SCH_EDIT_FRAME::OpenProjectFiles( const std::vector<wxString>& aFileSet, int aCtl )
{
    // implement the pseudo code from KIWAY_PLAYER.h:

    SCH_SCREENS screenList;

    // This is for python:
    if( aFileSet.size() != 1 )
    {
        UTF8 msg = StrPrintf( "Eeschema:%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( _(
                "Schematic file '%s' is already open." ),
                GetChars( fullFileName )
                );
        DisplayError( this, msg );
        return false;
    }

    // save any currently open and modified project files.
    for( SCH_SCREEN* screen = screenList.GetFirst(); screen; screen = screenList.GetNext() )
    {
        if( screen->IsModify() )
        {
            int response = YesNoCancelDialog( this, _(
                "The current schematic 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 )
            {
                wxCommandEvent dummy;
                OnSaveProject( dummy );
            }
            else
            {
                // response == wxID_NO, fall thru
            }
            break;
        }
    }

    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( _(
                "Schematic '%s' does not exist.  Do you wish to create it?" ),
                GetChars( fullFileName )
                );
        if( !IsOK( this, ask ) )
            return false;
    }

    // unload current project file before loading new
    {
        delete g_RootSheet;
        g_RootSheet = NULL;

        CreateScreens();
    }

    GetScreen()->SetFileName( fullFileName );
    g_RootSheet->SetFileName( fullFileName );

    SetStatusText( wxEmptyString );
    ClearMsgPanel();

    wxString msg = wxString::Format( _(
            "Ready\nProject dir: '%s'\n" ),
            GetChars( wxPathOnly( Prj().GetProjectFullName() ) )
            );
    SetStatusText( msg );

    // 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() );

    LoadProjectFile();

    // load the libraries here, not in SCH_SCREEN::Draw() which is a context
    // that will not tolerate DisplayError() dialog since we're already in an
    // event handler in there.
    // And when a schematic file is loaded, we need these libs to initialize
    // some parameters (links to PART LIB, dangling ends ...)
    Prj().SchLibs();

    if( is_new )
    {
        // mark new, unsaved file as modified.
        GetScreen()->SetModify();
    }
    else
    {
        g_RootSheet->SetScreen( NULL );

        DBG( printf( "%s: loading schematic %s\n", __func__, TO_UTF8( fullFileName ) );)

        bool diag = g_RootSheet->Load( this );
        (void) diag;

        SetScreen( m_CurrentSheet->LastScreen() );

        GetScreen()->ClrModify();

        UpdateFileHistory( fullFileName );
    }
Example #20
0
void VaultTextNoteNode::SetVisitInfo (const plAgeInfoStruct & info) {
    
    ARRAY(wchar_t) buf;
    
    for (unsigned i = 0; i < kNumAgeInfoFields; ++i) {
        switch (i) {
            case kAgeFilename: {
                wchar_t src[128];
                StrToUnicode(src, info.GetAgeFilename(), arrsize(src));
                unsigned len = StrLen(src);
                wchar_t * dst = buf.New(len);
                memcpy(dst, src, len * sizeof(src[0]));
            }
            break;
            
            case kAgeInstName: {
                wchar_t src[128];
                StrToUnicode(src, info.GetAgeInstanceName(), arrsize(src));
                unsigned len = StrLen(src);
                wchar_t * dst = buf.New(len);
                memcpy(dst, src, len * sizeof(src[0]));
            }
            break;
            
            case kAgeUserName: {
                wchar_t src[128];
                StrToUnicode(src, info.GetAgeUserDefinedName(), arrsize(src));
                unsigned len = StrLen(src);
                wchar_t * dst = buf.New(len);
                memcpy(dst, src, len * sizeof(src[0]));
            }
            break;
            
            case kAgeDesc: {
                wchar_t src[128];
                StrToUnicode(src, info.GetAgeDescription(), arrsize(src));
                unsigned len = StrLen(src);
                wchar_t * dst = buf.New(len);
                memcpy(dst, src, len * sizeof(src[0]));
            }
            break;
            
            case kAgeInstGuid: {
                plUUID guid = *info.GetAgeInstanceGuid();
                wchar_t src[64];
                wcsncpy(src, guid.AsString().ToWchar(), 64);
                unsigned len = StrLen(src);
                wchar_t * dst = buf.New(len);
                memcpy(dst, src, len * sizeof(src[0]));
            }
            break;
            
            case kAgeLanguage: {
                wchar_t src[32];
                StrPrintf(src, arrsize(src), L"%u", info.GetAgeLanguage());
                unsigned len = StrLen(src);
                wchar_t * dst = buf.New(len);
                memcpy(dst, src, len * sizeof(src[0]));
            }
            break;
            
            case kAgeSequence: {
                wchar_t src[32];
                StrPrintf(src, arrsize(src), L"%u", info.GetAgeSequenceNumber());
                unsigned len = StrLen(src);
                wchar_t * dst = buf.New(len);
                memcpy(dst, src, len * sizeof(src[0]));
            }
            break;

            DEFAULT_FATAL(i);
        }
        
        wchar_t * sep = buf.New(1);
        *sep = L'|';            
    }
    
    wchar_t * term = buf.New(1);
    *term = 0;
    
    SetNoteText(buf.Ptr());
}
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
    if( m_Draw3DFrame )
        m_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;
}
Example #22
0
int LabelManager::OnGetRevID(LPTSTR buffer)
{
    // This is the string displayed in Litestep's about box
    StrPrintf(buffer, MAX_REVID, "%s %s", MODULE_NAME, MODULE_VERSION);
    return StrLen(buffer);
}
Example #23
0
//============================================================================
void plNCAgeJoiner::ExecNextOp () {
    plNetClientMgr *    nc = plNetClientMgr::GetInstance();
    plAvatarMgr *       am = plAvatarMgr::GetInstance();
    plAgeLoader *       al = plAgeLoader::GetInstance();

    NextOp next = nextOp;
    nextOp      = kNoOp;
    switch (next) {
        //====================================================================
        case kNoOp: {
        }
        break;
            
        //====================================================================
        case kLoadAge: {
            LogMsg(kLogPerf, L"AgeJoiner: Exec:kLoadAge");

            // Start progress bar
            char str[256];
        #ifdef PLASMA_EXTERNAL_RELEASE
            StrCopy(str, "Loading age...", arrsize(str));
        #else
            StrPrintf(str, arrsize(str), "Loading age %s...", age.ageDatasetName);
        #endif
            progressBar = plProgressMgr::GetInstance()->RegisterOperation(0, str, plProgressMgr::kNone, false, true);
            plDispatch::SetMsgRecieveCallback(IDispatchMsgReceiveCallback);
            ((plResManager*)hsgResMgr::ResMgr())->SetProgressBarProc(IResMgrProgressBarCallback);

            // Start loading age data
            al->LoadAge(age.ageDatasetName);
        }
        break;

        //====================================================================
        case kLoadPlayer: {
            LogMsg(kLogPerf, L"AgeJoiner: Exec:kLoadPlayer");
            // Start loading local player
            const char * avatarName;
            if (NetCommNeedToLoadAvatar()) {
                if (nc->GetFlagsBit(plNetClientApp::kLinkingToOfflineAge))
                    avatarName = "Male";
                else
                    avatarName = NetCommGetPlayer()->avatarDatasetName;
                plString linkInName = plNetLinkingMgr::GetInstance()->GetAgeLink()->SpawnPoint().GetName();
                am->LoadPlayer( avatarName, nil, linkInName.c_str() );
            }
            else {
                LogMsg(kLogPerf, L"AgeJoiner: Next:kPropagatePlayer");
                nextOp = kPropagatePlayer;
            }
        }
        break;

        //====================================================================
        case kPropagatePlayer: {
            LogMsg(kLogPerf, L"AgeJoiner: Exec:kPropagatePlayer");
            // Add our avatar to the scene
            int spawnPt = am->FindSpawnPoint(age.spawnPtName);
            nc->IPlayerChangeAge(false /*not exiting*/, spawnPt);

            if (!nc->GetFlagsBit(plNetClientApp::kLinkingToOfflineAge))
                // Add our avatar to the game state
                am->PropagateLocalPlayer(spawnPt);
            
            LogMsg(kLogPerf, L"AgeJoiner: Next:kRequestAgeState");
            nextOp = kRequestAgeState;
        }
        break;

        //============================================================================
        case kRequestAgeState: {
            LogMsg(kLogPerf, L"AgeJoiner: Exec:kRequestAgeState");
            if (nc->GetFlagsBit(plNetClientApp::kLinkingToOfflineAge)) {
                LogMsg(kLogPerf, L"AgeJoiner: Next:kSimStateRcvd");
                nextOp = kSimStateRcvd;
            }
            else {
                // Request age player list
                nc->ISendMembersListRequest();

                // Request initial SDL state
                plNetMsgGameStateRequest gsmsg;
                gsmsg.SetNetProtocol(kNetProtocolCli2Game);
                gsmsg.SetBit(plNetMessage::kInitialAgeStateRequest);
                nc->SendMsg(&gsmsg);
                
                // Send our avatar settings
                nc->SendLocalPlayerAvatarCustomizations();
            }
        }
        break;

        //====================================================================
        case kSimStateRcvd: {
            nc->NotifyRcvdAllSDLStates();
        }
        break;

        //============================================================================
        case kDestroyProgressBar: {
            plDispatch::SetMsgRecieveCallback(nil);
            ((plResManager*)hsgResMgr::ResMgr())->SetProgressBarProc(nil);
            delete progressBar;
            progressBar = nil;
            nc->EndTask();

            nextOp = kEnableClickables;
        }
        break;

        //====================================================================
        case kEnableClickables: {
            LogMsg(kLogPerf, L"AgeJoiner: Exec:kEnableClickables");
            // Enable scene clickables
            (void)(new plInputIfaceMgrMsg(plInputIfaceMgrMsg::kEnableClickables))->Send();

            LogMsg(kLogPerf, L"AgeJoiner: Next:kNotifyAgeLoaded");
            nextOp = kNotifyAgeLoaded;
        }
        break;
        
        //====================================================================
        case kNotifyAgeLoaded: {
            LogMsg(kLogPerf, L"AgeJoiner: Exec:kNotifyAgeLoaded");
            nc->SetFlagsBit(plNetClientApp::kPlayingGame);
            nc->SetFlagsBit(plNetClientApp::kNeedToSendInitialAgeStateLoadedMsg);
            plAgeLoader::GetInstance()->NotifyAgeLoaded(true);
            nextOp = kNoOp;
        }
        break;

        DEFAULT_FATAL(nextOp);
    }
}