diff --git a/3d-viewer/3d_aux.cpp b/3d-viewer/3d_aux.cpp index 0878053869..a8ccab2b8d 100644 --- a/3d-viewer/3d_aux.cpp +++ b/3d-viewer/3d_aux.cpp @@ -45,16 +45,11 @@ #include #include -// Exported function: -void Set_Object_Data( std::vector< S3D_VERTEX >& aVertices, double aBiuTo3DUnits ); - -void S3D_MASTER::Set_Object_Coords( std::vector< S3D_VERTEX >& aVertices ) +void S3D_MASTER::ObjectCoordsTo3DUnits( std::vector< S3D_VERTEX >& aVertices ) { - unsigned ii; - /* adjust object scale, rotation and offset position */ - for( ii = 0; ii < aVertices.size(); ii++ ) + for( unsigned ii = 0; ii < aVertices.size(); ii++ ) { aVertices[ii].x *= m_MatScale.x; aVertices[ii].y *= m_MatScale.y; @@ -79,7 +74,7 @@ void S3D_MASTER::Set_Object_Coords( std::vector< S3D_VERTEX >& aVertices ) } -void Set_Object_Data( std::vector< S3D_VERTEX >& aVertices, double aBiuTo3DUnits ) +void TransfertToGLlist( std::vector< S3D_VERTEX >& aVertices, double aBiuTo3DUnits ) { unsigned ii; GLfloat ax, ay, az, bx, by, bz, nx, ny, nz, r; @@ -138,44 +133,6 @@ void Set_Object_Data( std::vector< S3D_VERTEX >& aVertices, double aBiuTo3DUnits glEnd(); } - -GLuint EDA_3D_CANVAS::DisplayCubeforTest() -{ - GLuint gllist = glGenLists( 1 ); - - glNewList( gllist, GL_COMPILE_AND_EXECUTE ); - /* draw six faces of a cube */ - glBegin( GL_QUADS ); - glNormal3f( 0.0F, 0.0F, 1.0F ); - glVertex3f( 0.5F, 0.5F, 0.5F ); glVertex3f( -0.5F, 0.5F, 0.5F ); - glVertex3f( -0.5F, -0.5F, 0.5F ); glVertex3f( 0.5F, -0.5F, 0.5F ); - - glNormal3f( 0.0F, 0.0F, -1.0F ); - glVertex3f( -0.5F, -0.5F, -0.5F ); glVertex3f( -0.5F, 0.5F, -0.5F ); - glVertex3f( 0.5F, 0.5F, -0.5F ); glVertex3f( 0.5F, -0.5F, -0.5F ); - - glNormal3f( 0.0F, 1.0F, 0.0F ); - glVertex3f( 0.5F, 0.5F, 0.5F ); glVertex3f( 0.5F, 0.5F, -0.5F ); - glVertex3f( -0.5F, 0.5F, -0.5F ); glVertex3f( -0.5F, 0.5F, 0.5F ); - - glNormal3f( 0.0F, -1.0F, 0.0F ); - glVertex3f( -0.5F, -0.5F, -0.5F ); glVertex3f( 0.5F, -0.5F, -0.5F ); - glVertex3f( 0.5F, -0.5F, 0.5F ); glVertex3f( -0.5F, -0.5F, 0.5F ); - - glNormal3f( 1.0F, 0.0F, 0.0F ); - glVertex3f( 0.5F, 0.5F, 0.5F ); glVertex3f( 0.5F, -0.5F, 0.5F ); - glVertex3f( 0.5F, -0.5F, -0.5F ); glVertex3f( 0.5F, 0.5F, -0.5F ); - - glNormal3f( -1.0F, 0.0F, 0.0F ); - glVertex3f( -0.5F, -0.5F, -0.5F ); glVertex3f( -0.5F, -0.5F, 0.5F ); - glVertex3f( -0.5F, 0.5F, 0.5F ); glVertex3f( -0.5F, 0.5F, -0.5F ); - glEnd(); - - glEndList(); - - return gllist; -} - VERTEX_VALUE_CTRL::VERTEX_VALUE_CTRL( wxWindow* aParent, wxBoxSizer* aBoxSizer ) { wxString text; diff --git a/3d-viewer/3d_canvas.cpp b/3d-viewer/3d_canvas.cpp index 1764d6faa0..db1ace2851 100644 --- a/3d-viewer/3d_canvas.cpp +++ b/3d-viewer/3d_canvas.cpp @@ -78,7 +78,11 @@ EDA_3D_CANVAS::EDA_3D_CANVAS( EDA_3D_FRAME* parent, int* attribList ) : wxFULL_REPAINT_ON_RESIZE ) { m_init = false; - m_gllist = 0; + + // Clear all gl list identifiers: + for( int ii = GL_ID_BEGIN; ii < GL_ID_END; ii++ ) + m_glLists[ii] = 0; + // Explicitly create a new rendering context instance for this canvas. m_glRC = new wxGLContext( this ); @@ -94,12 +98,25 @@ EDA_3D_CANVAS::~EDA_3D_CANVAS() } -void EDA_3D_CANVAS::ClearLists() +void EDA_3D_CANVAS::ClearLists( GLuint aGlList ) { - if( m_gllist > 0 ) - glDeleteLists( m_gllist, 1 ); + if( aGlList ) + { + if( m_glLists[aGlList] > 0 ) + glDeleteLists( m_glLists[aGlList], 1 ); - m_gllist = 0; + m_glLists[aGlList] = 0; + + return; + } + + for( int ii = GL_ID_BEGIN; ii < GL_ID_END; ii++ ) + { + if( m_glLists[ii] > 0 ) + glDeleteLists( m_glLists[ii], 1 ); + + m_glLists[ii] = 0; + } } diff --git a/3d-viewer/3d_canvas.h b/3d-viewer/3d_canvas.h index cb931c991f..43a1f7ed85 100644 --- a/3d-viewer/3d_canvas.h +++ b/3d-viewer/3d_canvas.h @@ -50,14 +50,29 @@ class S3D_VERTEX; class SEGVIA; class D_PAD; +// We are using GL lists to store layers and other items +// to draw or not +// GL_LIST_ID are the GL lists indexes in m_glLists +enum GL_LIST_ID +{ + GL_ID_BEGIN = 0, + GL_ID_AXIS = GL_ID_BEGIN, // list id for 3D axis + GL_ID_GRID, // list id for 3D grid + GL_ID_BOARD, // List id for copper layers + GL_ID_TECH_LAYERS, // List id for non copper layers (masks...) + GL_ID_AUX_LAYERS, // List id for user layers (draw, eco, comment) + GL_ID_3DSHAPES_SOLID, // List id for 3D shapes, non transparent entities + GL_ID_3DSHAPES_TRANSP, // List id for 3D shapes, transparent entities + GL_ID_END +}; class EDA_3D_CANVAS : public wxGLCanvas { private: bool m_init; - GLuint m_gllist; + GLuint m_glLists[GL_ID_END]; // GL lists wxGLContext* m_glRC; - wxRealPoint m_draw3dOffset; // offset to draw the 3 mesh. + wxRealPoint m_draw3dOffset; // offset to draw the 3D mesh. double m_ZBottom; // position of the back layer double m_ZTop; // position of the front layer @@ -67,7 +82,15 @@ public: EDA_3D_FRAME* Parent() { return (EDA_3D_FRAME*)GetParent(); } - void ClearLists(); + BOARD* GetBoard() { return Parent()->GetBoard(); } + + /** + * Function ClearLists + * Clear the display list. + * @param aGlList = the list to clear. + * if 0 (default) all lists are cleared + */ + void ClearLists( GLuint aGlList = 0 ); // Event functions: void OnPaint( wxPaintEvent& event ); @@ -81,7 +104,6 @@ public: void OnEnterWindow( wxMouseEvent& event ); // Display functions - GLuint DisplayCubeforTest(); // Just a test function void SetView3D( int keycode ); void DisplayStatus(); void Redraw(); @@ -92,7 +114,7 @@ public: * Prepares the parameters of the OpenGL draw list * creates the OpenGL draw list items (board, grid ... */ - GLuint CreateDrawGL_List(); + void CreateDrawGL_List(); void InitGL(); void SetLights(); void SetOffset(double aPosX, double aPosY) @@ -104,11 +126,40 @@ public: /** * Function BuildBoard3DView * Called by CreateDrawGL_List() - * Fills the OpenGL draw list with board items draw list. + * Populates the OpenGL GL_ID_BOARD draw list with board items only on copper layers. + * 3D footprint shapes, tech layers and aux layers are not on this list */ void BuildBoard3DView(); - void DrawGrid( double aGriSizeMM ); + /** + * Function BuildTechLayers3DView + * Called by CreateDrawGL_List() + * Populates the OpenGL GL_ID_BOARD draw list with items on tech layers + */ + void BuildTechLayers3DView(); + + /** + * Function BuildFootprintShape3DList + * Called by CreateDrawGL_List() + * Fills the OpenGL GL_ID_3DSHAPES_SOLID and GL_ID_3DSHAPES_TRANSP + * draw lists with 3D footprint shapes + * @param aOpaqueList is the gl list for non transparent items + * @param aTransparentList is the gl list for non transparent items, + * which need to be drawn after all other items + */ + void BuildFootprintShape3DList( GLuint aOpaqueList, + GLuint aTransparentList); + /** + * Function BuildBoard3DAuxLayers + * Called by CreateDrawGL_List() + * Fills the OpenGL GL_ID_AUX_LAYERS draw list + * with items on aux layers only + */ + void BuildBoard3DAuxLayers(); + + void Draw3DGrid( double aGriSizeMM ); + void Draw3DAxis(); + void Draw3DViaHole( SEGVIA * aVia ); void Draw3DPadHole( D_PAD * aPad ); diff --git a/3d-viewer/3d_class.cpp b/3d-viewer/3d_class.cpp index 79ea755b2f..b364d23e5b 100644 --- a/3d-viewer/3d_class.cpp +++ b/3d-viewer/3d_class.cpp @@ -41,9 +41,14 @@ S3D_MATERIAL::S3D_MATERIAL( S3D_MASTER* father, const wxString& name ) : m_Name = name; } - void S3D_MATERIAL::SetMaterial() { + S3D_MASTER * s3dParent = (S3D_MASTER *) GetParent(); + s3dParent->SetLastTransparency( m_Transparency ); + + if( ! s3dParent->IsOpenGlAllowed() ) + return; + glColorMaterial( GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE ); glColor4f( m_DiffuseColor.x * m_AmbientIntensity, m_DiffuseColor.y * m_AmbientIntensity, @@ -56,6 +61,20 @@ void S3D_MATERIAL::SetMaterial() #endif } +bool S3D_MASTER::IsOpenGlAllowed() +{ + if( m_loadNonTransparentObjects ) // return true for non transparent objects only + { + if( m_lastTransparency == 0.0 ) + return true; + } + if( m_loadTransparentObjects ) // return true for transparent objects only + if( m_lastTransparency != 0.0 ) + return true; + + return false; +} + void S3D_MASTER::Insert( S3D_MATERIAL* aMaterial ) { @@ -79,6 +98,7 @@ S3D_MASTER::S3D_MASTER( EDA_ITEM* aParent ) : EDA_ITEM( aParent, NOT_USED ) { m_MatScale.x = m_MatScale.y = m_MatScale.z = 1.0; + m_lastTransparency = 0.0; m_3D_Drawings = NULL; m_Materials = NULL; m_ShapeType = FILE3D_NONE; diff --git a/3d-viewer/3d_draw.cpp b/3d-viewer/3d_draw.cpp index 909d15a4aa..1afdfe9c27 100644 --- a/3d-viewer/3d_draw.cpp +++ b/3d-viewer/3d_draw.cpp @@ -52,7 +52,8 @@ // Imported function: extern void CheckGLError(); -/* returns true if aLayer should be displayed, false otherwise +/* Helper function + * returns true if aLayer should be displayed, false otherwise */ static bool Is3DLayerEnabled( LAYER_NUM aLayer ); @@ -76,7 +77,7 @@ static void BuildPadShapeThickOutlineAsPolygon( D_PAD* aPad, { if( aPad->GetShape() == PAD_CIRCLE ) // Draw a ring { - TransformRingToPolygon( aCornerBuffer, aPad->ReturnShapePos(), + TransformRingToPolygon( aCornerBuffer, aPad->ShapePos(), aPad->GetSize().x / 2, aCircleToSegmentsCount, aWidth ); return; } @@ -133,11 +134,48 @@ void EDA_3D_CANVAS::Redraw() glRotatef( g_Parm_3D_Visu.m_Rot[1], 0.0, 1.0, 0.0 ); glRotatef( g_Parm_3D_Visu.m_Rot[2], 0.0, 0.0, 1.0 ); - if( m_gllist ) - glCallList( m_gllist ); - else + if( ! m_glLists[GL_ID_BOARD] || ! m_glLists[GL_ID_TECH_LAYERS] ) CreateDrawGL_List(); + if( g_Parm_3D_Visu.GetFlag( FL_AXIS ) && m_glLists[GL_ID_AXIS] ) + glCallList( m_glLists[GL_ID_AXIS] ); + + // move the board in order to draw it with its center at 0,0 3D coordinates + glTranslatef( -g_Parm_3D_Visu.m_BoardPos.x * g_Parm_3D_Visu.m_BiuTo3Dunits, + -g_Parm_3D_Visu.m_BoardPos.y * g_Parm_3D_Visu.m_BiuTo3Dunits, + 0.0F ); + + // draw all objects in lists + // transparent objects should be drawn after opaque objects + glCallList( m_glLists[GL_ID_BOARD] ); + glCallList( m_glLists[GL_ID_TECH_LAYERS] ); + + if( g_Parm_3D_Visu.GetFlag( FL_COMMENTS ) || g_Parm_3D_Visu.GetFlag( FL_COMMENTS ) ) + { + if( ! m_glLists[GL_ID_AUX_LAYERS] ) + CreateDrawGL_List(); + + glCallList( m_glLists[GL_ID_AUX_LAYERS] ); + } + + if( g_Parm_3D_Visu.GetFlag( FL_MODULE ) ) + { + if( ! m_glLists[GL_ID_3DSHAPES_SOLID] ) + CreateDrawGL_List(); + + glCallList( m_glLists[GL_ID_3DSHAPES_SOLID] ); + } + + // Grid uses transparency: draw it after all objects + if( g_Parm_3D_Visu.GetFlag( FL_GRID ) && m_glLists[GL_ID_GRID] ) + glCallList( m_glLists[GL_ID_GRID] ); + + // This list must be drawn last, because it contains the + // transparent gl objects, which should be drawn after all + // non transparent objects + if( g_Parm_3D_Visu.GetFlag( FL_MODULE ) && m_glLists[GL_ID_3DSHAPES_TRANSP] ) + glCallList( m_glLists[GL_ID_3DSHAPES_TRANSP] ); + SwapBuffers(); } @@ -198,8 +236,7 @@ static inline void SetGLTechLayersColor( LAYER_NUM aLayer ) void EDA_3D_CANVAS::BuildBoard3DView() { - PCB_BASE_FRAME* pcbframe = Parent()->Parent(); - BOARD* pcb = pcbframe->GetBoard(); + BOARD* pcb = GetBoard(); bool realistic_mode = g_Parm_3D_Visu.IsRealisticMode(); // Number of segments to draw a circle using segments @@ -323,7 +360,7 @@ void EDA_3D_CANVAS::BuildBoard3DView() } } - // draw graphic items + // draw graphic items on copper layers (texts) for( BOARD_ITEM* item = pcb->m_Drawings; item; item = item->Next() ) { if( !item->IsOnLayer( layer ) ) @@ -331,11 +368,9 @@ void EDA_3D_CANVAS::BuildBoard3DView() switch( item->Type() ) { - case PCB_LINE_T: + case PCB_LINE_T: // should not exist on copper layers ( (DRAWSEGMENT*) item )->TransformShapeWithClearanceToPolygon( - bufferPolys, 0, - segcountforcircle, - correctionFactor ); + bufferPolys, 0, segcountforcircle, correctionFactor ); break; case PCB_TEXT_T: @@ -456,14 +491,78 @@ void EDA_3D_CANVAS::BuildBoard3DView() Draw3D_SolidHorizontalPolyPolygons( bufferPcbOutlines, zpos + board_thickness/2, board_thickness, g_Parm_3D_Visu.m_BiuTo3Dunits ); } +} + + +void EDA_3D_CANVAS::BuildTechLayers3DView() +{ + BOARD* pcb = GetBoard(); + + // Number of segments to draw a circle using segments + const int segcountforcircle = 16; + double correctionFactor = 1.0 / cos( M_PI / (segcountforcircle * 2) ); + const int segcountLowQuality = 12; // segments to draw a circle with low quality + // to reduce time calculations + // for holes and items which do not need + // a fine representation + + CPOLYGONS_LIST bufferPolys; + bufferPolys.reserve( 100000 ); // Reserve for large board + CPOLYGONS_LIST allLayerHoles; // Contains through holes, calculated only once + allLayerHoles.reserve( 20000 ); + + CPOLYGONS_LIST bufferPcbOutlines; // stores the board main outlines + // Build a polygon from edge cut items + wxString msg; + if( ! pcb->GetBoardPolygonOutlines( bufferPcbOutlines, + allLayerHoles, &msg ) ) + { + msg << wxT("\n\n") << + _("Unable to calculate the board outlines.\n" + "Therefore use the board boundary box."); + wxMessageBox( msg ); + } + + int thickness = g_Parm_3D_Visu.GetCopperThicknessBIU(); + for( TRACK* track = pcb->m_Track; track != NULL; track = track->Next() ) + { + // Add via hole + if( track->Type() == PCB_VIA_T ) + { + int shape = track->GetShape(); + int holediameter = track->GetDrillValue(); + int hole_outer_radius = (holediameter + thickness) / 2; + + if( shape == VIA_THROUGH ) + TransformCircleToPolygon( allLayerHoles, + track->GetStart(), hole_outer_radius, + segcountLowQuality ); + } + } + + // draw pads holes + for( MODULE* module = pcb->m_Modules; module != NULL; module = module->Next() ) + { + // Add pad hole, if any + D_PAD* pad = module->Pads(); + + for( ; pad != NULL; pad = pad->Next() ) + pad->BuildPadDrillShapePolygon( allLayerHoles, 0, + segcountLowQuality ); + } + + // draw graphic items, on technical layers - // draw graphic items, not on copper layers KI_POLYGON_SET brdpolysetHoles; allLayerHoles.ExportTo( brdpolysetHoles ); for( LAYER_NUM layer = FIRST_NON_COPPER_LAYER; layer <= LAST_NON_COPPER_LAYER; layer++ ) { + // Skip user layers, which are not drawn here + if( IsUserLayer( layer) ) + continue; + if( !Is3DLayerEnabled( layer ) ) continue; @@ -481,9 +580,7 @@ void EDA_3D_CANVAS::BuildBoard3DView() { case PCB_LINE_T: ( (DRAWSEGMENT*) item )->TransformShapeWithClearanceToPolygon( - bufferPolys, 0, - segcountforcircle, - correctionFactor ); + bufferPolys, 0, segcountforcircle, correctionFactor ); break; case PCB_TEXT_T: @@ -556,10 +653,8 @@ void EDA_3D_CANVAS::BuildBoard3DView() currLayerPolyset += polyset; } - SetGLTechLayersColor( layer ); int thickness = g_Parm_3D_Visu.GetLayerObjectThicknessBIU( layer ); int zpos = g_Parm_3D_Visu.GetLayerZcoordBIU( layer ); - glNormal3f( 0.0, 0.0, Get3DLayer_Z_Orientation( layer ) ); if( layer == EDGE_N ) { @@ -582,38 +677,222 @@ void EDA_3D_CANVAS::BuildBoard3DView() bufferPolys.RemoveAllContours(); bufferPolys.ImportFrom( currLayerPolyset ); + + SetGLTechLayersColor( layer ); + glNormal3f( 0.0, 0.0, Get3DLayer_Z_Orientation( layer ) ); Draw3D_SolidHorizontalPolyPolygons( bufferPolys, zpos, thickness, g_Parm_3D_Visu.m_BiuTo3Dunits ); } +} - // draw modules 3D shapes - if( g_Parm_3D_Visu.GetFlag( FL_MODULE ) ) +/** + * Function BuildBoard3DAuxLayers + * Called by CreateDrawGL_List() + * Fills the OpenGL GL_ID_BOARD draw list with items + * on aux layers only + */ +void EDA_3D_CANVAS::BuildBoard3DAuxLayers() +{ + const int segcountforcircle = 16; + double correctionFactor = 1.0 / cos( M_PI / (segcountforcircle * 2) ); + BOARD* pcb = GetBoard(); + CPOLYGONS_LIST bufferPolys; + bufferPolys.reserve( 5000 ); // Reserve for items not on board + + for( LAYER_NUM layer = FIRST_USER_LAYER; layer <= LAST_USER_LAYER; + layer++ ) { - for( MODULE* module = pcb->m_Modules; module; module = module->Next() ) - module->ReadAndInsert3DComponentShape( this ); + if( !Is3DLayerEnabled( layer ) ) + continue; + + bufferPolys.RemoveAllContours(); + + for( BOARD_ITEM* item = pcb->m_Drawings; item; item = item->Next() ) + { + if( !item->IsOnLayer( layer ) ) + continue; + + switch( item->Type() ) + { + case PCB_LINE_T: + ( (DRAWSEGMENT*) item )->TransformShapeWithClearanceToPolygon( + bufferPolys, 0, segcountforcircle, correctionFactor ); + break; + + case PCB_TEXT_T: + ( (TEXTE_PCB*) item )->TransformShapeWithClearanceToPolygonSet( + bufferPolys, 0, segcountforcircle, correctionFactor ); + break; + + default: + break; + } + } + + for( MODULE* module = pcb->m_Modules; module != NULL; module = module->Next() ) + { + module->TransformPadsShapesWithClearanceToPolygon( layer, + bufferPolys, + 0, + segcountforcircle, + correctionFactor ); + + module->TransformGraphicShapesWithClearanceToPolygonSet( layer, + bufferPolys, + 0, + segcountforcircle, + correctionFactor ); + } + + // bufferPolys contains polygons to merge. Many overlaps . + // Calculate merged polygons and remove pads and vias holes + if( bufferPolys.GetCornersCount() == 0 ) + continue; + KI_POLYGON_SET currLayerPolyset; + KI_POLYGON_SET polyset; + bufferPolys.ExportTo( polyset ); + currLayerPolyset += polyset; + + int thickness = g_Parm_3D_Visu.GetLayerObjectThicknessBIU( layer ); + int zpos = g_Parm_3D_Visu.GetLayerZcoordBIU( layer ); + // for Draw3D_SolidHorizontalPolyPolygons, + // zpos it the middle between bottom and top sides. + // However for top layers, zpos should be the bottom layer pos, + // and for bottom layers, zpos should be the top layer pos. + if( Get3DLayer_Z_Orientation( layer ) > 0 ) + zpos += thickness/2; + else + zpos -= thickness/2 ; + + bufferPolys.RemoveAllContours(); + bufferPolys.ImportFrom( currLayerPolyset ); + + SetGLTechLayersColor( layer ); + glNormal3f( 0.0, 0.0, Get3DLayer_Z_Orientation( layer ) ); + Draw3D_SolidHorizontalPolyPolygons( bufferPolys, zpos, + thickness, g_Parm_3D_Visu.m_BiuTo3Dunits ); } } - -GLuint EDA_3D_CANVAS::CreateDrawGL_List() +void EDA_3D_CANVAS::CreateDrawGL_List() { - PCB_BASE_FRAME* pcbframe = Parent()->Parent(); - BOARD* pcb = pcbframe->GetBoard(); + BOARD* pcb = GetBoard(); wxBusyCursor dummy; - m_gllist = glGenLists( 1 ); - // Build 3D board parameters: g_Parm_3D_Visu.InitSettings( pcb ); - glNewList( m_gllist, GL_COMPILE_AND_EXECUTE ); - glColorMaterial( GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE ); - // draw axis - if( g_Parm_3D_Visu.GetFlag( FL_AXIS ) ) + // Create axis gl list (if it is not shown, the list will be not called + Draw3DAxis(); + + // Create grid gl list + if( ! m_glLists[GL_ID_GRID] ) { + m_glLists[GL_ID_GRID] = glGenLists( 1 ); + glNewList( m_glLists[GL_ID_GRID], GL_COMPILE ); + + Draw3DGrid( g_Parm_3D_Visu.m_3D_Grid ); + glEndList(); + } + + // Create Board full gl lists: + +// For testing purpose only, display calculation time to generate 3D data +// #define PRINT_CALCULATION_TIME + +#ifdef PRINT_CALCULATION_TIME + unsigned strtime = GetRunningMicroSecs(); +#endif + + if( ! m_glLists[GL_ID_BOARD] ) + { + m_glLists[GL_ID_BOARD] = glGenLists( 1 ); + glNewList( m_glLists[GL_ID_BOARD], GL_COMPILE ); + BuildBoard3DView(); + glEndList(); + } + + if( ! m_glLists[GL_ID_TECH_LAYERS] ) + { + m_glLists[GL_ID_TECH_LAYERS] = glGenLists( 1 ); + glNewList( m_glLists[GL_ID_TECH_LAYERS], GL_COMPILE ); + BuildTechLayers3DView(); + glEndList(); + } + + if( ! m_glLists[GL_ID_AUX_LAYERS] ) + { + m_glLists[GL_ID_AUX_LAYERS] = glGenLists( 1 ); + glNewList( m_glLists[GL_ID_AUX_LAYERS], GL_COMPILE ); + BuildBoard3DAuxLayers(); + glEndList(); + } + + + // draw modules 3D shapes + if( ! m_glLists[GL_ID_3DSHAPES_SOLID] && g_Parm_3D_Visu.GetFlag( FL_MODULE ) ) + { + m_glLists[GL_ID_3DSHAPES_SOLID] = glGenLists( 1 ); + + // GL_ID_3DSHAPES_TRANSP is an auxiliary list for 3D shapes; + // Ensure it is cleared before rebuilding it + if( m_glLists[GL_ID_3DSHAPES_TRANSP] ) + glDeleteLists( m_glLists[GL_ID_3DSHAPES_TRANSP], 1 ); + + m_glLists[GL_ID_3DSHAPES_TRANSP] = glGenLists( 1 ); + BuildFootprintShape3DList( m_glLists[GL_ID_3DSHAPES_SOLID], + m_glLists[GL_ID_3DSHAPES_TRANSP] ); + } + + // Test for errors + CheckGLError(); + +#ifdef PRINT_CALCULATION_TIME + unsigned endtime = GetRunningMicroSecs(); + wxString msg; + msg.Printf( "Built data %.1f ms", (double) (endtime - strtime) / 1000 ); + Parent()->SetStatusText( msg, 0 ); +#endif +} + + +void EDA_3D_CANVAS::BuildFootprintShape3DList( GLuint aOpaqueList, + GLuint aTransparentList) +{ + // aOpaqueList is the gl list for non transparent items + // aTransparentList is the gl list for non transparent items, + // which need to be drawn after all other items + + BOARD* pcb = GetBoard(); + glNewList( aOpaqueList, GL_COMPILE ); + bool loadTransparentObjects = false; + + for( MODULE* module = pcb->m_Modules; module; module = module->Next() ) + module->ReadAndInsert3DComponentShape( this, !loadTransparentObjects, + loadTransparentObjects ); + + glEndList(); + + glNewList( aTransparentList, GL_COMPILE ); + loadTransparentObjects = true; + + for( MODULE* module = pcb->m_Modules; module; module = module->Next() ) + module->ReadAndInsert3DComponentShape( this, !loadTransparentObjects, + loadTransparentObjects ); + + glEndList(); +} + +void EDA_3D_CANVAS::Draw3DAxis() +{ + if( ! m_glLists[GL_ID_AXIS] ) + { + m_glLists[GL_ID_AXIS] = glGenLists( 1 ); + glNewList( m_glLists[GL_ID_AXIS], GL_COMPILE ); + glEnable( GL_COLOR_MATERIAL ); SetGLColor( WHITE ); glBegin( GL_LINES ); @@ -626,52 +905,20 @@ GLuint EDA_3D_CANVAS::CreateDrawGL_List() glVertex3f( 0.0f, 0.0f, 0.0f ); glVertex3f( 0.0f, 0.0f, 0.3f ); // Z axis glEnd(); + + glEndList(); } - - // move the board in order to draw it with its center at 0,0 3D coordinates - glTranslatef( -g_Parm_3D_Visu.m_BoardPos.x * g_Parm_3D_Visu.m_BiuTo3Dunits, - -g_Parm_3D_Visu.m_BoardPos.y * g_Parm_3D_Visu.m_BiuTo3Dunits, - 0.0F ); - - // Draw Board: -// For testing purpose only, display calculation time to generate 3D data -// #define PRINT_CALCULATION_TIME - -#ifdef PRINT_CALCULATION_TIME - unsigned strtime = GetRunningMicroSecs(); -#endif - - BuildBoard3DView(); - - // Draw grid - if( g_Parm_3D_Visu.GetFlag( FL_GRID ) ) - DrawGrid( g_Parm_3D_Visu.m_3D_Grid ); - - glEndList(); - - // Test for errors - CheckGLError(); - -#ifdef PRINT_CALCULATION_TIME - unsigned endtime = GetRunningMicroSecs(); - wxString msg; - msg.Printf( "Built data %.1f ms", (double) (endtime - strtime) / 1000 ); - Parent()->SetStatusText( msg, 0 ); -#endif - - return m_gllist; } - // draw a 3D grid: an horizontal grid (XY plane and Z = 0, // and a vertical grid (XZ plane and Y = 0) -void EDA_3D_CANVAS::DrawGrid( double aGriSizeMM ) +void EDA_3D_CANVAS::Draw3DGrid( double aGriSizeMM ) { double zpos = 0.0; EDA_COLOR_T gridcolor = DARKGRAY; // Color of grid lines EDA_COLOR_T gridcolor_marker = LIGHTGRAY; // Color of grid lines every 5 lines - double scale = g_Parm_3D_Visu.m_BiuTo3Dunits; - double transparency = 0.4; + const double scale = g_Parm_3D_Visu.m_BiuTo3Dunits; + const double transparency = 0.3; glNormal3f( 0.0, 0.0, 1.0 ); @@ -806,7 +1053,7 @@ void EDA_3D_CANVAS::Draw3DViaHole( SEGVIA* aVia ) int inner_radius = aVia->GetDrillValue() / 2; int thickness = g_Parm_3D_Visu.GetCopperThicknessBIU(); - aVia->ReturnLayerPair( &top_layer, &bottom_layer ); + aVia->LayerPair( &top_layer, &bottom_layer ); // Drawing via hole: if( g_Parm_3D_Visu.IsRealisticMode() ) @@ -826,8 +1073,11 @@ void EDA_3D_CANVAS::Draw3DViaHole( SEGVIA* aVia ) } -void MODULE::ReadAndInsert3DComponentShape( EDA_3D_CANVAS* glcanvas ) +void MODULE::ReadAndInsert3DComponentShape( EDA_3D_CANVAS* glcanvas, + bool aAllowNonTransparentObjects, + bool aAllowTransparentObjects ) { + // Read from disk and draws the footprint 3D shapes if exists S3D_MASTER* shape3D = m_3D_Drawings; double zpos = g_Parm_3D_Visu.GetModulesZcoord3DIU( IsFlipped() ); @@ -849,6 +1099,9 @@ void MODULE::ReadAndInsert3DComponentShape( EDA_3D_CANVAS* glcanvas ) for( ; shape3D != NULL; shape3D = shape3D->Next() ) { + shape3D->SetLoadNonTransparentObjects( aAllowNonTransparentObjects ); + shape3D->SetLoadTransparentObjects( aAllowTransparentObjects ); + if( shape3D->Is3DType( S3D_MASTER::FILE3D_VRML ) ) shape3D->ReadData(); } diff --git a/3d-viewer/3d_draw_basic_functions.cpp b/3d-viewer/3d_draw_basic_functions.cpp index ef49a3e4bb..81654c4af7 100644 --- a/3d-viewer/3d_draw_basic_functions.cpp +++ b/3d-viewer/3d_draw_basic_functions.cpp @@ -35,7 +35,7 @@ #include <3d_draw_basic_functions.h> // Imported function: -extern void Set_Object_Data( std::vector& aVertices, double aBiuTo3DUnits ); +extern void TransfertToGLlist( std::vector& aVertices, double aBiuTo3DUnits ); extern void CheckGLError(); // Number of segments to approximate a circle by segments @@ -116,7 +116,7 @@ static void Draw3D_VerticalPolygonalCylinder( const CPOLYGONS_LIST& aPolysList, coords[3].y = coords[2].y; // only z change // Creates the GL_QUAD - Set_Object_Data( coords, aBiuTo3DUnits ); + TransfertToGLlist( coords, aBiuTo3DUnits ); } } diff --git a/3d-viewer/3d_frame.cpp b/3d-viewer/3d_frame.cpp index 1b0561bb16..55058bc911 100644 --- a/3d-viewer/3d_frame.cpp +++ b/3d-viewer/3d_frame.cpp @@ -26,7 +26,8 @@ */ #include -#include +#include +#include #include <3d_viewer.h> #include <3d_canvas.h> @@ -40,21 +41,24 @@ INFO3D_VISU g_Parm_3D_Visu; // Key to store 3D Viewer config: -static const wxString keyBgColor_Red( wxT( "BgColor_Red" ) ); -static const wxString keyBgColor_Green( wxT( "BgColor_Green" ) ); -static const wxString keyBgColor_Blue( wxT( "BgColor_Blue" ) ); -static const wxString keyShowRealisticMode( wxT( "ShowRealisticMode" ) ); -static const wxString keyShowAxis( wxT( "ShowAxis" ) ); -static const wxString keyShowZones( wxT( "ShowZones" ) ); -static const wxString keyShowFootprints( wxT( "ShowFootprints" ) ); -static const wxString keyShowCopperThickness( wxT( "ShowCopperThickness" ) ); -static const wxString keyShowAdhesiveLayers( wxT( "ShowAdhesiveLayers" ) ); -static const wxString keyShowSilkScreenLayers( wxT( "ShowSilkScreenLayers" ) ); -static const wxString keyShowSolderMaskLayers( wxT( "ShowSolderMasLayers" ) ); -static const wxString keyShowSolderPasteLayers( wxT( "ShowSolderPasteLayers" ) ); -static const wxString keyShowCommentsLayer( wxT( "ShowCommentsLayers" ) ); -static const wxString keyShowBoardBody( wxT( "ShowBoardBody" ) ); -static const wxString keyShowEcoLayers( wxT( "ShowEcoLayers" ) ); +static const wxChar keyBgColor_Red[] = wxT( "BgColor_Red" ); +static const wxChar keyBgColor_Green[] = wxT( "BgColor_Green" ); +static const wxChar keyBgColor_Blue[] = wxT( "BgColor_Blue" ); +static const wxChar keyShowRealisticMode[] = wxT( "ShowRealisticMode" ); +static const wxChar keyShowAxis[] = wxT( "ShowAxis" ); +static const wxChar keyShowGrid[] = wxT( "ShowGrid3D" ); +static const wxChar keyShowGridSize[] = wxT( "Grid3DSize" ); +static const wxChar keyShowZones[] = wxT( "ShowZones" ); +static const wxChar keyShowFootprints[] = wxT( "ShowFootprints" ); +static const wxChar keyShowCopperThickness[] = wxT( "ShowCopperThickness" ); +static const wxChar keyShowAdhesiveLayers[] = wxT( "ShowAdhesiveLayers" ); +static const wxChar keyShowSilkScreenLayers[] = wxT( "ShowSilkScreenLayers" ); +static const wxChar keyShowSolderMaskLayers[] = wxT( "ShowSolderMasLayers" ); +static const wxChar keyShowSolderPasteLayers[] =wxT( "ShowSolderPasteLayers" ); +static const wxChar keyShowCommentsLayer[] = wxT( "ShowCommentsLayers" ); +static const wxChar keyShowBoardBody[] = wxT( "ShowBoardBody" ); +static const wxChar keyShowEcoLayers[] = wxT( "ShowEcoLayers" ); + BEGIN_EVENT_TABLE( EDA_3D_FRAME, EDA_BASE_FRAME ) EVT_ACTIVATE( EDA_3D_FRAME::OnActivate ) @@ -72,11 +76,13 @@ EVT_MENU_RANGE( ID_MENU3D_GRID, ID_MENU3D_GRID_END, EVT_CLOSE( EDA_3D_FRAME::OnCloseWindow ) -END_EVENT_TABLE() EDA_3D_FRAME::EDA_3D_FRAME( PCB_BASE_FRAME* parent, - const wxString& title, - long style ) : - EDA_BASE_FRAME( parent, DISPLAY3D_FRAME_TYPE, title, - wxDefaultPosition, wxDefaultSize, style, wxT( "Frame3D" ) ) +END_EVENT_TABLE() + + +EDA_3D_FRAME::EDA_3D_FRAME( KIWAY* aKiway, PCB_BASE_FRAME* aParent, + const wxString& aTitle, long style ) : + KIWAY_PLAYER( aKiway, aParent, DISPLAY3D_FRAME_TYPE, aTitle, + wxDefaultPosition, wxDefaultSize, style, wxT( "Frame3D" ) ) { m_canvas = NULL; m_reloadRequest = false; @@ -87,7 +93,7 @@ END_EVENT_TABLE() EDA_3D_FRAME::EDA_3D_FRAME( PCB_BASE_FRAME* parent, icon.CopyFromBitmap( KiBitmap( icon_3d_xpm ) ); SetIcon( icon ); - GetSettings(); + LoadSettings( config() ); SetSize( m_FramePos.x, m_FramePos.y, m_FrameSize.x, m_FrameSize.y ); // Create the status line @@ -139,84 +145,84 @@ void EDA_3D_FRAME::OnCloseWindow( wxCloseEvent& Event ) } -void EDA_3D_FRAME::GetSettings() +void EDA_3D_FRAME::LoadSettings( wxConfigBase* aCfg ) { - wxConfig* config = wxGetApp().GetSettings(); // Current config used by application - class INFO3D_VISU& prms = g_Parm_3D_Visu; + EDA_BASE_FRAME::LoadSettings( aCfg ); - if( config ) - { - EDA_BASE_FRAME::LoadSettings(); + INFO3D_VISU& prms = g_Parm_3D_Visu; - config->Read( keyBgColor_Red, &g_Parm_3D_Visu.m_BgColor.m_Red, 0.0 ); - config->Read( keyBgColor_Green, &g_Parm_3D_Visu.m_BgColor.m_Green, 0.0 ); - config->Read( keyBgColor_Blue, &g_Parm_3D_Visu.m_BgColor.m_Blue, 0.0 ); + aCfg->Read( keyBgColor_Red, &g_Parm_3D_Visu.m_BgColor.m_Red, 0.0 ); + aCfg->Read( keyBgColor_Green, &g_Parm_3D_Visu.m_BgColor.m_Green, 0.0 ); + aCfg->Read( keyBgColor_Blue, &g_Parm_3D_Visu.m_BgColor.m_Blue, 0.0 ); - bool tmp; - config->Read( keyShowRealisticMode, &tmp, false ); - prms.SetFlag( FL_USE_REALISTIC_MODE, tmp ); + bool tmp; + aCfg->Read( keyShowRealisticMode, &tmp, false ); + prms.SetFlag( FL_USE_REALISTIC_MODE, tmp ); - config->Read( keyShowAxis, &tmp, true ); - prms.SetFlag( FL_AXIS, tmp ); + aCfg->Read( keyShowAxis, &tmp, true ); + prms.SetFlag( FL_AXIS, tmp ); - config->Read( keyShowFootprints, &tmp, true ); - prms.SetFlag( FL_MODULE, tmp ); + aCfg->Read( keyShowGrid, &tmp, true ); + prms.SetFlag( FL_GRID, tmp ); - config->Read( keyShowCopperThickness, &tmp, false ); - prms.SetFlag( FL_USE_COPPER_THICKNESS, tmp ); + aCfg->Read( keyShowGridSize, &prms.m_3D_Grid, 10.0 ); + prms.SetFlag( FL_MODULE, tmp ); - config->Read( keyShowZones, &tmp, true ); - prms.SetFlag( FL_ZONE, tmp ); + aCfg->Read( keyShowFootprints, &tmp, true ); + prms.SetFlag( FL_MODULE, tmp ); - config->Read( keyShowAdhesiveLayers, &tmp, true ); - prms.SetFlag( FL_ADHESIVE, tmp ); + aCfg->Read( keyShowCopperThickness, &tmp, false ); + prms.SetFlag( FL_USE_COPPER_THICKNESS, tmp ); - config->Read( keyShowSilkScreenLayers, &tmp, true ); - prms.SetFlag( FL_SILKSCREEN, tmp ); + aCfg->Read( keyShowZones, &tmp, true ); + prms.SetFlag( FL_ZONE, tmp ); - config->Read( keyShowSolderMaskLayers, &tmp, true ); - prms.SetFlag( FL_SOLDERMASK, tmp ); + aCfg->Read( keyShowAdhesiveLayers, &tmp, true ); + prms.SetFlag( FL_ADHESIVE, tmp ); - config->Read( keyShowSolderPasteLayers, &tmp, true ); - prms.SetFlag( FL_SOLDERPASTE, tmp ); + aCfg->Read( keyShowSilkScreenLayers, &tmp, true ); + prms.SetFlag( FL_SILKSCREEN, tmp ); - config->Read( keyShowCommentsLayer, &tmp, true ); - prms.SetFlag( FL_COMMENTS, tmp ); + aCfg->Read( keyShowSolderMaskLayers, &tmp, true ); + prms.SetFlag( FL_SOLDERMASK, tmp ); - config->Read( keyShowEcoLayers, &tmp, true ); - prms.SetFlag( FL_ECO, tmp ); + aCfg->Read( keyShowSolderPasteLayers, &tmp, true ); + prms.SetFlag( FL_SOLDERPASTE, tmp ); - config->Read( keyShowBoardBody, &tmp, true ); - prms.SetFlag( FL_SHOW_BOARD_BODY, tmp ); - } + aCfg->Read( keyShowCommentsLayer, &tmp, true ); + prms.SetFlag( FL_COMMENTS, tmp ); + + aCfg->Read( keyShowEcoLayers, &tmp, true ); + prms.SetFlag( FL_ECO, tmp ); + + aCfg->Read( keyShowBoardBody, &tmp, true ); + prms.SetFlag( FL_SHOW_BOARD_BODY, tmp ); } -void EDA_3D_FRAME::SaveSettings() +void EDA_3D_FRAME::SaveSettings( wxConfigBase* aCfg ) { - wxConfig* config = wxGetApp().GetSettings(); // Current config used by application + EDA_BASE_FRAME::SaveSettings( aCfg ); - if( !config ) - return; + INFO3D_VISU& prms = g_Parm_3D_Visu; - EDA_BASE_FRAME::SaveSettings(); - - config->Write( keyBgColor_Red, g_Parm_3D_Visu.m_BgColor.m_Red ); - config->Write( keyBgColor_Green, g_Parm_3D_Visu.m_BgColor.m_Green ); - config->Write( keyBgColor_Blue, g_Parm_3D_Visu.m_BgColor.m_Blue ); - class INFO3D_VISU& prms = g_Parm_3D_Visu; - config->Write( keyShowRealisticMode, prms.GetFlag( FL_USE_REALISTIC_MODE ) ); - config->Write( keyShowAxis, prms.GetFlag( FL_AXIS ) ); - config->Write( keyShowFootprints, prms.GetFlag( FL_MODULE ) ); - config->Write( keyShowCopperThickness, prms.GetFlag( FL_USE_COPPER_THICKNESS ) ); - config->Write( keyShowZones, prms.GetFlag( FL_ZONE ) ); - config->Write( keyShowAdhesiveLayers, prms.GetFlag( FL_ADHESIVE ) ); - config->Write( keyShowSilkScreenLayers, prms.GetFlag( FL_SILKSCREEN ) ); - config->Write( keyShowSolderMaskLayers, prms.GetFlag( FL_SOLDERMASK ) ); - config->Write( keyShowSolderPasteLayers, prms.GetFlag( FL_SOLDERPASTE ) ); - config->Write( keyShowCommentsLayer, prms.GetFlag( FL_COMMENTS ) ); - config->Write( keyShowEcoLayers, prms.GetFlag( FL_ECO ) ); - config->Write( keyShowBoardBody, prms.GetFlag( FL_SHOW_BOARD_BODY ) ); + aCfg->Write( keyBgColor_Red, g_Parm_3D_Visu.m_BgColor.m_Red ); + aCfg->Write( keyBgColor_Green, g_Parm_3D_Visu.m_BgColor.m_Green ); + aCfg->Write( keyBgColor_Blue, g_Parm_3D_Visu.m_BgColor.m_Blue ); + aCfg->Write( keyShowRealisticMode, prms.GetFlag( FL_USE_REALISTIC_MODE ) ); + aCfg->Write( keyShowAxis, prms.GetFlag( FL_AXIS ) ); + aCfg->Write( keyShowGrid, prms.GetFlag( FL_GRID ) ); + aCfg->Write( keyShowGridSize, prms.m_3D_Grid ); + aCfg->Write( keyShowFootprints, prms.GetFlag( FL_MODULE ) ); + aCfg->Write( keyShowCopperThickness, prms.GetFlag( FL_USE_COPPER_THICKNESS ) ); + aCfg->Write( keyShowZones, prms.GetFlag( FL_ZONE ) ); + aCfg->Write( keyShowAdhesiveLayers, prms.GetFlag( FL_ADHESIVE ) ); + aCfg->Write( keyShowSilkScreenLayers, prms.GetFlag( FL_SILKSCREEN ) ); + aCfg->Write( keyShowSolderMaskLayers, prms.GetFlag( FL_SOLDERMASK ) ); + aCfg->Write( keyShowSolderPasteLayers, prms.GetFlag( FL_SOLDERPASTE ) ); + aCfg->Write( keyShowCommentsLayer, prms.GetFlag( FL_COMMENTS ) ); + aCfg->Write( keyShowEcoLayers, prms.GetFlag( FL_ECO ) ); + aCfg->Write( keyShowBoardBody, prms.GetFlag( FL_SHOW_BOARD_BODY ) ); } @@ -364,52 +370,52 @@ void EDA_3D_FRAME::Process_Special_Functions( wxCommandEvent& event ) case ID_MENU3D_AXIS_ONOFF: g_Parm_3D_Visu.SetFlag( FL_AXIS, isChecked ); - NewDisplay(); + m_canvas->Refresh(); return; case ID_MENU3D_MODULE_ONOFF: g_Parm_3D_Visu.SetFlag( FL_MODULE, isChecked ); - NewDisplay(); + m_canvas->Refresh(); return; case ID_MENU3D_USE_COPPER_THICKNESS: g_Parm_3D_Visu.SetFlag( FL_USE_COPPER_THICKNESS, isChecked ); - NewDisplay(); + NewDisplay(GL_ID_BOARD); return; case ID_MENU3D_ZONE_ONOFF: g_Parm_3D_Visu.SetFlag( FL_ZONE, isChecked ); - NewDisplay(); + NewDisplay(GL_ID_BOARD); return; case ID_MENU3D_ADHESIVE_ONOFF: g_Parm_3D_Visu.SetFlag( FL_ADHESIVE, isChecked ); - NewDisplay(); + NewDisplay(GL_ID_TECH_LAYERS); return; case ID_MENU3D_SILKSCREEN_ONOFF: g_Parm_3D_Visu.SetFlag( FL_SILKSCREEN, isChecked ); - NewDisplay(); + NewDisplay(GL_ID_TECH_LAYERS); return; case ID_MENU3D_SOLDER_MASK_ONOFF: g_Parm_3D_Visu.SetFlag( FL_SOLDERMASK, isChecked ); - NewDisplay(); + NewDisplay(GL_ID_TECH_LAYERS); return; case ID_MENU3D_SOLDER_PASTE_ONOFF: g_Parm_3D_Visu.SetFlag( FL_SOLDERPASTE, isChecked ); - NewDisplay(); + NewDisplay(GL_ID_TECH_LAYERS); return; case ID_MENU3D_COMMENTS_ONOFF: g_Parm_3D_Visu.SetFlag( FL_COMMENTS, isChecked ); - NewDisplay(); + NewDisplay(GL_ID_AUX_LAYERS); return; case ID_MENU3D_ECO_ONOFF: g_Parm_3D_Visu.SetFlag( FL_ECO, isChecked ); - NewDisplay(); + NewDisplay(GL_ID_AUX_LAYERS); return; default: @@ -434,7 +440,6 @@ void EDA_3D_FRAME::On3DGridSelection( wxCommandEvent& event ) GetMenuBar()->Check( ii, false ); } - switch( id ) { case ID_MENU3D_GRID_NOGRID: @@ -466,18 +471,17 @@ void EDA_3D_FRAME::On3DGridSelection( wxCommandEvent& event ) return; } - NewDisplay(); + NewDisplay( GL_ID_GRID ); } -void EDA_3D_FRAME::NewDisplay() +void EDA_3D_FRAME::NewDisplay( GLuint aGlList ) { m_reloadRequest = false; - m_canvas->ClearLists(); + m_canvas->ClearLists( aGlList ); m_canvas->CreateDrawGL_List(); -// m_canvas->InitGL(); m_canvas->Refresh( true ); m_canvas->DisplayStatus(); } @@ -507,6 +511,9 @@ void EDA_3D_FRAME::Set3DBgColor() newcolor = wxGetColourFromUser( this, oldcolor ); + if( !newcolor.IsOk() ) // Happens on cancel dialog + return; + if( newcolor != oldcolor ) { g_Parm_3D_Visu.m_BgColor.m_Red = (double) newcolor.Red() / 255.0; @@ -515,3 +522,8 @@ void EDA_3D_FRAME::Set3DBgColor() NewDisplay(); } } + +BOARD* EDA_3D_FRAME::GetBoard() +{ + return Parent()->GetBoard(); +} diff --git a/3d-viewer/3d_read_mesh.cpp b/3d-viewer/3d_read_mesh.cpp index d093dbecf9..6e35c85a51 100644 --- a/3d-viewer/3d_read_mesh.cpp +++ b/3d-viewer/3d_read_mesh.cpp @@ -31,7 +31,7 @@ #include #include #include -#include +#include #include <3d_viewer.h> #include diff --git a/3d-viewer/3d_struct.h b/3d-viewer/3d_struct.h index 56a083f8c9..2a82effd93 100644 --- a/3d-viewer/3d_struct.h +++ b/3d-viewer/3d_struct.h @@ -109,6 +109,10 @@ public: private: wxString m_Shape3DName; /* 3D shape name in 3D library */ FILE3D_TYPE m_ShapeType; + double m_lastTransparency; // last transparency value from + // last material in use + bool m_loadTransparentObjects; + bool m_loadNonTransparentObjects; public: S3D_MASTER( EDA_ITEM* aParent ); @@ -117,11 +121,41 @@ public: S3D_MASTER* Next() const { return (S3D_MASTER*) Pnext; } S3D_MASTER* Back() const { return (S3D_MASTER*) Pback; } + // Accessors + void SetLastTransparency( double aValue ) { m_lastTransparency = aValue; } + + void SetLoadTransparentObjects( bool aLoad ) + { m_loadTransparentObjects = aLoad; } + + void SetLoadNonTransparentObjects( bool aLoad ) + { m_loadNonTransparentObjects = aLoad; } + void Insert( S3D_MATERIAL* aMaterial ); + /** + * Function IsOpenGlAllowed + * @return true if opengl current list accepts a gl data + * used to filter transparent objects, which are drawn after + * non transparent objects + */ + bool IsOpenGlAllowed(); + void Copy( S3D_MASTER* pattern ); + + /** + * Function ReadData + * Select the parser to read the 3D data file (vrml, x3d ...) + * and build the description objects list + */ int ReadData(); - void Set_Object_Coords( std::vector< S3D_VERTEX >& aVertices ); + + /** + * Function ObjectCoordsTo3DUnits + * @param aVertices = a list of 3D coordinates in shape units + * to convert to 3D canvas units, according to the + * footprint 3Dshape rotation, offset and scale parameters + */ + void ObjectCoordsTo3DUnits( std::vector< S3D_VERTEX >& aVertices ); #if defined(DEBUG) void Show( int nestLevel, std::ostream& os ) const { ShowDummy( os ); } // override @@ -147,6 +181,13 @@ public: */ const wxString GetShape3DFullFilename(); + /** + * Function SetShape3DName + * @param aShapeName = file name of the data file relative to the 3D shape + * + * Set the filename of the 3D shape, and depending on the file extention + * (vrl, x3d, idf ) the type of file. + */ void SetShape3DName( const wxString& aShapeName ); }; diff --git a/3d-viewer/3d_toolbar.cpp b/3d-viewer/3d_toolbar.cpp index ed0e3eefbe..a1c7d2c90a 100644 --- a/3d-viewer/3d_toolbar.cpp +++ b/3d-viewer/3d_toolbar.cpp @@ -166,13 +166,22 @@ void EDA_3D_FRAME::CreateMenuBar() wxMenu * gridlistMenu = new wxMenu; AddMenuItem( prefsMenu, gridlistMenu, ID_MENU3D_GRID, _( "3D Grid" ), KiBitmap( grid_xpm ) ); - gridlistMenu->Append( ID_MENU3D_GRID_NOGRID, _( "No 3D Grid" ), wxEmptyString, true ); - gridlistMenu->Check( ID_MENU3D_GRID_NOGRID, true ); + gridlistMenu->Append( ID_MENU3D_GRID_NOGRID, _( "No 3D Grid" ), wxEmptyString, true ); + gridlistMenu->Append( ID_MENU3D_GRID_10_MM, _( "3D Grid 10 mm" ), wxEmptyString, true ); + gridlistMenu->Append( ID_MENU3D_GRID_5_MM, _( "3D Grid 5 mm" ), wxEmptyString, true ); + gridlistMenu->Append( ID_MENU3D_GRID_2P5_MM, _( "3D Grid 2.5 mm" ), wxEmptyString, true ); + gridlistMenu->Append( ID_MENU3D_GRID_1_MM, _( "3D Grid 1 mm" ), wxEmptyString, true ); - gridlistMenu->Append( ID_MENU3D_GRID_10_MM, _( "3D Grid 10 mm" ), wxEmptyString, true ); - gridlistMenu->Append( ID_MENU3D_GRID_5_MM, _( "3D Grid 5 mm" ), wxEmptyString, true ); - gridlistMenu->Append( ID_MENU3D_GRID_2P5_MM, _( "3D Grid 2.5 mm" ), wxEmptyString, true ); - gridlistMenu->Append( ID_MENU3D_GRID_1_MM, _( "3D Grid 1 mm" ), wxEmptyString, true ); + // If the grid is on, check the corresponding menuitem showing the grid size + if( g_Parm_3D_Visu.GetFlag( FL_GRID ) ) + { + gridlistMenu->Check( ID_MENU3D_GRID_10_MM, g_Parm_3D_Visu.m_3D_Grid == 10.0 ); + gridlistMenu->Check( ID_MENU3D_GRID_5_MM, g_Parm_3D_Visu.m_3D_Grid == 5.0 ); + gridlistMenu->Check( ID_MENU3D_GRID_2P5_MM, g_Parm_3D_Visu.m_3D_Grid == 2.5 ); + gridlistMenu->Check( ID_MENU3D_GRID_1_MM, g_Parm_3D_Visu.m_3D_Grid == 1.0 ); + } + else + gridlistMenu->Check( ID_MENU3D_GRID_NOGRID, true ); prefsMenu->AppendSeparator(); diff --git a/3d-viewer/3d_viewer.h b/3d-viewer/3d_viewer.h index dc94f933ef..46c92053b7 100644 --- a/3d-viewer/3d_viewer.h +++ b/3d-viewer/3d_viewer.h @@ -30,7 +30,7 @@ #ifndef __3D_VIEWER_H__ #define __3D_VIEWER_H__ -#include // for EDA_BASE_FRAME. +#include #if !wxUSE_GLCANVAS #error Please build wxWidgets with Opengl support (./configure --with-opengl) @@ -53,24 +53,29 @@ #include <3d_struct.h> +#define KISYS3DMOD "KISYS3DMOD" + class EDA_3D_CANVAS; class PCB_BASE_FRAME; -#define KICAD_DEFAULT_3D_DRAWFRAME_STYLE wxDEFAULT_FRAME_STYLE | wxWANTS_CHARS -#define LIB3D_PATH wxT( "packages3d" ) +#define KICAD_DEFAULT_3D_DRAWFRAME_STYLE (wxDEFAULT_FRAME_STYLE | wxWANTS_CHARS) +#define LIB3D_PATH wxT( "packages3d" ) -class EDA_3D_FRAME : public EDA_BASE_FRAME + +class EDA_3D_FRAME : public KIWAY_PLAYER { private: EDA_3D_CANVAS* m_canvas; bool m_reloadRequest; wxString m_defaultFileName; /// Filename to propose for screenshot + /// Tracks whether to use Orthographic or Perspective projection bool m_ortho; public: - EDA_3D_FRAME( PCB_BASE_FRAME* parent, const wxString& title, + EDA_3D_FRAME( KIWAY* aKiway, PCB_BASE_FRAME* aParent, const wxString& aTitle, long style = KICAD_DEFAULT_3D_DRAWFRAME_STYLE ); + ~EDA_3D_FRAME() { m_auimgr.UnInit(); @@ -78,6 +83,8 @@ public: PCB_BASE_FRAME* Parent() { return (PCB_BASE_FRAME*)GetParent(); } + BOARD* GetBoard(); + /** * Function ReloadRequest * must be called when reloading data from Pcbnew is needed @@ -93,8 +100,10 @@ public: * Function NewDisplay * Rebuild the display list. * must be called when 3D opengl data is modified + * @param aGlList = the list to rebuild. + * if 0 (default) all lists are rebuilt */ - void NewDisplay(); + void NewDisplay( GLuint aGlList = 0 ); void SetDefaultFileName(const wxString &aFn) { m_defaultFileName = aFn; } const wxString &GetDefaultFileName() const { return m_defaultFileName; } @@ -121,8 +130,9 @@ private: // to the current display options void ReCreateMainToolbar(); void SetToolbars(); - void GetSettings(); - void SaveSettings(); + + void LoadSettings( wxConfigBase* aCfg ); // overload virtual + void SaveSettings( wxConfigBase* aCfg ); // overload virtual // Other functions void OnLeftClick( wxDC* DC, const wxPoint& MousePos ); diff --git a/3d-viewer/info3d_visu.h b/3d-viewer/info3d_visu.h index 00acbbd226..7c7fe02918 100644 --- a/3d-viewer/info3d_visu.h +++ b/3d-viewer/info3d_visu.h @@ -74,7 +74,6 @@ enum DISPLAY3D_FLG { FL_LAST }; - class INFO3D_VISU { public: diff --git a/3d-viewer/modelparsers.h b/3d-viewer/modelparsers.h index 147a0fda16..d1c5f23461 100644 --- a/3d-viewer/modelparsers.h +++ b/3d-viewer/modelparsers.h @@ -37,7 +37,7 @@ class S3D_MASTER; class S3D_VERTEX; -extern void Set_Object_Data( std::vector< S3D_VERTEX >& aVertices, double aBiuTo3DUnits ); +extern void TransfertToGLlist( std::vector< S3D_VERTEX >& aVertices, double aBiuTo3DUnits ); class S3D_MODEL_PARSER; class X3D_MODEL_PARSER; diff --git a/3d-viewer/vrmlmodelparser.cpp b/3d-viewer/vrmlmodelparser.cpp index fa6367793b..8891a424aa 100644 --- a/3d-viewer/vrmlmodelparser.cpp +++ b/3d-viewer/vrmlmodelparser.cpp @@ -519,8 +519,12 @@ int VRML_MODEL_PARSER::readGeometry( FILE* file, int* LineNum ) vertices.push_back( vertex ); } - GetMaster()->Set_Object_Coords( vertices ); - Set_Object_Data( vertices, vrmlunits_to_3Dunits ); + if( GetMaster()->IsOpenGlAllowed() ) + { + GetMaster()->ObjectCoordsTo3DUnits( vertices ); + TransfertToGLlist( vertices, vrmlunits_to_3Dunits ); + } + vertices.clear(); coordIndex.clear(); } diff --git a/3d-viewer/x3dmodelparser.cpp b/3d-viewer/x3dmodelparser.cpp index 012d3df959..e4f7d283b2 100644 --- a/3d-viewer/x3dmodelparser.cpp +++ b/3d-viewer/x3dmodelparser.cpp @@ -479,8 +479,11 @@ void X3D_MODEL_PARSER::readIndexedFaceSet( wxXmlNode* aFaceNode, vertices.push_back( triplets.at( *id ) ); } - GetMaster()->Set_Object_Coords( vertices ); - Set_Object_Data( vertices, vrmlunits_to_3Dunits ); + if( GetMaster()->IsOpenGlAllowed() ) + { + GetMaster()->ObjectCoordsTo3DUnits( vertices ); + TransfertToGLlist( vertices, vrmlunits_to_3Dunits ); + } vertices.clear(); coordIndex.clear(); diff --git a/CMakeLists.txt b/CMakeLists.txt index 4a923759cf..d009bd529c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -23,8 +23,9 @@ set( CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/CMakeModules ) # reports. # -option( USE_KIWAY_DLLS - "Build the major modules as KIFACE DLLs or DSOs, will soon be the norm." OFF ) +#option( USE_KIWAY_DLLS "Build the major modules as KIFACE DLLs or DSOs, will soon be the norm." ON ) +set( USE_KIWAY_DLLS true ) # this is now mandatory, the code is the same anyways, the old code is gone. + # The desire is to migrate designs *away from* case independence, and to create designs which use # literally (case specific) interpreted component names. But for backwards compatibility, @@ -81,7 +82,7 @@ mark_as_advanced( KICAD_SKIP_BOOST ) # Normal builders should build Boost. # when not defined by user, the default is python.exe under Windows and python2 for others # python binary file should be is exec path. -option( BUILD_GITHUB_PLUGIN "Build the GITHUB_PLUGIN for pcbnew." OFF ) +option( BUILD_GITHUB_PLUGIN "Build the GITHUB_PLUGIN for pcbnew." ON ) # This can be set to a custom name to brag about a particular branch in the "About" dialog: set( KICAD_REPO_NAME "product" CACHE STRING "Name of the tree from which this build came." ) @@ -115,6 +116,12 @@ if( CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang" ) OUTPUT_VARIABLE GCC_VERSION OUTPUT_STRIP_TRAILING_WHITESPACE ) + if( CMAKE_CXX_COMPILER_ID MATCHES "Clang" ) + set( TO_LINKER -XLinker ) + else() + set( TO_LINKER -Wl ) + endif() + # Establish -Wall early, so specialized relaxations of this may come # subsequently on the command line, such as in pcbnew/github/CMakeLists.txt set( CMAKE_C_FLAGS "-Wall ${CMAKE_C_FLAGS}" ) @@ -150,10 +157,17 @@ if( CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang" ) endif() find_package( OpenMP QUIET ) + if( OPENMP_FOUND ) set( CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}" ) set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}" ) add_definitions( -DUSE_OPENMP ) + + # MinGW does not include the OpenMP link library and FindOpenMP.cmake does not + # set it either. Not sure this is the most elegant solution but it works. + if( MINGW ) + set( OPENMP_LIBRARIES gomp ) + endif() endif() if( MINGW ) @@ -189,19 +203,14 @@ if( CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang" ) set( CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${PIC_FLAG}" ) set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${PIC_FLAG}" ) - if( CMAKE_CXX_COMPILER_ID MATCHES "Clang" ) - set( TO_LINKER -XLinker ) - else() - set( TO_LINKER -Wl ) - endif() - # Thou shalt not link vaporware and tell us it's a valid DSO (apple ld doesn't support it) if( NOT APPLE ) set( CMAKE_SHARED_LINKER_FLAGS "${TO_LINKER},--no-undefined" ) set( CMAKE_MODULE_LINKER_FLAGS "${TO_LINKER},--no-undefined" ) + + set( CMAKE_EXE_LINKER_FLAGS_RELEASE "-s" ) endif() - set( CMAKE_EXE_LINKER_FLAGS_RELEASE "-s" ) endif() # quiet GCC while in boost @@ -215,16 +224,16 @@ if( CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang" ) set( CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -D__ASSERTMACROS__ -mmacosx-version-min=10.5" ) set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D__ASSERTMACROS__ -mmacosx-version-min=10.5" ) - # Allows .dylib relocation in the future + # Allows .dylib relocation in the future - needed by fixbundle set( CMAKE_LD_FLAGS "${CMAKE_LD_FLAGS} -headerpad_max_install_names") if( NOT CMAKE_CXX_COMPILER ) EXEC_PROGRAM( wx-config ARGS --cc OUTPUT_VARIABLE CMAKE_C_COMPILER ) - endif( NOT CMAKE_CXX_COMPILER ) + endif() if( NOT CMAKE_CXX_COMPILER ) EXEC_PROGRAM( wx-config ARGS --cxx OUTPUT_VARIABLE CMAKE_CXX_COMPILER ) - endif( NOT CMAKE_CXX_COMPILER ) + endif() endif() @@ -340,7 +349,7 @@ include( ExternalProject ) include( CheckFindPackageResult ) # Turn on wxWidgets compatibility mode for some classes -add_definitions(-DWX_COMPATIBILITY) +add_definitions( -DWX_COMPATIBILITY ) ####################### # Find OpenGL library # @@ -348,6 +357,12 @@ add_definitions(-DWX_COMPATIBILITY) find_package( OpenGL QUIET ) check_find_package_result( OPENGL_FOUND "OpenGL" ) +# Dick 5-Feb-2014: +# Marco: We cannot use both ExternalProject_Add() add and find_package() +# in the same CMake tree and have them both reference the same package: +# http://stackoverflow.com/questions/6351609/cmake-linking-to-library-downloaded-from-externalproject-add +# https://www.mail-archive.com/cmake@cmake.org/msg47501.html + # Handle target used to specify if a target needs wx-widgets or other libraries # Always defined, empty if no libraries are to be build add_custom_target( lib-dependencies ) @@ -380,8 +395,8 @@ if( KICAD_BUILD_STATIC OR KICAD_BUILD_DYNAMIC ) if( KICAD_SCRIPTING OR KICAD_SCRIPTING_WXPYTHON OR KICAD_SCRIPTING_MODULES ) - - message(STATUS "Scripting ENABLED") + + message(STATUS "Scripting ENABLED") include( download_wxpython ) set( SWIG_EXECUTABLE ${SWIG_ROOT}/bin/swig ) @@ -439,14 +454,18 @@ endif( KICAD_BUILD_STATIC OR KICAD_BUILD_DYNAMIC) ##################### # Find GLEW library # ##################### -find_package(GLEW) -check_find_package_result(GLEW_FOUND "GLEW") +if( NOT GLEW_FOUND ) + find_package( GLEW ) + check_find_package_result( GLEW_FOUND "GLEW" ) +endif() ###################### # Find Cairo library # ###################### -find_package(Cairo 1.8.1 QUIET) -check_find_package_result(CAIRO_FOUND "Cairo") +if( NOT CAIRO_FOUND ) + find_package( Cairo 1.8.1 QUIET ) + check_find_package_result( CAIRO_FOUND "Cairo" ) +endif() # Download boost and possibly build parts of it ################################################# @@ -458,6 +477,8 @@ if( KICAD_SKIP_BOOST ) message( FATAL_ERROR "Boost 1.54+ libraries are required." ) endif() + add_custom_target( boost ) # it is required to meet some further dependencies + message( WARNING " WARNING: You decided to skip building boost library. KiCad developers strongly advise you to build the bundled boost library, as it is known to work with KiCad. @@ -482,8 +503,8 @@ else() endif() if( NOT (KICAD_BUILD_STATIC OR KICAD_BUILD_DYNAMIC) ) -check_find_package_result( wxWidgets_FOUND "wxWidgets" ) -endif( NOT (KICAD_BUILD_STATIC OR KICAD_BUILD_DYNAMIC) ) + check_find_package_result( wxWidgets_FOUND "wxWidgets" ) +endif() # Include wxWidgets macros. include( ${wxWidgets_USE_FILE} ) @@ -531,15 +552,15 @@ if( KICAD_SCRIPTING OR KICAD_SCRIPTING_MODULES ) set( PythonInterp_FIND_VERSION 2.6 ) set( PythonLibs_FIND_VERSION 2.6 ) endif() - + # force a python version < 3.0 set( PythonInterp_FIND_VERSION 2.6) set( PythonLibs_FIND_VERSION 2.6 ) find_package( PythonInterp ) - + check_find_package_result( PYTHONINTERP_FOUND "Python Interpreter" ) - + if( NOT PYTHON_VERSION_MAJOR EQUAL 2 ) message( FATAL_ERROR "Python 2.x is required." ) endif() diff --git a/CMakeModules/download_boost.cmake b/CMakeModules/download_boost.cmake index 9230b334e2..e929a2aae5 100644 --- a/CMakeModules/download_boost.cmake +++ b/CMakeModules/download_boost.cmake @@ -59,7 +59,9 @@ set( BOOST_LIBS_BUILT ) #-------------------------------------------------------------------- -find_package( BZip2 REQUIRED ) +if( NOT BZIP2_FOUND ) + find_package( BZip2 REQUIRED ) +endif() string( REGEX REPLACE "\\." "_" BOOST_VERS "${BOOST_RELEASE}" ) set( PREFIX ${DOWNLOAD_DIR}/boost_${BOOST_VERS} ) @@ -99,7 +101,7 @@ else() endif() -if( MINGW ) +if( MINGW AND NOT CMAKE_HOST_UNIX ) # building for MINGW on windows not UNIX if( MSYS ) # The Boost system does not build properly on MSYS using bootstrap.sh. Running # bootstrap.bat with cmd.exe does. It's ugly but it works. At least for Boost @@ -113,14 +115,16 @@ if( MINGW ) set( b2_libs ${b2_libs} --with-${lib} ) endforeach() unset( BOOST_CFLAGS ) + else() string( REGEX REPLACE "\\;" "," libs_csv "${boost_libs_list}" ) #message( STATUS "libs_csv:${libs_csv}" ) set( bootstrap ./bootstrap.sh --with-libraries=${libs_csv} ) # pass to *both* C and C++ compilers - set( BOOST_CFLAGS "cflags=${PIC_FLAG}" ) - set( BOOST_INCLUDE "${BOOST_ROOT}/include" ) + set( BOOST_CFLAGS "cflags=${PIC_FLAG}" ) + set( BOOST_CXXFLAGS "cxxflags=${PIC_FLAG}" ) + set( BOOST_INCLUDE "${BOOST_ROOT}/include" ) unset( b2_libs ) endif() diff --git a/CMakeModules/download_cairo.cmake b/CMakeModules/download_cairo.cmake index 51d136750b..2d8b30eb98 100644 --- a/CMakeModules/download_cairo.cmake +++ b/CMakeModules/download_cairo.cmake @@ -33,7 +33,9 @@ set( CAIRO_ROOT "${PROJECT_SOURCE_DIR}/cairo_root" ) #-------------------------------------------------------------------- -find_package( BZip2 REQUIRED ) +if( NOT BZIP2_FOUND ) + find_package( BZip2 REQUIRED ) +endif() set( PREFIX ${DOWNLOAD_DIR}/cairo ) @@ -42,7 +44,7 @@ if ( KICAD_BUILD_STATIC ) endif( KICAD_BUILD_STATIC ) -if (APPLE) +if (APPLE) set( CAIRO_CFLAGS "CFLAGS=" ) set( CAIRO_LDFLAGS "LDFLAGS=-framework CoreServices -framework Cocoa" ) @@ -94,8 +96,14 @@ ExternalProject_Add( cairo #BINARY_DIR "${PREFIX}" - BUILD_COMMAND $(MAKE) + BUILD_COMMAND $(MAKE) INSTALL_DIR "${CAIRO_ROOT}" INSTALL_COMMAND $(MAKE) install ) + +# match these with whatever FindCairo.cmake sets +# Dick i'vent set it because /lib and /lib64 issue in non multiarch binaries OSs +#set( CAIRO_FOUND true ) +set( CAIRO_INCLUDE_DIR ${CAIRO_ROOT}/include ) +set( CAIRO_LIBRARIES ${CAIRO_ROOT}/lib ) diff --git a/CMakeModules/download_glew.cmake b/CMakeModules/download_glew.cmake index 74e28a98f3..1c7d690809 100644 --- a/CMakeModules/download_glew.cmake +++ b/CMakeModules/download_glew.cmake @@ -33,11 +33,13 @@ set( GLEW_ROOT "${PROJECT_SOURCE_DIR}/glew_root" ) #-------------------------------------------------------------------- -find_package( BZip2 REQUIRED ) +if( NOT BZIP2_FOUND ) + find_package( BZip2 REQUIRED ) +endif() set( PREFIX ${DOWNLOAD_DIR}/glew ) -if (APPLE) +if (APPLE) if( CMAKE_OSX_ARCHITECTURES ) set( GLEW_CFLAGS "CFLAGS.EXTRA=-arch ${CMAKE_OSX_ARCHITECTURES} -mmacosx-version-min=10.5" ) set( GLEW_LDFLAGS "LDFLAGS.EXTRA=-arch ${CMAKE_OSX_ARCHITECTURES} -mmacosx-version-min=10.5" ) diff --git a/CMakeModules/download_pixman.cmake b/CMakeModules/download_pixman.cmake index a925d1bf1a..cba41a13ca 100644 --- a/CMakeModules/download_pixman.cmake +++ b/CMakeModules/download_pixman.cmake @@ -33,13 +33,15 @@ set( PIXMAN_ROOT "${PROJECT_SOURCE_DIR}/pixman_root" ) #-------------------------------------------------------------------- -find_package( BZip2 REQUIRED ) +if( NOT BZIP2_FOUND ) + find_package( BZip2 REQUIRED ) +endif() set( PREFIX ${DOWNLOAD_DIR}/pixman ) set(PIXMAN_CPPFLAGS "CFLAGS=") -if (APPLE) +if (APPLE) if( CMAKE_OSX_ARCHITECTURES ) set(PIXMAN_CPPFLAGS "${PIXMAN_CPPFLAGS} -arch ${CMAKE_OSX_ARCHITECTURES} -fno-common -mmacosx-version-min=10.5") else() diff --git a/CMakeModules/download_pkgconfig.cmake b/CMakeModules/download_pkgconfig.cmake index 1960af317a..a0f6c530c1 100644 --- a/CMakeModules/download_pkgconfig.cmake +++ b/CMakeModules/download_pkgconfig.cmake @@ -33,7 +33,9 @@ set( PKGCONFIG_ROOT "${PROJECT_SOURCE_DIR}/pkgconfig_root" ) #-------------------------------------------------------------------- -find_package( BZip2 REQUIRED ) +if( NOT BZIP2_FOUND ) + find_package( BZip2 REQUIRED ) +endif() set( PREFIX ${DOWNLOAD_DIR}/pkgconfig ) diff --git a/CMakeModules/download_wxpython.cmake b/CMakeModules/download_wxpython.cmake index 4e1a71f688..112a8de5ff 100644 --- a/CMakeModules/download_wxpython.cmake +++ b/CMakeModules/download_wxpython.cmake @@ -46,6 +46,10 @@ if (APPLE) STRING(REGEX REPLACE " -arch " "," LIBWXPYTHON_ARCHITECTURES ${CMAKE_OSX_ARCHITECTURES}) SET( LIBWXPYTHON_OPTS ${LIBWXPYTHON_OPTS} --mac_arch=${LIBWXPYTHON_ARCHITECTURES}) endif( CMAKE_OSX_ARCHITECTURES ) + + if( CMAKE_CXX_COMPILER_ID MATCHES "Clang" ) + SET( LIBWXPYTHON_PRECMD export CFLAGS=-Qunused-arguments && ) + endif() endif(APPLE) if ( KICAD_BUILD_STATIC ) @@ -74,7 +78,7 @@ ExternalProject_Add( libwxpython UPDATE_COMMAND ${CMAKE_COMMAND} -E remove_directory "${LIBWXPYTHON_ROOT}" COMMAND ${LIBWXPYTHON_EXEC} wxPython/build-wxpython.py --clean - CONFIGURE_COMMAND ${LIBWXPYTHON_EXEC} wxPython/build-wxpython.py --prefix=${LIBWXPYTHON_ROOT} --unicode --install ${LIBWXPYTHON_OPTS} + CONFIGURE_COMMAND ${LIBWXPYTHON_PRECMD} ${LIBWXPYTHON_EXEC} wxPython/build-wxpython.py --prefix=${LIBWXPYTHON_ROOT} --unicode --install ${LIBWXPYTHON_OPTS} #BINARY_DIR "${PREFIX}" diff --git a/CMakeModules/download_wxwidgets.cmake b/CMakeModules/download_wxwidgets.cmake index 693d490df3..ed7ebe879c 100644 --- a/CMakeModules/download_wxwidgets.cmake +++ b/CMakeModules/download_wxwidgets.cmake @@ -33,11 +33,13 @@ set( LIBWX_ROOT "${PROJECT_SOURCE_DIR}/libwx_root" ) #-------------------------------------------------------------------- -find_package( BZip2 REQUIRED ) +if( NOT BZIP2_FOUND ) + find_package( BZip2 REQUIRED ) +endif() set( PREFIX ${DOWNLOAD_DIR}/libwx ) -if (APPLE) +if (APPLE) if( CMAKE_OSX_ARCHITECTURES ) STRING(REGEX REPLACE " -arch " "," LIBWX_ARCHITECTURES ${CMAKE_OSX_ARCHITECTURES}) SET( LIBWX_ARCHITECTURES --enable-universal_binary=${LIBWX_ARCHITECTURES}) @@ -80,7 +82,7 @@ ExternalProject_Add( libwx #SET directories set(wxWidgets_BIN_DIR ${LIBWX_ROOT}/bin) set(wxWidgets_CONFIG_EXECUTABLE ${LIBWX_ROOT}/bin/wx-config) -set(wxWidgets_INCLUDE_DIRS ${LIBWX_ROOT}/include) +set(wxWidgets_INCLUDE_DIRS ${LIBWX_ROOT}/include) set(wxWidgets_LIBRARY_DIRS ${LIBWX_ROOT}/lib) @@ -110,7 +112,7 @@ ExternalProject_Add_Step( libwx bzr_init_libwx ###### ExternalProject_Add_Step( libwx libwx_recursive_message - COMMAND cmake . + COMMAND cmake . COMMENT "*** RERUN CMAKE - wxWidgets built, now reissue a cmake to build Kicad" DEPENDEES install ) diff --git a/Documentation/GUI_Translation_HOWTO.odt b/Documentation/GUI_Translation_HOWTO.odt index 031e2d682a..163846098d 100644 Binary files a/Documentation/GUI_Translation_HOWTO.odt and b/Documentation/GUI_Translation_HOWTO.odt differ diff --git a/Documentation/GUI_Translation_HOWTO.pdf b/Documentation/GUI_Translation_HOWTO.pdf index 484c38a277..6e6e408def 100644 Binary files a/Documentation/GUI_Translation_HOWTO.pdf and b/Documentation/GUI_Translation_HOWTO.pdf differ diff --git a/Documentation/KIWAY_Build_Symbols_Defined.txt b/Documentation/KIWAY_Build_Symbols_Defined.txt new file mode 100644 index 0000000000..f10dea9b1c --- /dev/null +++ b/Documentation/KIWAY_Build_Symbols_Defined.txt @@ -0,0 +1,29 @@ + +KIWAY Build Symbols, Definitions and Intentions + + +COMPILING_DLL: + + This is a signal to import_export.h, and when present, toggles the + interpretation of the #defines in that file. Its purpose should not be + extended beyond this. + + +USE_KIWAY_DLLS: + + Comes from CMake as a user configuration variable, settable in the Cmake + user interface. It decides if KiCad will be built with the *.kiface program + modules. + + +BUILD_KIWAY_DLL: + + Comes from CMake, but at the 2nd tier, not the top tier. By 2nd tier, + something like pcbnew/CMakeLists.txt, not /CMakeLists.txt is meant. It is + not a user configuration variable. Instead, the 2nd tier CMakeLists.txt file + looks at the top level USE_KIWAY_DLLS and decides how the object files under + the 2nd tier's control will be built. If it decides it wants to march in + lockstep with USE_KIWAY_DLLS, then this local CMakeLists.txt file may pass a + defined BUILD_KIWAY_DLL (singular) on the compiler command line to the + pertinent set of compilation steps under its control. + diff --git a/Documentation/wxWidgets_patch_notes.txt b/Documentation/wxWidgets_patch_notes.txt index bb2e31ae9e..bc2f0df066 100644 --- a/Documentation/wxWidgets_patch_notes.txt +++ b/Documentation/wxWidgets_patch_notes.txt @@ -5,8 +5,7 @@ Last Revised: 28-Feb-2010 Kicad needs wxWidgets, the multi platform G.U.I. Known problems: wxMSW: -*DO NOT* use wxMSW.2.8.1 -in fact: use wxWidgets >= 2.9.3 +use *only* wxWidgets >= 3.0 wxGTK Use wxWidgets 2.8.10 or later @@ -21,15 +20,6 @@ So use a very recent version (>= 2.8.10 (that also solve other bugs) wxWidgets patch: -wxMSW, version 2.8.x -Some zoom values smaller than 3 to 5 create artifacts on screen, mainly values < 1. -(corresponding to draw scale factor > 1 ) - -See http://trac.wxwidgets.org/ticket/9554 (and 11669). - -This is fixed in version 2.9.3 - - wxWidgets 2.9.1 (all platforms) Has a problem when using the built in string to double conversion: In countries using a comm instead of a point as floating number separator @@ -41,7 +31,7 @@ Use a version >= 2.9.3 ************************************************************************************* -wxGTK version: All +wxGTK version: All before wxWidgets 3.0 ************************************************************************************* Patch for printing wide traces that were shown with missing rounded end caps. Without this patch, printing boards and schematics under Linux, and perhaps OSX @@ -57,3 +47,10 @@ Add after this line: PsPrint( "1 setlinecap\n" ); PsPrint("%%EndSetup\n"); + +Known bug on Windows: +Postscript printers print tracks like tin line. +It happens only for PS drivers, and PDF printer. +Other drivers (PCL for instance) work fine, +so it is unlikely a bug inside Kicad/wxWidgets + diff --git a/TODO.txt b/TODO.txt index 0eeec9f0d9..690c07e01c 100644 --- a/TODO.txt +++ b/TODO.txt @@ -62,7 +62,11 @@ PCBNew Dick's Final TODO List: ====================== -*) Get licensing cleaned up. -*) DLL-ization of pcbnew & eeschema - http://www.eevblog.com/forum/open-source-kicad-geda/seriously-irritated-with-the-library-editor!/ - https://blueprints.launchpad.net/kicad/+spec/modular-kicad +*) Get licensing cleaned up. + +*) DLL-ization of pcbnew & eeschema + http://www.eevblog.com/forum/open-source-kicad-geda/seriously-irritated-with-the-library-editor!/ + https://blueprints.launchpad.net/kicad/+spec/modular-kicad + + Issues as a result of minimal testing: + Kicad project manager will crash when requesting help file. diff --git a/bitmap2component/CMakeLists.txt b/bitmap2component/CMakeLists.txt index 9488b896be..5bf7debd48 100644 --- a/bitmap2component/CMakeLists.txt +++ b/bitmap2component/CMakeLists.txt @@ -1,53 +1,68 @@ -include_directories(BEFORE ${INC_BEFORE}) +include_directories( BEFORE ${INC_BEFORE} ) include_directories( ../potrace ../common ${INC_AFTER} ) -set(BITMAP2COMPONENT_SRCS +set( BITMAP2COMPONENT_SRCS + ../common/single_top.cpp bitmap2component.cpp bitmap2cmp_gui_base bitmap2cmp_gui ) -if(WIN32) - if(MINGW) - # BITMAP2COMPONENT_RESOURCES variable is set by the macro. - mingw_resource_compiler(bitmap2component) - else(MINGW) - set(BITMAP2COMPONENT_RESOURCES bitmap2component.rc) - endif(MINGW) -endif(WIN32) +set_source_files_properties( ../common/single_top.cpp PROPERTIES + COMPILE_DEFINITIONS "TOP_FRAME=0" + ) +set_source_files_properties( bitmap2cmp_gui.cpp PROPERTIES + COMPILE_DEFINITIONS "COMPILING_DLL" + ) + +add_executable( bitmap2component WIN32 MACOSX_BUNDLE + ${BITMAP2COMPONENT_SRCS} + ${BITMAP2COMPONENT_RESOURCES} + ) + +target_link_libraries( bitmap2component + common + polygon + bitmaps + ${wxWidgets_LIBRARIES} + potrace + ) + +install( TARGETS bitmap2component + DESTINATION ${KICAD_BIN} + COMPONENT binary + ) -if(APPLE) - set(BITMAP2COMPONENT_RESOURCES bitmap2component.icns) - set_source_files_properties("${CMAKE_CURRENT_SOURCE_DIR}/bitmap2component.icns" - PROPERTIES MACOSX_PACKAGE_LOCATION Resources) - set(MACOSX_BUNDLE_ICON_FILE bitmap2component.icns) - set(MACOSX_BUNDLE_GUI_IDENTIFIER org.kicad-eda.bitmap2component) -endif(APPLE) +if( false ) # linker map with cross reference + set_target_properties( bitmap2component PROPERTIES + LINK_FLAGS "${TO_LINKER},-cref ${TO_LINKER},-Map=bitmap2component.map" + ) +endif() - -add_executable(bitmap2component WIN32 MACOSX_BUNDLE - ${BITMAP2COMPONENT_SRCS} - ${BITMAP2COMPONENT_RESOURCES}) +if( MINGW ) + # BITMAP2COMPONENT_RESOURCES variable is set by the macro. + mingw_resource_compiler( bitmap2component ) +else() + set( BITMAP2COMPONENT_RESOURCES bitmap2component.rc ) +endif() -if(APPLE) - set_target_properties(bitmap2component PROPERTIES MACOSX_BUNDLE_INFO_PLIST - ${CMAKE_CURRENT_SOURCE_DIR}/Info.plist) -endif(APPLE) - -target_link_libraries( bitmap2component common polygon bitmaps - ${wxWidgets_LIBRARIES} - potrace - ) - -install(TARGETS bitmap2component - DESTINATION ${KICAD_BIN} - COMPONENT binary) +if( APPLE ) + set( BITMAP2COMPONENT_RESOURCES bitmap2component.icns ) + set_source_files_properties( "${CMAKE_CURRENT_SOURCE_DIR}/bitmap2component.icns" PROPERTIES + MACOSX_PACKAGE_LOCATION Resources + ) + set( MACOSX_BUNDLE_ICON_FILE bitmap2component.icns ) + set( MACOSX_BUNDLE_GUI_IDENTIFIER org.kicad-eda.bitmap2component ) + set_target_properties( bitmap2component PROPERTIES + MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/Info.plist + ) +endif() diff --git a/bitmap2component/bitmap2cmp_gui.cpp b/bitmap2component/bitmap2cmp_gui.cpp index d83a0fce8c..7b11ffb860 100644 --- a/bitmap2component/bitmap2cmp_gui.cpp +++ b/bitmap2component/bitmap2cmp_gui.cpp @@ -21,16 +21,15 @@ * or you may write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ + #include -#include +#include + +#include #include #include #include -#include -#include -#include - #include #include @@ -39,47 +38,57 @@ #include #include #include +#include +#include -#define KEYWORD_FRAME_POSX wxT( "Bmconverter_Pos_x" ) -#define KEYWORD_FRAME_POSY wxT( "Bmconverter_Pos_y" ) -#define KEYWORD_FRAME_SIZEX wxT( "Bmconverter_Size_x" ) -#define KEYWORD_FRAME_SIZEY wxT( "Bmconverter_Size_y" ) -#define KEYWORD_LAST_INPUT_FILE wxT( "Last_input" ) -#define KEYWORD_LAST_OUTPUT_FILE wxT( "Last_output" ) -#define KEYWORD_LAST_FORMAT wxT( "Last_format" ) -#define KEYWORD_BINARY_THRESHOLD wxT( "Threshold" ) -#define KEYWORD_BW_NEGATIVE wxT( "Negative_choice" ) +#define KEYWORD_FRAME_POSX wxT( "Bmconverter_Pos_x" ) +#define KEYWORD_FRAME_POSY wxT( "Bmconverter_Pos_y" ) +#define KEYWORD_FRAME_SIZEX wxT( "Bmconverter_Size_x" ) +#define KEYWORD_FRAME_SIZEY wxT( "Bmconverter_Size_y" ) +#define KEYWORD_LAST_INPUT_FILE wxT( "Last_input" ) +#define KEYWORD_LAST_OUTPUT_FILE wxT( "Last_output" ) +#define KEYWORD_LAST_FORMAT wxT( "Last_format" ) +#define KEYWORD_BINARY_THRESHOLD wxT( "Threshold" ) +#define KEYWORD_BW_NEGATIVE wxT( "Negative_choice" ) -extern int bitmap2component( potrace_bitmap_t* aPotrace_bitmap, FILE* aOutfile, int aFormat ); +#define DEFAULT_DPI 300 // Default resolution in Bit per inches -/* Class BM2CMP_FRAME_BASE -This is the main frame for this application -*/ +extern int bitmap2component( potrace_bitmap_t* aPotrace_bitmap, FILE* aOutfile, + int aFormat, int aDpi_X, int aDpi_Y ); + +/** + * Class BM2CMP_FRAME_BASE + * is the main frame for this application + */ class BM2CMP_FRAME : public BM2CMP_FRAME_BASE { private: - wxImage m_Pict_Image; - wxBitmap m_Pict_Bitmap; - wxImage m_Greyscale_Image; - wxBitmap m_Greyscale_Bitmap; - wxImage m_NB_Image; - wxBitmap m_BN_Bitmap; - wxString m_BitmapFileName; - wxString m_ConvertedFileName; - wxSize m_FrameSize; - wxPoint m_FramePos; - wxConfig * m_Config; + wxImage m_Pict_Image; + wxBitmap m_Pict_Bitmap; + wxImage m_Greyscale_Image; + wxBitmap m_Greyscale_Bitmap; + wxImage m_NB_Image; + wxBitmap m_BN_Bitmap; + wxSize m_imageDPI; // The initial image resolution. When unknown, + // set to DEFAULT_DPI x DEFAULT_DPI per Inch + wxString m_BitmapFileName; + wxString m_ConvertedFileName; + wxSize m_frameSize; + wxPoint m_framePos; + wxConfig* m_config; public: - BM2CMP_FRAME(); + BM2CMP_FRAME( KIWAY* aKiway, wxWindow* aParent ); ~BM2CMP_FRAME(); + // overload KIWAY_PLAYER virtual + bool OpenProjectFiles( const std::vector& aFilenames, int aCtl=0 ); + private: // Event handlers void OnPaint( wxPaintEvent& event ); void OnLoadFile( wxCommandEvent& event ); - bool LoadFile( wxString& aFullFileName ); void OnExport( wxCommandEvent& event ); /** @@ -109,30 +118,51 @@ private: void Binarize( double aThreshold ); // aThreshold = 0.0 (black level) to 1.0 (white level) void OnOptionsSelection( wxCommandEvent& event ); void OnThresholdChange( wxScrollEvent& event ); + void OnResolutionChange( wxCommandEvent& event ); + + // called when texts controls which handle the image resolution + // lose the focus, to ensure the rigyht vaules are displayed + // because the m_imageDPI are clipped to acceptable values, and + // the text displayed could be differ duringa text edition + // We are using ChangeValue here to avoid generating a wxEVT_TEXT event. + void UpdateDPITextValueX( wxMouseEvent& event ) + { + m_DPIValueX->ChangeValue( wxString::Format( wxT( "%d" ), m_imageDPI.x ) ); + } + void UpdateDPITextValueY( wxMouseEvent& event ) + { + m_DPIValueY->ChangeValue( wxString::Format( wxT( "%d" ), m_imageDPI.y ) ); + } + void NegateGreyscaleImage( ); void ExportFile( FILE* aOutfile, int aFormat ); + void updateImageInfo(); }; -BM2CMP_FRAME::BM2CMP_FRAME() : BM2CMP_FRAME_BASE( NULL ) +BM2CMP_FRAME::BM2CMP_FRAME( KIWAY* aKiway, wxWindow* aParent ) : + BM2CMP_FRAME_BASE( aParent ) { + SetKiway( this, aKiway ); + int tmp; - m_Config = new wxConfig(); - m_Config->Read( KEYWORD_FRAME_POSX, & m_FramePos.x, -1 ); - m_Config->Read( KEYWORD_FRAME_POSY, & m_FramePos.y, -1 ); - m_Config->Read( KEYWORD_FRAME_SIZEX, & m_FrameSize.x, -1 ); - m_Config->Read( KEYWORD_FRAME_SIZEY, & m_FrameSize.y, -1 ); - m_Config->Read( KEYWORD_LAST_INPUT_FILE, &m_BitmapFileName ); - m_Config->Read( KEYWORD_LAST_OUTPUT_FILE, &m_ConvertedFileName ); - if( m_Config->Read( KEYWORD_BINARY_THRESHOLD, &tmp ) ) + m_config = new wxConfig(); + m_config->Read( KEYWORD_FRAME_POSX, & m_framePos.x, -1 ); + m_config->Read( KEYWORD_FRAME_POSY, & m_framePos.y, -1 ); + m_config->Read( KEYWORD_FRAME_SIZEX, & m_frameSize.x, -1 ); + m_config->Read( KEYWORD_FRAME_SIZEY, & m_frameSize.y, -1 ); + m_config->Read( KEYWORD_LAST_INPUT_FILE, &m_BitmapFileName ); + m_config->Read( KEYWORD_LAST_OUTPUT_FILE, &m_ConvertedFileName ); + + if( m_config->Read( KEYWORD_BINARY_THRESHOLD, &tmp ) ) m_sliderThreshold->SetValue( tmp ); - if( m_Config->Read( KEYWORD_BW_NEGATIVE, &tmp ) ) + + if( m_config->Read( KEYWORD_BW_NEGATIVE, &tmp ) ) m_rbOptions->SetSelection( tmp ? 1 : 0 ); - m_Config->Read( KEYWORD_LAST_FORMAT, &tmp ); + m_config->Read( KEYWORD_LAST_FORMAT, &tmp ); m_radioBoxFormat->SetSelection( tmp ); - // Give an icon wxIcon icon; icon.CopyFromBitmap( KiBitmap( icon_bitmap2component_xpm ) ); @@ -140,34 +170,36 @@ BM2CMP_FRAME::BM2CMP_FRAME() : BM2CMP_FRAME_BASE( NULL ) GetSizer()->SetSizeHints( this ); - SetSize( m_FramePos.x, m_FramePos.y, m_FrameSize.x, m_FrameSize.y ); + SetSize( m_framePos.x, m_framePos.y, m_frameSize.x, m_frameSize.y ); m_buttonExport->Enable( false ); - if ( m_FramePos == wxDefaultPosition ) + m_imageDPI.x = m_imageDPI.y = DEFAULT_DPI; // Default resolution in Bit per inches + + if ( m_framePos == wxDefaultPosition ) Centre(); } BM2CMP_FRAME::~BM2CMP_FRAME() { - if( ( m_Config == NULL ) || IsIconized() ) + if( !m_config || IsIconized() ) return; - m_FrameSize = GetSize(); - m_FramePos = GetPosition(); + m_frameSize = GetSize(); + m_framePos = GetPosition(); - m_Config->Write( KEYWORD_FRAME_POSX, (long) m_FramePos.x ); - m_Config->Write( KEYWORD_FRAME_POSY, (long) m_FramePos.y ); - m_Config->Write( KEYWORD_FRAME_SIZEX, (long) m_FrameSize.x ); - m_Config->Write( KEYWORD_FRAME_SIZEY, (long) m_FrameSize.y ); - m_Config->Write( KEYWORD_LAST_INPUT_FILE, m_BitmapFileName ); - m_Config->Write( KEYWORD_LAST_OUTPUT_FILE, m_ConvertedFileName ); - m_Config->Write( KEYWORD_BINARY_THRESHOLD, m_sliderThreshold->GetValue() ); - m_Config->Write( KEYWORD_BW_NEGATIVE, m_rbOptions->GetSelection() ); - m_Config->Write( KEYWORD_LAST_FORMAT, m_radioBoxFormat->GetSelection() ); + m_config->Write( KEYWORD_FRAME_POSX, (long) m_framePos.x ); + m_config->Write( KEYWORD_FRAME_POSY, (long) m_framePos.y ); + m_config->Write( KEYWORD_FRAME_SIZEX, (long) m_frameSize.x ); + m_config->Write( KEYWORD_FRAME_SIZEY, (long) m_frameSize.y ); + m_config->Write( KEYWORD_LAST_INPUT_FILE, m_BitmapFileName ); + m_config->Write( KEYWORD_LAST_OUTPUT_FILE, m_ConvertedFileName ); + m_config->Write( KEYWORD_BINARY_THRESHOLD, m_sliderThreshold->GetValue() ); + m_config->Write( KEYWORD_BW_NEGATIVE, m_rbOptions->GetSelection() ); + m_config->Write( KEYWORD_LAST_FORMAT, m_radioBoxFormat->GetSelection() ); - delete m_Config; + delete m_config; /* This needed for OSX: avoids further OnDraw processing after this * destructor and before the native window is destroyed @@ -207,23 +239,24 @@ void BM2CMP_FRAME::OnPaint( wxPaintEvent& event ) */ void BM2CMP_FRAME::OnLoadFile( wxCommandEvent& event ) { - wxFileName fn(m_BitmapFileName); - wxString path = fn.GetPath(); + wxFileName fn( m_BitmapFileName ); + wxString path = fn.GetPath(); if( path.IsEmpty() || !wxDirExists(path) ) path = wxGetCwd(); - wxFileDialog FileDlg( this, _( "Choose Image" ), path, wxEmptyString, + wxFileDialog fileDlg( this, _( "Choose Image" ), path, wxEmptyString, _( "Image Files " ) + wxImage::GetImageExtWildcard(), wxFD_OPEN ); - int diag = FileDlg.ShowModal(); + + int diag = fileDlg.ShowModal(); if( diag != wxID_OK ) return; - wxString fullFilename = FileDlg.GetPath(); + wxString fullFilename = fileDlg.GetPath(); - if( ! LoadFile( fullFilename ) ) + if( !OpenProjectFiles( std::vector( 1, fullFilename ) ) ) return; m_buttonExport->Enable( true ); @@ -232,13 +265,22 @@ void BM2CMP_FRAME::OnLoadFile( wxCommandEvent& event ) } -bool BM2CMP_FRAME::LoadFile( wxString& aFullFileName ) +bool BM2CMP_FRAME::OpenProjectFiles( const std::vector& aFileSet, int aCtl ) { - m_BitmapFileName = aFullFileName; + // Prj().MaybeLoadProjectSettings(); + + m_BitmapFileName = aFileSet[0]; if( !m_Pict_Image.LoadFile( m_BitmapFileName ) ) { - wxMessageBox( _( "Couldn't load image from <%s>" ), m_BitmapFileName.c_str() ); + /* LoadFile has its own UI, no need for further failure notification here + wxString msg = wxString::Format( + _( "Could not load image '%s'" ), + GetChars( aFilename ) + ); + + wxMessageBox( msg ); + */ return false; } @@ -246,15 +288,32 @@ bool BM2CMP_FRAME::LoadFile( wxString& aFullFileName ) int h = m_Pict_Bitmap.GetHeight(); int w = m_Pict_Bitmap.GetWidth(); - int nb = m_Pict_Bitmap.GetDepth(); - wxString msg; - msg.Printf( wxT( "%d" ), w ); - m_SizeXValue->SetLabel(msg); - msg.Printf( wxT( "%d" ), h ); - m_SizeYValue->SetLabel(msg); - msg.Printf( wxT( "%d" ), nb ); - m_BPPValue->SetLabel(msg); + // Determine image resolution in DPI (does not existing in all formats). + // the resolution can be given in bit per inches or bit per cm in file + m_imageDPI.x = m_Pict_Image.GetOptionInt( wxIMAGE_OPTION_RESOLUTIONX ); + m_imageDPI.y = m_Pict_Image.GetOptionInt( wxIMAGE_OPTION_RESOLUTIONY ); + + if( m_imageDPI.x > 1 && m_imageDPI.y > 1 ) + { + if( m_Pict_Image.GetOptionInt( wxIMAGE_OPTION_RESOLUTIONUNIT ) == wxIMAGE_RESOLUTION_CM ) + { + // When the initial resolution is given in bits per cm, + // experience shows adding 1.27 to the resolution converted in dpi + // before convert to int value reduce the conversion error + // but it is not perfect + m_imageDPI.x = m_imageDPI.x * 2.54 + 1.27; + m_imageDPI.y = m_imageDPI.y * 2.54 + 1.27; + } + } + else // fallback to the default value + m_imageDPI.x = m_imageDPI.y = DEFAULT_DPI; + + // Display image info: + // We are using ChangeValue here to avoid generating a wxEVT_TEXT event. + m_DPIValueX->ChangeValue( wxString::Format( wxT( "%d" ), m_imageDPI.x ) ); + m_DPIValueY->ChangeValue( wxString::Format( wxT( "%d" ), m_imageDPI.y ) ); + updateImageInfo(); m_InitialPicturePanel->SetVirtualSize( w, h ); m_GreyscalePicturePanel->SetVirtualSize( w, h ); @@ -262,16 +321,55 @@ bool BM2CMP_FRAME::LoadFile( wxString& aFullFileName ) m_Greyscale_Image.Destroy(); m_Greyscale_Image = m_Pict_Image.ConvertToGreyscale( ); + if( m_rbOptions->GetSelection() > 0 ) NegateGreyscaleImage( ); + m_Greyscale_Bitmap = wxBitmap( m_Greyscale_Image ); m_NB_Image = m_Greyscale_Image; - Binarize( (double)m_sliderThreshold->GetValue()/m_sliderThreshold->GetMax() ); + Binarize( (double) m_sliderThreshold->GetValue()/m_sliderThreshold->GetMax() ); return true; } +void BM2CMP_FRAME::updateImageInfo() +{ + // Note: the image resolution text controls are not modified + // here, to avoid a race between text change when entered by user and + // a text change if it is modifed here. + int h = m_Pict_Bitmap.GetHeight(); + int w = m_Pict_Bitmap.GetWidth(); + int nb = m_Pict_Bitmap.GetDepth(); + + m_SizeXValue->SetLabel( wxString::Format( wxT( "%d" ), w ) ); + m_SizeYValue->SetLabel( wxString::Format( wxT( "%d" ), h ) ); + m_BPPValue->SetLabel( wxString::Format( wxT( "%d" ), nb ) ); + + m_SizeXValue_mm->SetLabel( wxString::Format( wxT( "%.1f" ), + (double) w / m_imageDPI.x * 25.4 ) ); + m_SizeYValue_mm->SetLabel( wxString::Format( wxT( "%.1f" ), + (double) h / m_imageDPI.y * 25.4 ) ); +} + +void BM2CMP_FRAME::OnResolutionChange( wxCommandEvent& event ) +{ + long tmp; + + if( m_DPIValueX->GetValue().ToLong( &tmp ) ) + m_imageDPI.x = tmp; + + if( m_DPIValueY->GetValue().ToLong( &tmp ) ) + m_imageDPI.y = tmp; + + if( m_imageDPI.x < 32 ) + m_imageDPI.x = 32; + + if( m_imageDPI.y < 32 ) + m_imageDPI.y = 32; + + updateImageInfo(); +} void BM2CMP_FRAME::Binarize( double aThreshold ) { @@ -297,11 +395,12 @@ void BM2CMP_FRAME::Binarize( double aThreshold ) m_BN_Bitmap = wxBitmap( m_NB_Image ); } + void BM2CMP_FRAME::NegateGreyscaleImage( ) { unsigned char pix; - int h = m_Greyscale_Image.GetHeight(); - int w = m_Greyscale_Image.GetWidth(); + int h = m_Greyscale_Image.GetHeight(); + int w = m_Greyscale_Image.GetWidth(); for( int y = 0; y < h; y++ ) for( int x = 0; x < w; x++ ) @@ -321,58 +420,61 @@ void BM2CMP_FRAME::OnOptionsSelection( wxCommandEvent& event ) Refresh(); } + void BM2CMP_FRAME::OnThresholdChange( wxScrollEvent& event ) { Binarize( (double)m_sliderThreshold->GetValue()/m_sliderThreshold->GetMax() ); Refresh(); } + void BM2CMP_FRAME::OnExport( wxCommandEvent& event ) { int sel = m_radioBoxFormat->GetSelection(); switch( sel ) { - case 0: - OnExportEeschema(); - break; + case 0: + OnExportEeschema(); + break; - case 1: - OnExportPcbnew( true ); - break; + case 1: + OnExportPcbnew( true ); + break; - case 2: - OnExportPcbnew( false ); - break; + case 2: + OnExportPcbnew( false ); + break; - case 3: - OnExportPostScript(); - break; + case 3: + OnExportPostScript(); + break; - case 4: - OnExportLogo(); - break; + case 4: + OnExportLogo(); + break; } } + void BM2CMP_FRAME::OnExportLogo() { - wxFileName fn(m_ConvertedFileName); - wxString path = fn.GetPath(); + wxFileName fn( m_ConvertedFileName ); + wxString path = fn.GetPath(); if( path.IsEmpty() || !wxDirExists(path) ) path = ::wxGetCwd(); wxString msg = _( "Logo file (*.kicad_wks)|*.kicad_wks" ); - wxFileDialog FileDlg( this, _( "Create a logo file" ), path, wxEmptyString, + wxFileDialog fileDlg( this, _( "Create a logo file" ), path, wxEmptyString, msg, wxFD_SAVE | wxFD_OVERWRITE_PROMPT ); - int diag = FileDlg.ShowModal(); + int diag = fileDlg.ShowModal(); if( diag != wxID_OK ) return; - m_ConvertedFileName = FileDlg.GetPath(); + m_ConvertedFileName = fileDlg.GetPath(); FILE* outfile; outfile = wxFopen( m_ConvertedFileName, wxT( "w" ) ); @@ -389,24 +491,26 @@ void BM2CMP_FRAME::OnExportLogo() fclose( outfile ); } + void BM2CMP_FRAME::OnExportPostScript() { - wxFileName fn(m_ConvertedFileName); - wxString path = fn.GetPath(); + wxFileName fn( m_ConvertedFileName ); + wxString path = fn.GetPath(); - if( path.IsEmpty() || !wxDirExists(path) ) + if( path.IsEmpty() || !wxDirExists( path ) ) path = ::wxGetCwd(); wxString msg = _( "Postscript file (*.ps)|*.ps" ); - wxFileDialog FileDlg( this, _( "Create a Postscript file" ), path, wxEmptyString, + wxFileDialog fileDlg( this, _( "Create a Postscript file" ), path, wxEmptyString, msg, wxFD_SAVE | wxFD_OVERWRITE_PROMPT ); - int diag = FileDlg.ShowModal(); + + int diag = fileDlg.ShowModal(); if( diag != wxID_OK ) return; - m_ConvertedFileName = FileDlg.GetPath(); + m_ConvertedFileName = fileDlg.GetPath(); FILE* outfile; outfile = wxFopen( m_ConvertedFileName, wxT( "w" ) ); @@ -423,27 +527,29 @@ void BM2CMP_FRAME::OnExportPostScript() fclose( outfile ); } + void BM2CMP_FRAME::OnExportEeschema() { - wxFileName fn(m_ConvertedFileName); - wxString path = fn.GetPath(); + wxFileName fn( m_ConvertedFileName ); + wxString path = fn.GetPath(); if( path.IsEmpty() || !wxDirExists(path) ) path = ::wxGetCwd(); wxString msg = _( "Schematic lib file (*.lib)|*.lib" ); - wxFileDialog FileDlg( this, _( "Create a lib file for Eeschema" ), path, wxEmptyString, + + wxFileDialog fileDlg( this, _( "Create a lib file for Eeschema" ), path, wxEmptyString, msg, wxFD_SAVE | wxFD_OVERWRITE_PROMPT ); - int diag = FileDlg.ShowModal(); + + int diag = fileDlg.ShowModal(); if( diag != wxID_OK ) return; - m_ConvertedFileName = FileDlg.GetPath(); + m_ConvertedFileName = fileDlg.GetPath(); - FILE* outfile; - outfile = wxFopen( m_ConvertedFileName, wxT( "w" ) ); + FILE* outfile = wxFopen( m_ConvertedFileName, wxT( "w" ) ); if( outfile == NULL ) { @@ -460,29 +566,29 @@ void BM2CMP_FRAME::OnExportEeschema() void BM2CMP_FRAME::OnExportPcbnew( bool aLegacyFormat ) { - wxFileName fn(m_ConvertedFileName); - wxString path = fn.GetPath(); + wxFileName fn( m_ConvertedFileName ); + wxString path = fn.GetPath(); - if( path.IsEmpty() || !wxDirExists(path) ) + if( path.IsEmpty() || !wxDirExists( path ) ) path = ::wxGetCwd(); wxString msg = aLegacyFormat ? _( "Footprint file (*.emp)|*.emp" ) : _( "Footprint file (*.kicad_mod)|*.kicad_mod" ); - wxFileDialog FileDlg( this, _( "Create a footprint file for PcbNew" ), + + wxFileDialog fileDlg( this, _( "Create a footprint file for PcbNew" ), path, wxEmptyString, msg, wxFD_SAVE | wxFD_OVERWRITE_PROMPT ); - int diag = FileDlg.ShowModal(); + + int diag = fileDlg.ShowModal(); if( diag != wxID_OK ) return; - m_ConvertedFileName = FileDlg.GetPath(); + m_ConvertedFileName = fileDlg.GetPath(); - - FILE* outfile; - outfile = wxFopen( m_ConvertedFileName, wxT( "w" ) ); + FILE* outfile = wxFopen( m_ConvertedFileName, wxT( "w" ) ); if( outfile == NULL ) { @@ -496,6 +602,7 @@ void BM2CMP_FRAME::OnExportPcbnew( bool aLegacyFormat ) fclose( outfile ); } + void BM2CMP_FRAME::ExportFile( FILE* aOutfile, int aFormat ) { // Create a potrace bitmap @@ -514,40 +621,93 @@ void BM2CMP_FRAME::ExportFile( FILE* aOutfile, int aFormat ) /* fill the bitmap with data */ for( int y = 0; y < h; y++ ) { - for( int x = 0; x----------------------------------------------------------------- -///----------------------------------------------------------------------------- -// EDA_APP -// main program -//----------------------------------------------------------------------------- +namespace BMP2CMP { -bool EDA_APP::OnInit() +static struct IFACE : public KIFACE_I { - wxInitAllImageHandlers(); + bool OnKifaceStart( PGM_BASE* aProgram ); - InitEDA_Appl( wxT( "BMP2CMP" ) ); + wxWindow* CreateWindow( wxWindow* aParent, int aClassId, KIWAY* aKiway, int aCtlBits = 0 ) + { + switch( aClassId ) + { - wxFrame* frame = new BM2CMP_FRAME(); - SetTopWindow( frame ); - frame->Show( true ); + default: + { + KIWAY_PLAYER* frame = new BM2CMP_FRAME( aKiway, aParent ); + return frame; + } + } + } - return true; -} + /** + * Function IfaceOrAddress + * return a pointer to the requested object. The safest way to use this + * is to retrieve a pointer to a static instance of an interface, similar to + * how the KIFACE interface is exported. But if you know what you are doing + * use it to retrieve anything you want. + * + * @param aDataId identifies which object you want the address of. + * + * @return void* - and must be cast into the know type. + */ + void* IfaceOrAddress( int aDataId ) + { + return NULL; + } + IFACE( const char* aDSOname, KIWAY::FACE_T aType ) : + KIFACE_I( aDSOname, aType ) + {} -void EDA_APP::MacOpenFile( const wxString& aFileName ) +} kiface( "BMP2CMP", KIWAY::FACE_BMP2CMP ); + +} // namespace BMP2CMP + +using namespace BMP2CMP; + +static PGM_BASE* process; + +KIFACE_I& Kiface() { + return kiface; } + + +// KIFACE_GETTER's actual spelling is a substitution macro found in kiway.h. +// KIFACE_GETTER will not have name mangling due to declaration in kiway.h. +MY_API( KIFACE* ) KIFACE_GETTER( int* aKIFACEversion, int aKIWAYversion, PGM_BASE* aProgram ) +{ + process = (PGM_BASE*) aProgram; + return &kiface; +} + + +#if defined(BUILD_KIWAY_DLLS) +PGM_BASE& Pgm() +{ + wxASSERT( process ); // KIFACE_GETTER has already been called. + return *process; +} +#endif + + +bool IFACE::OnKifaceStart( PGM_BASE* aProgram ) +{ + return start_common(); +} + diff --git a/bitmap2component/bitmap2cmp_gui_base.cpp b/bitmap2component/bitmap2cmp_gui_base.cpp index 92315a9545..594bcff5e0 100644 --- a/bitmap2component/bitmap2cmp_gui_base.cpp +++ b/bitmap2component/bitmap2cmp_gui_base.cpp @@ -1,5 +1,5 @@ /////////////////////////////////////////////////////////////////////////// -// C++ code generated with wxFormBuilder (version Oct 8 2012) +// C++ code generated with wxFormBuilder (version Nov 5 2013) // http://www.wxformbuilder.org/ // // PLEASE DO "NOT" EDIT THIS FILE! @@ -9,7 +9,7 @@ /////////////////////////////////////////////////////////////////////////// -BM2CMP_FRAME_BASE::BM2CMP_FRAME_BASE( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxFrame( parent, id, title, pos, size, style ) +BM2CMP_FRAME_BASE::BM2CMP_FRAME_BASE( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : KIWAY_PLAYER( parent, id, title, pos, size, style ) { this->SetSizeHints( wxDefaultSize, wxDefaultSize ); @@ -41,33 +41,43 @@ BM2CMP_FRAME_BASE::BM2CMP_FRAME_BASE( wxWindow* parent, wxWindowID id, const wxS sbSizerInfo = new wxStaticBoxSizer( new wxStaticBox( m_panelRight, wxID_ANY, _("Bitmap Info:") ), wxVERTICAL ); wxFlexGridSizer* fgSizerInfo; - fgSizerInfo = new wxFlexGridSizer( 3, 3, 0, 0 ); + fgSizerInfo = new wxFlexGridSizer( 0, 4, 0, 0 ); + fgSizerInfo->AddGrowableCol( 1 ); + fgSizerInfo->AddGrowableCol( 2 ); fgSizerInfo->SetFlexibleDirection( wxBOTH ); fgSizerInfo->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); - m_staticTextSizeX = new wxStaticText( m_panelRight, wxID_ANY, _("Size X:"), wxDefaultPosition, wxDefaultSize, 0 ); - m_staticTextSizeX->Wrap( -1 ); - fgSizerInfo->Add( m_staticTextSizeX, 0, wxALIGN_RIGHT|wxALL|wxALIGN_CENTER_VERTICAL, 5 ); + m_staticTextSize = new wxStaticText( m_panelRight, wxID_ANY, _("Size:"), wxDefaultPosition, wxDefaultSize, 0 ); + m_staticTextSize->Wrap( -1 ); + fgSizerInfo->Add( m_staticTextSize, 0, wxALIGN_RIGHT|wxALL|wxALIGN_CENTER_VERTICAL, 5 ); m_SizeXValue = new wxStaticText( m_panelRight, wxID_ANY, _("0000"), wxDefaultPosition, wxDefaultSize, 0 ); m_SizeXValue->Wrap( -1 ); - fgSizerInfo->Add( m_SizeXValue, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - - m_SizeXunits = new wxStaticText( m_panelRight, wxID_ANY, _("pixels"), wxDefaultPosition, wxDefaultSize, 0 ); - m_SizeXunits->Wrap( -1 ); - fgSizerInfo->Add( m_SizeXunits, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - - m_staticTextSizeY = new wxStaticText( m_panelRight, wxID_ANY, _("Size Y:"), wxDefaultPosition, wxDefaultSize, 0 ); - m_staticTextSizeY->Wrap( -1 ); - fgSizerInfo->Add( m_staticTextSizeY, 0, wxALIGN_RIGHT|wxBOTTOM|wxRIGHT|wxLEFT|wxALIGN_CENTER_VERTICAL, 5 ); + fgSizerInfo->Add( m_SizeXValue, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxRIGHT, 5 ); m_SizeYValue = new wxStaticText( m_panelRight, wxID_ANY, _("0000"), wxDefaultPosition, wxDefaultSize, 0 ); m_SizeYValue->Wrap( -1 ); - fgSizerInfo->Add( m_SizeYValue, 0, wxBOTTOM|wxRIGHT|wxLEFT|wxALIGN_CENTER_VERTICAL, 5 ); + fgSizerInfo->Add( m_SizeYValue, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxRIGHT, 5 ); - m_SizeYunits = new wxStaticText( m_panelRight, wxID_ANY, _("pixels"), wxDefaultPosition, wxDefaultSize, 0 ); - m_SizeYunits->Wrap( -1 ); - fgSizerInfo->Add( m_SizeYunits, 0, wxBOTTOM|wxRIGHT|wxLEFT|wxALIGN_CENTER_VERTICAL, 5 ); + m_SizePixUnits = new wxStaticText( m_panelRight, wxID_ANY, _("pixels"), wxDefaultPosition, wxDefaultSize, 0 ); + m_SizePixUnits->Wrap( -1 ); + fgSizerInfo->Add( m_SizePixUnits, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxRIGHT, 5 ); + + m_staticTextSize1 = new wxStaticText( m_panelRight, wxID_ANY, _("Size:"), wxDefaultPosition, wxDefaultSize, 0 ); + m_staticTextSize1->Wrap( -1 ); + fgSizerInfo->Add( m_staticTextSize1, 0, wxBOTTOM|wxRIGHT|wxLEFT|wxALIGN_RIGHT, 5 ); + + m_SizeXValue_mm = new wxStaticText( m_panelRight, wxID_ANY, _("0000"), wxDefaultPosition, wxDefaultSize, 0 ); + m_SizeXValue_mm->Wrap( -1 ); + fgSizerInfo->Add( m_SizeXValue_mm, 0, wxBOTTOM|wxRIGHT, 5 ); + + m_SizeYValue_mm = new wxStaticText( m_panelRight, wxID_ANY, _("0000"), wxDefaultPosition, wxDefaultSize, 0 ); + m_SizeYValue_mm->Wrap( -1 ); + fgSizerInfo->Add( m_SizeYValue_mm, 0, wxBOTTOM|wxRIGHT, 5 ); + + m_Size_mmxUnits = new wxStaticText( m_panelRight, wxID_ANY, _("mm"), wxDefaultPosition, wxDefaultSize, 0 ); + m_Size_mmxUnits->Wrap( -1 ); + fgSizerInfo->Add( m_Size_mmxUnits, 0, wxBOTTOM|wxRIGHT, 5 ); m_staticTextBPP = new wxStaticText( m_panelRight, wxID_ANY, _("BPP:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticTextBPP->Wrap( -1 ); @@ -75,17 +85,38 @@ BM2CMP_FRAME_BASE::BM2CMP_FRAME_BASE( wxWindow* parent, wxWindowID id, const wxS m_BPPValue = new wxStaticText( m_panelRight, wxID_ANY, _("0000"), wxDefaultPosition, wxDefaultSize, 0 ); m_BPPValue->Wrap( -1 ); - fgSizerInfo->Add( m_BPPValue, 0, wxBOTTOM|wxRIGHT|wxLEFT|wxALIGN_CENTER_VERTICAL, 5 ); + fgSizerInfo->Add( m_BPPValue, 0, wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxRIGHT, 5 ); m_BPPunits = new wxStaticText( m_panelRight, wxID_ANY, _("bits"), wxDefaultPosition, wxDefaultSize, 0 ); m_BPPunits->Wrap( -1 ); fgSizerInfo->Add( m_BPPunits, 0, wxBOTTOM|wxRIGHT|wxLEFT|wxALIGN_CENTER_VERTICAL, 5 ); + fgSizerInfo->Add( 0, 0, 1, wxEXPAND, 5 ); + + m_staticTextBPI = new wxStaticText( m_panelRight, wxID_ANY, _("Resolution:"), wxDefaultPosition, wxDefaultSize, 0 ); + m_staticTextBPI->Wrap( -1 ); + fgSizerInfo->Add( m_staticTextBPI, 0, wxALIGN_RIGHT|wxBOTTOM|wxRIGHT|wxLEFT|wxALIGN_CENTER_VERTICAL, 5 ); + + m_DPIValueX = new wxTextCtrl( m_panelRight, wxID_ANY, _("300"), wxDefaultPosition, wxDefaultSize, 0 ); + m_DPIValueX->SetMinSize( wxSize( 40,-1 ) ); + + fgSizerInfo->Add( m_DPIValueX, 0, wxBOTTOM|wxRIGHT, 5 ); + + m_DPIValueY = new wxTextCtrl( m_panelRight, wxID_ANY, _("300"), wxDefaultPosition, wxDefaultSize, 0 ); + m_DPIValueY->SetMinSize( wxSize( 40,-1 ) ); + + fgSizerInfo->Add( m_DPIValueY, 0, wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxRIGHT, 5 ); + + m_DPI_Units = new wxStaticText( m_panelRight, wxID_ANY, _("DPI"), wxDefaultPosition, wxDefaultSize, 0 ); + m_DPI_Units->Wrap( -1 ); + fgSizerInfo->Add( m_DPI_Units, 0, wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxRIGHT, 5 ); + + sbSizerInfo->Add( fgSizerInfo, 0, wxEXPAND|wxBOTTOM, 5 ); - brightSizer->Add( sbSizerInfo, 0, wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT, 5 ); + brightSizer->Add( sbSizerInfo, 0, wxEXPAND|wxALL, 5 ); m_buttonLoad = new wxButton( m_panelRight, wxID_ANY, _("Load Bitmap"), wxDefaultPosition, wxDefaultSize, 0 ); brightSizer->Add( m_buttonLoad, 0, wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxBOTTOM|wxRIGHT|wxLEFT, 5 ); @@ -98,18 +129,18 @@ BM2CMP_FRAME_BASE::BM2CMP_FRAME_BASE( wxWindow* parent, wxWindowID id, const wxS wxString m_radioBoxFormatChoices[] = { _("Eeschema"), _("Pcbnew old fmt (.emp)"), _("Pcbnew kicad_mod"), _("Postscript"), _("Logo for title block") }; int m_radioBoxFormatNChoices = sizeof( m_radioBoxFormatChoices ) / sizeof( wxString ); m_radioBoxFormat = new wxRadioBox( m_panelRight, wxID_ANY, _("Format"), wxDefaultPosition, wxDefaultSize, m_radioBoxFormatNChoices, m_radioBoxFormatChoices, 1, wxRA_SPECIFY_COLS ); - m_radioBoxFormat->SetSelection( 4 ); - brightSizer->Add( m_radioBoxFormat, 0, wxBOTTOM|wxRIGHT|wxLEFT, 5 ); + m_radioBoxFormat->SetSelection( 2 ); + brightSizer->Add( m_radioBoxFormat, 0, wxEXPAND|wxALL, 5 ); wxString m_rbOptionsChoices[] = { _("Normal"), _("Negative") }; int m_rbOptionsNChoices = sizeof( m_rbOptionsChoices ) / sizeof( wxString ); m_rbOptions = new wxRadioBox( m_panelRight, wxID_ANY, _("Options"), wxDefaultPosition, wxDefaultSize, m_rbOptionsNChoices, m_rbOptionsChoices, 1, wxRA_SPECIFY_COLS ); m_rbOptions->SetSelection( 0 ); - brightSizer->Add( m_rbOptions, 0, wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT, 5 ); + brightSizer->Add( m_rbOptions, 0, wxEXPAND|wxALL, 5 ); m_ThresholdText = new wxStaticText( m_panelRight, wxID_ANY, _("Threshold Value:"), wxDefaultPosition, wxDefaultSize, 0 ); m_ThresholdText->Wrap( -1 ); - brightSizer->Add( m_ThresholdText, 0, wxRIGHT|wxLEFT, 5 ); + brightSizer->Add( m_ThresholdText, 0, wxTOP|wxRIGHT|wxLEFT, 5 ); m_sliderThreshold = new wxSlider( m_panelRight, wxID_ANY, 50, 0, 100, wxDefaultPosition, wxDefaultSize, wxSL_HORIZONTAL|wxSL_LABELS ); m_sliderThreshold->SetToolTip( _("Adjust the level to convert the greyscale picture to a black and white picture.") ); @@ -131,6 +162,10 @@ BM2CMP_FRAME_BASE::BM2CMP_FRAME_BASE( wxWindow* parent, wxWindowID id, const wxS m_InitialPicturePanel->Connect( wxEVT_PAINT, wxPaintEventHandler( BM2CMP_FRAME_BASE::OnPaint ), NULL, this ); m_GreyscalePicturePanel->Connect( wxEVT_PAINT, wxPaintEventHandler( BM2CMP_FRAME_BASE::OnPaint ), NULL, this ); m_BNPicturePanel->Connect( wxEVT_PAINT, wxPaintEventHandler( BM2CMP_FRAME_BASE::OnPaint ), NULL, this ); + m_DPIValueX->Connect( wxEVT_LEAVE_WINDOW, wxMouseEventHandler( BM2CMP_FRAME_BASE::UpdatePPITextValueX ), NULL, this ); + m_DPIValueX->Connect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( BM2CMP_FRAME_BASE::OnResolutionChange ), NULL, this ); + m_DPIValueY->Connect( wxEVT_LEAVE_WINDOW, wxMouseEventHandler( BM2CMP_FRAME_BASE::UpdatePPITextValueY ), NULL, this ); + m_DPIValueY->Connect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( BM2CMP_FRAME_BASE::OnResolutionChange ), NULL, this ); m_buttonLoad->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( BM2CMP_FRAME_BASE::OnLoadFile ), NULL, this ); m_buttonExport->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( BM2CMP_FRAME_BASE::OnExport ), NULL, this ); m_rbOptions->Connect( wxEVT_COMMAND_RADIOBOX_SELECTED, wxCommandEventHandler( BM2CMP_FRAME_BASE::OnOptionsSelection ), NULL, this ); @@ -143,6 +178,10 @@ BM2CMP_FRAME_BASE::~BM2CMP_FRAME_BASE() m_InitialPicturePanel->Disconnect( wxEVT_PAINT, wxPaintEventHandler( BM2CMP_FRAME_BASE::OnPaint ), NULL, this ); m_GreyscalePicturePanel->Disconnect( wxEVT_PAINT, wxPaintEventHandler( BM2CMP_FRAME_BASE::OnPaint ), NULL, this ); m_BNPicturePanel->Disconnect( wxEVT_PAINT, wxPaintEventHandler( BM2CMP_FRAME_BASE::OnPaint ), NULL, this ); + m_DPIValueX->Disconnect( wxEVT_LEAVE_WINDOW, wxMouseEventHandler( BM2CMP_FRAME_BASE::UpdatePPITextValueX ), NULL, this ); + m_DPIValueX->Disconnect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( BM2CMP_FRAME_BASE::OnResolutionChange ), NULL, this ); + m_DPIValueY->Disconnect( wxEVT_LEAVE_WINDOW, wxMouseEventHandler( BM2CMP_FRAME_BASE::UpdatePPITextValueY ), NULL, this ); + m_DPIValueY->Disconnect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( BM2CMP_FRAME_BASE::OnResolutionChange ), NULL, this ); m_buttonLoad->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( BM2CMP_FRAME_BASE::OnLoadFile ), NULL, this ); m_buttonExport->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( BM2CMP_FRAME_BASE::OnExport ), NULL, this ); m_rbOptions->Disconnect( wxEVT_COMMAND_RADIOBOX_SELECTED, wxCommandEventHandler( BM2CMP_FRAME_BASE::OnOptionsSelection ), NULL, this ); diff --git a/bitmap2component/bitmap2cmp_gui_base.fbp b/bitmap2component/bitmap2cmp_gui_base.fbp index d848aa0d8c..6ebddf257d 100644 --- a/bitmap2component/bitmap2cmp_gui_base.fbp +++ b/bitmap2component/bitmap2cmp_gui_base.fbp @@ -20,8 +20,10 @@ . 1 + 1 1 1 + UI 0 0 @@ -44,7 +46,7 @@ 527,470 wxDEFAULT_FRAME_STYLE|wxRESIZE_BORDER - + KIWAY_PLAYER; kiway_player.h Bitmap to Component Converter @@ -506,7 +508,7 @@ none 5 - wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT + wxEXPAND|wxALL 0 wxID_ANY @@ -521,16 +523,16 @@ wxEXPAND|wxBOTTOM 0 - 3 + 4 wxBOTH - + 1,2 0 fgSizerInfo wxFLEX_GROWMODE_SPECIFIED none - 3 + 0 0 5 @@ -564,7 +566,7 @@ 0 0 wxID_ANY - Size X: + Size: 0 @@ -572,7 +574,7 @@ 0 1 - m_staticTextSizeX + m_staticTextSize 1 @@ -617,7 +619,7 @@ 5 - wxALL|wxALIGN_CENTER_VERTICAL + wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxRIGHT 0 1 @@ -700,173 +702,7 @@ 5 - wxALL|wxALIGN_CENTER_VERTICAL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - pixels - - 0 - - - 0 - - 1 - m_SizeXunits - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALIGN_RIGHT|wxBOTTOM|wxRIGHT|wxLEFT|wxALIGN_CENTER_VERTICAL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Size Y: - - 0 - - - 0 - - 1 - m_staticTextSizeY - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxBOTTOM|wxRIGHT|wxLEFT|wxALIGN_CENTER_VERTICAL + wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxRIGHT 0 1 @@ -949,7 +785,7 @@ 5 - wxBOTTOM|wxRIGHT|wxLEFT|wxALIGN_CENTER_VERTICAL + wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxRIGHT 0 1 @@ -987,7 +823,339 @@ 0 1 - m_SizeYunits + m_SizePixUnits + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxBOTTOM|wxRIGHT|wxLEFT|wxALIGN_RIGHT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Size: + + 0 + + + 0 + + 1 + m_staticTextSize1 + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxBOTTOM|wxRIGHT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + 0000 + + 0 + + + 0 + + 1 + m_SizeXValue_mm + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxBOTTOM|wxRIGHT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + 0000 + + 0 + + + 0 + + 1 + m_SizeYValue_mm + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxBOTTOM|wxRIGHT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + mm + + 0 + + + 0 + + 1 + m_Size_mmxUnits 1 @@ -1115,7 +1283,7 @@ 5 - wxBOTTOM|wxRIGHT|wxLEFT|wxALIGN_CENTER_VERTICAL + wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxRIGHT 0 1 @@ -1279,6 +1447,364 @@ + + 5 + wxEXPAND + 1 + + 0 + protected + 0 + + + + 5 + wxALIGN_RIGHT|wxBOTTOM|wxRIGHT|wxLEFT|wxALIGN_CENTER_VERTICAL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Resolution: + + 0 + + + 0 + + 1 + m_staticTextBPI + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxBOTTOM|wxRIGHT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + + 0 + 40,-1 + 1 + m_DPIValueX + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + 300 + + + + + + + + + + UpdatePPITextValueX + + + + + + + + + + + + + + + + OnResolutionChange + + + + + + + + 5 + wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxRIGHT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + + 0 + 40,-1 + 1 + m_DPIValueY + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + 300 + + + + + + + + + + UpdatePPITextValueY + + + + + + + + + + + + + + + + OnResolutionChange + + + + + + + + 5 + wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxRIGHT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + DPI + + 0 + + + 0 + + 1 + m_DPI_Units + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + @@ -1461,7 +1987,7 @@ 5 - wxBOTTOM|wxRIGHT|wxLEFT + wxEXPAND|wxALL 0 1 @@ -1509,7 +2035,7 @@ 1 Resizable - 4 + 2 1 wxRA_SPECIFY_COLS @@ -1551,7 +2077,7 @@ 5 - wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT + wxEXPAND|wxALL 0 1 @@ -1641,7 +2167,7 @@ 5 - wxRIGHT|wxLEFT + wxTOP|wxRIGHT|wxLEFT 0 1 diff --git a/bitmap2component/bitmap2cmp_gui_base.h b/bitmap2component/bitmap2cmp_gui_base.h index 301a63398b..11f333506e 100644 --- a/bitmap2component/bitmap2cmp_gui_base.h +++ b/bitmap2component/bitmap2cmp_gui_base.h @@ -1,5 +1,5 @@ /////////////////////////////////////////////////////////////////////////// -// C++ code generated with wxFormBuilder (version Oct 8 2012) +// C++ code generated with wxFormBuilder (version Nov 5 2013) // http://www.wxformbuilder.org/ // // PLEASE DO "NOT" EDIT THIS FILE! @@ -11,6 +11,9 @@ #include #include #include +class KIWAY_PLAYER; + +#include "kiway_player.h" #include #include #include @@ -22,6 +25,7 @@ #include #include #include +#include #include #include #include @@ -37,7 +41,7 @@ /////////////////////////////////////////////////////////////////////////////// /// Class BM2CMP_FRAME_BASE /////////////////////////////////////////////////////////////////////////////// -class BM2CMP_FRAME_BASE : public wxFrame +class BM2CMP_FRAME_BASE : public KIWAY_PLAYER { private: @@ -47,15 +51,21 @@ class BM2CMP_FRAME_BASE : public wxFrame wxScrolledWindow* m_GreyscalePicturePanel; wxScrolledWindow* m_BNPicturePanel; wxPanel* m_panelRight; - wxStaticText* m_staticTextSizeX; + wxStaticText* m_staticTextSize; wxStaticText* m_SizeXValue; - wxStaticText* m_SizeXunits; - wxStaticText* m_staticTextSizeY; wxStaticText* m_SizeYValue; - wxStaticText* m_SizeYunits; + wxStaticText* m_SizePixUnits; + wxStaticText* m_staticTextSize1; + wxStaticText* m_SizeXValue_mm; + wxStaticText* m_SizeYValue_mm; + wxStaticText* m_Size_mmxUnits; wxStaticText* m_staticTextBPP; wxStaticText* m_BPPValue; wxStaticText* m_BPPunits; + wxStaticText* m_staticTextBPI; + wxTextCtrl* m_DPIValueX; + wxTextCtrl* m_DPIValueY; + wxStaticText* m_DPI_Units; wxButton* m_buttonLoad; wxButton* m_buttonExport; wxRadioBox* m_radioBoxFormat; @@ -66,6 +76,9 @@ class BM2CMP_FRAME_BASE : public wxFrame // Virtual event handlers, overide them in your derived class virtual void OnPaint( wxPaintEvent& event ) { event.Skip(); } + virtual void UpdatePPITextValueX( wxMouseEvent& event ) { event.Skip(); } + virtual void OnResolutionChange( wxCommandEvent& event ) { event.Skip(); } + virtual void UpdatePPITextValueY( wxMouseEvent& event ) { event.Skip(); } virtual void OnLoadFile( wxCommandEvent& event ) { event.Skip(); } virtual void OnExport( wxCommandEvent& event ) { event.Skip(); } virtual void OnOptionsSelection( wxCommandEvent& event ) { event.Skip(); } diff --git a/bitmap2component/bitmap2component.cpp b/bitmap2component/bitmap2component.cpp index 245cfc3447..83014cfa93 100644 --- a/bitmap2component/bitmap2component.cpp +++ b/bitmap2component/bitmap2component.cpp @@ -138,12 +138,12 @@ BITMAPCONV_INFO::BITMAPCONV_INFO() } -int bitmap2component( potrace_bitmap_t* aPotrace_bitmap, FILE* aOutfile, int aFormat ) +int bitmap2component( potrace_bitmap_t* aPotrace_bitmap, FILE* aOutfile, + int aFormat, int aDpi_X, int aDpi_Y ) { potrace_param_t* param; potrace_state_t* st; - // set tracing parameters, starting from defaults param = potrace_param_default(); if( !param ) @@ -171,8 +171,8 @@ int bitmap2component( potrace_bitmap_t* aPotrace_bitmap, FILE* aOutfile, int aFo { case 4: info.m_Format = KICAD_LOGO; - info.m_ScaleX = 1e3 * 25.4 / 300; // the conversion scale from PPI to micro - info.m_ScaleY = info.m_ScaleX; // Y axis is top to bottom + info.m_ScaleX = 1e3 * 25.4 / aDpi_X; // the conversion scale from PPI to micro + info.m_ScaleY = 1e3 * 25.4 / aDpi_Y; // Y axis is top to bottom info.CreateOutputFile(); break; @@ -186,22 +186,22 @@ int bitmap2component( potrace_bitmap_t* aPotrace_bitmap, FILE* aOutfile, int aFo case 2: info.m_Format = EESCHEMA_FMT; - info.m_ScaleX = 1000.0 / 300; // the conversion scale from PPI to UI - info.m_ScaleY = -info.m_ScaleX; // Y axis is bottom to Top for components in libs + info.m_ScaleX = 1000.0 / aDpi_X; // the conversion scale from PPI to UI + info.m_ScaleY = -1000.0 / aDpi_Y; // Y axis is bottom to Top for components in libs info.CreateOutputFile(); break; case 1: info.m_Format = PCBNEW_KICAD_MOD; - info.m_ScaleX = 1e6 * 25.4 / 300; // the conversion scale from PPI to UI - info.m_ScaleY = info.m_ScaleX; // Y axis is top to bottom in modedit + info.m_ScaleX = 1e6 * 25.4 / aDpi_X; // the conversion scale from PPI to UI + info.m_ScaleY = 1e6 * 25.4 / aDpi_Y; // Y axis is top to bottom in modedit info.CreateOutputFile(); break; case 0: info.m_Format = PCBNEW_LEGACY_EMP; - info.m_ScaleX = 10000.0 / 300; // the conversion scale - info.m_ScaleY = info.m_ScaleX; // Y axis is top to bottom in modedit + info.m_ScaleX = 10000.0 / aDpi_X; // the conversion scale + info.m_ScaleY = 10000.0 / aDpi_Y; // Y axis is top to bottom in modedit info.CreateOutputFile(); break; diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index ea5c2b3144..f6deda5e49 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -66,6 +66,48 @@ if( WIN32 AND MSYS ) add_definitions( -DGLEW_STATIC ) endif() + +# A shared library subsetted from common which restricts what can go into +# a single_top link image. By not linking to common, we control what does +# statically go into single_top link images. My current thinking is that only +# wxWidgets should be a shared link from single top, everything else should be +# statically bound into it. Otherwise you will have DSO loading problems. After it +# sets the LIB PATHS however, we want the *.kiface modules to use shared linking. +add_library( singletop STATIC EXCLUDE_FROM_ALL + confirm.cpp + eda_doc.cpp + kiway.cpp + kiway_holder.cpp + ) + + +# A shared library used by multiple *.kiface files and one or two program +# launchers. Object files can migrate into here over time, but only if they are +# surely needed and certainly used from more than one place without recompilation. +# Functions and data all need to use the #include and be declared +# as APIEXPORT +set( LIB_KICAD_SRCS + colors.cpp + dlist.cpp + string.cpp + ) + +if( future ) +add_library( lib_kicad SHARED + ) +target_link_libraries( lib_kicad + ${wxWidgets_LIBRARIES} + ) +set_target_properties( lib_kicad PROPERTIES + OUTPUT_NAME ki + ) +install( TARGETS lib_kicad + DESTINATION ${KICAD_BIN} + COMPONENT binary + ) +endif() + + set( COMMON_ABOUT_DLG_SRCS dialog_about/AboutDialog_main.cpp dialog_about/dialog_about.cpp @@ -93,11 +135,13 @@ set( COMMON_PAGE_LAYOUT_SRCS ) set( COMMON_SRCS + ${LIB_KICAD_SRCS} ${COMMON_ABOUT_DLG_SRCS} ${COMMON_PAGE_LAYOUT_SRCS} base_struct.cpp basicframe.cpp bezier_curves.cpp + bin_mod.cpp bitmap.cpp block_commande.cpp build_version.cpp @@ -107,6 +151,7 @@ set( COMMON_SRCS class_marker_base.cpp class_plotter.cpp class_undoredo_container.cpp + colors.cpp common.cpp common_plot_functions.cpp common_plotHPGL_functions.cpp @@ -115,13 +160,13 @@ set( COMMON_SRCS common_plotGERBER_functions.cpp common_plotDXF_functions.cpp common_plotSVG_functions.cpp + config_params.cpp confirm.cpp copy_to_clipboard.cpp dialog_shim.cpp displlst.cpp - dlist.cpp - drawframe.cpp - drawpanel.cpp + draw_frame.cpp + draw_panel.cpp drawtxt.cpp dsnlexer.cpp eda_dde.cpp @@ -134,16 +179,19 @@ set( COMMON_SRCS hotkeys_basic.cpp hotkey_grid_table.cpp html_messagebox.cpp + kiface_i.cpp kiway.cpp + kiway_holder.cpp msgpanel.cpp netlist_keywords.cpp newstroke_font.cpp - projet_config.cpp + project.cpp ptree.cpp reporter.cpp richio.cpp + search_stack.cpp selcolor.cpp - string.cpp + systemdirsappend.cpp trigo.cpp utf8.cpp wildcards_and_files_ext.cpp @@ -153,9 +201,11 @@ set( COMMON_SRCS zoom.cpp ) -# We will not want edaappl.cpp linked into the KIFACE, only into the KIWAY. if( TRUE OR NOT USE_KIWAY_DLLS ) - list( APPEND COMMON_SRCS edaappl.cpp ) +#if( NOT USE_KIWAY_DLLS ) + # We DO NOT want pgm_base.cpp linked into the KIFACE, only into the KIWAY. + # Check the map files to verify eda_pgm.o not being linked in. + list( APPEND COMMON_SRCS pgm_base.cpp ) endif() if( NOT HAVE_STRTOKR ) @@ -184,11 +234,10 @@ set( COMMON_SRCS geometry/shape_collisions.cpp geometry/shape_index.cpp ) - - add_library( common STATIC ${COMMON_SRCS} ) add_dependencies( common lib-dependencies ) + set( PCB_COMMON_SRCS base_screen.cpp eda_text.cpp diff --git a/common/base_units.cpp b/common/base_units.cpp index 38a0279786..5b79ab5746 100644 --- a/common/base_units.cpp +++ b/common/base_units.cpp @@ -197,7 +197,7 @@ void StripTrailingZeros( wxString& aStringValue, unsigned aTrailingZeroAllowed ) * otherwise the actual value is rounded when read from dialog and converted * in internal units, and therefore modified. */ -wxString ReturnStringFromValue( EDA_UNITS_T aUnit, int aValue, bool aAddUnitSymbol ) +wxString StringFromValue( EDA_UNITS_T aUnit, int aValue, bool aAddUnitSymbol ) { double value_to_print = To_User_Unit( aUnit, aValue ); @@ -257,7 +257,7 @@ wxString ReturnStringFromValue( EDA_UNITS_T aUnit, int aValue, bool aAddUnitSymb void PutValueInLocalUnits( wxTextCtrl& aTextCtr, int aValue ) { - wxString msg = ReturnStringFromValue( g_UserUnit, aValue ); + wxString msg = StringFromValue( g_UserUnit, aValue ); aTextCtr.SetValue( msg ); } @@ -286,7 +286,7 @@ double From_User_Unit( EDA_UNITS_T aUnit, double aValue ) } -int ReturnValueFromString( EDA_UNITS_T aUnits, const wxString& aTextValue ) +int ValueFromString( EDA_UNITS_T aUnits, const wxString& aTextValue ) { double value; double dtmp = 0; @@ -348,21 +348,21 @@ int ReturnValueFromString( EDA_UNITS_T aUnits, const wxString& aTextValue ) } -int ReturnValueFromString( const wxString& aTextValue ) +int ValueFromString( const wxString& aTextValue ) { int value; - value = ReturnValueFromString( g_UserUnit, aTextValue); + value = ValueFromString( g_UserUnit, aTextValue); return value; } -int ReturnValueFromTextCtrl( const wxTextCtrl& aTextCtr ) +int ValueFromTextCtrl( const wxTextCtrl& aTextCtr ) { int value; wxString msg = aTextCtr.GetValue(); - value = ReturnValueFromString( g_UserUnit, msg ); + value = ValueFromString( g_UserUnit, msg ); return value; } diff --git a/common/basicframe.cpp b/common/basicframe.cpp index d1616dd722..3efb4af478 100644 --- a/common/basicframe.cpp +++ b/common/basicframe.cpp @@ -36,7 +36,8 @@ #include #include -#include +#include +#include #include #include #include @@ -61,11 +62,9 @@ static const wxChar entryPerspective[] = wxT( "Perspective" ); -EDA_BASE_FRAME::EDA_BASE_FRAME( wxWindow* aParent, - ID_DRAWFRAME_TYPE aFrameType, - const wxString& aTitle, - const wxPoint& aPos, const wxSize& aSize, - long aStyle, const wxString & aFrameName ) : +EDA_BASE_FRAME::EDA_BASE_FRAME( wxWindow* aParent, ID_DRAWFRAME_TYPE aFrameType, + const wxString& aTitle, const wxPoint& aPos, const wxSize& aSize, + long aStyle, const wxString& aFrameName ) : wxFrame( aParent, wxID_ANY, aTitle, aPos, aSize, aStyle, aFrameName ) { wxSize minsize; @@ -108,7 +107,7 @@ EDA_BASE_FRAME::EDA_BASE_FRAME( wxWindow* aParent, void EDA_BASE_FRAME::windowClosing( wxCloseEvent& event ) { - SaveSettings(); // virtual, wxFrame specific + SaveSettings( config() ); // virtual, wxFrame specific event.Skip(); // we did not "handle" the event, only eavesdropped on it. } @@ -116,9 +115,6 @@ void EDA_BASE_FRAME::windowClosing( wxCloseEvent& event ) EDA_BASE_FRAME::~EDA_BASE_FRAME() { - if( wxGetApp().GetHtmlHelpController() ) - wxGetApp().SetHtmlHelpController( NULL ); - delete m_autoSaveTimer; // This is needed for OSX: avoids further OnDraw processing after this @@ -174,54 +170,45 @@ void EDA_BASE_FRAME::SetLanguage( wxCommandEvent& event ) { int id = event.GetId(); - wxGetApp().SetLanguageIdentifier( id ); - wxGetApp().SetLanguage(); + Pgm().SetLanguageIdentifier( id ); + Pgm().SetLanguage(); ReCreateMenuBar(); GetMenuBar()->Refresh(); } -void EDA_BASE_FRAME::LoadSettings() +void EDA_BASE_FRAME::LoadSettings( wxConfigBase* aCfg ) { - wxString text; - int Ypos_min; - wxConfig* config; - - config = wxGetApp().GetSettings(); - int maximized = 0; - if( config ) + wxString text = m_FrameName + wxT( "Pos_x" ); + aCfg->Read( text, &m_FramePos.x ); + + text = m_FrameName + wxT( "Pos_y" ); + aCfg->Read( text, &m_FramePos.y ); + + text = m_FrameName + wxT( "Size_x" ); + aCfg->Read( text, &m_FrameSize.x, 600 ); + + text = m_FrameName + wxT( "Size_y" ); + aCfg->Read( text, &m_FrameSize.y, 400 ); + + text = m_FrameName + wxT( "Maximized" ); + aCfg->Read( text, &maximized, 0 ); + + if( m_hasAutoSave ) { - text = m_FrameName + wxT( "Pos_x" ); - config->Read( text, &m_FramePos.x ); - - text = m_FrameName + wxT( "Pos_y" ); - config->Read( text, &m_FramePos.y ); - - text = m_FrameName + wxT( "Size_x" ); - config->Read( text, &m_FrameSize.x, 600 ); - - text = m_FrameName + wxT( "Size_y" ); - config->Read( text, &m_FrameSize.y, 400 ); - - text = m_FrameName + wxT( "Maximized" ); - config->Read( text, &maximized, 0 ); - - if( m_hasAutoSave ) - { - text = m_FrameName + entryAutoSaveInterval; - config->Read( text, &m_autoSaveInterval, DEFAULT_AUTO_SAVE_INTERVAL ); - } + text = m_FrameName + entryAutoSaveInterval; + aCfg->Read( text, &m_autoSaveInterval, DEFAULT_AUTO_SAVE_INTERVAL ); } // Ensure Window title bar is visible #if defined( __WXMAC__ ) // for macOSX, the window must be below system (macOSX) toolbar -// Ypos_min = GetMBarHeight(); seems no more exist in new API (subject to change) - Ypos_min = 20; + // Ypos_min = GetMBarHeight(); seems no more exist in new API (subject to change) + int Ypos_min = 20; #else - Ypos_min = 0; + int Ypos_min = 0; #endif if( m_FramePos.y < Ypos_min ) m_FramePos.y = Ypos_min; @@ -229,44 +216,39 @@ void EDA_BASE_FRAME::LoadSettings() if( maximized ) Maximize(); - // Once this is fully implemented, wxAuiManager will be used to maintain the persistance of - // the main frame and all it's managed windows and all of the legacy frame persistence - // position code can be removed. - if( config ) - config->Read( m_FrameName + entryPerspective, &m_perspective ); + aCfg->Read( m_FrameName + entryPerspective, &m_perspective ); } -void EDA_BASE_FRAME::SaveSettings() +void EDA_BASE_FRAME::SaveSettings( wxConfigBase* aCfg ) { - wxString text; - wxConfig* config = wxGetApp().GetSettings(); + wxString text; - if( !config || IsIconized() ) + if( IsIconized() ) return; m_FrameSize = GetSize(); m_FramePos = GetPosition(); text = m_FrameName + wxT( "Pos_x" ); - config->Write( text, (long) m_FramePos.x ); + aCfg->Write( text, (long) m_FramePos.x ); text = m_FrameName + wxT( "Pos_y" ); - config->Write( text, (long) m_FramePos.y ); + aCfg->Write( text, (long) m_FramePos.y ); text = m_FrameName + wxT( "Size_x" ); - config->Write( text, (long) m_FrameSize.x ); + aCfg->Write( text, (long) m_FrameSize.x ); text = m_FrameName + wxT( "Size_y" ); - config->Write( text, (long) m_FrameSize.y ); + aCfg->Write( text, (long) m_FrameSize.y ); text = m_FrameName + wxT( "Maximized" ); - config->Write( text, IsMaximized() ); + aCfg->Write( text, IsMaximized() ); if( m_hasAutoSave ) { text = m_FrameName + entryAutoSaveInterval; - config->Write( text, m_autoSaveInterval ); + aCfg->Write( text, m_autoSaveInterval ); } // Once this is fully implemented, wxAuiManager will be used to maintain @@ -276,8 +258,16 @@ void EDA_BASE_FRAME::SaveSettings() // printf( "perspective(%s): %s\n", // TO_UTF8( m_FrameName + entryPerspective ), TO_UTF8( perspective ) ); + aCfg->Write( m_FrameName + entryPerspective, perspective ); +} - config->Write( m_FrameName + entryPerspective, perspective ); + +wxConfigBase* EDA_BASE_FRAME::config() +{ + // KICAD_MANAGER_FRAME overrides this + wxConfigBase* ret = Kiface().KifaceSettings(); + wxASSERT( ret ); + return ret; } @@ -288,12 +278,12 @@ void EDA_BASE_FRAME::PrintMsg( const wxString& text ) void EDA_BASE_FRAME::UpdateFileHistory( const wxString& FullFileName, - wxFileHistory * aFileHistory ) + wxFileHistory* aFileHistory ) { wxFileHistory* fileHistory = aFileHistory; - if( fileHistory == NULL ) - fileHistory = & wxGetApp().GetFileHistory(); + if( !fileHistory ) + fileHistory = &Kiface().GetFileHistory(); fileHistory->AddFileToHistory( FullFileName ); } @@ -302,33 +292,36 @@ void EDA_BASE_FRAME::UpdateFileHistory( const wxString& FullFileName, wxString EDA_BASE_FRAME::GetFileFromHistory( int cmdId, const wxString& type, wxFileHistory* aFileHistory ) { - wxString fn, msg; - size_t i; wxFileHistory* fileHistory = aFileHistory; - if( fileHistory == NULL ) - fileHistory = & wxGetApp().GetFileHistory(); + if( !fileHistory ) + fileHistory = &Kiface().GetFileHistory(); int baseId = fileHistory->GetBaseId(); - wxASSERT( cmdId >= baseId && cmdId < baseId + ( int )fileHistory->GetCount() ); + wxASSERT( cmdId >= baseId && cmdId < baseId + (int) fileHistory->GetCount() ); - i = ( size_t )( cmdId - baseId ); + unsigned i = cmdId - baseId; if( i < fileHistory->GetCount() ) { - fn = fileHistory->GetHistoryFile( i ); + wxString fn = fileHistory->GetHistoryFile( i ); - if( !wxFileName::FileExists( fn ) ) + if( wxFileName::FileExists( fn ) ) + return fn; + else { - msg.Printf( wxT( "file <%s> was not found." ), GetChars( fn ) ); + wxString msg = wxString::Format( + wxT( "file '%s' was not found." ), + GetChars( fn ) ); + wxMessageBox( msg ); + fileHistory->RemoveFileFromHistory( i ); - fn = wxEmptyString; } } - return fn; + return wxEmptyString; } @@ -339,28 +332,28 @@ void EDA_BASE_FRAME::GetKicadHelp( wxCommandEvent& event ) /* We have to get document for beginners, * or the the full specific doc * if event id is wxID_INDEX, we want the document for beginners. - * else the specific doc file (its name is in wxGetApp().GetHelpFileName()) + * else the specific doc file (its name is in Kiface().GetHelpFileName()) * The document for beginners is the same for all KiCad utilities */ if( event.GetId() == wxID_INDEX ) { - // Temporary change the help filename - wxString tmp = wxGetApp().GetHelpFileName(); + // Temporarily change the help filename + wxString tmp = Kiface().GetHelpFileName(); // Search for "getting_started_in_kicad.pdf" or "Getting_Started_in_KiCad.pdf" - wxGetApp().SetHelpFileName( wxT( "getting_started_in_kicad.pdf" ) ); - wxString helpFile = wxGetApp().GetHelpFile(); + Kiface().SetHelpFileName( wxT( "getting_started_in_kicad.pdf" ) ); + wxString helpFile = Kiface().GetHelpFile(); if( !helpFile ) { // Try to find "Getting_Started_in_KiCad.pdf" - wxGetApp().SetHelpFileName( wxT( "Getting_Started_in_KiCad.pdf" ) ); - helpFile = wxGetApp().GetHelpFile(); + Kiface().SetHelpFileName( wxT( "Getting_Started_in_KiCad.pdf" ) ); + helpFile = Kiface().GetHelpFile(); } if( !helpFile ) { msg.Printf( _( "Help file %s could not be found." ), - GetChars( wxGetApp().GetHelpFileName() ) ); + GetChars( Kiface().GetHelpFileName() ) ); wxMessageBox( msg ); } else @@ -368,36 +361,36 @@ void EDA_BASE_FRAME::GetKicadHelp( wxCommandEvent& event ) GetAssociatedDocument( this, helpFile ); } - wxGetApp().SetHelpFileName( tmp ); + Kiface().SetHelpFileName( tmp ); return; } #if defined ONLINE_HELP_FILES_FORMAT_IS_HTML - if( wxGetApp().GetHtmlHelpController() == NULL ) + if( Kiface().GetHtmlHelpController() == NULL ) { - wxGetApp().InitOnLineHelp(); + Kiface().InitOnLineHelp(); } - if( wxGetApp().GetHtmlHelpController() ) + if( Kiface().GetHtmlHelpController() ) { - wxGetApp().GetHtmlHelpController()->DisplayContents(); - wxGetApp().GetHtmlHelpController()->Display( wxGetApp().GetHelpFileName() ); + Kiface().GetHtmlHelpController()->DisplayContents(); + Kiface().GetHtmlHelpController()->Display( Kiface().GetHelpFileName() ); } else { - msg.Printf( _( "Help file %s could not be found." ), GetChars( wxGetApp().GetHelpFileName() ) ); + msg.Printf( _( "Help file %s could not be found." ), GetChars( Kiface().GetHelpFileName() ) ); wxMessageBox( msg ); } #elif defined ONLINE_HELP_FILES_FORMAT_IS_PDF - wxString helpFile = wxGetApp().GetHelpFile(); + wxString helpFile = Kiface().GetHelpFile(); if( !helpFile ) { msg.Printf( _( "Help file %s could not be found." ), - GetChars( wxGetApp().GetHelpFileName() ) ); + GetChars( Kiface().GetHelpFileName() ) ); wxMessageBox( msg ); } else @@ -413,8 +406,8 @@ void EDA_BASE_FRAME::GetKicadHelp( wxCommandEvent& event ) void EDA_BASE_FRAME::OnSelectPreferredEditor( wxCommandEvent& event ) { - wxFileName fn = wxGetApp().GetEditorName(); - wxString wildcard( wxT( "*" ) ); + wxFileName fn = Pgm().GetEditorName(); + wxString wildcard( wxT( "*" ) ); #ifdef __WINDOWS__ wildcard += wxT( ".exe" ); @@ -430,18 +423,16 @@ void EDA_BASE_FRAME::OnSelectPreferredEditor( wxCommandEvent& event ) if( dlg.ShowModal() == wxID_CANCEL ) return; - wxASSERT( wxGetApp().GetCommonSettings() ); + wxString editor = dlg.GetPath(); - wxConfig* cfg = wxGetApp().GetCommonSettings(); - wxGetApp().SetEditorName( dlg.GetPath() ); - cfg->Write( wxT( "Editor" ), wxGetApp().GetEditorName() ); + Pgm().SetEditorName( editor ); } void EDA_BASE_FRAME::GetKicadAbout( wxCommandEvent& event ) { bool ShowAboutDialog(wxWindow * parent); - ShowAboutDialog(this); + ShowAboutDialog( this ); } @@ -535,7 +526,7 @@ void EDA_BASE_FRAME::CopyVersionInfoToClipboard( wxCommandEvent& event ) wxString tmp; wxPlatformInfo info; - tmp = wxT( "Application: " ) + wxGetApp().GetTitle() + wxT( "\n" ); + tmp = wxT( "Application: " ) + Pgm().App().GetAppName() + wxT( "\n" ); tmp << wxT( "Version: " ) << GetBuildVersion() #ifdef DEBUG << wxT( " Debug" ) @@ -666,14 +657,14 @@ void EDA_BASE_FRAME::CheckForAutoSaveFile( const wxFileName& aFileName, if( !autoSaveFileName.FileExists() ) return; - wxString msg; + wxString msg = wxString::Format( _( + "Well this is potentially embarrassing! It appears that the last time " + "you were editing the file '%s' it was not saved properly. Do you wish to restore the last " + "edits you made?" ), + GetChars( aFileName.GetFullName() ) + ); - msg.Printf( _( "Well this is potentially embarrassing! It appears that the last time \ -you were editing the file <%s> it was not saved properly. Do you wish to restore the last \ -edits you made?" ), - GetChars( aFileName.GetFullName() ) ); - - int response = wxMessageBox( msg, wxGetApp().GetAppName(), wxYES_NO | wxICON_QUESTION, this ); + int response = wxMessageBox( msg, Pgm().App().GetAppName(), wxYES_NO | wxICON_QUESTION, this ); // Make a backup of the current file, delete the file, and rename the auto save file to // the file name. @@ -703,7 +694,7 @@ edits you made?" ), if( !wxRenameFile( autoSaveFileName.GetFullPath(), aFileName.GetFullPath() ) ) { wxMessageBox( _( "The auto save file could not be renamed to the board file name." ), - wxGetApp().GetAppName(), wxOK | wxICON_EXCLAMATION, this ); + Pgm().App().GetAppName(), wxOK | wxICON_EXCLAMATION, this ); } } else @@ -716,29 +707,21 @@ edits you made?" ), } } -/** - * Function SetModalMode - * Disable or enable all other windows, to emulate a dialog behavior - * Useful when the frame is used to show and selec items - * (see FOOTPRINT_VIEWER_FRAME and LIB_VIEW_FRAME) - * - * @param aModal = true to disable all other opened windows (i.e. - * this windows is in dialog mode - * = false to enable other windows - * This function is analog to MakeModal( aModal ), deprecated since wxWidgets 2.9.4 - */ + void EDA_BASE_FRAME::SetModalMode( bool aModal ) { // Disable all other windows #if wxCHECK_VERSION(2, 9, 4) - if ( IsTopLevel() ) + if( IsTopLevel() ) { wxWindowList::compatibility_iterator node = wxTopLevelWindows.GetFirst(); - while (node) + + while( node ) { - wxWindow *win = node->GetData(); - if (win != this) - win->Enable(!aModal); + wxWindow* win = node->GetData(); + + if( win != this ) + win->Enable( !aModal ); node = node->GetNext(); } diff --git a/common/bin_mod.cpp b/common/bin_mod.cpp new file mode 100644 index 0000000000..fec950e415 --- /dev/null +++ b/common/bin_mod.cpp @@ -0,0 +1,52 @@ + + +#include +#include +#include + + +BIN_MOD::BIN_MOD( const char* aName ) : + m_name( aName ), + m_config( 0 ) +{ +} + + +void BIN_MOD::Init() +{ + // do an OS specific wxConfig instantiation, using the bin_mod (EXE/DLL/DSO) name. + m_config = new wxConfig( wxString::FromUTF8( m_name ) ); + + m_history.Load( *m_config ); + + // Prepare On Line Help. Use only lower case for help file names, in order to + // avoid problems with upper/lower case file names under windows and unix. +#if defined ONLINE_HELP_FILES_FORMAT_IS_HTML + m_help_file = wxString::FromUTF8( m_name ) + wxT( ".html" ); +#elif defined ONLINE_HELP_FILES_FORMAT_IS_PDF + m_help_file = wxString::FromUTF8( m_name ) + wxT( ".pdf" ); +#else + #error Help files format not defined +#endif +} + + +void BIN_MOD::End() +{ + if( m_config ) + { + m_history.Save( *m_config ); + + // Deleting a wxConfigBase writes its contents to disk if changed. + // Might be NULL if called twice, in which case nothing happens. + delete m_config; + m_config = 0; + } +} + + +BIN_MOD::~BIN_MOD() +{ + End(); +} + diff --git a/common/block_commande.cpp b/common/block_commande.cpp index 19a7a0ccfa..dfc27995b3 100644 --- a/common/block_commande.cpp +++ b/common/block_commande.cpp @@ -29,7 +29,7 @@ #include #include -#include +#include #include #include #include diff --git a/common/colors.cpp b/common/colors.cpp new file mode 100644 index 0000000000..ca12867b6e --- /dev/null +++ b/common/colors.cpp @@ -0,0 +1,156 @@ + +#include + + +/** + * The predefined colors used in KiCad. + * Please: if you change a value, remember these values are carefully chosen + * to have good results in Pcbnew, that uses the ORed value of basic colors + * when displaying superimposed objects + * This list must have exactly NBCOLORS items + */ +const StructColors g_ColorRefs[NBCOLORS] = +{ + { 0, 0, 0, BLACK, wxT( "Black" ), DARKDARKGRAY }, + { 72, 72, 72, DARKDARKGRAY, wxT( "Gray 1" ), DARKGRAY }, + { 132, 132, 132, DARKGRAY, wxT( "Gray 2" ), LIGHTGRAY }, + { 194, 194, 194, LIGHTGRAY, wxT( "Gray 3" ), WHITE }, + { 255, 255, 255, WHITE, wxT( "White" ), WHITE }, + { 194, 255, 255, LIGHTYELLOW, wxT( "L.Yellow" ), WHITE }, + { 72, 0, 0, DARKBLUE, wxT( "Blue 1" ), BLUE }, + { 0, 72, 0, DARKGREEN, wxT( "Green 1" ), GREEN }, + { 72, 72, 0, DARKCYAN, wxT( "Cyan 1" ), CYAN }, + { 0, 0, 72, DARKRED, wxT( "Red 1" ), RED }, + { 72, 0, 72, DARKMAGENTA, wxT( "Magenta 1" ), MAGENTA }, + { 0, 72, 72, DARKBROWN, wxT( "Brown 1" ), BROWN }, + { 132, 0, 0, BLUE, wxT( "Blue 2" ), LIGHTBLUE }, + { 0, 132, 0, GREEN, wxT( "Green 2" ), LIGHTGREEN }, + { 132, 132, 0, CYAN, wxT( "Cyan 2" ), LIGHTCYAN }, + { 0, 0, 132, RED, wxT( "Red 2" ), LIGHTRED }, + { 132, 0, 132, MAGENTA, wxT( "Magenta 2" ), LIGHTMAGENTA }, + { 0, 132, 132, BROWN, wxT( "Brown 2" ), YELLOW }, + { 194, 0, 0, LIGHTBLUE, wxT( "Blue 3" ), PUREBLUE, }, + { 0, 194, 0, LIGHTGREEN, wxT( "Green 3" ), PUREGREEN }, + { 194, 194, 0, LIGHTCYAN, wxT( "Cyan 3" ), PURECYAN }, + { 0, 0, 194, LIGHTRED, wxT( "Red 3" ), PURERED }, + { 194, 0, 194, LIGHTMAGENTA, wxT( "Magenta 3" ), PUREMAGENTA }, + { 0, 194, 194, YELLOW, wxT( "Yellow 3" ), PUREYELLOW }, + { 255, 0, 0, PUREBLUE, wxT( "Blue 4" ), WHITE }, + { 0, 255, 0, PUREGREEN, wxT( "Green 4" ), WHITE }, + { 255, 255, 0, PURECYAN, wxT( "Cyan 4" ), WHITE }, + { 0, 0, 255, PURERED, wxT( "Red 4" ), WHITE }, + { 255, 0, 255, PUREMAGENTA, wxT( "Magenta 4" ), WHITE }, + { 0, 255, 255, PUREYELLOW, wxT( "Yellow 4" ), WHITE }, +}; + + +EDA_COLOR_T ColorByName( const wxString& aName ) +{ + // look for a match in the palette itself + for( EDA_COLOR_T trying = BLACK; trying < NBCOLORS; trying = NextColor(trying) ) + { + if( 0 == aName.CmpNoCase( g_ColorRefs[trying].m_Name ) ) + return trying; + } + + // Not found, no idea... + return UNSPECIFIED_COLOR; +} + + +bool ColorIsLight( EDA_COLOR_T aColor ) +{ + const StructColors &c = g_ColorRefs[ColorGetBase( aColor )]; + int r = c.m_Red; + int g = c.m_Green; + int b = c.m_Blue; + return ((r * r) + (g * g) + (b * b)) > (128 * 128 * 3); +} + + +EDA_COLOR_T ColorFindNearest( const wxColour &aColor ) +{ + return ColorFindNearest( aColor.Red(), aColor.Green(), aColor.Blue() ); +} + + +EDA_COLOR_T ColorFindNearest( int aR, int aG, int aB ) +{ + EDA_COLOR_T candidate = BLACK; + + /* Find the 'nearest' color in the palette. This is fun. There is + a gazilion of metrics for the color space and no one of the + useful one is in the RGB color space. Who cares, this is a CAD, + not a photosomething... + + I hereby declare that the distance is the sum of the square of the + component difference. Think about the RGB color cube. Now get the + euclidean distance, but without the square root... for ordering + purposes it's the same, obviously. Also each component can't be + less of the target one, since I found this currently work better... + */ + int nearest_distance = 255 * 255 * 3 + 1; // Can't beat this + + for( EDA_COLOR_T trying = BLACK; trying < NBCOLORS; trying = NextColor(trying) ) + { + const StructColors &c = g_ColorRefs[trying]; + int distance = (aR - c.m_Red) * (aR - c.m_Red) + + (aG - c.m_Green) * (aG - c.m_Green) + + (aB - c.m_Blue) * (aB - c.m_Blue); + if( distance < nearest_distance && c.m_Red >= aR && + c.m_Green >= aG && c.m_Blue >= aB ) + { + nearest_distance = distance; + candidate = trying; + } + } + + return candidate; +} + + +EDA_COLOR_T ColorMix( EDA_COLOR_T aColor1, EDA_COLOR_T aColor2 ) +{ + /* Memoization storage. This could be potentially called for each + * color merge so a cache is useful (there are few colours anyway) */ + static EDA_COLOR_T mix_cache[NBCOLORS][NBCOLORS]; + + // TODO how is alpha used? it's a mac only thing, I have no idea + aColor1 = ColorGetBase( aColor1 ); + aColor2 = ColorGetBase( aColor2 ); + + // First easy thing: a black gives always the other colour + if( aColor1 == BLACK ) + return aColor2; + if( aColor2 == BLACK) + return aColor1; + + /* Now we are sure that black can't occur, so the rule is: + * BLACK means not computed yet. If we're lucky we already have + * an answer */ + EDA_COLOR_T candidate = mix_cache[aColor1][aColor2]; + if( candidate != BLACK ) + return candidate; + + // Blend the two colors (i.e. OR the RGB values) + const StructColors &c1 = g_ColorRefs[aColor1]; + const StructColors &c2 = g_ColorRefs[aColor2]; + + // Ask the palette for the nearest color to the mix + wxColour mixed( c1.m_Red | c2.m_Red, + c1.m_Green | c2.m_Green, + c1.m_Blue | c2.m_Blue ); + candidate = ColorFindNearest( mixed ); + + /* Here, BLACK is *not* a good answer, since it would recompute the next time. + * Even theorically its not possible (with the current rules), but + * maybe the metric will change in the future */ + if( candidate == BLACK) + candidate = DARKDARKGRAY; + + // Store the result in the cache. The operation is commutative, too + mix_cache[aColor1][aColor2] = candidate; + mix_cache[aColor2][aColor1] = candidate; + return candidate; +} + diff --git a/common/common.cpp b/common/common.cpp index 46d2670fb7..f52e6469b9 100644 --- a/common/common.cpp +++ b/common/common.cpp @@ -65,48 +65,6 @@ EDA_UNITS_T g_UserUnit; EDA_COLOR_T g_GhostColor; -/** - * The predefined colors used in KiCad. - * Please: if you change a value, remember these values are carefully chosen - * to have good results in Pcbnew, that uses the ORed value of basic colors - * when displaying superimposed objects - * This list must have exactly NBCOLORS items - */ -const StructColors g_ColorRefs[NBCOLORS] = -{ - { 0, 0, 0, BLACK, wxT( "Black" ), DARKDARKGRAY }, - { 72, 72, 72, DARKDARKGRAY, wxT( "Gray 1" ), DARKGRAY }, - { 132, 132, 132, DARKGRAY, wxT( "Gray 2" ), LIGHTGRAY }, - { 194, 194, 194, LIGHTGRAY, wxT( "Gray 3" ), WHITE }, - { 255, 255, 255, WHITE, wxT( "White" ), WHITE }, - { 194, 255, 255, LIGHTYELLOW, wxT( "L.Yellow" ), WHITE }, - { 72, 0, 0, DARKBLUE, wxT( "Blue 1" ), BLUE }, - { 0, 72, 0, DARKGREEN, wxT( "Green 1" ), GREEN }, - { 72, 72, 0, DARKCYAN, wxT( "Cyan 1" ), CYAN }, - { 0, 0, 72, DARKRED, wxT( "Red 1" ), RED }, - { 72, 0, 72, DARKMAGENTA, wxT( "Magenta 1" ), MAGENTA }, - { 0, 72, 72, DARKBROWN, wxT( "Brown 1" ), BROWN }, - { 132, 0, 0, BLUE, wxT( "Blue 2" ), LIGHTBLUE }, - { 0, 132, 0, GREEN, wxT( "Green 2" ), LIGHTGREEN }, - { 132, 132, 0, CYAN, wxT( "Cyan 2" ), LIGHTCYAN }, - { 0, 0, 132, RED, wxT( "Red 2" ), LIGHTRED }, - { 132, 0, 132, MAGENTA, wxT( "Magenta 2" ), LIGHTMAGENTA }, - { 0, 132, 132, BROWN, wxT( "Brown 2" ), YELLOW }, - { 194, 0, 0, LIGHTBLUE, wxT( "Blue 3" ), PUREBLUE, }, - { 0, 194, 0, LIGHTGREEN, wxT( "Green 3" ), PUREGREEN }, - { 194, 194, 0, LIGHTCYAN, wxT( "Cyan 3" ), PURECYAN }, - { 0, 0, 194, LIGHTRED, wxT( "Red 3" ), PURERED }, - { 194, 0, 194, LIGHTMAGENTA, wxT( "Magenta 3" ), PUREMAGENTA }, - { 0, 194, 194, YELLOW, wxT( "Yellow 3" ), PUREYELLOW }, - { 255, 0, 0, PUREBLUE, wxT( "Blue 4" ), WHITE }, - { 0, 255, 0, PUREGREEN, wxT( "Green 4" ), WHITE }, - { 255, 255, 0, PURECYAN, wxT( "Cyan 4" ), WHITE }, - { 0, 0, 255, PURERED, wxT( "Red 4" ), WHITE }, - { 255, 0, 255, PUREMAGENTA, wxT( "Magenta 4" ), WHITE }, - { 0, 255, 255, PUREYELLOW, wxT( "Yellow 4" ), WHITE }, -}; - - /** * Function to use local notation or C standard notation for floating point numbers * some countries use 1,5 and others (and C) 1.5 diff --git a/common/common_plotPDF_functions.cpp b/common/common_plotPDF_functions.cpp index 8349c5ff45..ec9cef66d3 100644 --- a/common/common_plotPDF_functions.cpp +++ b/common/common_plotPDF_functions.cpp @@ -28,7 +28,7 @@ */ #include -#include +#include #include #include #include diff --git a/common/common_plotPS_functions.cpp b/common/common_plotPS_functions.cpp index cad37ae694..9e1644485b 100644 --- a/common/common_plotPS_functions.cpp +++ b/common/common_plotPS_functions.cpp @@ -211,34 +211,34 @@ void PSLIKE_PLOTTER::fputsPostscriptString(FILE *fout, const wxString& txt) putc( '(', fout ); for( unsigned i = 0; i < txt.length(); i++ ) { - // Lazyness made me use stdio buffering yet another time... - wchar_t ch = txt[i]; - if( ch < 256 ) - { - switch (ch) - { - // The ~ shouldn't reach the outside - case '~': - break; - // These characters must be escaped - case '(': - case ')': - case '\\': - putc( '\\', fout ); + // Lazyness made me use stdio buffering yet another time... + wchar_t ch = txt[i]; + if( ch < 256 ) + { + switch (ch) + { + // The ~ shouldn't reach the outside + case '~': + break; + // These characters must be escaped + case '(': + case ')': + case '\\': + putc( '\\', fout ); - // FALLTHRU - default: - putc( ch, fout ); - break; - } - } + // FALLTHRU + default: + putc( ch, fout ); + break; + } + } } putc( ')', fout ); } /** - * Sister function for the ReturnGraphicTextWidth in drawtxt.cpp + * Sister function for the GraphicTextWidth in drawtxt.cpp * Does the same processing (i.e. calculates a text string width) but * using postscript metrics for the Helvetica font (optionally used for * PS and PDF plotting @@ -303,7 +303,7 @@ void PSLIKE_PLOTTER::postscriptOverlinePositions( const wxString& aText, int aXS } void PS_PLOTTER::SetViewport( const wxPoint& aOffset, double aIusPerDecimil, - double aScale, bool aMirror ) + double aScale, bool aMirror ) { wxASSERT( !outputFile ); m_plotMirror = aMirror; @@ -354,31 +354,31 @@ void PSLIKE_PLOTTER::computeTextParameters( const wxPoint& aPos, switch( aH_justify ) { case GR_TEXT_HJUSTIFY_CENTER: - dx = -tw / 2; - break; + dx = -tw / 2; + break; case GR_TEXT_HJUSTIFY_RIGHT: - dx = -tw; - break; + dx = -tw; + break; case GR_TEXT_HJUSTIFY_LEFT: - dx = 0; - break; + dx = 0; + break; } switch( aV_justify ) { case GR_TEXT_VJUSTIFY_CENTER: - dy = th / 2; - break; + dy = th / 2; + break; case GR_TEXT_VJUSTIFY_TOP: dy = th; - break; + break; case GR_TEXT_VJUSTIFY_BOTTOM: - dy = 0; - break; + dy = 0; + break; } RotatePoint( &dx, &dy, aOrient ); @@ -620,7 +620,7 @@ void PS_PLOTTER::PenTo( const wxPoint& pos, char plume ) } if( penState != plume || pos != penLastpos ) { - DPOINT pos_dev = userToDeviceCoordinates( pos ); + DPOINT pos_dev = userToDeviceCoordinates( pos ); fprintf( outputFile, "%g %g %sto\n", pos_dev.x, pos_dev.y, ( plume=='D' ) ? "line" : "move" ); @@ -650,39 +650,39 @@ bool PS_PLOTTER::StartPlot() static const char* PSMacro[] = { - "%%BeginProlog\n" - "/line { newpath moveto lineto stroke } bind def\n", - "/cir0 { newpath 0 360 arc stroke } bind def\n", - "/cir1 { newpath 0 360 arc gsave fill grestore stroke } bind def\n", - "/cir2 { newpath 0 360 arc gsave fill grestore stroke } bind def\n", - "/arc0 { newpath arc stroke } bind def\n", - "/arc1 { newpath 4 index 4 index moveto arc closepath gsave fill\n", - " grestore stroke } bind def\n", - "/arc2 { newpath 4 index 4 index moveto arc closepath gsave fill\n", - " grestore stroke } bind def\n", - "/poly0 { stroke } bind def\n", - "/poly1 { closepath gsave fill grestore stroke } bind def\n", - "/poly2 { closepath gsave fill grestore stroke } bind def\n", - "/rect0 { rectstroke } bind def\n", - "/rect1 { rectfill } bind def\n", - "/rect2 { rectfill } bind def\n", - "/linemode0 { 0 setlinecap 0 setlinejoin 0 setlinewidth } bind def\n", - "/linemode1 { 1 setlinecap 1 setlinejoin } bind def\n", - "/dashedline { [200] 100 setdash } bind def\n", - "/solidline { [] 0 setdash } bind def\n", + "%%BeginProlog\n" + "/line { newpath moveto lineto stroke } bind def\n", + "/cir0 { newpath 0 360 arc stroke } bind def\n", + "/cir1 { newpath 0 360 arc gsave fill grestore stroke } bind def\n", + "/cir2 { newpath 0 360 arc gsave fill grestore stroke } bind def\n", + "/arc0 { newpath arc stroke } bind def\n", + "/arc1 { newpath 4 index 4 index moveto arc closepath gsave fill\n", + " grestore stroke } bind def\n", + "/arc2 { newpath 4 index 4 index moveto arc closepath gsave fill\n", + " grestore stroke } bind def\n", + "/poly0 { stroke } bind def\n", + "/poly1 { closepath gsave fill grestore stroke } bind def\n", + "/poly2 { closepath gsave fill grestore stroke } bind def\n", + "/rect0 { rectstroke } bind def\n", + "/rect1 { rectfill } bind def\n", + "/rect2 { rectfill } bind def\n", + "/linemode0 { 0 setlinecap 0 setlinejoin 0 setlinewidth } bind def\n", + "/linemode1 { 1 setlinecap 1 setlinejoin } bind def\n", + "/dashedline { [200] 100 setdash } bind def\n", + "/solidline { [] 0 setdash } bind def\n", - // This is for 'hidden' text (search anchors for PDF) + // This is for 'hidden' text (search anchors for PDF) "/phantomshow { moveto\n", " /KicadFont findfont 0.000001 scalefont setfont\n", - " show } bind def\n", + " show } bind def\n", // This is for regular postscript text "/textshow { gsave\n", " findfont exch scalefont setfont concat 1 scale 0 0 moveto show\n", " } bind def\n", - // Utility for getting Latin1 encoded fonts - "/reencodefont {\n", + // Utility for getting Latin1 encoded fonts + "/reencodefont {\n", " findfont dup length dict begin\n", " { 1 index /FID ne\n", " { def }\n", @@ -692,13 +692,13 @@ bool PS_PLOTTER::StartPlot() " currentdict\n", " end } bind def\n" - // Remap AdobeStandard fonts to Latin1 - "/KicadFont /Helvetica reencodefont definefont pop\n", - "/KicadFont-Bold /Helvetica-Bold reencodefont definefont pop\n", - "/KicadFont-Oblique /Helvetica-Oblique reencodefont definefont pop\n", - "/KicadFont-BoldOblique /Helvetica-BoldOblique reencodefont definefont pop\n", - "%%EndProlog\n", - NULL + // Remap AdobeStandard fonts to Latin1 + "/KicadFont /Helvetica reencodefont definefont pop\n", + "/KicadFont-Bold /Helvetica-Bold reencodefont definefont pop\n", + "/KicadFont-Oblique /Helvetica-Oblique reencodefont definefont pop\n", + "/KicadFont-BoldOblique /Helvetica-BoldOblique reencodefont definefont pop\n", + "%%EndProlog\n", + NULL }; time_t time1970 = time( NULL ); @@ -726,8 +726,8 @@ bool PS_PLOTTER::StartPlot() psPaperSize.Set( pageInfo.GetHeightMils(), pageInfo.GetWidthMils() ); fprintf( outputFile, "%%%%BoundingBox: 0 0 %d %d\n", - (int) ceil( psPaperSize.x * BIGPTsPERMIL ), - (int) ceil( psPaperSize.y * BIGPTsPERMIL ) ); + (int) ceil( psPaperSize.x * BIGPTsPERMIL ), + (int) ceil( psPaperSize.y * BIGPTsPERMIL ) ); // Specify the size of the sheet and the name associated with that size. // (If the "User size" option has been selected for the sheet size, @@ -775,9 +775,9 @@ bool PS_PLOTTER::StartPlot() // within the Document Structuring Convention. fputs( "%%Page: 1 1\n" "%%BeginPageSetup\n" - "gsave\n" - "0.0072 0.0072 scale\n" // Configure postscript for decimils coordinates - "linemode1\n", outputFile ); + "gsave\n" + "0.0072 0.0072 scale\n" // Configure postscript for decimils coordinates + "linemode1\n", outputFile ); // Rototranslate the coordinate to achieve the landscape layout @@ -803,7 +803,7 @@ bool PS_PLOTTER::EndPlot() wxASSERT( outputFile ); fputs( "showpage\n" "grestore\n" - "%%EOF\n", outputFile ); + "%%EOF\n", outputFile ); fclose( outputFile ); outputFile = NULL; @@ -813,15 +813,15 @@ bool PS_PLOTTER::EndPlot() void PS_PLOTTER::Text( const wxPoint& aPos, - enum EDA_COLOR_T aColor, - const wxString& aText, - double aOrient, - const wxSize& aSize, - enum EDA_TEXT_HJUSTIFY_T aH_justify, - enum EDA_TEXT_VJUSTIFY_T aV_justify, - int aWidth, - bool aItalic, - bool aBold ) + enum EDA_COLOR_T aColor, + const wxString& aText, + double aOrient, + const wxSize& aSize, + enum EDA_TEXT_HJUSTIFY_T aH_justify, + enum EDA_TEXT_VJUSTIFY_T aV_justify, + int aWidth, + bool aItalic, + bool aBold ) { SetCurrentLineWidth( aWidth ); SetColor( aColor ); @@ -874,7 +874,7 @@ void PS_PLOTTER::Text( const wxPoint& aPos, if( m_textMode == PLOTTEXTMODE_PHANTOM ) { fputsPostscriptString( outputFile, aText ); - DPOINT pos_dev = userToDeviceCoordinates( aPos ); + DPOINT pos_dev = userToDeviceCoordinates( aPos ); fprintf( outputFile, " %g %g phantomshow\n", pos_dev.x, pos_dev.y ); } diff --git a/common/projet_config.cpp b/common/config_params.cpp similarity index 62% rename from common/projet_config.cpp rename to common/config_params.cpp index 2d50a29b5f..6f7fabcbbc 100644 --- a/common/projet_config.cpp +++ b/common/config_params.cpp @@ -1,15 +1,36 @@ -/*********************/ -/* projet_config.cpp */ -/*********************/ +/* + * This program source code file is part of KiCad, a free EDA CAD application. + * + * Copyright (C) 2004 Jean-Pierre Charras, jaen-pierre.charras@gipsa-lab.inpg.com + * Copyright (C) 2008-2011 Wayne Stambaugh + * Copyright (C) 1992-2011 KiCad Developers, see AUTHORS.txt for contributors. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, you may find one here: + * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html + * or you may search the http://www.gnu.org website for the version 2 license, + * or you may write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + */ #include #include -#include +#include #include #include #include #include -#include +#include #include #include @@ -19,8 +40,89 @@ #include -#define CONFIG_VERSION 1 -#define FORCE_LOCAL_CONFIG true +void wxConfigSaveParams( wxConfigBase* aCfg, + const PARAM_CFG_ARRAY& aList, const wxString& aGroup ) +{ + wxASSERT( aCfg ); + + BOOST_FOREACH( const PARAM_CFG_BASE& param, aList ) + { + if( param.m_Group ) + aCfg->SetPath( param.m_Group ); + else + aCfg->SetPath( aGroup ); + + if( param.m_Setup ) + continue; + + if( param.m_Type == PARAM_COMMAND_ERASE ) // Erase all data + { + if( param.m_Ident ) + aCfg->DeleteGroup( param.m_Ident ); + } + else + { + param.SaveParam( aCfg ); + } + } +} + + +void wxConfigLoadParams( wxConfigBase* aCfg, + const PARAM_CFG_ARRAY& aList, const wxString& aGroup ) +{ + wxASSERT( aCfg ); + + BOOST_FOREACH( const PARAM_CFG_BASE& param, aList ) + { + if( param.m_Group ) + aCfg->SetPath( param.m_Group ); + else + aCfg->SetPath( aGroup ); + + if( param.m_Setup ) + continue; + + param.ReadParam( aCfg ); + } +} + + +void wxConfigSaveSetups( wxConfigBase* aCfg, const PARAM_CFG_ARRAY& aList ) +{ + wxASSERT( aCfg ); + + BOOST_FOREACH( const PARAM_CFG_BASE& param, aList ) + { + if( !param.m_Setup ) + continue; + + if( param.m_Type == PARAM_COMMAND_ERASE ) // Erase all data + { + if( param.m_Ident ) + aCfg->DeleteGroup( param.m_Ident ); + } + else + { + param.SaveParam( aCfg ); + } + } +} + + +void wxConfigLoadSetups( wxConfigBase* aCfg, const PARAM_CFG_ARRAY& aList ) +{ + wxASSERT( aCfg ); + + BOOST_FOREACH( const PARAM_CFG_BASE& param, aList ) + { + if( !param.m_Setup ) + continue; + + param.ReadParam( aCfg ); + } +} + void ConfigBaseWriteDouble( wxConfigBase* aConfig, const wxString& aKey, double aValue ) @@ -35,220 +137,6 @@ void ConfigBaseWriteDouble( wxConfigBase* aConfig, const wxString& aKey, double } -bool EDA_APP::ReCreatePrjConfig( const wxString& fileName, - const wxString& GroupName, - bool ForceUseLocalConfig ) -{ - wxFileName fn = fileName; - - // Free old config file. - if( m_projectSettings ) - { - delete m_projectSettings; - m_projectSettings = NULL; - } - - /* Force the file extension. - * This allows the user to enter a filename without extension - * or use an existing name to create the project file - */ - if( fn.GetExt() != ProjectFileExtension ) - { - fn.SetExt( ProjectFileExtension ); - } - - /* Update the library search path list if a new project file is loaded. */ - if( m_projectFileName != fn ) - { - RemoveLibraryPath( m_projectFileName.GetPath() ); - InsertLibraryPath( fn.GetPath(), 0 ); - m_projectFileName = fn; - } - - // Init local config filename - if( ForceUseLocalConfig || fn.FileExists() ) - { - m_CurrentOptionFile = fn.GetFullPath(); - m_projectSettings = new wxFileConfig( wxEmptyString, wxEmptyString, - m_CurrentOptionFile, wxEmptyString ); - m_projectSettings->DontCreateOnDemand(); - - if( ForceUseLocalConfig ) - return true; - - /* Check the application version against the version saved in the - * project file. - * - * TODO: Push the version test up the stack so that when one of the - * KiCad application version changes, the other applications - * settings do not get updated. Practically, this can go away. - * It isn't used anywhere as far as I know (WLS). - */ - int version = -1; - int def_version = 0; - - m_projectSettings->SetPath( GroupName ); - version = m_projectSettings->Read( wxT( "version" ), def_version ); - m_projectSettings->SetPath( wxCONFIG_PATH_SEPARATOR ); - - if( version > 0 ) - { - return true; - } - else - { - delete m_projectSettings; // Version incorrect - } - } - - wxString defaultFileName; - defaultFileName = m_libSearchPaths.FindValidPath( wxT( "kicad.pro" ) ); - - if( defaultFileName.IsEmpty() ) - { - wxLogDebug( wxT( "Template file not found." ) ); - fn = wxFileName( GetTraits()->GetStandardPaths().GetDocumentsDir(), - wxT( "kicad" ), ProjectFileExtension ); - } - else - { - fn = defaultFileName; - } - - // Create new project file using the default name. - m_CurrentOptionFile = fn.GetFullPath(); - m_projectSettings = new wxFileConfig( wxEmptyString, wxEmptyString, - wxEmptyString, fn.GetFullPath() ); - m_projectSettings->DontCreateOnDemand(); - - return false; -} - - -void EDA_APP::WriteProjectConfig( const wxString& fileName, - const wxString& GroupName, - const PARAM_CFG_ARRAY& params ) -{ - ReCreatePrjConfig( fileName, GroupName, FORCE_LOCAL_CONFIG ); - - /* Write date ( surtout pour eviter bug de wxFileConfig - * qui se trompe de rubrique si declaration [xx] en premiere ligne - * (en fait si groupe vide) */ - m_projectSettings->SetPath( wxCONFIG_PATH_SEPARATOR ); - - m_projectSettings->Write( wxT( "update" ), DateAndTime() ); - m_projectSettings->Write( wxT( "last_client" ), GetAppName() ); - - /* Save parameters */ - m_projectSettings->DeleteGroup( GroupName ); // Erase all data - m_projectSettings->Flush(); - - m_projectSettings->SetPath( GroupName ); - m_projectSettings->Write( wxT( "version" ), CONFIG_VERSION ); - m_projectSettings->SetPath( wxCONFIG_PATH_SEPARATOR ); - - BOOST_FOREACH( const PARAM_CFG_BASE& param, params ) - { - if( param.m_Group ) - m_projectSettings->SetPath( param.m_Group ); - else - m_projectSettings->SetPath( GroupName ); - - if( param.m_Setup ) - continue; - - if ( param.m_Type == PARAM_COMMAND_ERASE ) // Erase all data - { - if( param.m_Ident ) - m_projectSettings->DeleteGroup( param.m_Ident ); - } - else - { - param.SaveParam( m_projectSettings ); - } - } - - m_projectSettings->SetPath( UNIX_STRING_DIR_SEP ); - - delete m_projectSettings; - m_projectSettings = NULL; -} - -void EDA_APP::SaveCurrentSetupValues( const PARAM_CFG_ARRAY& List ) -{ - if( m_settings == NULL ) - return; - - unsigned count = List.size(); - for( unsigned i=0; iDeleteGroup( param.m_Ident ); - } - else - { - param.SaveParam( m_settings ); - } - } -} - -bool EDA_APP::ReadProjectConfig( const wxString& local_config_filename, - const wxString& GroupName, - const PARAM_CFG_ARRAY& params, - bool Load_Only_if_New ) -{ - ReCreatePrjConfig( local_config_filename, GroupName, false ); - - m_projectSettings->SetPath( wxCONFIG_PATH_SEPARATOR ); - wxString timestamp = m_projectSettings->Read( wxT( "update" ) ); - - if( Load_Only_if_New && ( !timestamp.IsEmpty() ) - && (timestamp == m_CurrentOptionFileDateAndTime) ) - { - return false; - } - - m_CurrentOptionFileDateAndTime = timestamp; - - BOOST_FOREACH( const PARAM_CFG_BASE& param, params ) - { - if( param.m_Group ) - m_projectSettings->SetPath( param.m_Group ); - else - m_projectSettings->SetPath( GroupName ); - - if( param.m_Setup ) - continue; - - param.ReadParam( m_projectSettings ); - } - - delete m_projectSettings; - m_projectSettings = NULL; - - return true; -} - - -void EDA_APP::ReadCurrentSetupValues( const PARAM_CFG_ARRAY& List ) -{ - BOOST_FOREACH( const PARAM_CFG_BASE& param, List ) - { - if( param.m_Setup == false ) - continue; - - param.ReadParam( m_settings ); - } -} - - PARAM_CFG_BASE::PARAM_CFG_BASE( const wxChar* ident, const paramcfg_id type, const wxChar* group ) { @@ -286,7 +174,7 @@ PARAM_CFG_INT::PARAM_CFG_INT( bool Insetup, const wxChar* ident, int* ptparam, void PARAM_CFG_INT::ReadParam( wxConfigBase* aConfig ) const { - if( m_Pt_param == NULL || aConfig == NULL ) + if( !m_Pt_param || !aConfig ) return; int itmp = aConfig->Read( m_Ident, m_Default ); @@ -300,7 +188,7 @@ void PARAM_CFG_INT::ReadParam( wxConfigBase* aConfig ) const void PARAM_CFG_INT::SaveParam( wxConfigBase* aConfig ) const { - if( m_Pt_param == NULL || aConfig == NULL ) + if( !m_Pt_param || !aConfig ) return; aConfig->Write( m_Ident, *m_Pt_param ); @@ -330,7 +218,7 @@ PARAM_CFG_INT_WITH_SCALE::PARAM_CFG_INT_WITH_SCALE( bool Insetup, void PARAM_CFG_INT_WITH_SCALE::ReadParam( wxConfigBase* aConfig ) const { - if( m_Pt_param == NULL || aConfig == NULL ) + if( !m_Pt_param || !aConfig ) return; double dtmp = (double) m_Default * m_BIU_to_cfgunit; @@ -347,7 +235,7 @@ void PARAM_CFG_INT_WITH_SCALE::ReadParam( wxConfigBase* aConfig ) const void PARAM_CFG_INT_WITH_SCALE::SaveParam( wxConfigBase* aConfig ) const { - if( m_Pt_param == NULL || aConfig == NULL ) + if( !m_Pt_param || !aConfig ) return; // We cannot use aConfig->Write for a double, because @@ -383,8 +271,9 @@ PARAM_CFG_SETCOLOR::PARAM_CFG_SETCOLOR( bool Insetup, void PARAM_CFG_SETCOLOR::ReadParam( wxConfigBase* aConfig ) const { - if( m_Pt_param == NULL || aConfig == NULL ) + if( !m_Pt_param || !aConfig ) return; + EDA_COLOR_T itmp = ColorByName( aConfig->Read( m_Ident, wxT("NONE") ) ); if( itmp == UNSPECIFIED_COLOR ) @@ -395,7 +284,7 @@ void PARAM_CFG_SETCOLOR::ReadParam( wxConfigBase* aConfig ) const void PARAM_CFG_SETCOLOR::SaveParam( wxConfigBase* aConfig ) const { - if( m_Pt_param == NULL || aConfig == NULL ) + if( !m_Pt_param || !aConfig ) return; aConfig->Write( m_Ident, ColorGetName( *m_Pt_param ) ); @@ -433,7 +322,7 @@ PARAM_CFG_DOUBLE::PARAM_CFG_DOUBLE( bool Insetup, void PARAM_CFG_DOUBLE::ReadParam( wxConfigBase* aConfig ) const { - if( m_Pt_param == NULL || aConfig == NULL ) + if( !m_Pt_param || !aConfig ) return; double dtmp = m_Default; @@ -448,7 +337,7 @@ void PARAM_CFG_DOUBLE::ReadParam( wxConfigBase* aConfig ) const void PARAM_CFG_DOUBLE::SaveParam( wxConfigBase* aConfig ) const { - if( m_Pt_param == NULL || aConfig == NULL ) + if( !m_Pt_param || !aConfig ) return; // We cannot use aConfig->Write for a double, because @@ -483,7 +372,7 @@ PARAM_CFG_BOOL::PARAM_CFG_BOOL( bool Insetup, void PARAM_CFG_BOOL::ReadParam( wxConfigBase* aConfig ) const { - if( m_Pt_param == NULL || aConfig == NULL ) + if( !m_Pt_param || !aConfig ) return; int itmp = aConfig->Read( m_Ident, (int) m_Default ); @@ -494,7 +383,7 @@ void PARAM_CFG_BOOL::ReadParam( wxConfigBase* aConfig ) const void PARAM_CFG_BOOL::SaveParam( wxConfigBase* aConfig ) const { - if( m_Pt_param == NULL || aConfig == NULL ) + if( !m_Pt_param || !aConfig ) return; aConfig->Write( m_Ident, *m_Pt_param ); @@ -524,22 +413,22 @@ PARAM_CFG_WXSTRING::PARAM_CFG_WXSTRING( bool Insetup, const wxChar* ident, void PARAM_CFG_WXSTRING::ReadParam( wxConfigBase* aConfig ) const { - if( m_Pt_param == NULL || aConfig == NULL ) + if( !m_Pt_param || !aConfig ) return; + *m_Pt_param = aConfig->Read( m_Ident, m_default ); } void PARAM_CFG_WXSTRING::SaveParam( wxConfigBase* aConfig ) const { - if( m_Pt_param == NULL || aConfig == NULL ) + if( !m_Pt_param || !aConfig ) return; aConfig->Write( m_Ident, *m_Pt_param ); } - PARAM_CFG_FILENAME::PARAM_CFG_FILENAME( const wxChar* ident, wxString* ptparam, const wxChar* group ) : @@ -551,7 +440,7 @@ PARAM_CFG_FILENAME::PARAM_CFG_FILENAME( const wxChar* ident, void PARAM_CFG_FILENAME::ReadParam( wxConfigBase* aConfig ) const { - if( m_Pt_param == NULL || aConfig == NULL ) + if( !m_Pt_param || !aConfig ) return; wxString prm = aConfig->Read( m_Ident ); @@ -567,7 +456,7 @@ void PARAM_CFG_FILENAME::ReadParam( wxConfigBase* aConfig ) const void PARAM_CFG_FILENAME::SaveParam( wxConfigBase* aConfig ) const { - if( m_Pt_param == NULL || aConfig == NULL ) + if( !m_Pt_param || !aConfig ) return; wxString prm = *m_Pt_param; @@ -588,7 +477,7 @@ PARAM_CFG_LIBNAME_LIST::PARAM_CFG_LIBNAME_LIST( const wxChar* ident, void PARAM_CFG_LIBNAME_LIST::ReadParam( wxConfigBase* aConfig ) const { - if( m_Pt_param == NULL || aConfig == NULL ) + if( !m_Pt_param || !aConfig ) return; int indexlib = 1; // We start indexlib to 1 because first @@ -617,15 +506,15 @@ void PARAM_CFG_LIBNAME_LIST::ReadParam( wxConfigBase* aConfig ) const void PARAM_CFG_LIBNAME_LIST::SaveParam( wxConfigBase* aConfig ) const { - if( m_Pt_param == NULL || aConfig == NULL ) + if( !m_Pt_param || !aConfig ) return; + wxArrayString* libname_list = m_Pt_param; - unsigned indexlib = 0; wxString configkey; wxString libname; - for( ; indexlib < libname_list->GetCount(); indexlib++ ) + for( unsigned indexlib = 0; indexlib < libname_list->GetCount(); indexlib++ ) { configkey = m_Ident; diff --git a/common/copy_to_clipboard.cpp b/common/copy_to_clipboard.cpp index 4f3130b7f7..5e710d81a7 100644 --- a/common/copy_to_clipboard.cpp +++ b/common/copy_to_clipboard.cpp @@ -34,7 +34,7 @@ #include #include #include -#include +#include static bool DrawPageOnClipboard( EDA_DRAW_FRAME* aFrame ); diff --git a/common/dialog_about/AboutDialog_main.cpp b/common/dialog_about/AboutDialog_main.cpp index 91377a60a1..975abbd46f 100644 --- a/common/dialog_about/AboutDialog_main.cpp +++ b/common/dialog_about/AboutDialog_main.cpp @@ -21,7 +21,7 @@ #include #include #include -#include +#include #include @@ -41,7 +41,7 @@ static wxString HtmlNewline( const unsigned int amount = 1 ); static void InitKiCadAboutNew( AboutAppInfo& info ) { // Set application specific icon - const wxTopLevelWindow * const tlw = wxDynamicCast(::wxGetApp().GetTopWindow(), wxTopLevelWindow); + const wxTopLevelWindow* const tlw = wxDynamicCast( Pgm().App().GetTopWindow(), wxTopLevelWindow); if( tlw ) info.SetIcon( tlw->GetIcon() ); @@ -56,10 +56,10 @@ static void InitKiCadAboutNew( AboutAppInfo& info ) } /* Set title */ - info.SetAppName( wxT( ".: " ) + wxGetApp().GetTitle() + wxT( " :." ) ); + info.SetAppName( wxT( ".: " ) + Pgm().App().GetAppName() + wxT( " :." ) ); /* Copyright information */ - info.SetCopyright( wxT( "(C) 1992-2013 KiCad Developers Team" ) ); + info.SetCopyright( wxT( "(C) 1992-2014 KiCad Developers Team" ) ); /* KiCad build version */ wxString version; diff --git a/common/dialog_shim.cpp b/common/dialog_shim.cpp index 1d50a08908..354444c4ff 100644 --- a/common/dialog_shim.cpp +++ b/common/dialog_shim.cpp @@ -24,12 +24,22 @@ */ #include - +#include DIALOG_SHIM::DIALOG_SHIM( wxWindow* aParent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style, const wxString& name ) : - wxDialog( aParent, id, title, pos, size, style, name ) + wxDialog( aParent, id, title, pos, size, style, name ), + KIWAY_HOLDER( 0 ) { + // pray that aParent is either a KIWAY_PLAYER or DIALOG_SHIM derivation. + KIWAY_HOLDER* h = dynamic_cast( aParent ); + + wxASSERT_MSG( h, + wxT( "DIALOG_SHIM's parent not derived from KIWAY_PLAYER nor DIALOG_SHIM" ) ); + + if( h ) + SetKiway( this, &h->Kiway() ); + #if DLGSHIM_USE_SETFOCUS Connect( wxEVT_INIT_DIALOG, wxInitDialogEventHandler( DIALOG_SHIM::onInit ) ); #endif diff --git a/common/dialogs/dialog_get_component.cpp b/common/dialogs/dialog_get_component.cpp index 0fddd7f992..c0516bb5ba 100644 --- a/common/dialogs/dialog_get_component.cpp +++ b/common/dialogs/dialog_get_component.cpp @@ -5,7 +5,7 @@ #include #include #include -#include +#include #include diff --git a/common/dialogs/dialog_hotkeys_editor.cpp b/common/dialogs/dialog_hotkeys_editor.cpp index a1457febca..bb3b85f523 100644 --- a/common/dialogs/dialog_hotkeys_editor.cpp +++ b/common/dialogs/dialog_hotkeys_editor.cpp @@ -28,7 +28,7 @@ #include #include -#include +#include #include #include @@ -202,7 +202,7 @@ void HOTKEYS_EDITOR_DIALOG::OnRightClickOnCell( wxGridEvent& event ) wxString keyname = wxGetSingleChoice( _( "Special keys only. For others keys, use keyboard" ), _( "Select a key" ), C_COUNT, choices, this ); - int key = ReturnKeyCodeFromKeyName( keyname ); + int key = KeyCodeFromKeyName( keyname ); if( key == 0 ) return; @@ -251,7 +251,7 @@ void HOTKEYS_EDITOR_DIALOG::OnKeyPressed( wxKeyEvent& event ) #endif // See if this key code is handled in hotkeys names list bool exists; - ReturnKeyNameFromKeyCode( key, &exists ); + KeyNameFromKeyCode( key, &exists ); if( !exists ) // not handled, see hotkeys_basic.cpp { diff --git a/common/dialogs/dialog_page_settings.cpp b/common/dialogs/dialog_page_settings.cpp index 7462e6afe4..ad703b87a1 100644 --- a/common/dialogs/dialog_page_settings.cpp +++ b/common/dialogs/dialog_page_settings.cpp @@ -33,7 +33,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/common/displlst.cpp b/common/displlst.cpp index 1717f2a0f8..e78a72eac8 100644 --- a/common/displlst.cpp +++ b/common/displlst.cpp @@ -29,7 +29,7 @@ #include #include -#include +#include #include #include diff --git a/common/drawframe.cpp b/common/draw_frame.cpp similarity index 96% rename from common/drawframe.cpp rename to common/draw_frame.cpp index 45913b5171..80230e245f 100644 --- a/common/drawframe.cpp +++ b/common/draw_frame.cpp @@ -28,7 +28,8 @@ */ #include -#include +#include +#include #include #include #include @@ -38,7 +39,7 @@ #include #include #include -#include +#include #include #include #include @@ -89,12 +90,12 @@ BEGIN_EVENT_TABLE( EDA_DRAW_FRAME, EDA_BASE_FRAME ) END_EVENT_TABLE() -EDA_DRAW_FRAME::EDA_DRAW_FRAME( wxWindow* aParent, +EDA_DRAW_FRAME::EDA_DRAW_FRAME( KIWAY* aKiway, wxWindow* aParent, ID_DRAWFRAME_TYPE aFrameType, const wxString& aTitle, const wxPoint& aPos, const wxSize& aSize, long aStyle, const wxString & aFrameName ) : - EDA_BASE_FRAME( aParent, aFrameType, aTitle, aPos, aSize, aStyle, aFrameName ) + KIWAY_PLAYER( aKiway, aParent, aFrameType, aTitle, aPos, aSize, aStyle, aFrameName ) { m_drawToolBar = NULL; m_optionsToolBar = NULL; @@ -564,7 +565,7 @@ void EDA_DRAW_FRAME::SetPrevGrid() } -int EDA_DRAW_FRAME::ReturnBlockCommand( int key ) +int EDA_DRAW_FRAME::BlockCommand( int key ) { return 0; } @@ -615,25 +616,21 @@ void EDA_DRAW_FRAME::UpdateStatusBar() } -void EDA_DRAW_FRAME::LoadSettings() +void EDA_DRAW_FRAME::LoadSettings( wxConfigBase* aCfg ) { - wxASSERT( wxGetApp().GetSettings() != NULL ); + EDA_BASE_FRAME::LoadSettings( aCfg ); - wxConfig* cfg = wxGetApp().GetSettings(); + aCfg->Read( m_FrameName + CursorShapeEntryKeyword, &m_cursorShape, ( long )0 ); - EDA_BASE_FRAME::LoadSettings(); - cfg->Read( m_FrameName + CursorShapeEntryKeyword, &m_cursorShape, ( long )0 ); bool btmp; - - if ( cfg->Read( m_FrameName + ShowGridEntryKeyword, &btmp ) ) + if( aCfg->Read( m_FrameName + ShowGridEntryKeyword, &btmp ) ) SetGridVisibility( btmp ); int itmp; - - if( cfg->Read( m_FrameName + GridColorEntryKeyword, &itmp ) ) + if( aCfg->Read( m_FrameName + GridColorEntryKeyword, &itmp ) ) SetGridColor( ColorFromInt( itmp ) ); - cfg->Read( m_FrameName + LastGridSizeIdKeyword, &m_LastGridSizeId, 0L ); + aCfg->Read( m_FrameName + LastGridSizeIdKeyword, &m_LastGridSizeId, 0L ); // m_LastGridSizeId is an offset, expected to be >= 0 if( m_LastGridSizeId < 0 ) @@ -641,17 +638,14 @@ void EDA_DRAW_FRAME::LoadSettings() } -void EDA_DRAW_FRAME::SaveSettings() +void EDA_DRAW_FRAME::SaveSettings( wxConfigBase* aCfg ) { - wxASSERT( wxGetApp().GetSettings() != NULL ); + EDA_BASE_FRAME::SaveSettings( aCfg ); - wxConfig* cfg = wxGetApp().GetSettings(); - - EDA_BASE_FRAME::SaveSettings(); - cfg->Write( m_FrameName + CursorShapeEntryKeyword, m_cursorShape ); - cfg->Write( m_FrameName + ShowGridEntryKeyword, IsGridVisible() ); - cfg->Write( m_FrameName + GridColorEntryKeyword, ( long ) GetGridColor() ); - cfg->Write( m_FrameName + LastGridSizeIdKeyword, ( long ) m_LastGridSizeId ); + aCfg->Write( m_FrameName + CursorShapeEntryKeyword, m_cursorShape ); + aCfg->Write( m_FrameName + ShowGridEntryKeyword, IsGridVisible() ); + aCfg->Write( m_FrameName + GridColorEntryKeyword, ( long ) GetGridColor() ); + aCfg->Write( m_FrameName + LastGridSizeIdKeyword, ( long ) m_LastGridSizeId ); } @@ -715,7 +709,7 @@ bool EDA_DRAW_FRAME::HandleBlockBegin( wxDC* aDC, int aKey, const wxPoint& aPosi if( ( Block->GetCommand() != BLOCK_IDLE ) || ( Block->GetState() != STATE_NO_BLOCK ) ) return false; - Block->SetCommand( (BLOCK_COMMAND_T) ReturnBlockCommand( aKey ) ); + Block->SetCommand( (BLOCK_COMMAND_T) BlockCommand( aKey ) ); if( Block->GetCommand() == 0 ) return false; diff --git a/common/drawpanel.cpp b/common/draw_panel.cpp similarity index 97% rename from common/drawpanel.cpp rename to common/draw_panel.cpp index a055fb83b8..1e3adb750b 100644 --- a/common/drawpanel.cpp +++ b/common/draw_panel.cpp @@ -28,7 +28,8 @@ */ #include -#include +#include +#include #include #include #include @@ -36,7 +37,7 @@ #include #include #include -#include +#include #include @@ -45,16 +46,17 @@ static const int CURSOR_SIZE = 12; ///< Cursor size in pixels #define CLIP_BOX_PADDING 2 // keys to store options in config: -#define ENBL_ZOOM_NO_CENTER_KEY wxT( "ZoomNoCenter" ) -#define ENBL_MIDDLE_BUTT_PAN_KEY wxT( "MiddleButtonPAN" ) -#define MIDDLE_BUTT_PAN_LIMITED_KEY wxT( "MiddleBtnPANLimited" ) -#define ENBL_AUTO_PAN_KEY wxT( "AutoPAN" ) +#define ENBL_ZOOM_NO_CENTER_KEY wxT( "ZoomNoCenter" ) +#define ENBL_MIDDLE_BUTT_PAN_KEY wxT( "MiddleButtonPAN" ) +#define MIDDLE_BUTT_PAN_LIMITED_KEY wxT( "MiddleBtnPANLimited" ) +#define ENBL_AUTO_PAN_KEY wxT( "AutoPAN" ) -/* Definitions for enabling and disabling debugging features in drawpanel.cpp. - * Please don't forget to turn these off before making any commits to Launchpad. - */ + +// Definitions for enabling and disabling debugging features in drawpanel.cpp. +// Please don't forget to turn these off before making any commits to Launchpad. #define DEBUG_SHOW_CLIP_RECT 0 // Set to 1 to draw clipping rectangle. + /** * Trace mask used to enable or disable the trace output of coordinates during drawing * functions. The coordinate dumping can be turned on by setting the WXTRACE environment @@ -122,12 +124,14 @@ EDA_DRAW_PANEL::EDA_DRAW_PANEL( EDA_DRAW_FRAME* parent, int id, m_mouseCaptureCallback = NULL; m_endMouseCaptureCallback = NULL; - if( wxGetApp().GetSettings() ) + wxConfigBase* cfg = Kiface().KifaceSettings(); + + if( cfg ) { - wxGetApp().GetSettings()->Read( ENBL_MIDDLE_BUTT_PAN_KEY, &m_enableMiddleButtonPan, false ); - wxGetApp().GetSettings()->Read( ENBL_ZOOM_NO_CENTER_KEY, &m_enableZoomNoCenter, false ); - wxGetApp().GetSettings()->Read( MIDDLE_BUTT_PAN_LIMITED_KEY, &m_panScrollbarLimits, false ); - wxGetApp().GetSettings()->Read( ENBL_AUTO_PAN_KEY, &m_enableAutoPan, true ); + cfg->Read( ENBL_MIDDLE_BUTT_PAN_KEY, &m_enableMiddleButtonPan, false ); + cfg->Read( ENBL_ZOOM_NO_CENTER_KEY, &m_enableZoomNoCenter, false ); + cfg->Read( MIDDLE_BUTT_PAN_LIMITED_KEY, &m_panScrollbarLimits, false ); + cfg->Read( ENBL_AUTO_PAN_KEY, &m_enableAutoPan, true ); } m_requestAutoPan = false; @@ -149,10 +153,15 @@ EDA_DRAW_PANEL::EDA_DRAW_PANEL( EDA_DRAW_FRAME* parent, int id, EDA_DRAW_PANEL::~EDA_DRAW_PANEL() { - wxGetApp().GetSettings()->Write( ENBL_MIDDLE_BUTT_PAN_KEY, m_enableMiddleButtonPan ); - wxGetApp().GetSettings()->Write( ENBL_ZOOM_NO_CENTER_KEY, m_enableZoomNoCenter ); - wxGetApp().GetSettings()->Write( MIDDLE_BUTT_PAN_LIMITED_KEY, m_panScrollbarLimits ); - wxGetApp().GetSettings()->Write( ENBL_AUTO_PAN_KEY, m_enableAutoPan ); + wxConfigBase* cfg = Kiface().KifaceSettings(); + + if( cfg ) + { + cfg->Write( ENBL_MIDDLE_BUTT_PAN_KEY, m_enableMiddleButtonPan ); + cfg->Write( ENBL_ZOOM_NO_CENTER_KEY, m_enableZoomNoCenter ); + cfg->Write( MIDDLE_BUTT_PAN_LIMITED_KEY, m_panScrollbarLimits ); + cfg->Write( ENBL_AUTO_PAN_KEY, m_enableAutoPan ); + } } diff --git a/common/drawtxt.cpp b/common/drawtxt.cpp index 29286be5b4..33c79529b0 100644 --- a/common/drawtxt.cpp +++ b/common/drawtxt.cpp @@ -161,7 +161,7 @@ static const char* GetHersheyShapeDescription( int AsciiCode ) } -int ReturnGraphicTextWidth( const wxString& aText, int aXSize, bool aItalic, bool aWidth ) +int GraphicTextWidth( const wxString& aText, int aXSize, bool aItalic, bool aWidth ) { int tally = 0; int char_count = aText.length(); @@ -315,7 +315,7 @@ void DrawGraphicText( EDA_RECT* aClipBox, current_char_pos = aPos; - dx = ReturnGraphicTextWidth( aText, size_h, aItalic, aWidth ); + dx = GraphicTextWidth( aText, size_h, aItalic, aWidth ); dy = size_v; /* Do not draw the text if out of draw area! */ diff --git a/common/eda_dde.cpp b/common/eda_dde.cpp index 8fd540433f..b00cc11cad 100644 --- a/common/eda_dde.cpp +++ b/common/eda_dde.cpp @@ -4,7 +4,7 @@ #include #include -#include +#include #include #include #include diff --git a/common/eda_doc.cpp b/common/eda_doc.cpp index 0c5d756fa5..8a4dd423ee 100644 --- a/common/eda_doc.cpp +++ b/common/eda_doc.cpp @@ -3,7 +3,7 @@ */ #include -#include +#include #include #include #include @@ -14,23 +14,25 @@ #include -void EDA_APP::ReadPdfBrowserInfos() +void PGM_BASE::ReadPdfBrowserInfos() { - wxASSERT( m_commonSettings != NULL ); + wxASSERT( m_common_settings ); + + wxString browser = m_common_settings->Read( wxT( "PdfBrowserName" ), wxEmptyString ); + SetPdfBrowserName( browser ); - m_PdfBrowser = m_commonSettings->Read( wxT( "PdfBrowserName" ), wxEmptyString ); int tmp; - m_commonSettings->Read( wxT( "UseSystemBrowser" ), &tmp, 0 ); - m_useSystemPdfBrowser = tmp != 0; + m_common_settings->Read( wxT( "UseSystemBrowser" ), &tmp, 0 ); + m_use_system_pdf_browser = bool( tmp ); } -void EDA_APP::WritePdfBrowserInfos() +void PGM_BASE::WritePdfBrowserInfos() { - wxASSERT( m_commonSettings != NULL ); + wxASSERT( m_common_settings ); - m_commonSettings->Write( wxT( "PdfBrowserName" ), m_PdfBrowser ); - m_commonSettings->Write( wxT( "UseSystemBrowser" ), m_useSystemPdfBrowser ); + m_common_settings->Write( wxT( "PdfBrowserName" ), GetPdfBrowserName() ); + m_common_settings->Write( wxT( "UseSystemBrowser" ), m_use_system_pdf_browser ); } @@ -126,7 +128,7 @@ bool GetAssociatedDocument( wxFrame* aFrame, if( !wxFileExists( fullfilename ) ) { - msg.Printf( _( "Doc File <%s> not found" ), GetChars( aDocName ) ); + msg.Printf( _( "Doc File '%s' not found" ), GetChars( aDocName ) ); DisplayError( aFrame, msg ); return false; } diff --git a/common/eda_text.cpp b/common/eda_text.cpp index 35983951af..97da020d55 100644 --- a/common/eda_text.cpp +++ b/common/eda_text.cpp @@ -94,7 +94,7 @@ EDA_TEXT::~EDA_TEXT() int EDA_TEXT::LenSize( const wxString& aLine ) const { - return ReturnGraphicTextWidth( aLine, m_Size.x, m_Italic, m_Bold ); + return GraphicTextWidth( aLine, m_Size.x, m_Italic, m_Bold ); } /** diff --git a/common/edaappl.cpp b/common/edaappl.cpp deleted file mode 100644 index 6ac3ba3d1e..0000000000 --- a/common/edaappl.cpp +++ /dev/null @@ -1,1297 +0,0 @@ -/* - * This program source code file is part of KiCad, a free EDA CAD application. - * - * Copyright (C) 2004 Jean-Pierre Charras, jaen-pierre.charras@gipsa-lab.inpg.com - * Copyright (C) 2008-2011 Wayne Stambaugh - * Copyright (C) 1992-2011 KiCad Developers, see AUTHORS.txt for contributors. - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, you may find one here: - * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html - * or you may search the http://www.gnu.org website for the version 2 license, - * or you may write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA - */ - -/** - * @file edaappl.cpp - * - * @brief For the main application: init functions, and language selection - * (locale handling) - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -static const wxChar* CommonConfigPath = wxT( "kicad_common" ); - - -// some key strings used to store parameters in config -static const wxChar backgroundColorKey[] = wxT( "BackgroundColor" ); -static const wxChar showPageLimitsKey[] = wxT( "ShowPageLimits" ); -static const wxChar workingDirKey[] = wxT( "WorkingDir" ); -static const wxChar languageCfgKey[] = wxT( "LanguageID" ); -static const wxChar kicadFpLibPath[] = wxT( "KicadFootprintLibraryPath" ); - - -/** - * A small class to handle the list of existing translations. - * The locale translation is automatic. - * The selection of languages is mainly for maintainer's convenience - * To add a support to a new translation: - * create a new icon (flag of the country) (see Lang_Fr.xpm as an example) - * add a new item to s_Languages[]. - */ -struct LANGUAGE_DESCR -{ - /// wxWidgets locale identifier (See wxWidgets doc) - int m_WX_Lang_Identifier; - - /// KiCad identifier used in menu selection (See id.h) - int m_KI_Lang_Identifier; - - /// The menu language icons - BITMAP_DEF m_Lang_Icon; - - /// Labels used in menus - wxString m_Lang_Label; - - /// Set to true if the m_Lang_Label must not be translated - bool m_DoNotTranslate; -}; - - -/** - * Variable s_Languages - * Note: because this list is not created on the fly, wxTranslation - * must be called when a language name must be displayed after translation. - * Do not change this behavior, because m_Lang_Label is also used as key in config - */ -static LANGUAGE_DESCR s_Languages[] = -{ - // Default language - { - wxLANGUAGE_DEFAULT, - ID_LANGUAGE_DEFAULT, - lang_def_xpm, - _( "Default" ) - }, - - // English language - { - wxLANGUAGE_ENGLISH, - ID_LANGUAGE_ENGLISH, - lang_en_xpm, - wxT( "English" ), - true - }, - - // French language - { - wxLANGUAGE_FRENCH, - ID_LANGUAGE_FRENCH, - lang_fr_xpm, - _( "French" ) - }, - - // Finnish language - { - wxLANGUAGE_FINNISH, - ID_LANGUAGE_FINNISH, - lang_fi_xpm, - _( "Finnish" ) - }, - - // Spanish language - { - wxLANGUAGE_SPANISH, - ID_LANGUAGE_SPANISH, - lang_es_xpm, - _( "Spanish" ) - }, - - // Portuguese language - { - wxLANGUAGE_PORTUGUESE, - ID_LANGUAGE_PORTUGUESE, - lang_pt_xpm, - _( "Portuguese" ) - }, - - // Italian language - { - wxLANGUAGE_ITALIAN, - ID_LANGUAGE_ITALIAN, - lang_it_xpm, - _( "Italian" ) - }, - - // German language - { - wxLANGUAGE_GERMAN, - ID_LANGUAGE_GERMAN, - lang_de_xpm, - _( "German" ) - }, - - // Greek language - { - wxLANGUAGE_GREEK, - ID_LANGUAGE_GREEK, - lang_gr_xpm, - _( "Greek" ) - }, - - // Slovenian language - { - wxLANGUAGE_SLOVENIAN, - ID_LANGUAGE_SLOVENIAN, - lang_sl_xpm, - _( "Slovenian" ) - }, - - // Hungarian language - { - wxLANGUAGE_HUNGARIAN, - ID_LANGUAGE_HUNGARIAN, - lang_hu_xpm, - _( "Hungarian" ) - }, - - // Polish language - { - wxLANGUAGE_POLISH, - ID_LANGUAGE_POLISH, - lang_pl_xpm, - _( "Polish" ) - }, - - // Czech language - { - wxLANGUAGE_CZECH, - ID_LANGUAGE_CZECH, - lang_cs_xpm, - _( "Czech" ) - }, - - // Russian language - { - wxLANGUAGE_RUSSIAN, - ID_LANGUAGE_RUSSIAN, - lang_ru_xpm, - _( "Russian" ) - }, - - // Korean language - { - wxLANGUAGE_KOREAN, - ID_LANGUAGE_KOREAN, - lang_ko_xpm, - _( "Korean" ) - }, - - // Chinese simplified - { - wxLANGUAGE_CHINESE_SIMPLIFIED, - ID_LANGUAGE_CHINESE_SIMPLIFIED, - lang_chinese_xpm, - _( "Chinese simplified" ) - }, - - // Catalan language - { - wxLANGUAGE_CATALAN, - ID_LANGUAGE_CATALAN, - lang_catalan_xpm, - _( "Catalan" ) - }, - - // Dutch language - { - wxLANGUAGE_DUTCH, - ID_LANGUAGE_DUTCH, - lang_nl_xpm, - _( "Dutch" ) - }, - - // Japanese language - { - wxLANGUAGE_JAPANESE, - ID_LANGUAGE_JAPANESE, - lang_jp_xpm, - _( "Japanese" ) - }, - - // Bulgarian language - { - wxLANGUAGE_BULGARIAN, - ID_LANGUAGE_BULGARIAN, - lang_bg_xpm, - _( "Bulgarian" ) - } -}; - - -EDA_APP::EDA_APP() -{ - m_Checker = NULL; - m_oneInstancePerFileChecker = NULL; - m_HtmlCtrl = NULL; - m_settings = NULL; - setLanguageId( wxLANGUAGE_DEFAULT ); - m_Locale = NULL; - m_projectSettings = NULL; - m_commonSettings = NULL; - ForceSystemPdfBrowser( false ); -} - - -EDA_APP::~EDA_APP() -{ - SaveSettings(); - - // delete user datas - delete m_projectSettings; - delete m_commonSettings; - delete m_settings; - delete m_Checker; - delete m_oneInstancePerFileChecker; - delete m_Locale; -} - - -void EDA_APP::InitEDA_Appl( const wxString& aName, EDA_APP_T aId ) -{ - m_Id = aId; - m_Checker = new wxSingleInstanceChecker( aName.Lower() + wxT( "-" ) + wxGetUserId() ); - - // Init KiCad environment - // the environment variable KICAD (if exists) gives the kicad path: - // something like set KICAD=d:\kicad - bool isDefined = wxGetEnv( wxT( "KICAD" ), &m_KicadEnv ); - - if( isDefined ) // ensure m_KicadEnv ends by "/" - { - m_KicadEnv.Replace( WIN_STRING_DIR_SEP, UNIX_STRING_DIR_SEP ); - - if( !m_KicadEnv.IsEmpty() && m_KicadEnv.Last() != '/' ) - m_KicadEnv += UNIX_STRING_DIR_SEP; - } - - // Prepare On Line Help. Use only lower case for help file names, in order to - // avoid problems with upper/lower case file names under windows and unix. -#if defined ONLINE_HELP_FILES_FORMAT_IS_HTML - m_HelpFileName = aName.Lower() + wxT( ".html" ); -#elif defined ONLINE_HELP_FILES_FORMAT_IS_PDF - m_HelpFileName = aName.Lower() + wxT( ".pdf" ); -#else - #error Help files format not defined -#endif - - // Init parameters for configuration - SetVendorName( wxT( "KiCad" ) ); - SetAppName( aName.Lower() ); - SetTitle( aName ); - - m_settings = new wxConfig(); - - wxASSERT( m_settings != NULL ); - - m_commonSettings = new wxConfig( CommonConfigPath ); - wxASSERT( m_commonSettings != NULL ); - - // Install some image handlers, mainly for help - wxImage::AddHandler( new wxPNGHandler ); - wxImage::AddHandler( new wxGIFHandler ); - wxImage::AddHandler( new wxJPEGHandler ); - wxFileSystem::AddHandler( new wxZipFSHandler ); - - // Analyze the command line & init binary path - SetBinDir(); - SetDefaultSearchPaths(); - SetLanguagePath(); - ReadPdfBrowserInfos(); - - // Internationalization: loading the kicad suitable Dictionary - wxString languageSel; - m_commonSettings->Read( languageCfgKey, &languageSel); - - setLanguageId( wxLANGUAGE_DEFAULT ); - - // Search for the current selection - for( unsigned ii = 0; ii < DIM( s_Languages ); ii++ ) - { - if( s_Languages[ii].m_Lang_Label == languageSel ) - { - setLanguageId( s_Languages[ii].m_WX_Lang_Identifier ); - break; - } - } - - bool succes = SetLanguage( true ); - - if( !succes ) - { - } - - // Set locale option for separator used in float numbers - SetLocaleTo_Default(); -} - - -void EDA_APP::SetHtmlHelpController( wxHtmlHelpController* aController ) -{ - delete m_HtmlCtrl; - - m_HtmlCtrl = aController; -} - - -void EDA_APP::InitOnLineHelp() -{ - wxString fullfilename = FindKicadHelpPath(); - -#if defined ONLINE_HELP_FILES_FORMAT_IS_HTML - m_HelpFileName = fullfilename + wxT( ".html" ); - fullfilename += wxT( "kicad.hhp" ); - - if( wxFileExists( fullfilename ) ) - { - m_HtmlCtrl = new wxHtmlHelpController( wxHF_TOOLBAR | wxHF_CONTENTS | - wxHF_PRINT | wxHF_OPEN_FILES - /*| wxHF_SEARCH */ ); - m_HtmlCtrl->UseConfig( m_commonSettings ); - m_HtmlCtrl->SetTitleFormat( wxT( "KiCad Help" ) ); - m_HtmlCtrl->AddBook( fullfilename ); - } - -#elif defined ONLINE_HELP_FILES_FORMAT_IS_PDF - m_HtmlCtrl = NULL; - -#else - #error Help files format not defined -#endif -} - - -bool EDA_APP::SetBinDir() -{ -// Apple MacOSx -#ifdef __APPLE__ - - // Derive path from location of the app bundle - CFBundleRef mainBundle = CFBundleGetMainBundle(); - - if( mainBundle == NULL ) - return false; - - CFURLRef urlref = CFBundleCopyBundleURL( mainBundle ); - - if( urlref == NULL ) - return false; - - CFStringRef str = CFURLCopyFileSystemPath( urlref, kCFURLPOSIXPathStyle ); - - if( str == NULL ) - return false; - - char* native_str = NULL; - int len = CFStringGetMaximumSizeForEncoding( CFStringGetLength( str ), - kCFStringEncodingUTF8 ) + 1; - native_str = new char[len]; - - CFStringGetCString( str, native_str, len, kCFStringEncodingUTF8 ); - m_BinDir = FROM_UTF8( native_str ); - delete[] native_str; - -#elif defined(__UNIX__) // Linux and non-Apple Unix - m_BinDir = wxStandardPaths::Get().GetExecutablePath(); - -#else - m_BinDir = argv[0]; -#endif - - // Use unix notation for paths. I am not sure this is a good idea, - // but it simplifies compatibility between Windows and Unices. - // However it is a potential problem in path handling under Windows. - m_BinDir.Replace( WIN_STRING_DIR_SEP, UNIX_STRING_DIR_SEP ); - - // Remove file name form command line: - while( m_BinDir.Last() != '/' && !m_BinDir.IsEmpty() ) - m_BinDir.RemoveLast(); - - return true; -} - - -void EDA_APP::SetDefaultSearchPaths() -{ - wxString path = m_BinDir; - wxPathList tmp; - - m_searchPaths.Clear(); - -#ifdef __WINDOWS__ - - /* m_BinDir path is in unix notation. - * But wxFileName expect (to work fine) native notation - * specifically when using a path including a server, like - * \\myserver\local_path . - */ - path.Replace( UNIX_STRING_DIR_SEP, WIN_STRING_DIR_SEP ); - -#endif - wxFileName fn( path, wxEmptyString ); - - /* User environment variable path is the first search path. Chances are - * if the user is savvy enough to set an environment variable they know - * what they are doing. */ - if( ::wxGetEnv( wxT( "KICAD" ), NULL ) ) - tmp.AddEnvList( wxT( "KICAD" ) ); - - // Add the user's home path. - tmp.Add( GetTraits()->GetStandardPaths().GetUserDataDir() ); - - // Standard application data path if it is different from the binary path. - if( fn.GetPath() != GetTraits()->GetStandardPaths().GetDataDir() ) - { - tmp.Add( GetTraits()->GetStandardPaths().GetDataDir() ); - } - - // Up one level relative to binary path with "share" appended for Windows. - fn.RemoveLastDir(); - tmp.Add( fn.GetPath() ); - - /* The normal OS program file install paths allow for binary to be - * installed in a different path from the library files. This is - * useful for development purposes so the library and documentation - * files do not need to be installed separately. If someone can - * figure out a way to implement this without #ifdef, please do. - */ -#ifdef __WXMSW__ - tmp.AddEnvList( wxT( "PROGRAMFILES" ) ); -#elif __WXMAC__ - tmp.Add( wxString( wxGetenv( wxT( "HOME" ) ) ) + wxT( "/Library/Application Support/kicad/" ) ); - tmp.Add( wxT( "/Library/Application Support/kicad/" ) ); -#else - tmp.AddEnvList( wxT( "PATH" ) ); -#endif - - // This is the equivalent of CMAKE_INSTALL_PREFIX. Useful when installed by `make install`. - tmp.Add( wxT( DEFAULT_INSTALL_PATH ) ); - - // Add kicad, kicad/share, share, and share/kicad to each possible base path. - for( unsigned i = 0; i < tmp.GetCount(); i++ ) - { - fn = wxFileName( tmp[i], wxEmptyString ); - - if( fn.GetPath().AfterLast( fn.GetPathSeparator() ) == wxT( "bin" ) ) - fn.RemoveLastDir(); - - m_searchPaths.Add( fn.GetPath() ); - fn.AppendDir( wxT( "kicad" ) ); - m_searchPaths.Add( fn.GetPath() ); - fn.AppendDir( wxT( "share" ) ); - m_searchPaths.Add( fn.GetPath() ); - fn.RemoveLastDir(); - fn.RemoveLastDir(); - fn.AppendDir( wxT( "share" ) ); - m_searchPaths.Add( fn.GetPath() ); - fn.AppendDir( wxT( "kicad" ) ); - m_searchPaths.Add( fn.GetPath() ); - } - - // Remove all non-existent paths from the list. - for( unsigned i = 0; i < m_searchPaths.GetCount(); i++ ) - { - if( !wxFileName::IsDirReadable( m_searchPaths[i] ) ) - { - m_searchPaths.RemoveAt( i ); - i -= 1; - } - else - { - fn.Clear(); - fn.SetPath( m_searchPaths[i] ); - - /* Add schematic library file path to search path list. - * we must add /library and /library/doc - */ - if( m_Id == APP_EESCHEMA_T ) - { - fn.AppendDir( wxT( "library" ) ); - - if( fn.IsDirReadable() ) - { - m_libSearchPaths.Add( fn.GetPath() ); - } - - // Add schematic doc file path (library/doc)to search path list. - fn.AppendDir( wxT( "doc" ) ); - - if( fn.IsDirReadable() ) - { - m_libSearchPaths.Add( fn.GetPath() ); - } - - fn.RemoveLastDir(); - fn.RemoveLastDir(); // point to - } - - // Add PCB library file path to search path list. - if( m_Id == APP_PCBNEW_T || m_Id == APP_CVPCB_T ) - { - fn.AppendDir( wxT( "modules" ) ); - - if( fn.IsDirReadable() ) - { - m_libSearchPaths.Add( fn.GetPath() ); - } - - // Add 3D module library file path to search path list. - fn.AppendDir( wxT( "packages3d" ) ); - - if( fn.IsDirReadable() ) - { - m_libSearchPaths.Add( fn.GetPath() ); - } - - fn.RemoveLastDir(); - fn.RemoveLastDir(); // point to - } - - // Add KiCad template file path to search path list. - fn.AppendDir( wxT( "template" ) ); - - if( fn.IsDirReadable() ) - { - m_libSearchPaths.Add( fn.GetPath() ); - } - - fn.RemoveLastDir(); - } - } - -#if 0 && defined( DEBUG ) - wxLogDebug( wxT( "Library search paths:" ) ); - - for( unsigned i = 0; i < m_libSearchPaths.GetCount(); i++ ) - wxLogDebug( wxT( " %s" ), GetChars( m_libSearchPaths[i] ) ); -#endif -} - - -void EDA_APP::GetSettings( bool aReopenLastUsedDirectory ) -{ - wxASSERT( m_settings != NULL && m_commonSettings != NULL ); - - m_HelpSize.x = 500; - m_HelpSize.y = 400; - - wxString languageSel; - - m_commonSettings->Read( languageCfgKey, &languageSel ); - setLanguageId( wxLANGUAGE_DEFAULT ); - - // Search for the current selection - for( unsigned ii = 0; ii < DIM( s_Languages ); ii++ ) - { - if( s_Languages[ii].m_Lang_Label == languageSel ) - { - setLanguageId( s_Languages[ii].m_WX_Lang_Identifier ); - break; - } - } - - m_EditorName = m_commonSettings->Read( wxT( "Editor" ) ); - - m_fileHistory.Load( *m_settings ); - - m_settings->Read( showPageLimitsKey, &g_ShowPageLimits ); - - if( aReopenLastUsedDirectory ) - { - wxString dir; - - if( m_settings->Read( workingDirKey, &dir ) && wxDirExists( dir ) ) - { - wxSetWorkingDirectory( dir ); - } - } - - // FIXME OSX Mountain Lion (10.8) - // Seems that Read doesn't found anything and ColorFromInt Asserts - I'm unable to reproduce - // on 10.7 - // In general terms I think is better have a failsafe default than an uninit variable - int draw_bg_color = (int)BLACK; // Default for all apps but Eeschema - - if( m_Id == APP_EESCHEMA_T ) - draw_bg_color = (int)WHITE; // Default for Eeschema - - m_settings->Read( backgroundColorKey, &draw_bg_color ); - g_DrawBgColor = ColorFromInt( draw_bg_color ); - - // Load per-user search paths from settings file - - wxString upath; - int i = 1; - - while( 1 ) - { - upath = m_commonSettings->Read( - wxString::Format( wxT( "LibraryPath%d" ), i ), wxT( "" ) ); - - if( upath.IsSameAs( wxT( "" ) ) ) - break; - - m_libSearchPaths.Add( upath ); - i++; - } -} - - -void EDA_APP::SaveSettings() -{ - wxASSERT( m_settings != NULL ); - - m_settings->Write( showPageLimitsKey, g_ShowPageLimits ); - m_settings->Write( workingDirKey, wxGetCwd() ); - m_settings->Write( backgroundColorKey, (long) g_DrawBgColor ); - - // Save the file history list - m_fileHistory.Save( *m_settings ); -} - - -bool EDA_APP::SetLanguage( bool first_time ) -{ - bool retv = true; - - // dictionary file name without extend (full name is kicad.mo) - wxString DictionaryName( wxT( "kicad" ) ); - - delete m_Locale; - m_Locale = new wxLocale; - -#if wxCHECK_VERSION( 2, 9, 0 ) - if( !m_Locale->Init( m_LanguageId ) ) -#else - if( !m_Locale->Init( m_LanguageId, wxLOCALE_CONV_ENCODING ) ) -#endif - { - wxLogDebug( wxT( "This language is not supported by the system." ) ); - - setLanguageId( wxLANGUAGE_DEFAULT ); - delete m_Locale; - - m_Locale = new wxLocale; - m_Locale->Init(); - retv = false; - } - else if( !first_time ) - { - wxLogDebug( wxT( "Search for dictionary %s.mo in %s" ), - GetChars( DictionaryName ), GetChars( m_Locale->GetName() ) ); - } - - if( !first_time ) - { - wxString languageSel; - - // Search for the current selection - for( unsigned ii = 0; ii < DIM( s_Languages ); ii++ ) - { - if( s_Languages[ii].m_WX_Lang_Identifier == m_LanguageId ) - { - languageSel = s_Languages[ii].m_Lang_Label; - break; - } - } - - m_commonSettings->Write( languageCfgKey, languageSel ); - } - - // Test if floating point notation is working (bug in cross compilation, using wine) - // Make a conversion double <=> string - double dtst = 0.5; - wxString msg; - - extern bool g_DisableFloatingPointLocalNotation; // See common.cpp - - g_DisableFloatingPointLocalNotation = false; - - msg << dtst; - double result; - msg.ToDouble( &result ); - - if( result != dtst ) // string to double encode/decode does not work! Bug detected - { - // Disable floating point localization: - g_DisableFloatingPointLocalNotation = true; - SetLocaleTo_C_standard( ); - } - - if( !m_Locale->IsLoaded( DictionaryName ) ) - m_Locale->AddCatalog( DictionaryName ); - - if( !retv ) - return retv; - - return m_Locale->IsOk(); -} - - -void EDA_APP::SetLanguageIdentifier( int menu_id ) -{ - wxLogDebug( wxT( "Select language ID %d from %zd possible languages." ), - menu_id, DIM( s_Languages ) ); - - for( unsigned ii = 0; ii < DIM( s_Languages ); ii++ ) - { - if( menu_id == s_Languages[ii].m_KI_Lang_Identifier ) - { - setLanguageId( s_Languages[ii].m_WX_Lang_Identifier ); - break; - } - } -} - - -void EDA_APP::SetLanguagePath() -{ - // Add defined search paths to locale paths - if( !m_searchPaths.IsEmpty() ) - { - for( unsigned i = 0; i < m_searchPaths.GetCount(); i++ ) - { - wxFileName fn( m_searchPaths[i], wxEmptyString ); - - // Append path for Windows and unix KiCad pack install - fn.AppendDir( wxT( "share" ) ); - fn.AppendDir( wxT( "internat" ) ); - - if( fn.DirExists() ) - { - wxLogDebug( wxT( "Adding locale lookup path: " ) + fn.GetPath() ); - wxLocale::AddCatalogLookupPathPrefix( fn.GetPath() ); - } - - // Append path for unix standard install - fn.RemoveLastDir(); - - // Append path for unix standard install - fn.AppendDir( wxT( "kicad" ) ); - fn.AppendDir( wxT( "internat" ) ); - - if( fn.DirExists() ) - { - wxLogDebug( wxT( "Adding locale lookup path: " ) + fn.GetPath() ); - wxLocale::AddCatalogLookupPathPrefix( fn.GetPath() ); - } - } - } -} - - -void EDA_APP::AddMenuLanguageList( wxMenu* MasterMenu ) -{ - wxMenu* menu = NULL; - wxMenuItem* item; - - item = MasterMenu->FindItem( ID_LANGUAGE_CHOICE ); - - if( item ) // This menu exists, do nothing - return; - - menu = new wxMenu; - - for( unsigned ii = 0; ii < DIM( s_Languages ); ii++ ) - { - wxString label; - - if( s_Languages[ii].m_DoNotTranslate ) - label = s_Languages[ii].m_Lang_Label; - else - label = wxGetTranslation( s_Languages[ii].m_Lang_Label ); - - AddMenuItem( menu, s_Languages[ii].m_KI_Lang_Identifier, - label, KiBitmap(s_Languages[ii].m_Lang_Icon ), - wxITEM_CHECK ); - } - - AddMenuItem( MasterMenu, menu, - ID_LANGUAGE_CHOICE, - _( "Language" ), - _( "Select application language (only for testing!)" ), - KiBitmap( language_xpm ) ); - - // Set Check mark on current selected language - for( unsigned ii = 0; ii < DIM( s_Languages ); ii++ ) - { - if( m_LanguageId == s_Languages[ii].m_WX_Lang_Identifier ) - menu->Check( s_Languages[ii].m_KI_Lang_Identifier, true ); - else - menu->Check( s_Languages[ii].m_KI_Lang_Identifier, false ); - } -} - - -wxString EDA_APP::FindFileInSearchPaths( - const wxString& filename, const wxArrayString* subdirs ) -{ - size_t i, j; - wxFileName fn; - wxPathList paths; - - for( i = 0; i < m_searchPaths.GetCount(); i++ ) - { - fn = wxFileName( m_searchPaths[i], wxEmptyString ); - if( subdirs ) - { - for( j = 0; j < subdirs->GetCount(); j++ ) - fn.AppendDir( subdirs->Item( j ) ); - } - - if( fn.DirExists() ) - { - paths.Add( fn.GetPath() ); - } - } - - return paths.FindValidPath( filename ); -} - - -wxString EDA_APP::GetHelpFile() -{ - wxString fn; - wxArrayString subdirs, altsubdirs; - - /* FIXME: This is not the ideal way to handle this. Unfortunately, the - * CMake install paths seem to be a moving target so this crude - * hack solve the problem of install path differences between - * Windows and non-Windows platforms. */ - - // Partially fixed, but must be enhanced - - // Create subdir tree for "standard" linux distributions, when KiCad comes - // from a distribution files are in /usr/share/doc/kicad/help and binaries - // in /usr/bin or /usr/local/bin - subdirs.Add( wxT( "share" ) ); - subdirs.Add( _T( "doc" ) ); - subdirs.Add( wxT( "kicad" ) ); - subdirs.Add( _T( "help" ) ); - - // Create subdir tree for linux and Windows KiCad pack. - // Note the pack form under linux is also useful if a user wants to - // install KiCad to a server because there is only one path to mount - // or export (something like /usr/local/kicad). - // files are in /kicad/doc/help - // (often /usr/local/kicad/kicad/doc/help) - // /kicad/ is retrieved from m_BinDir - altsubdirs.Add( _T( "doc" ) ); - altsubdirs.Add( _T( "help" ) ); - - /* Search for a help file. - * we *must* find a help file. - * so help is searched in directories in this order: - * help/ like help/en_GB - * help/ like help/en - * help/en - */ - - // Step 1 : Try to find help file in help/ - subdirs.Add( m_Locale->GetCanonicalName() ); - altsubdirs.Add( m_Locale->GetCanonicalName() ); - - fn = FindFileInSearchPaths( m_HelpFileName, &altsubdirs ); - - if( !fn ) - fn = FindFileInSearchPaths( m_HelpFileName, &subdirs ); - - // Step 2 : if not found Try to find help file in help/ - if( !fn ) - { - subdirs.RemoveAt( subdirs.GetCount() - 1 ); - altsubdirs.RemoveAt( altsubdirs.GetCount() - 1 ); - - // wxLocale::GetName() does not return always the short name - subdirs.Add( m_Locale->GetName().BeforeLast( '_' ) ); - altsubdirs.Add( m_Locale->GetName().BeforeLast( '_' ) ); - - fn = FindFileInSearchPaths( m_HelpFileName, &altsubdirs ); - - if( !fn ) - fn = FindFileInSearchPaths( m_HelpFileName, &subdirs ); - } - - // Step 3 : if not found Try to find help file in help/en - if( !fn ) - { - subdirs.RemoveAt( subdirs.GetCount() - 1 ); - altsubdirs.RemoveAt( altsubdirs.GetCount() - 1 ); - subdirs.Add( _T( "en" ) ); - altsubdirs.Add( _T( "en" ) ); - - fn = FindFileInSearchPaths( m_HelpFileName, &altsubdirs ); - - if( !fn ) - fn = FindFileInSearchPaths( m_HelpFileName, &subdirs ); - } - - return fn; -} - - -wxString EDA_APP::ReturnLastVisitedLibraryPath( const wxString& aSubPathToSearch ) -{ - if( !m_LastVisitedLibPath.IsEmpty() ) - return m_LastVisitedLibPath; - - wxString path; - - /* Initialize default path to the main default lib path - * this is the second path in list (the first is the project path) - */ - unsigned pcount = m_libSearchPaths.GetCount(); - - if( pcount ) - { - unsigned ipath = 0; - - if( m_libSearchPaths[0] == wxGetCwd() ) - ipath = 1; - - // First choice of path: - if( ipath < pcount ) - path = m_libSearchPaths[ipath]; - - // Search a sub path matching aSubPathToSearch - if( !aSubPathToSearch.IsEmpty() ) - { - for( ; ipath < pcount; ipath++ ) - { - if( m_libSearchPaths[ipath].Contains( aSubPathToSearch ) ) - { - path = m_libSearchPaths[ipath]; - break; - } - } - } - } - - if( path.IsEmpty() ) - path = wxGetCwd(); - - return path; -} - - -void EDA_APP::SaveLastVisitedLibraryPath( const wxString& aPath ) -{ - m_LastVisitedLibPath = aPath; -} - - -wxString EDA_APP::ReturnFilenameWithRelativePathInLibPath( const wxString& aFullFilename ) -{ - /* 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 - * Note we accept only sub paths, - * not relative paths starting by ../ that are not subpaths and are outside kicad libs paths - */ - wxFileName fn = aFullFilename; - wxString filename = aFullFilename; - unsigned pathlen = fn.GetPath().Len(); /* path len, used to find the better (shortest) - * subpath within defaults paths */ - - for( unsigned kk = 0; kk < m_libSearchPaths.GetCount(); kk++ ) - { - fn = aFullFilename; - - // Search for the shortest subpath within m_libSearchPaths: - if( fn.MakeRelativeTo( m_libSearchPaths[kk] ) ) - { - if( fn.GetPathWithSep().StartsWith( wxT("..") ) ) // Path outside kicad libs paths - continue; - - if( pathlen > fn.GetPath().Len() ) // A better (shortest) subpath is found - { - filename = fn.GetPathWithSep() + fn.GetFullName(); - pathlen = fn.GetPath().Len(); - } - } - } - - return filename; -} - - -wxString EDA_APP::FindLibraryPath( const wxString& aFileName ) -{ - if( wxFileName::FileExists( aFileName ) ) - return aFileName; - else - return m_libSearchPaths.FindValidPath( aFileName ); -} - - -void EDA_APP::RemoveLibraryPath( const wxString& aPaths ) -{ - wxStringTokenizer Token( aPaths, wxT( ";\n\r" ) ); - - while( Token.HasMoreTokens() ) - { - wxString path = Token.GetNextToken(); - - if( m_libSearchPaths.Index( path, wxFileName::IsCaseSensitive() ) != wxNOT_FOUND ) - { - m_libSearchPaths.Remove( path ); - } - } -} - - -void EDA_APP::InsertLibraryPath( const wxString& aPaths, size_t aIndex ) -{ - wxStringTokenizer Token( aPaths, wxT( ";\n\r" ) ); - - while( Token.HasMoreTokens() ) - { - wxString path = Token.GetNextToken(); - - if( wxFileName::DirExists( path ) - && m_libSearchPaths.Index( path, wxFileName::IsCaseSensitive() ) == wxNOT_FOUND ) - { - if( aIndex >= m_libSearchPaths.GetCount() ) - { - m_libSearchPaths.Add( path ); - } - else - { - m_libSearchPaths.Insert( path, aIndex ); - } - - aIndex++; - } - } -} - - -bool EDA_APP::LockFile( const wxString& fileName ) -{ - // first make absolute and normalize, to avoid that different lock files - // for the same file can be created - wxFileName fn = fileName; - - fn.MakeAbsolute(); - - // semaphore to protect the edition of the file by more than one instance - if( m_oneInstancePerFileChecker != NULL ) - { - // it means that we had an open file and we are opening a different one - delete m_oneInstancePerFileChecker; - } - - wxString lockFileName = fn.GetFullPath() + wxT( ".lock" ); - - lockFileName.Replace( wxT( "/" ), wxT( "_" ) ); - - // We can have filenames coming from Windows, so also convert Windows separator - lockFileName.Replace( wxT( "\\" ), wxT( "_" ) ); - - m_oneInstancePerFileChecker = new wxSingleInstanceChecker( lockFileName ); - - if( m_oneInstancePerFileChecker && - m_oneInstancePerFileChecker->IsAnotherRunning() ) - { - return false; - } - - return true; -} - - -bool EDA_APP::SetFootprintLibTablePath() -{ - wxString path; - wxString kisysmod( wxT( KISYSMOD ) ); - - // Set the KISYSMOD environment variable for the current process if it is not already - // defined in the user's environment. This is required to expand the global footprint - // library table paths. - if( wxGetEnv( kisysmod, &path ) && wxFileName::DirExists( path ) ) - return true; - - // Set the KISYSMOD environment variable to the path defined in the user's configuration - // if it is defined and the path exists. - if( m_commonSettings->Read( kicadFpLibPath, &path ) && wxFileName::DirExists( path ) ) - { - wxSetEnv( kisysmod, path ); - return true; - } - - // Attempt to determine where the footprint libraries were installed using the legacy - // library search paths. - if( !GetLibraryPathList().IsEmpty() ) - { - unsigned modFileCount = 0; - wxString bestPath; - wxArrayString tmp; - - for( unsigned i = 0; i < GetLibraryPathList().GetCount(); i++ ) - { - unsigned cnt = wxDir::GetAllFiles( GetLibraryPathList()[i], &tmp, wxT( "*.mod" ), - wxDIR_FILES ); - - if( cnt > modFileCount ) - { - modFileCount = cnt; - bestPath = GetLibraryPathList()[i]; - } - } - - if( modFileCount != 0 ) - { - wxSetEnv( kisysmod, bestPath ); - return true; - } - } - - return false; -} - -/** - * Function Set3DShapesPath - * attempts set the environment variable given by aKiSys3Dmod to a valid path. - * (typically "KISYS3DMOD" ) - * If the environment variable is already set, - * then it left as is to respect the wishes of the user. - * - * The path is determined by attempting to find the path modules/packages3d - * files in kicad tree. - * This may or may not be the best path but it provides the best solution for - * backwards compatibility with the previous 3D shapes search path implementation. - * - * @note This must be called after #SetBinDir() is called at least on Windows. - * Otherwise, the kicad path is not known (Windows specific) - * - * @param aKiSys3Dmod = the value of environment variable, typically "KISYS3DMOD" - * @return false if the aKiSys3Dmod path is not valid. - */ -bool EDA_APP::Set3DShapesPath( const wxString& aKiSys3Dmod ) -{ - wxString path; - - // Set the KISYS3DMOD environment variable for the current process, - // if it is not already defined in the user's environment and valid. - if( wxGetEnv( aKiSys3Dmod, &path ) && wxFileName::DirExists( path ) ) - return true; - - // Attempt to determine where the 3D shape libraries were installed using the - // legacy path: - // on Unix: /usr/local/kicad/share/modules/packages3d - // or /usr/share/kicad/modules/packages3d - // On Windows: bin../share/modules/packages3d - wxString relpath( wxT( "modules/packages3d" ) ); - -// Apple MacOSx -#ifdef __WXMAC__ - path = wxT("/Library/Application Support/kicad/modules/packages3d/"); - - if( wxFileName::DirExists( path ) ) - { - wxSetEnv( aKiSys3Dmod, path ); - return true; - } - - path = wxString( wxGetenv( wxT( "HOME" ) ) ) + wxT("/Library/Application Support/kicad/modules/packages3d/"); - - if( wxFileName::DirExists( path ) ) - { - wxSetEnv( aKiSys3Dmod, path ); - return true; - } - -#elif defined(__UNIX__) // Linux and non-Apple Unix - // Try the home directory: - path.Empty(); - wxGetEnv( wxT("HOME"), &path ); - path += wxT("/kicad/share/") + relpath; - - if( wxFileName::DirExists( path ) ) - { - wxSetEnv( aKiSys3Dmod, path ); - return true; - } - - // Try the standard install path: - path = wxT("/usr/local/kicad/share/") + relpath; - - if( wxFileName::DirExists( path ) ) - { - wxSetEnv( aKiSys3Dmod, path ); - return true; - } - - // Try the official distrib standard install path: - path = wxT("/usr/share/kicad/") + relpath; - - if( wxFileName::DirExists( path ) ) - { - wxSetEnv( aKiSys3Dmod, path ); - return true; - } - -#else // Windows - // On Windows, the install path is given by the path of executables - wxFileName fn; - fn.AssignDir( m_BinDir ); - fn.RemoveLastDir(); - path = fn.GetPathWithSep() + wxT("share/") + relpath; - - if( wxFileName::DirExists( path ) ) - { - wxSetEnv( aKiSys3Dmod, path ); - return true; - } -#endif - - return false; -} - diff --git a/common/footprint_info.cpp b/common/footprint_info.cpp index 99d9cd4a9b..99dde1c4bd 100644 --- a/common/footprint_info.cpp +++ b/common/footprint_info.cpp @@ -38,7 +38,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/common/fp_lib_table.cpp b/common/fp_lib_table.cpp index fd208eb0cb..8c0d6f5a29 100644 --- a/common/fp_lib_table.cpp +++ b/common/fp_lib_table.cpp @@ -24,13 +24,16 @@ */ +#include #include // wxExpandEnvVars() #include #include #include -#include +//#include +#include +#include #include #include #include @@ -43,20 +46,7 @@ using namespace FP_LIB_TABLE_T; -/** - * Definition for enabling and disabling footprint library trace output. See the - * wxWidgets documentation on using the WXTRACE environment variable. - */ -static const wxString traceFpLibTable( wxT( "KicadFpLibTable" ) ); - - -/// The footprint library table name used when no project file is passed to Pcbnew or CvPcb. -/// This is used temporarily to store the project specific library table until the project -/// file being edited is save. It is then moved to the file fp-lib-table in the folder where -/// the project file is saved. -static wxString defaultProjectFileName( wxT( "prj-fp-lib-table" ) ); - -static wxString defaultFileName( wxT( "fp-lib-table" ) ); +static const wxChar global_tbl_name[] = wxT( "fp-lib-table" ); void FP_LIB_TABLE::ROW::SetType( const wxString& aType ) @@ -406,19 +396,6 @@ void FP_LIB_TABLE::ROW::Format( OUTPUTFORMATTER* out, int nestLevel ) const ); } - -void FP_LIB_TABLE::Save( const wxFileName& aPath ) const throw( IO_ERROR ) -{ - wxFileName fn = GetProjectFileName( aPath ); - - wxLogTrace( traceFpLibTable, wxT( "Saving footprint libary table <%s>." ), - GetChars( fn.GetFullPath() ) ); - - FILE_OUTPUTFORMATTER sf( fn.GetFullPath() ); - Format( &sf, 0 ); -} - - #define OPT_SEP '|' ///< options separator character PROPERTIES* FP_LIB_TABLE::ParseOptions( const std::string& aOptionsList ) @@ -680,33 +657,8 @@ bool FP_LIB_TABLE::IsEmpty( bool aIncludeFallback ) } -bool FP_LIB_TABLE::MissingLegacyLibs( const wxArrayString& aLibNames, wxString* aErrorMsg ) -{ - bool retv = false; - - for( unsigned i = 0; i < aLibNames.GetCount(); i++ ) - { - wxFileName fn = wxFileName( wxEmptyString, aLibNames[i], LegacyFootprintLibPathExtension ); - wxString legacyLibPath = wxGetApp().FindLibraryPath( fn ); - - if( legacyLibPath.IsEmpty() ) - continue; - - if( FindRowByURI( legacyLibPath ) == 0 ) - { - retv = true; - - if( aErrorMsg ) - *aErrorMsg += wxT( "\"" ) + legacyLibPath + wxT( "\"\n" ); - } - } - - return retv; -} - - -bool FP_LIB_TABLE::ConvertFromLegacy( NETLIST& aNetList, const wxArrayString& aLibNames, - REPORTER* aReporter ) throw( IO_ERROR ) +bool FP_LIB_TABLE::ConvertFromLegacy( SEARCH_STACK& aSStack, NETLIST& aNetList, + const wxArrayString& aLibNames, REPORTER* aReporter ) throw( IO_ERROR ) { wxString msg; FPID lastFPID; @@ -720,7 +672,6 @@ bool FP_LIB_TABLE::ConvertFromLegacy( NETLIST& aNetList, const wxArrayString& aL aNetList.SortByFPID(); wxString libPath; - wxFileName fn; PLUGIN::RELEASER pi( IO_MGR::PluginFind( IO_MGR::LEGACY ) ); @@ -738,9 +689,9 @@ bool FP_LIB_TABLE::ConvertFromLegacy( NETLIST& aNetList, const wxArrayString& aL for( unsigned ii = 0; ii < aLibNames.GetCount(); ii++ ) { - fn = wxFileName( wxEmptyString, aLibNames[ii], LegacyFootprintLibPathExtension ); + wxFileName fn( wxEmptyString, aLibNames[ii], LegacyFootprintLibPathExtension ); - libPath = wxGetApp().FindLibraryPath( fn ); + libPath = aSStack.FindValidPath( fn ); if( !libPath ) { @@ -766,7 +717,7 @@ bool FP_LIB_TABLE::ConvertFromLegacy( NETLIST& aNetList, const wxArrayString& aL } } - if( module == NULL ) + if( !module ) { if( aReporter ) { @@ -780,6 +731,7 @@ bool FP_LIB_TABLE::ConvertFromLegacy( NETLIST& aNetList, const wxArrayString& aL // Clear the footprint assignment since the old library lookup method is no // longer valid. FPID emptyFPID; + component->SetFPID( emptyFPID ); retv = false; continue; @@ -800,7 +752,9 @@ bool FP_LIB_TABLE::ConvertFromLegacy( NETLIST& aNetList, const wxArrayString& aL if( wxFileName::GetPathSeparator() == wxChar( '\\' ) && uri.Find( wxChar( '/' ) ) >= 0 ) + { uri.Replace( wxT( "/"), wxT( "\\" ) ); + } #ifdef __WINDOWS__ if( uri.CmpNoCase( libPath ) ) #else @@ -818,7 +772,7 @@ bool FP_LIB_TABLE::ConvertFromLegacy( NETLIST& aNetList, const wxArrayString& aL { if( aReporter ) { - msg.Printf( _( "Component `%s` footprint '%s' legacy library path <%s > " + msg.Printf( _( "Component '%s' footprint '%s' legacy library path '%s' " "was not found in the footprint library table.\n" ), GetChars( component->GetReference() ), GetChars( component->GetFPID().Format() ) ); @@ -836,7 +790,7 @@ bool FP_LIB_TABLE::ConvertFromLegacy( NETLIST& aNetList, const wxArrayString& aL { if( aReporter ) { - msg.Printf( _( "Component `%s` FPID '%s' is not valid.\n" ), + msg.Printf( _( "Component '%s' FPID '%s' is not valid.\n" ), GetChars( component->GetReference() ), GetChars( newFPID.Format() ) ); aReporter->Report( msg ); @@ -857,65 +811,16 @@ bool FP_LIB_TABLE::ConvertFromLegacy( NETLIST& aNetList, const wxArrayString& aL } -void FP_LIB_TABLE::SetProjectPathEnvVariable( const wxFileName& aPath ) -{ - wxString path; - - if( !aPath.IsOk() || !aPath.DirExists() ) - path = wxEmptyString; - else - path = aPath.GetPath(); - - wxLogTrace( traceFpLibTable, wxT( "Setting env %s to '%s'." ), - GetChars( ProjectPathEnvVariableName() ), GetChars( path ) ); - wxSetEnv( ProjectPathEnvVariableName(), path ); -} - - -const wxString FP_LIB_TABLE::ProjectPathEnvVariableName() -{ - return wxT( "KIPRJMOD" ); -} - - const wxString FP_LIB_TABLE::GlobalPathEnvVariableName() { - return wxT( KISYSMOD ); -} - - -wxString FP_LIB_TABLE::GetProjectFileName( const wxFileName& aPath ) -{ - wxFileName fn = aPath; - - // Set $KICAD_PRJ_PATH to user's configuration path if aPath is not set or does not exist. - if( !aPath.IsOk() || !aPath.DirExists() ) - { - fn.AssignDir( wxStandardPaths::Get().GetUserConfigDir() ); - -#if defined( __WINDOWS__ ) - fn.AppendDir( wxT( "kicad" ) ); -#endif - - fn.SetName( defaultProjectFileName ); - } - else - { - fn.AssignDir( aPath.GetPath() ); - fn.SetName( defaultFileName ); - } - - wxLogTrace( traceFpLibTable, wxT( "Project specific footprint library table file '%s'." ), - GetChars( fn.GetFullPath() ) ); - - return fn.GetFullPath(); + return wxT( "KISYSMOD" ); } bool FP_LIB_TABLE::LoadGlobalTable( FP_LIB_TABLE& aTable ) throw (IO_ERROR, PARSE_ERROR ) { - bool tableExists = true; - wxFileName fn = GetGlobalTableFileName(); + bool tableExists = true; + wxFileName fn = GetGlobalTableFileName(); if( !fn.FileExists() ) { @@ -927,21 +832,22 @@ bool FP_LIB_TABLE::LoadGlobalTable( FP_LIB_TABLE& aTable ) throw (IO_ERROR, PARS GetChars( fn.GetPath() ) ) ); } - // Attempt to copy the default global file table from the KiCad template folder to - // the users home configuration path. - wxString fileName = wxGetApp().FindLibraryPath( defaultFileName ); + // Attempt to copy the default global file table from the KiCad + // template folder to the user's home configuration path. + wxString fileName = Kiface().KifaceSearch().FindValidPath( global_tbl_name ); // The fallback is to create an empty global footprint table for the user to populate. if( fileName.IsEmpty() || !::wxCopyFile( fileName, fn.GetFullPath(), false ) ) { - FP_LIB_TABLE emptyTable; - FILE_OUTPUTFORMATTER sf( fn.GetFullPath() ); + FP_LIB_TABLE emptyTable; + FILE_OUTPUTFORMATTER sf( fn.GetFullPath() ); + emptyTable.Format( &sf, 0 ); } } - FILE_LINE_READER reader( fn.GetFullPath() ); - FP_LIB_TABLE_LEXER lexer( &reader ); + FILE_LINE_READER reader( fn.GetFullPath() ); + FP_LIB_TABLE_LEXER lexer( &reader ); aTable.Parse( &lexer ); return tableExists; @@ -952,38 +858,38 @@ wxString FP_LIB_TABLE::GetGlobalTableFileName() { wxFileName fn; + // This is possibly problematic with an uncertain wxApp title, which is now + // the case. We'll need a better technique soon. fn.SetPath( wxStandardPaths::Get().GetUserConfigDir() ); #if defined( __WINDOWS__ ) fn.AppendDir( wxT( "kicad" ) ); #endif - fn.SetName( GetFileName() ); - - wxLogTrace( traceFpLibTable, wxT( "Global footprint library table file '%s'." ), - GetChars( fn.GetFullPath() ) ); + fn.SetName( global_tbl_name ); return fn.GetFullPath(); } +// prefer wxString filename so it can be seen in a debugger easier than wxFileName. -const wxString& FP_LIB_TABLE::GetFileName() -{ - return defaultFileName; -} - - -void FP_LIB_TABLE::Load( const wxFileName& aFileName, FP_LIB_TABLE* aFallBackTable ) +void FP_LIB_TABLE::Load( const wxString& aFileName ) throw( IO_ERROR ) { - fallBack = aFallBackTable; - // Empty footprint library tables are valid. - if( aFileName.IsOk() && aFileName.FileExists() ) + if( wxFileName::IsFileReadable( aFileName ) ) { - FILE_LINE_READER reader( aFileName.GetFullPath() ); - FP_LIB_TABLE_LEXER lexer( &reader ); + FILE_LINE_READER reader( aFileName ); + FP_LIB_TABLE_LEXER lexer( &reader ); + Parse( &lexer ); } } + +void FP_LIB_TABLE::Save( const wxString& aFileName ) const throw( IO_ERROR ) +{ + FILE_OUTPUTFORMATTER sf( aFileName ); + Format( &sf, 0 ); +} + diff --git a/common/gal/opengl/opengl_gal.cpp b/common/gal/opengl/opengl_gal.cpp index fb8a0fcf4d..5bd59303a2 100644 --- a/common/gal/opengl/opengl_gal.cpp +++ b/common/gal/opengl/opengl_gal.cpp @@ -952,11 +952,11 @@ void OPENGL_GAL::initGlew() // Check the OpenGL version (minimum 2.1 is required) if( GLEW_VERSION_2_1 ) { - wxLogInfo( wxT( "OpenGL Version 2.1 supported." ) ); + wxLogInfo( wxT( "OpenGL 2.1 supported." ) ); } else { - DisplayError( parentWindow, wxT( "OpenGL Version 2.1 is not supported!" ) ); + DisplayError( parentWindow, wxT( "OpenGL 2.1 or higher is required!" ) ); exit( 1 ); } diff --git a/common/gestfich.cpp b/common/gestfich.cpp index 900b5b10a9..a66b396c7f 100644 --- a/common/gestfich.cpp +++ b/common/gestfich.cpp @@ -30,7 +30,7 @@ // For compilers that support precompilation, includes "wx.h". #include -#include +#include #include #include @@ -299,14 +299,14 @@ wxString FindKicadHelpPath() bool PathFound = false; /* find kicad/help/ */ - tmp = wxGetApp().GetExecutablePath(); + tmp = Pgm().GetExecutablePath(); if( tmp.Last() == '/' ) tmp.RemoveLast(); FullPath = tmp.BeforeLast( '/' ); // cd .. FullPath += wxT( "/doc/help/" ); - LocaleString = wxGetApp().GetLocale()->GetCanonicalName(); + LocaleString = Pgm().GetLocale()->GetCanonicalName(); wxString path_tmp = FullPath; #ifdef __WINDOWS__ @@ -319,9 +319,9 @@ wxString FindKicadHelpPath() } /* find kicad/help/ from environment variable KICAD */ - if( !PathFound && wxGetApp().IsKicadEnvVariableDefined() ) + if( !PathFound && Pgm().IsKicadEnvVariableDefined() ) { - FullPath = wxGetApp().GetKicadEnvVariable() + wxT( "/doc/help/" ); + FullPath = Pgm().GetKicadEnvVariable() + wxT( "/doc/help/" ); if( wxDirExists( FullPath ) ) PathFound = true; @@ -379,7 +379,7 @@ wxString FindKicadFile( const wxString& shortname ) /* Test the presence of the file in the directory shortname of * the KiCad binary path. */ - FullFileName = wxGetApp().GetExecutablePath() + shortname; + FullFileName = Pgm().GetExecutablePath() + shortname; if( wxFileExists( FullFileName ) ) return FullFileName; @@ -387,9 +387,9 @@ wxString FindKicadFile( const wxString& shortname ) /* Test the presence of the file in the directory shortname * defined by the environment variable KiCad. */ - if( wxGetApp().IsKicadEnvVariableDefined() ) + if( Pgm().IsKicadEnvVariableDefined() ) { - FullFileName = wxGetApp().GetKicadEnvVariable() + shortname; + FullFileName = Pgm().GetKicadEnvVariable() + shortname; if( wxFileExists( FullFileName ) ) return FullFileName; @@ -426,7 +426,7 @@ int ExecuteFile( wxWindow* frame, const wxString& ExecFile, const wxString& para #ifdef __WXMAC__ if( wxFileExists( FullFileName ) || wxDir::Exists( FullFileName ) ) { - return ProcessExecute( wxGetApp().GetExecutablePath() + wxT( "/" ) + return ProcessExecute( Pgm().GetExecutablePath() + wxT( "/" ) + ExecFile + wxT( " " ) + param, wxEXEC_ASYNC, callback ); } @@ -450,26 +450,26 @@ int ExecuteFile( wxWindow* frame, const wxString& ExecFile, const wxString& para } -wxString ReturnKicadDatasPath() +wxString KicadDatasPath() { bool PathFound = false; wxString data_path; - if( wxGetApp().IsKicadEnvVariableDefined() ) // Path defined by the KICAD environment variable. + if( Pgm().IsKicadEnvVariableDefined() ) // Path defined by the KICAD environment variable. { - data_path = wxGetApp().GetKicadEnvVariable(); + data_path = Pgm().GetKicadEnvVariable(); PathFound = true; } else // Path of executables. { - wxString tmp = wxGetApp().GetExecutablePath(); + wxString tmp = Pgm().GetExecutablePath(); #ifdef __WINDOWS__ tmp.MakeLower(); #endif if( tmp.Contains( wxT( "kicad" ) ) ) { #ifdef __WINDOWS__ - tmp = wxGetApp().GetExecutablePath(); + tmp = Pgm().GetExecutablePath(); #endif if( tmp.Last() == '/' ) tmp.RemoveLast(); @@ -527,47 +527,6 @@ wxString ReturnKicadDatasPath() } -wxString& EDA_APP::GetEditorName() -{ - wxString editorname = m_EditorName; - - // We get the preferred editor name from environment variable first. - if( editorname.IsEmpty() ) - { - // If there is no EDITOR variable set, try the desktop default - if(!wxGetEnv( wxT( "EDITOR" ), &editorname )) - { -#ifdef __WXMAC__ - editorname = "/usr/bin/open"; -#elif __WXX11__ - editorname = "/usr/bin/xdg-open"; -#endif - } - } - if( editorname.IsEmpty() ) // We must get a preferred editor name - { - DisplayInfoMessage( NULL, - _( "No default editor found, you must choose it" ) ); - wxString mask( wxT( "*" ) ); - -#ifdef __WINDOWS__ - mask += wxT( ".exe" ); -#endif - editorname = EDA_FileSelector( _( "Preferred Editor:" ), wxEmptyString, - wxEmptyString, wxEmptyString, mask, - NULL, wxFD_OPEN, true ); - } - - if( !editorname.IsEmpty() ) - { - m_EditorName = editorname; - m_commonSettings->Write( wxT( "Editor" ), m_EditorName ); - } - - return m_EditorName; -} - - bool OpenPDF( const wxString& file ) { wxString command; @@ -575,12 +534,12 @@ bool OpenPDF( const wxString& file ) wxString type; bool success = false; - wxGetApp().ReadPdfBrowserInfos(); + Pgm().ReadPdfBrowserInfos(); - if( !wxGetApp().UseSystemPdfBrowser() ) // Run the preferred PDF Browser + if( !Pgm().UseSystemPdfBrowser() ) // Run the preferred PDF Browser { AddDelimiterString( filename ); - command = wxGetApp().GetPdfBrowserFileName() + wxT( " " ) + filename; + command = Pgm().GetPdfBrowserName() + wxT( " " ) + filename; } else { diff --git a/common/gr_basic.cpp b/common/gr_basic.cpp index 1e256225b0..f46ca2ad17 100644 --- a/common/gr_basic.cpp +++ b/common/gr_basic.cpp @@ -1346,113 +1346,6 @@ void GRBezier( EDA_RECT* ClipBox, } -EDA_COLOR_T ColorMix( EDA_COLOR_T aColor1, EDA_COLOR_T aColor2 ) -{ - /* Memoization storage. This could be potentially called for each - * color merge so a cache is useful (there are few colours anyway) */ - static EDA_COLOR_T mix_cache[NBCOLORS][NBCOLORS]; - - // TODO how is alpha used? it's a mac only thing, I have no idea - aColor1 = ColorGetBase( aColor1 ); - aColor2 = ColorGetBase( aColor2 ); - - // First easy thing: a black gives always the other colour - if( aColor1 == BLACK ) - return aColor2; - if( aColor2 == BLACK) - return aColor1; - - /* Now we are sure that black can't occur, so the rule is: - * BLACK means not computed yet. If we're lucky we already have - * an answer */ - EDA_COLOR_T candidate = mix_cache[aColor1][aColor2]; - if( candidate != BLACK ) - return candidate; - - // Blend the two colors (i.e. OR the RGB values) - const StructColors &c1 = g_ColorRefs[aColor1]; - const StructColors &c2 = g_ColorRefs[aColor2]; - - // Ask the palette for the nearest color to the mix - wxColour mixed( c1.m_Red | c2.m_Red, - c1.m_Green | c2.m_Green, - c1.m_Blue | c2.m_Blue ); - candidate = ColorFindNearest( mixed ); - - /* Here, BLACK is *not* a good answer, since it would recompute the next time. - * Even theorically its not possible (with the current rules), but - * maybe the metric will change in the future */ - if( candidate == BLACK) - candidate = DARKDARKGRAY; - - // Store the result in the cache. The operation is commutative, too - mix_cache[aColor1][aColor2] = candidate; - mix_cache[aColor2][aColor1] = candidate; - return candidate; -} - - -EDA_COLOR_T ColorByName( const wxString& aName ) -{ - // look for a match in the palette itself - for( EDA_COLOR_T trying = BLACK; trying < NBCOLORS; trying = NextColor(trying) ) - { - if( 0 == aName.CmpNoCase( g_ColorRefs[trying].m_Name ) ) - return trying; - } - - // Not found, no idea... - return UNSPECIFIED_COLOR; -} - -bool ColorIsLight( EDA_COLOR_T aColor ) -{ - const StructColors &c = g_ColorRefs[ColorGetBase( aColor )]; - int r = c.m_Red; - int g = c.m_Green; - int b = c.m_Blue; - return ((r * r) + (g * g) + (b * b)) > (128 * 128 * 3); -} - -EDA_COLOR_T ColorFindNearest( const wxColour &aColor ) -{ - return ColorFindNearest( aColor.Red(), aColor.Green(), aColor.Blue() ); -} - -EDA_COLOR_T ColorFindNearest( int aR, int aG, int aB ) -{ - EDA_COLOR_T candidate = BLACK; - - /* Find the 'nearest' color in the palette. This is fun. There is - a gazilion of metrics for the color space and no one of the - useful one is in the RGB color space. Who cares, this is a CAD, - not a photosomething... - - I hereby declare that the distance is the sum of the square of the - component difference. Think about the RGB color cube. Now get the - euclidean distance, but without the square root... for ordering - purposes it's the same, obviously. Also each component can't be - less of the target one, since I found this currently work better... - */ - int nearest_distance = 255 * 255 * 3 + 1; // Can't beat this - - for( EDA_COLOR_T trying = BLACK; trying < NBCOLORS; trying = NextColor(trying) ) - { - const StructColors &c = g_ColorRefs[trying]; - int distance = (aR - c.m_Red) * (aR - c.m_Red) + - (aG - c.m_Green) * (aG - c.m_Green) + - (aB - c.m_Blue) * (aB - c.m_Blue); - if( distance < nearest_distance && c.m_Red >= aR && - c.m_Green >= aG && c.m_Blue >= aB ) - { - nearest_distance = distance; - candidate = trying; - } - } - - return candidate; -} - void GRDrawAnchor( EDA_RECT *aClipBox, wxDC *aDC, int x, int y, int aSize, EDA_COLOR_T aColor ) { diff --git a/common/hotkey_grid_table.cpp b/common/hotkey_grid_table.cpp index ee884f26cf..ecb75182aa 100644 --- a/common/hotkey_grid_table.cpp +++ b/common/hotkey_grid_table.cpp @@ -78,7 +78,7 @@ wxString HOTKEY_EDITOR_GRID_TABLE::GetValue( int row, int col ) } else { - return ReturnKeyNameFromKeyCode( hotkey_descr->m_KeyCode ); + return KeyNameFromKeyCode( hotkey_descr->m_KeyCode ); } } } diff --git a/common/hotkeys_basic.cpp b/common/hotkeys_basic.cpp index 0881c0f96d..968bcb47ca 100644 --- a/common/hotkeys_basic.cpp +++ b/common/hotkeys_basic.cpp @@ -29,7 +29,7 @@ */ #include -#include +#include #include #include #include @@ -61,9 +61,11 @@ wxString g_ModuleEditSectionTag( wxT( "[footprinteditor]" ) ); EDA_HOTKEY::EDA_HOTKEY( const wxChar* infomsg, int idcommand, int keycode, int idmenuevent ) { m_KeyCode = keycode; // Key code (ascii value for ascii keys + // or wxWidgets code for function key m_InfoMsg = infomsg; // info message. m_Idcommand = idcommand; // internal id for the corresponding + // command (see hotkey_id_commnand list) m_IdMenuEvent = idmenuevent; // id to call the corresponding event // (if any) (see id.h) @@ -137,13 +139,13 @@ static struct hotkey_name_descr s_Hotkey_Name_List[] = { wxT( "" ), 0 } }; -#define MODIFIER_CTRL wxT( "Ctrl+" ) -#define MODIFIER_ALT wxT( "Alt+" ) +#define MODIFIER_CTRL wxT( "Ctrl+" ) +#define MODIFIER_ALT wxT( "Alt+" ) #define MODIFIER_SHIFT wxT( "Shift+" ) /** - * Function ReturnKeyNameFromKeyCode + * Function KeyNameFromKeyCode * return the key name from the key code * Only some wxWidgets key values are handled for function key ( see * s_Hotkey_Name_List[] ) @@ -151,7 +153,7 @@ static struct hotkey_name_descr s_Hotkey_Name_List[] = * @param aIsFound = a pointer to a bool to return true if found, or false. an be NULL default) * @return the key name in a wxString */ -wxString ReturnKeyNameFromKeyCode( int aKeycode, bool* aIsFound ) +wxString KeyNameFromKeyCode( int aKeycode, bool* aIsFound ) { wxString keyname, modifier, fullkeyname; int ii; @@ -237,7 +239,7 @@ wxString AddHotkeyName( const wxString& aText, EDA_HOTKEY** aList, wxString keyname; if( aList ) - keyname = ReturnKeyNameFromCommandId( aList, aCommandId ); + keyname = KeyNameFromCommandId( aList, aCommandId ); if( !keyname.IsEmpty() ) { @@ -278,14 +280,14 @@ wxString AddHotkeyName( const wxString& aText, { wxString msg = aText; wxString keyname; - EDA_HOTKEY** List; + EDA_HOTKEY** list; if( aDescList ) { for( ; aDescList->m_HK_InfoList != NULL; aDescList++ ) { - List = aDescList->m_HK_InfoList; - keyname = ReturnKeyNameFromCommandId( List, aCommandId ); + list = aDescList->m_HK_InfoList; + keyname = KeyNameFromCommandId( list, aCommandId ); if( !keyname.IsEmpty() ) { @@ -313,13 +315,13 @@ wxString AddHotkeyName( const wxString& aText, /** - * Function ReturnKeyNameFromCommandId + * Function KeyNameFromCommandId * return the key name from the Command id value ( m_Idcommand member value) * @param aList = pointer to a EDA_HOTKEY list of commands * @param aCommandId = Command Id value * @return the key name in a wxString */ -wxString ReturnKeyNameFromCommandId( EDA_HOTKEY** aList, int aCommandId ) +wxString KeyNameFromCommandId( EDA_HOTKEY** aList, int aCommandId ) { wxString keyname; @@ -329,7 +331,7 @@ wxString ReturnKeyNameFromCommandId( EDA_HOTKEY** aList, int aCommandId ) if( hk_decr->m_Idcommand == aCommandId ) { - keyname = ReturnKeyNameFromKeyCode( hk_decr->m_KeyCode ); + keyname = KeyNameFromKeyCode( hk_decr->m_KeyCode ); break; } } @@ -339,14 +341,14 @@ wxString ReturnKeyNameFromCommandId( EDA_HOTKEY** aList, int aCommandId ) /** - * Function ReturnKeyCodeFromKeyName + * Function KeyCodeFromKeyName * return the key code from its key name * Only some wxWidgets key values are handled for function key * @param keyname = wxString key name to find in s_Hotkey_Name_List[], * like F2 or space or an usual (ascii) char. * @return the key code */ -int ReturnKeyCodeFromKeyName( const wxString& keyname ) +int KeyCodeFromKeyName( const wxString& keyname ) { int ii, keycode = 0; @@ -406,7 +408,7 @@ int ReturnKeyCodeFromKeyName( const wxString& keyname ) void DisplayHotkeyList( EDA_DRAW_FRAME* aFrame, struct EDA_HOTKEY_CONFIG* aDescList ) { wxString keyname; - EDA_HOTKEY** List; + EDA_HOTKEY** list; wxString msg = wxT( "" ); @@ -416,15 +418,16 @@ void DisplayHotkeyList( EDA_DRAW_FRAME* aFrame, struct EDA_HOTKEY_CONFIG* aDescL for( ; aDescList->m_HK_InfoList != NULL; aDescList++ ) { - List = aDescList->m_HK_InfoList; + list = aDescList->m_HK_InfoList; - for( ; *List != NULL; List++ ) + for( ; *list != NULL; list++ ) { - EDA_HOTKEY* hk_decr = *List; + EDA_HOTKEY* hk_decr = *list; if( !hk_decr->m_InfoMsg.Contains( wxT( "Macros" ) ) ) { - keyname = ReturnKeyNameFromKeyCode( hk_decr->m_KeyCode ); + keyname = KeyNameFromKeyCode( hk_decr->m_KeyCode ); + // Some chars should be modified, using html encoding, to be // displayed by DisplayHtmlInfoMessage() keyname.Replace( wxT("<"), wxT("<") ); @@ -480,8 +483,8 @@ int EDA_BASE_FRAME::WriteHotkeyConfig( struct EDA_HOTKEY_CONFIG* aDescList, msg = wxT( "$hotkey list\n" ); - /* Print the current hotkey list */ - EDA_HOTKEY** List; + // Print the current hotkey list + EDA_HOTKEY** list; for( ; aDescList->m_HK_InfoList != NULL; aDescList++ ) { @@ -495,13 +498,13 @@ int EDA_BASE_FRAME::WriteHotkeyConfig( struct EDA_HOTKEY_CONFIG* aDescList, msg += *aDescList->m_SectionTag; msg += wxT( "\n" ); - List = aDescList->m_HK_InfoList; + list = aDescList->m_HK_InfoList; - for( ; *List != NULL; List++ ) + for( ; *list != NULL; list++ ) { - EDA_HOTKEY* hk_decr = *List; + EDA_HOTKEY* hk_decr = *list; msg += wxT( "shortcut " ); - keyname = ReturnKeyNameFromKeyCode( hk_decr->m_KeyCode ); + keyname = KeyNameFromKeyCode( hk_decr->m_KeyCode ); AddDelimiterString( keyname ); infokey = hk_decr->m_InfoMsg; AddDelimiterString( infokey ); @@ -548,21 +551,21 @@ int EDA_BASE_FRAME::ReadHotkeyConfigFile( const wxString& aFilename, { wxFile cfgfile( aFilename ); - /* get length */ + // get length cfgfile.SeekEnd(); wxFileOffset size = cfgfile.Tell(); cfgfile.Seek( 0 ); - /* read data */ + // read data char* buffer = new char[size]; cfgfile.Read( buffer, size ); wxString data( buffer, wxConvUTF8 ); - /* parse */ + // parse ParseHotkeyConfig( data, aDescList ); - /* cleanup */ + // cleanup delete[] buffer; cfgfile.Close(); return 1; @@ -603,7 +606,7 @@ int EDA_BASE_FRAME::ReadHotkeyConfig( struct EDA_HOTKEY_CONFIG* aDescList ) void ParseHotkeyConfig( const wxString& data, struct EDA_HOTKEY_CONFIG* aDescList ) { - /* Read the config */ + // Read the config wxStringTokenizer tokenizer( data, L"\r\n", wxTOKEN_STRTOK ); EDA_HOTKEY** CurrentHotkeyList = 0; @@ -643,23 +646,23 @@ void ParseHotkeyConfig( const wxString& data, if( CurrentHotkeyList == NULL ) continue; - /* Get the key name */ + // Get the key name lineTokenizer.SetString( lineTokenizer.GetString(), L"\"\r\n\t ", wxTOKEN_STRTOK ); wxString keyname = lineTokenizer.GetNextToken(); wxString remainder = lineTokenizer.GetString(); - /* Get the command name */ + // Get the command name wxString fctname = remainder.AfterFirst( '\"' ).BeforeFirst( '\"' ); - /* search the hotkey in current hotkey list */ - for( EDA_HOTKEY** List = CurrentHotkeyList; *List != NULL; List++ ) + // search the hotkey in current hotkey list + for( EDA_HOTKEY** list = CurrentHotkeyList; *list != NULL; list++ ) { - EDA_HOTKEY* hk_decr = *List; + EDA_HOTKEY* hk_decr = *list; if( hk_decr->m_InfoMsg == fctname ) { - int code = ReturnKeyCodeFromKeyName( keyname ); + int code = KeyCodeFromKeyName( keyname ); if( code ) hk_decr->m_KeyCode = code; @@ -681,7 +684,7 @@ void EDA_BASE_FRAME::ImportHotkeyConfigFromFile( struct EDA_HOTKEY_CONFIG* aDesc wxString ext = DEFAULT_HOTKEY_FILENAME_EXT; wxString mask = wxT( "*." ) + ext; wxString path = wxGetCwd(); - wxString filename = wxGetApp().GetAppName() + wxT( "." ) + ext; + wxString filename = Kiface().Name() + wxT( '.' ) + ext; filename = EDA_FileSelector( _( "Read Hotkey Configuration File:" ), path, @@ -709,7 +712,7 @@ void EDA_BASE_FRAME::ExportHotkeyConfigToFile( struct EDA_HOTKEY_CONFIG* aDescLi wxString ext = DEFAULT_HOTKEY_FILENAME_EXT; wxString mask = wxT( "*." ) + ext; wxString path = wxGetCwd(); - wxString filename = wxGetApp().GetAppName() + wxT( "." ) + ext; + wxString filename = Kiface().Name() + wxT( "." ) + ext; filename = EDA_FileSelector( _( "Write Hotkey Configuration File:" ), path, @@ -736,14 +739,14 @@ void AddHotkeyConfigMenu( wxMenu* aMenu ) wxMenu* HotkeySubmenu = new wxMenu(); - /* List existing hotkey menu*/ + // List existing hotkey menu AddMenuItem( HotkeySubmenu, ID_PREFERENCES_HOTKEY_SHOW_CURRENT_LIST, _( "&List Current Keys" ), _( "Displays the current hotkeys list and corresponding commands" ), KiBitmap( info_xpm ) ); - /* Call hotkeys editor*/ + // Call hotkeys editor AddMenuItem( HotkeySubmenu, ID_PREFERENCES_HOTKEY_SHOW_EDITOR, _( "&Edit Hotkeys" ), _( "Call the hotkeys editor" ), @@ -751,19 +754,19 @@ void AddHotkeyConfigMenu( wxMenu* aMenu ) HotkeySubmenu->AppendSeparator(); - /* create hotkey file to export current hotkeys config */ + // create hotkey file to export current hotkeys config AddMenuItem( HotkeySubmenu, ID_PREFERENCES_HOTKEY_EXPORT_CONFIG, _( "E&xport Hotkeys" ), _( "Create a hotkey configuration file to export the current hotkeys" ), KiBitmap( save_setup_xpm ) ); - /* Reload hotkey file */ + // Reload hotkey file AddMenuItem( HotkeySubmenu, ID_PREFERENCES_HOTKEY_IMPORT_CONFIG, _( "&Import Hotkeys" ), _( "Load an existing hotkey configuration file" ), KiBitmap( reload_xpm ) ); - /* Append HotkeySubmenu to menu */ + // Append HotkeySubmenu to menu AddMenuItem( aMenu, HotkeySubmenu, ID_PREFERENCES_HOTKEY_SUBMENU, _( "&Hotkeys" ), _( "Hotkeys configuration and preferences" ), diff --git a/common/kiface_i.cpp b/common/kiface_i.cpp new file mode 100644 index 0000000000..164195b231 --- /dev/null +++ b/common/kiface_i.cpp @@ -0,0 +1,206 @@ +/* + * This program source code file is part of KiCad, a free EDA CAD application. + * + * Copyright (C) 2004 Jean-Pierre Charras, jaen-pierre.charras@gipsa-lab.inpg.com + * Copyright (C) 2008-2011 Wayne Stambaugh + * Copyright (C) 1992-2014 KiCad Developers, see AUTHORS.txt for contributors. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, you may find one here: + * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html + * or you may search the http://www.gnu.org website for the version 2 license, + * or you may write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + */ + +#include // FROM_UTF8() +#include +#include + +#include +#include + +#include +#include + + +static const wxChar showPageLimitsKey[] = wxT( "ShowPageLimits" ); +static const wxChar backgroundColorKey[] = wxT( "BackgroundColor" ); + + +/// Initialize aDst SEARCH_STACK with KIFACE (DSO) specific settings. +/// A non-member function so it an be moved easily, plus it's nobody's business. +static void setSearchPaths( SEARCH_STACK* aDst, KIWAY::FACE_T aId ) +{ + SEARCH_STACK bases; + + SystemDirsAppend( &bases ); + aDst->Clear(); + + for( unsigned i = 0; i < bases.GetCount(); ++i ) + { + wxFileName fn( bases[i], wxEmptyString ); + + // Add schematic library file path to search path list. + // we must add /library and /library/doc + if( aId == KIWAY::FACE_SCH ) + { + fn.AppendDir( wxT( "library" ) ); + aDst->AddPaths( fn.GetPath() ); + + // Add schematic doc file path (library/doc)to search path list. + fn.AppendDir( wxT( "doc" ) ); + aDst->AddPaths( fn.GetPath() ); + + fn.RemoveLastDir(); + fn.RemoveLastDir(); // "../../" up twice, removing library/doc/ + } + + // Add PCB library file path to search path list. + if( aId == KIWAY::FACE_PCB || aId == KIWAY::FACE_CVPCB ) + { + fn.AppendDir( wxT( "modules" ) ); + aDst->AddPaths( fn.GetPath() ); + + // Add 3D module library file path to search path list. + fn.AppendDir( wxT( "packages3d" ) ); + aDst->AddPaths( fn.GetPath() ); + + fn.RemoveLastDir(); + fn.RemoveLastDir(); // "../../" up twice, remove modules/packages3d + } + + // Add KiCad template file path to search path list. + fn.AppendDir( wxT( "template" ) ); + aDst->AddPaths( fn.GetPath() ); + } + +#if 1 && defined(DEBUG) + aDst->Show( "kiway" ); +#endif +} + + +bool KIFACE_I::start_common() +{ + m_bm.Init(); + + m_bm.m_config->Read( showPageLimitsKey, &g_ShowPageLimits ); + + // FIXME OSX Mountain Lion (10.8) + // Seems that Read doesn't found anything and ColorFromInt + // Asserts - I'm unable to reproduce on 10.7 + + int draw_bg_color = BLACK; // Default for all apps but Eeschema + + if( m_id == KIWAY::FACE_SCH ) + draw_bg_color = WHITE; // Default for Eeschema + + m_bm.m_config->Read( backgroundColorKey, &draw_bg_color ); + + g_DrawBgColor = ColorFromInt( draw_bg_color ); + + setSearchPaths( &m_bm.m_search, m_id ); + + return true; +} + + +void KIFACE_I::end_common() +{ + m_bm.End(); +} + + +wxString KIFACE_I::GetHelpFile() +{ + wxString fn; + wxArrayString subdirs; + wxArrayString altsubdirs; + + // FIXME: This is not the ideal way to handle this. Unfortunately, the + // CMake install paths seem to be a moving target so this crude + // hack solves the problem of install path differences between + // Windows and non-Windows platforms. + + // Partially fixed, but must be enhanced + + // Create subdir tree for "standard" linux distributions, when KiCad comes + // from a distribution files are in /usr/share/doc/kicad/help and binaries + // in /usr/bin or /usr/local/bin + subdirs.Add( wxT( "share" ) ); + subdirs.Add( wxT( "doc" ) ); + subdirs.Add( wxT( "kicad" ) ); + subdirs.Add( wxT( "help" ) ); + + // Create subdir tree for linux and Windows KiCad pack. + // Note the pack form under linux is also useful if a user wants to + // install KiCad to a server because there is only one path to mount + // or export (something like /usr/local/kicad). + // files are in /kicad/doc/help + // (often /usr/local/kicad/kicad/doc/help) + // /kicad/ is retrieved from m_BinDir + altsubdirs.Add( wxT( "doc" ) ); + altsubdirs.Add( wxT( "help" ) ); + + /* Search for a help file. + * we *must* find a help file. + * so help is searched in directories in this order: + * help/ like help/en_GB + * help/ like help/en + * help/en + */ + + wxLocale* i18n = Pgm().GetLocale(); + + // Step 1 : Try to find help file in help/ + subdirs.Add( i18n->GetCanonicalName() ); + altsubdirs.Add( i18n->GetCanonicalName() ); + + fn = m_bm.m_search.FindFileInSearchPaths( m_bm.m_help_file, &altsubdirs ); + + if( !fn ) + fn = m_bm.m_search.FindFileInSearchPaths( m_bm.m_help_file, &subdirs ); + + // Step 2 : if not found Try to find help file in help/ + if( !fn ) + { + subdirs.RemoveAt( subdirs.GetCount() - 1 ); + altsubdirs.RemoveAt( altsubdirs.GetCount() - 1 ); + + // wxLocale::GetName() does not return always the short name + subdirs.Add( i18n->GetName().BeforeLast( '_' ) ); + altsubdirs.Add( i18n->GetName().BeforeLast( '_' ) ); + + fn = m_bm.m_search.FindFileInSearchPaths( m_bm.m_help_file, &altsubdirs ); + + if( !fn ) + fn = m_bm.m_search.FindFileInSearchPaths( m_bm.m_help_file, &subdirs ); + } + + // Step 3 : if not found Try to find help file in help/en + if( !fn ) + { + subdirs.RemoveAt( subdirs.GetCount() - 1 ); + altsubdirs.RemoveAt( altsubdirs.GetCount() - 1 ); + subdirs.Add( wxT( "en" ) ); + altsubdirs.Add( wxT( "en" ) ); + + fn = m_bm.m_search.FindFileInSearchPaths( m_bm.m_help_file, &altsubdirs ); + + if( !fn ) + fn = m_bm.m_search.FindFileInSearchPaths( m_bm.m_help_file, &subdirs ); + } + + return fn; +} diff --git a/common/kiway.cpp b/common/kiway.cpp index 92086838ca..577f118e66 100644 --- a/common/kiway.cpp +++ b/common/kiway.cpp @@ -35,10 +35,11 @@ wxDynamicLibrary KIWAY::s_pcb_dso; KIWAY::KIWAY() { - memset( &m_dso_players, 0, sizeof( m_dso_players ) ); + memset( &m_kiface, 0, sizeof( m_kiface ) ); } +/* const wxString KIWAY::dso_name( FACE_T aFaceId ) { switch( aFaceId ) @@ -51,11 +52,12 @@ const wxString KIWAY::dso_name( FACE_T aFaceId ) return wxEmptyString; } } +*/ -PROJECT& KIWAY::Project() +PROJECT& KIWAY::Prj() const { - return m_project; + return *(PROJECT*) &m_project; // strip const-ness, function really is const. } @@ -65,10 +67,8 @@ KIFACE* KIWAY::KiFACE( FACE_T aFaceId, bool doLoad ) { case FACE_SCH: case FACE_PCB: - //case FACE_LIB: - //case FACE_MOD: - if( m_dso_players[aFaceId] ) - return m_dso_players[aFaceId]; + if( m_kiface[aFaceId] ) + return m_kiface[aFaceId]; default: wxASSERT_MSG( 0, wxT( "caller has a bug, passed a bad aFaceId" ) ); @@ -86,8 +86,6 @@ KIFACE* KIWAY::KiFACE( FACE_T aFaceId, bool doLoad ) case FACE_PCB: break; - //case FACE_LIB: - //case FACE_MOD: default: ; } diff --git a/common/kiway_holder.cpp b/common/kiway_holder.cpp new file mode 100644 index 0000000000..a0a2dcfe76 --- /dev/null +++ b/common/kiway_holder.cpp @@ -0,0 +1,32 @@ + +#include +#include + +#if defined(DEBUG) + #include +#endif + + +PROJECT& KIWAY_HOLDER::Prj() const +{ + return Kiway().Prj(); +} + + +// this is not speed critical, hide it out of line. +void KIWAY_HOLDER::SetKiway( wxWindow* aDest, KIWAY* aKiway ) +{ +#if defined(DEBUG) + // offer a trap point for debugging most any window + wxASSERT( aDest ); + if( !strcmp( typeid(aDest).name(), "DIALOG_EDIT_LIBENTRY_FIELDS_IN_LIB" ) ) + { + int breakhere=1; + (void) breakhere; + } +#endif + + (void) aDest; + + m_kiway = aKiway; +} diff --git a/common/page_layout/class_worksheet_layout.cpp b/common/page_layout/class_worksheet_layout.cpp index 67cd12277d..379ba777ab 100644 --- a/common/page_layout/class_worksheet_layout.cpp +++ b/common/page_layout/class_worksheet_layout.cpp @@ -50,13 +50,14 @@ */ #include -#include +#include #include #include #include #include #include + // The layout shape used in the application // It is accessible by WORKSHEET_LAYOUT::GetTheInstance() WORKSHEET_LAYOUT wksTheInstance; @@ -70,21 +71,25 @@ WORKSHEET_LAYOUT::WORKSHEET_LAYOUT() m_bottomMargin = 10.0; // the bottom page margin in mm } + void WORKSHEET_LAYOUT::SetLeftMargin( double aMargin ) { m_leftMargin = aMargin; // the left page margin in mm } + void WORKSHEET_LAYOUT::SetRightMargin( double aMargin ) { m_rightMargin = aMargin; // the right page margin in mm } + void WORKSHEET_LAYOUT::SetTopMargin( double aMargin ) { m_topMargin = aMargin; // the top page margin in mm } + void WORKSHEET_LAYOUT::SetBottomMargin( double aMargin ) { m_bottomMargin = aMargin; // the bottom page margin in mm @@ -98,8 +103,7 @@ void WORKSHEET_LAYOUT::ClearList() m_list.clear(); } -/* Insert an item to the list of items at position aIdx - */ + void WORKSHEET_LAYOUT::Insert( WORKSHEET_DATAITEM* aItem, unsigned aIdx ) { if ( aIdx >= GetCount() ) @@ -108,8 +112,7 @@ void WORKSHEET_LAYOUT::Insert( WORKSHEET_DATAITEM* aItem, unsigned aIdx ) m_list.insert( m_list.begin() + aIdx, aItem ); } -/* Remove the item to the list of items at position aIdx - */ + bool WORKSHEET_LAYOUT::Remove( unsigned aIdx ) { if ( aIdx >= GetCount() ) @@ -118,8 +121,7 @@ bool WORKSHEET_LAYOUT::Remove( unsigned aIdx ) return true; } -/* Remove the item to the list of items at position aIdx - */ + bool WORKSHEET_LAYOUT::Remove( WORKSHEET_DATAITEM* aItem ) { unsigned idx = 0; @@ -135,8 +137,7 @@ bool WORKSHEET_LAYOUT::Remove( WORKSHEET_DATAITEM* aItem ) return Remove( idx ); } -/* return the index of aItem, or -1 if does not exist - */ + int WORKSHEET_LAYOUT::GetItemIndex( WORKSHEET_DATAITEM* aItem ) const { unsigned idx = 0; @@ -161,17 +162,13 @@ WORKSHEET_DATAITEM* WORKSHEET_LAYOUT::GetItem( unsigned aIdx ) const return NULL; } -/* return a short filename from a full filename: - * if the path is the current path,or if the path is the same - * as kicad.pro (in template), returns a shortname - * else do nothing and returns the full filename - */ + const wxString WORKSHEET_LAYOUT::MakeShortFileName( const wxString& aFullFileName ) { - wxFileName fn = aFullFileName; - wxString shortFileName = aFullFileName; + wxFileName fn = aFullFileName; + wxString shortFileName = aFullFileName; + wxString fileName = Kiface().KifaceSearch().FindValidPath( fn.GetFullName() ); - wxString fileName = wxGetApp().GetLibraryPathList().FindValidPath( fn.GetFullName() ); if( !fileName.IsEmpty() ) { fn = fileName; @@ -182,19 +179,15 @@ const wxString WORKSHEET_LAYOUT::MakeShortFileName( const wxString& aFullFileNam return shortFileName; } -/** - * @return a full filename from a short filename, - * if the short filename path is void - * In this case the path is the same as kicad.pro (in template) - * else return the short filename (which have an absolute os relative path - */ + const wxString WORKSHEET_LAYOUT::MakeFullFileName( const wxString& aShortFileName ) { - wxFileName fn = aShortFileName; - wxString fullFileName = aShortFileName; + wxFileName fn = aShortFileName; + wxString fullFileName = aShortFileName; + if( fn.GetPath().IsEmpty() && !fn.GetFullName().IsEmpty() ) { - wxString name = wxGetApp().GetLibraryPathList().FindValidPath( fn.GetFullName() ); + wxString name = Kiface().KifaceSearch().FindValidPath( fn.GetFullName() ); if( !name.IsEmpty() ) fullFileName = name; } diff --git a/common/pgm_base.cpp b/common/pgm_base.cpp new file mode 100644 index 0000000000..e0af909af6 --- /dev/null +++ b/common/pgm_base.cpp @@ -0,0 +1,739 @@ +/* + * This program source code file is part of KiCad, a free EDA CAD application. + * + * Copyright (C) 2004 Jean-Pierre Charras, jaen-pierre.charras@gipsa-lab.inpg.com + * Copyright (C) 2008-2011 Wayne Stambaugh + * Copyright (C) 1992-2011 KiCad Developers, see AUTHORS.txt for contributors. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, you may find one here: + * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html + * or you may search the http://www.gnu.org website for the version 2 license, + * or you may write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + */ + +/** + * @file pgm_base.cpp + * + * @brief For the main application: init functions, and language selection + * (locale handling) + */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +#define KICAD_COMMON wxT( "kicad_common" ) + +// some key strings used to store parameters in KICAD_COMMON + +const wxChar PGM_BASE::workingDirKey[] = wxT( "WorkingDir" ); // public + +static const wxChar languageCfgKey[] = wxT( "LanguageID" ); +static const wxChar kicadFpLibPath[] = wxT( "KicadFootprintLibraryPath" ); + + +/** + * A small class to handle the list of existing translations. + * The locale translation is automatic. + * The selection of languages is mainly for maintainer's convenience + * To add a support to a new translation: + * create a new icon (flag of the country) (see Lang_Fr.xpm as an example) + * add a new item to s_Languages[]. + */ +struct LANGUAGE_DESCR +{ + /// wxWidgets locale identifier (See wxWidgets doc) + int m_WX_Lang_Identifier; + + /// KiCad identifier used in menu selection (See id.h) + int m_KI_Lang_Identifier; + + /// The menu language icons + BITMAP_DEF m_Lang_Icon; + + /// Labels used in menus + wxString m_Lang_Label; + + /// Set to true if the m_Lang_Label must not be translated + bool m_DoNotTranslate; +}; + + +/** + * Variable s_Languages + * Note: because this list is not created on the fly, wxTranslation + * must be called when a language name must be displayed after translation. + * Do not change this behavior, because m_Lang_Label is also used as key in config + */ +static LANGUAGE_DESCR s_Languages[] = +{ + // Default language + { + wxLANGUAGE_DEFAULT, + ID_LANGUAGE_DEFAULT, + lang_def_xpm, + _( "Default" ) + }, + + // English language + { + wxLANGUAGE_ENGLISH, + ID_LANGUAGE_ENGLISH, + lang_en_xpm, + wxT( "English" ), + true + }, + + // French language + { + wxLANGUAGE_FRENCH, + ID_LANGUAGE_FRENCH, + lang_fr_xpm, + _( "French" ) + }, + + // Finnish language + { + wxLANGUAGE_FINNISH, + ID_LANGUAGE_FINNISH, + lang_fi_xpm, + _( "Finnish" ) + }, + + // Spanish language + { + wxLANGUAGE_SPANISH, + ID_LANGUAGE_SPANISH, + lang_es_xpm, + _( "Spanish" ) + }, + + // Portuguese language + { + wxLANGUAGE_PORTUGUESE, + ID_LANGUAGE_PORTUGUESE, + lang_pt_xpm, + _( "Portuguese" ) + }, + + // Italian language + { + wxLANGUAGE_ITALIAN, + ID_LANGUAGE_ITALIAN, + lang_it_xpm, + _( "Italian" ) + }, + + // German language + { + wxLANGUAGE_GERMAN, + ID_LANGUAGE_GERMAN, + lang_de_xpm, + _( "German" ) + }, + + // Greek language + { + wxLANGUAGE_GREEK, + ID_LANGUAGE_GREEK, + lang_gr_xpm, + _( "Greek" ) + }, + + // Slovenian language + { + wxLANGUAGE_SLOVENIAN, + ID_LANGUAGE_SLOVENIAN, + lang_sl_xpm, + _( "Slovenian" ) + }, + + // Hungarian language + { + wxLANGUAGE_HUNGARIAN, + ID_LANGUAGE_HUNGARIAN, + lang_hu_xpm, + _( "Hungarian" ) + }, + + // Polish language + { + wxLANGUAGE_POLISH, + ID_LANGUAGE_POLISH, + lang_pl_xpm, + _( "Polish" ) + }, + + // Czech language + { + wxLANGUAGE_CZECH, + ID_LANGUAGE_CZECH, + lang_cs_xpm, + _( "Czech" ) + }, + + // Russian language + { + wxLANGUAGE_RUSSIAN, + ID_LANGUAGE_RUSSIAN, + lang_ru_xpm, + _( "Russian" ) + }, + + // Korean language + { + wxLANGUAGE_KOREAN, + ID_LANGUAGE_KOREAN, + lang_ko_xpm, + _( "Korean" ) + }, + + // Chinese simplified + { + wxLANGUAGE_CHINESE_SIMPLIFIED, + ID_LANGUAGE_CHINESE_SIMPLIFIED, + lang_chinese_xpm, + _( "Chinese simplified" ) + }, + + // Catalan language + { + wxLANGUAGE_CATALAN, + ID_LANGUAGE_CATALAN, + lang_catalan_xpm, + _( "Catalan" ) + }, + + // Dutch language + { + wxLANGUAGE_DUTCH, + ID_LANGUAGE_DUTCH, + lang_nl_xpm, + _( "Dutch" ) + }, + + // Japanese language + { + wxLANGUAGE_JAPANESE, + ID_LANGUAGE_JAPANESE, + lang_jp_xpm, + _( "Japanese" ) + }, + + // Bulgarian language + { + wxLANGUAGE_BULGARIAN, + ID_LANGUAGE_BULGARIAN, + lang_bg_xpm, + _( "Bulgarian" ) + } +}; + + +PGM_BASE::PGM_BASE() +{ + m_pgm_checker = NULL; + m_file_checker = NULL; + m_html_ctrl = NULL; + m_locale = NULL; + m_common_settings = NULL; + + m_wx_app = NULL; + + setLanguageId( wxLANGUAGE_DEFAULT ); + + ForceSystemPdfBrowser( false ); +} + + +PGM_BASE::~PGM_BASE() +{ + destroy(); +} + + +void PGM_BASE::destroy() +{ + // unlike a normal destructor, this is designed to be called more than once safely: + + delete m_common_settings; + m_common_settings = 0; + + delete m_pgm_checker; + m_pgm_checker = 0; + + delete m_file_checker; + m_file_checker = 0; + + delete m_locale; + m_locale = 0; + + delete m_html_ctrl; + m_html_ctrl = 0; +} + + +void PGM_BASE::SetEditorName( const wxString& aFileName ) +{ + m_editor_name = aFileName; + wxASSERT( m_common_settings ); + m_common_settings->Write( wxT( "Editor" ), aFileName ); +} + + +const wxString& PGM_BASE::GetEditorName() +{ + wxString editorname = m_editor_name; + + if( !editorname ) + { + // Get the preferred editor name from environment variable first. + if(!wxGetEnv( wxT( "EDITOR" ), &editorname )) + { + // If there is no EDITOR variable set, try the desktop default +#ifdef __WXMAC__ + editorname = "/usr/bin/open"; +#elif __WXX11__ + editorname = "/usr/bin/xdg-open"; +#endif + } + } + + if( !editorname ) // We must get a preferred editor name + { + DisplayInfoMessage( NULL, + _( "No default editor found, you must choose it" ) ); + + wxString mask( wxT( "*" ) ); + +#ifdef __WINDOWS__ + mask += wxT( ".exe" ); +#endif + editorname = EDA_FileSelector( _( "Preferred Editor:" ), wxEmptyString, + wxEmptyString, wxEmptyString, mask, + NULL, wxFD_OPEN, true ); + } + + if( !editorname.IsEmpty() ) + { + m_editor_name = editorname; + m_common_settings->Write( wxT( "Editor" ), m_editor_name ); + } + + return m_editor_name; +} + + +bool PGM_BASE::initPgm() +{ + wxFileName pgm_name( App().argv[0] ); + + wxInitAllImageHandlers(); + + m_pgm_checker = new wxSingleInstanceChecker( pgm_name.GetName().Lower() + wxT( "-" ) + wxGetUserId() ); + + if( m_pgm_checker->IsAnotherRunning() ) + { + wxString quiz = wxString::Format( + _( "%s is already running, Continue?" ), + GetChars( pgm_name.GetName() ) + ); + if( !IsOK( NULL, quiz ) ) + return false; + } + + // Init KiCad environment + // the environment variable KICAD (if exists) gives the kicad path: + // something like set KICAD=d:\kicad + bool isDefined = wxGetEnv( wxT( "KICAD" ), &m_kicad_env ); + + if( isDefined ) // ensure m_kicad_env ends by "/" + { + m_kicad_env.Replace( WIN_STRING_DIR_SEP, UNIX_STRING_DIR_SEP ); + + if( !m_kicad_env.IsEmpty() && m_kicad_env.Last() != '/' ) + m_kicad_env += UNIX_STRING_DIR_SEP; + } + + // Init parameters for configuration + App().SetVendorName( wxT( "KiCad" ) ); + App().SetAppName( pgm_name.GetName().Lower() ); + + // Install some image handlers, mainly for help + wxImage::AddHandler( new wxPNGHandler ); + wxImage::AddHandler( new wxGIFHandler ); + wxImage::AddHandler( new wxJPEGHandler ); + wxFileSystem::AddHandler( new wxZipFSHandler ); + + // Analyze the command line & initialize the binary path + setExecutablePath(); + + SetLanguagePath(); + + // OS specific instantiation of wxConfigBase derivative: + m_common_settings = new wxConfig( KICAD_COMMON ); + + ReadPdfBrowserInfos(); // needs m_common_settings + + loadCommonSettings(); + + SetLanguage( true ); + + // Set locale option for separator used in float numbers + SetLocaleTo_Default(); + + return true; +} + + +void PGM_BASE::SetHtmlHelpController( wxHtmlHelpController* aController ) +{ + delete m_html_ctrl; + m_html_ctrl = aController; +} + + +void PGM_BASE::InitOnLineHelp() +{ + wxString fullfilename = FindKicadHelpPath(); + +#if defined ONLINE_HELP_FILES_FORMAT_IS_HTML + m_HelpFileName = fullfilename + wxT( ".html" ); + fullfilename += wxT( "kicad.hhp" ); + + if( wxFileExists( fullfilename ) ) + { + m_html_ctrl = new wxHtmlHelpController( wxHF_TOOLBAR | wxHF_CONTENTS | + wxHF_PRINT | wxHF_OPEN_FILES + /*| wxHF_SEARCH */ ); + m_html_ctrl->UseConfig( m_common_settings ); + m_html_ctrl->SetTitleFormat( wxT( "KiCad Help" ) ); + m_html_ctrl->AddBook( fullfilename ); + } + +#elif defined ONLINE_HELP_FILES_FORMAT_IS_PDF + m_html_ctrl = NULL; + +#else + #error Help files format not defined +#endif +} + + +bool PGM_BASE::setExecutablePath() +{ +// Apple MacOSx +#ifdef __APPLE__ + + // Derive path from location of the app bundle + CFBundleRef mainBundle = CFBundleGetMainBundle(); + + if( mainBundle == NULL ) + return false; + + CFURLRef urlref = CFBundleCopyBundleURL( mainBundle ); + + if( urlref == NULL ) + return false; + + CFStringRef str = CFURLCopyFileSystemPath( urlref, kCFURLPOSIXPathStyle ); + + if( str == NULL ) + return false; + + char* native_str = NULL; + int len = CFStringGetMaximumSizeForEncoding( CFStringGetLength( str ), + kCFStringEncodingUTF8 ) + 1; + native_str = new char[len]; + + CFStringGetCString( str, native_str, len, kCFStringEncodingUTF8 ); + m_bin_dir = FROM_UTF8( native_str ); + delete[] native_str; + +#else + m_bin_dir = wxStandardPaths::Get().GetExecutablePath(); + +#endif + + // Use unix notation for paths. I am not sure this is a good idea, + // but it simplifies compatibility between Windows and Unices. + // However it is a potential problem in path handling under Windows. + m_bin_dir.Replace( WIN_STRING_DIR_SEP, UNIX_STRING_DIR_SEP ); + + // Remove file name form command line: + while( m_bin_dir.Last() != '/' && !m_bin_dir.IsEmpty() ) + m_bin_dir.RemoveLast(); + + return true; +} + + +void PGM_BASE::loadCommonSettings() +{ + wxASSERT( m_common_settings ); + + m_help_size.x = 500; + m_help_size.y = 400; + + wxString languageSel; + + m_common_settings->Read( languageCfgKey, &languageSel ); + setLanguageId( wxLANGUAGE_DEFAULT ); + + // Search for the current selection + for( unsigned ii = 0; ii < DIM( s_Languages ); ii++ ) + { + if( s_Languages[ii].m_Lang_Label == languageSel ) + { + setLanguageId( s_Languages[ii].m_WX_Lang_Identifier ); + break; + } + } + + m_editor_name = m_common_settings->Read( wxT( "Editor" ) ); +} + + +void PGM_BASE::saveCommonSettings() +{ + // m_common_settings is not initialized until fairly late in the + // process startup: initPgm(), so test before using: + if( m_common_settings ) + { + m_common_settings->Write( workingDirKey, wxGetCwd() ); + } +} + + +bool PGM_BASE::SetLanguage( bool first_time ) +{ + bool retv = true; + + // dictionary file name without extend (full name is kicad.mo) + wxString dictionaryName( wxT( "kicad" ) ); + + delete m_locale; + m_locale = new wxLocale; + +#if wxCHECK_VERSION( 2, 9, 0 ) + if( !m_locale->Init( m_language_id ) ) +#else + if( !m_locale->Init( m_language_id, wxLOCALE_CONV_ENCODING ) ) +#endif + { + wxLogDebug( wxT( "This language is not supported by the system." ) ); + + setLanguageId( wxLANGUAGE_DEFAULT ); + delete m_locale; + + m_locale = new wxLocale; + m_locale->Init(); + retv = false; + } + else if( !first_time ) + { + wxLogDebug( wxT( "Search for dictionary %s.mo in %s" ), + GetChars( dictionaryName ), GetChars( m_locale->GetName() ) ); + } + + // how about a meaningful comment here. + if( !first_time ) + { + wxString languageSel; + + // Search for the current selection + for( unsigned ii = 0; ii < DIM( s_Languages ); ii++ ) + { + if( s_Languages[ii].m_WX_Lang_Identifier == m_language_id ) + { + languageSel = s_Languages[ii].m_Lang_Label; + break; + } + } + + m_common_settings->Write( languageCfgKey, languageSel ); + } + + // Test if floating point notation is working (bug in cross compilation, using wine) + // Make a conversion double <=> string + double dtst = 0.5; + wxString msg; + + extern bool g_DisableFloatingPointLocalNotation; // See common.cpp + + g_DisableFloatingPointLocalNotation = false; + + msg << dtst; + double result; + msg.ToDouble( &result ); + + if( result != dtst ) // string to double encode/decode does not work! Bug detected + { + // Disable floating point localization: + g_DisableFloatingPointLocalNotation = true; + SetLocaleTo_C_standard( ); + } + + if( !m_locale->IsLoaded( dictionaryName ) ) + m_locale->AddCatalog( dictionaryName ); + + if( !retv ) + return retv; + + return m_locale->IsOk(); +} + + +void PGM_BASE::SetLanguageIdentifier( int menu_id ) +{ + wxLogDebug( wxT( "Select language ID %d from %zd possible languages." ), + menu_id, DIM( s_Languages ) ); + + for( unsigned ii = 0; ii < DIM( s_Languages ); ii++ ) + { + if( menu_id == s_Languages[ii].m_KI_Lang_Identifier ) + { + setLanguageId( s_Languages[ii].m_WX_Lang_Identifier ); + break; + } + } +} + + +void PGM_BASE::SetLanguagePath() +{ + SEARCH_STACK guesses; + + SystemDirsAppend( &guesses ); + + // Add our internat dir to the wxLocale catalog of paths + for( unsigned i = 0; i < guesses.GetCount(); i++ ) + { + wxFileName fn( guesses[i], wxEmptyString ); + + // Append path for Windows and unix KiCad package install + fn.AppendDir( wxT( "share" ) ); + fn.AppendDir( wxT( "internat" ) ); + + if( fn.IsDirReadable() ) + { + wxLogDebug( wxT( "Adding locale lookup path: " ) + fn.GetPath() ); + wxLocale::AddCatalogLookupPathPrefix( fn.GetPath() ); + } + + // Append path for unix standard install + fn.RemoveLastDir(); + fn.AppendDir( wxT( "kicad" ) ); + fn.AppendDir( wxT( "internat" ) ); + + if( fn.IsDirReadable() ) + { + wxLogDebug( wxT( "Adding locale lookup path: " ) + fn.GetPath() ); + wxLocale::AddCatalogLookupPathPrefix( fn.GetPath() ); + } + } +} + + +void PGM_BASE::AddMenuLanguageList( wxMenu* MasterMenu ) +{ + wxMenu* menu = NULL; + wxMenuItem* item = MasterMenu->FindItem( ID_LANGUAGE_CHOICE ); + + if( item ) // This menu exists, do nothing + return; + + menu = new wxMenu; + + for( unsigned ii = 0; ii < DIM( s_Languages ); ii++ ) + { + wxString label; + + if( s_Languages[ii].m_DoNotTranslate ) + label = s_Languages[ii].m_Lang_Label; + else + label = wxGetTranslation( s_Languages[ii].m_Lang_Label ); + + AddMenuItem( menu, s_Languages[ii].m_KI_Lang_Identifier, + label, KiBitmap(s_Languages[ii].m_Lang_Icon ), + wxITEM_CHECK ); + } + + AddMenuItem( MasterMenu, menu, + ID_LANGUAGE_CHOICE, + _( "Language" ), + _( "Select application language (only for testing!)" ), + KiBitmap( language_xpm ) ); + + // Set Check mark on current selected language + for( unsigned ii = 0; ii < DIM( s_Languages ); ii++ ) + { + if( m_language_id == s_Languages[ii].m_WX_Lang_Identifier ) + menu->Check( s_Languages[ii].m_KI_Lang_Identifier, true ); + else + menu->Check( s_Languages[ii].m_KI_Lang_Identifier, false ); + } +} + + +bool PGM_BASE::LockFile( const wxString& aFileName ) +{ + // first make absolute and normalize, to avoid that different lock files + // for the same file can be created + wxFileName fn( aFileName ); + + fn.MakeAbsolute(); + + // semaphore to protect the edition of the file by more than one instance + if( m_file_checker != NULL ) + { + // it means that we had an open file and we are opening a different one + delete m_file_checker; + } + + wxString lockFileName = fn.GetFullPath() + wxT( ".lock" ); + + lockFileName.Replace( wxT( "/" ), wxT( "_" ) ); + + // We can have filenames coming from Windows, so also convert Windows separator + lockFileName.Replace( wxT( "\\" ), wxT( "_" ) ); + + m_file_checker = new wxSingleInstanceChecker( lockFileName ); + + if( m_file_checker && + m_file_checker->IsAnotherRunning() ) + { + return false; + } + + return true; +} diff --git a/common/project.cpp b/common/project.cpp new file mode 100644 index 0000000000..b69926e574 --- /dev/null +++ b/common/project.cpp @@ -0,0 +1,345 @@ + +/* + * This program source code file is part of KiCad, a free EDA CAD application. + * + * Copyright (C) 2014 KiCad Developers, see CHANGELOG.TXT for contributors. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, you may find one here: + * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html + * or you may search the http://www.gnu.org website for the version 2 license, + * or you may write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + */ + + +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +PROJECT::PROJECT() +{ + memset( m_elems, 0, sizeof(m_elems) ); +} + +PROJECT::~PROJECT() +{ + /* @todo + careful here, this may work, but the virtual destructor may not + be in the same link image as PROJECT. Won't enable this until + we're more stable and destructor is assuredly in same image, i.e. + libki.so + for( unsigned i = 0; iRead( key, wxEmptyString ); + + if( !upath ) + break; + + aDst->AddPaths( upath, aIndex ); + } +} + + +// non-member so it can be moved easily, and kept REALLY private. +// Do NOT Clear() in here. +static void add_search_paths( SEARCH_STACK* aDst, const SEARCH_STACK& aSrc, int aIndex ) +{ + for( unsigned i=0; iAddPaths( aSrc[i], aIndex ); +} + + +/* +bool PROJECT::MaybeLoadProjectSettings( const std::vector& aFileSet ) +{ + // @todo + return true; +} +*/ + + +wxConfigBase* PROJECT::configCreate( const SEARCH_STACK& aSList, const wxString& aFileName, + const wxString& aGroupName, bool aForceUseLocalConfig ) +{ + wxConfigBase* cfg = 0; + wxFileName fn = aFileName; + + fn.SetExt( ProjectFileExtension ); + + // is there an edge transition, a change in m_project_filename? + if( m_project_name != fn ) + { + m_sch_search.Clear(); + + SetProjectFullName( fn.GetFullPath() ); + + // to the empty list, add project dir as first + m_sch_search.AddPaths( fn.GetPath() ); + + // append all paths from aSList + add_search_paths( &m_sch_search, aSList, -1 ); + + // addLibrarySearchPaths( SEARCH_STACK* aSP, wxConfigBase* aCfg ) + // This is undocumented, but somebody wanted to store !schematic! + // library search paths in the .kicad_common file? + add_search_paths( &m_sch_search, Pgm().CommonSettings(), -1 ); + +#if 1 && defined(DEBUG) + m_sch_search.Show( __func__ ); +#endif + } + + // Init local config filename + if( aForceUseLocalConfig || fn.FileExists() ) + { + wxString cur_pro_fn = fn.GetFullPath(); + + cfg = new wxFileConfig( wxEmptyString, wxEmptyString, cur_pro_fn, wxEmptyString ); + + cfg->DontCreateOnDemand(); + + if( aForceUseLocalConfig ) + { + SetProjectFullName( cur_pro_fn ); + return cfg; + } + + /* Check the application version against the version saved in the + * project file. + * + * TODO: Push the version test up the stack so that when one of the + * KiCad application version changes, the other applications + * settings do not get updated. Practically, this can go away. + * It isn't used anywhere as far as I know (WLS). + */ + + cfg->SetPath( aGroupName ); + + int def_version = 0; + int version = cfg->Read( wxT( "version" ), def_version ); + + if( version > 0 ) + { + cfg->SetPath( wxCONFIG_PATH_SEPARATOR ); + SetProjectFullName( cur_pro_fn ); + return cfg; + } + else // Version incorrect + { + delete cfg; + cfg = 0; + } + } + + // Search for the template kicad.pro file by using caller's SEARCH_STACK. + + wxString kicad_pro_template = aSList.FindValidPath( wxT( "kicad.pro" ) ); + + if( !kicad_pro_template ) + { + wxLogDebug( wxT( "Template file not found." ) ); + + fn = wxFileName( wxStandardPaths::Get().GetDocumentsDir(), + wxT( "kicad" ), ProjectFileExtension ); + } + else + { + fn = kicad_pro_template; + } + + cfg = new wxFileConfig( wxEmptyString, wxEmptyString, wxEmptyString, fn.GetFullPath() ); + cfg->DontCreateOnDemand(); + + SetProjectFullName( fn.GetFullPath() ); + return cfg; +} + + +void PROJECT::ConfigSave( const SEARCH_STACK& aSList, const wxString& aFileName, + const wxString& aGroupName, const PARAM_CFG_ARRAY& aParams ) +{ + std::auto_ptr cfg( configCreate( aSList, aFileName, aGroupName, FORCE_LOCAL_CONFIG ) ); + + cfg->SetPath( wxCONFIG_PATH_SEPARATOR ); + + cfg->Write( wxT( "update" ), DateAndTime() ); + + // @todo: pass in aLastClient wxString: + cfg->Write( wxT( "last_client" ), Pgm().App().GetAppName() ); + + // Save parameters + cfg->DeleteGroup( aGroupName ); // Erase all data + cfg->Flush(); + + cfg->SetPath( aGroupName ); + cfg->Write( wxT( "version" ), CONFIG_VERSION ); + + cfg->SetPath( wxCONFIG_PATH_SEPARATOR ); + + wxConfigSaveParams( cfg.get(), aParams, aGroupName ); + + cfg->SetPath( UNIX_STRING_DIR_SEP ); + + // cfg is deleted here by std::auto_ptr, that saves the *.pro file to disk +} + + +bool PROJECT::ConfigLoad( const SEARCH_STACK& aSList, const wxString& aFileName, + const wxString& aGroupName, const PARAM_CFG_ARRAY& aParams, + bool doLoadOnlyIfNew ) +{ + std::auto_ptr cfg( configCreate( aSList, aFileName, aGroupName, false ) ); + + cfg->SetPath( wxCONFIG_PATH_SEPARATOR ); + + wxString timestamp = cfg->Read( wxT( "update" ) ); + + if( doLoadOnlyIfNew && timestamp.size() && + timestamp == m_pro_date_and_time ) + { + return false; + } + + m_pro_date_and_time = timestamp; + + wxConfigLoadParams( cfg.get(), aParams, aGroupName ); + + return true; +} + diff --git a/common/search_stack.cpp b/common/search_stack.cpp new file mode 100644 index 0000000000..f4792f89c2 --- /dev/null +++ b/common/search_stack.cpp @@ -0,0 +1,196 @@ + +#include +#include +#include + + +#if defined(__MINGW32__) + #define PATH_SEPS wxT(";\r\n") +#else + #define PATH_SEPS wxT(":;\r\n") // unix == linux | mac +#endif + + +wxString SEARCH_STACK::FilenameWithRelativePathInSearchList( const wxString& aFullFilename ) +{ + /* 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 + * Note we accept only sub paths, + * not relative paths starting by ../ that are not subpaths and are outside kicad libs paths + */ + wxFileName fn = aFullFilename; + wxString filename = aFullFilename; + + unsigned pathlen = fn.GetPath().Len(); // path len, used to find the better (shortest) + // subpath within defaults paths + + for( unsigned kk = 0; kk < GetCount(); kk++ ) + { + fn = aFullFilename; + + // Search for the shortest subpath within 'this': + if( fn.MakeRelativeTo( (*this)[kk] ) ) + { + if( fn.GetPathWithSep().StartsWith( wxT("..") ) ) // Path outside kicad libs paths + continue; + + if( pathlen > fn.GetPath().Len() ) // A better (shortest) subpath is found + { + filename = fn.GetPathWithSep() + fn.GetFullName(); + pathlen = fn.GetPath().Len(); + } + } + } + + return filename; +} + + +void SEARCH_STACK::RemovePaths( const wxString& aPaths ) +{ + wxStringTokenizer tokenizer( aPaths, PATH_SEPS, wxTOKEN_STRTOK ); + + while( tokenizer.HasMoreTokens() ) + { + wxString path = tokenizer.GetNextToken(); + + if( Index( path, wxFileName::IsCaseSensitive() ) != wxNOT_FOUND ) + { + Remove( path ); + } + } +} + + +void SEARCH_STACK::AddPaths( const wxString& aPaths, int aIndex ) +{ + bool isCS = wxFileName::IsCaseSensitive(); + wxStringTokenizer tokenizer( aPaths, PATH_SEPS, wxTOKEN_STRTOK ); + + // appending all of them, on large or negative aIndex + if( unsigned( aIndex ) >= GetCount() ) + { + while( tokenizer.HasMoreTokens() ) + { + wxString path = tokenizer.GetNextToken(); + + if( wxFileName::IsDirReadable( path ) + && Index( path, isCS ) == wxNOT_FOUND ) + { + Add( path ); + } + } + } + + // inserting all of them: + else + { + while( tokenizer.HasMoreTokens() ) + { + wxString path = tokenizer.GetNextToken(); + + if( wxFileName::IsDirReadable( path ) + && Index( path, isCS ) == wxNOT_FOUND ) + { + Insert( path, aIndex ); + aIndex++; + } + } + } +} + + +wxString SEARCH_STACK::FindFileInSearchPaths( + const wxString& aFilename, const wxArrayString* aSubdirs ) +{ + wxPathList paths; + + for( unsigned i = 0; i < GetCount(); ++i ) + { + wxFileName fn( (*this)[i] ); + + if( aSubdirs ) + { + for( unsigned j = 0; j < aSubdirs->GetCount(); j++ ) + fn.AppendDir( (*aSubdirs)[j] ); + } + + if( fn.DirExists() ) + { + paths.Add( fn.GetPath() ); + } + } + + return paths.FindValidPath( aFilename ); +} + + +void RETAINED_PATH::Clear() +{ + m_retained_path.Clear(); +} + + +wxString RETAINED_PATH::LastVisitedPath( const SEARCH_STACK& aSStack, const wxString& aSubPathToSearch ) +{ + if( !!m_retained_path ) + return m_retained_path; + + wxString path; + + // Initialize default path to the main default lib path + // this is the second path in list (the first is the project path) + unsigned pcount = aSStack.GetCount(); + + if( pcount ) + { + unsigned ipath = 0; + + if( aSStack[0] == wxGetCwd() ) + ipath = 1; + + // First choice of path: + if( ipath < pcount ) + path = aSStack[ipath]; + + // Search a sub path matching aSubPathToSearch + if( !aSubPathToSearch.IsEmpty() ) + { + for( ; ipath < pcount; ipath++ ) + { + if( aSStack[ipath].Contains( aSubPathToSearch ) ) + { + path = aSStack[ipath]; + break; + } + } + } + } + + if( path.IsEmpty() ) + path = wxGetCwd(); + + return path; +} + + +void RETAINED_PATH::SaveLastVisitedPath( const wxString& aPath ) +{ + m_retained_path = aPath; +} + + +#if defined(DEBUG) +void SEARCH_STACK::Show( const char* aPrefix ) const +{ + printf( "%s SEARCH_STACK:\n", aPrefix ); + for( unsigned i=0; i #include #include #include -#include #include +#include + +#include +#include +#include +#include -/** - * Class PROCESS - * provides its own OnInit() handler. - */ -class PROCESS : public wxApp -{ -public: - - bool OnInit(); -}; - - -IMPLEMENT_APP( PROCESS ) +// The functions we use will cause the program launcher to pull stuff in +// during linkage, keep the map file in mind to see what's going into it. #if !wxCHECK_VERSION( 3, 0, 0 ) @@ -107,41 +104,6 @@ static wxString wxJoin(const wxArrayString& arr, const wxChar sep, #endif -// POLICY CHOICE: return the full path of the DSO to load from single_top. -static const wxString dso_full_path( const wxString& aAbsoluteArgv0 ) -{ - // Prefix basename with '_' and change extension to DSO_EXT. - - // POLICY CHOICE: Keep same path, and therefore installer must put the major DSO - // in same dir as top process module. Obviously alternatives are possible - // and that is why this is a separate function. One alternative would be to use - // a portion of CMAKE_INSTALL_PREFIX and navigate to a "lib" dir, but that - // would require a recompile any time you chose to install into a different place. - - // It is my decision to treat _eeschema.so and _pcbnew.so as "executables", - // not "libraries" in this regard, since most all program functionality lives - // in them. They are basically spin-offs from what was once a top process module. - // That may not make linux package maintainers happy, but that is not my job. - // Get over it. KiCad is not a trivial suite, and multiple platforms come - // into play, not merely linux. If it freaks you out, we can use a different - // file extension than ".so", but they are not purely libraries, else they - // would begin with "lib" in basename. Like I said, get over it, we're serving - // too many masters here: python, windows, linux, OSX, multiple versions of wx... - - wxFileName fn( aAbsoluteArgv0 ); - wxString basename( KIFACE_PREFIX ); // start with special prefix - - basename += fn.GetName(); // add argv[0]'s basename - fn.SetName( basename ); - - // here a suffix == an extension with a preceding '.', - // so skip the preceding '.' to get an extension - fn.SetExt( KIFACE_SUFFIX + 1 ); // special extension, + 1 => &KIFACE_SUFFIX[1] - - return fn.GetFullPath(); -} - - /// Put aPriorityPath in front of all paths in the value of aEnvVar. const wxString PrePendPath( const wxString& aEnvVar, const wxString& aPriorityPath ) { @@ -157,13 +119,13 @@ const wxString PrePendPath( const wxString& aEnvVar, const wxString& aPriorityPa /// Extend LIB_ENV_VAR list with the directory from which I came, prepending it. void SetLibEnvVar( const wxString& aAbsoluteArgv0 ) { - // POLICY CHOICE: Keep same path, so that installer MAY put the - // "subsidiary shared libraries" in the same directory as the top process module. + // POLICY CHOICE 2: Keep same path, so that installer MAY put the + // "subsidiary DSOs" in the same directory as the kiway top process modules. // A subsidiary shared library is one that is not a top level DSO, but rather // some shared library that a top level DSO needs to even be loaded. It is // a static link to a shared object from a top level DSO. - // This directory POLICY CHOICE is not the only dir in play, since LIB_ENV_VAR + // This directory POLICY CHOICE 2 is not the only dir in play, since LIB_ENV_VAR // has numerous path options in it, as does DSO searching on linux, windows, and OSX. // See "man ldconfig" on linux. What's being done here is for quick installs // into a non-standard place, and especially for Windows users who may not @@ -186,28 +148,119 @@ void SetLibEnvVar( const wxString& aAbsoluteArgv0 ) #endif } +// POLICY CHOICE 1: return the full path of the DSO to load from single_top. +static const wxString dso_full_path( const wxString& aAbsoluteArgv0 ) +{ + // Prefix basename with ${KIFACE_PREFIX} and change extension to ${KIFACE_SUFFIX} -// Only a single KIWAY is supported in this single_top top level component, -// which is dedicated to loading only a single DSO. -static KIWAY standalone; + // POLICY CHOICE 1: Keep same path, and therefore installer must put the kiface DSO + // in same dir as top process module. Obviously alternatives are possible + // and that is why this is a separate function. One alternative would be to use + // a portion of CMAKE_INSTALL_PREFIX and navigate to a "lib" dir, but that + // would require a recompile any time you chose to install into a different place. + + // It is my decision to treat _eeschema.kiface and _pcbnew.kiface as "executables", + // not "libraries" in this regard, since most all program functionality lives + // in them. They are basically spin-offs from what was once a top process module. + // That may not make linux package maintainers happy, but that is not my job. + // Get over it. KiCad is not a trivial suite, and multiple platforms come + // into play, not merely linux. For starters they will use extension ".kicad", + // but later in time morph to ".so". They are not purely libraries, else they + // would begin with "lib" in basename. Like I said, get over it, we're serving + // too many masters here: python, windows, linux, OSX, multiple versions of wx... + + wxFileName fn( aAbsoluteArgv0 ); + wxString basename( KIFACE_PREFIX ); // start with special prefix + + basename += fn.GetName(); // add argv[0]'s basename + fn.SetName( basename ); + + // Here a "suffix" == an extension with a preceding '.', + // so skip the preceding '.' to get an extension + fn.SetExt( KIFACE_SUFFIX + 1 ); // + 1 => &KIFACE_SUFFIX[1] + + return fn.GetFullPath(); +} // Use of this is arbitrary, remember single_top only knows about a single DSO. // Could have used one from the KIWAY also. static wxDynamicLibrary dso; +// Only a single KIWAY is supported in this single_top top level component, +// which is dedicated to loading only a single DSO. +static KIWAY kiway; + + +// implement a PGM_BASE and a wxApp side by side: + +/** + * Struct PGM_SINGLE_TOP + * implements PGM_BASE with its own OnPgmInit() and OnPgmExit(). + */ +static struct PGM_SINGLE_TOP : public PGM_BASE +{ + bool OnPgmInit( wxApp* aWxApp ); // overload PGM_BASE virtual + void OnPgmExit(); // overload PGM_BASE virtual + void MacOpenFile( const wxString& aFileName ); // overload PGM_BASE virtual +} program; + + +PGM_BASE& Pgm() +{ + return program; +} + + +/** + * Struct APP_SINGLE_TOP + * implements a bare naked wxApp (so that we don't become dependent on + * functionality in a wxApp derivative that we cannot deliver under wxPython). + */ +struct APP_SINGLE_TOP : public wxApp +{ + bool OnInit() // overload wxApp virtual + { + return Pgm().OnPgmInit( this ); + } + + int OnExit() // overload wxApp virtual + { + Pgm().OnPgmExit(); + return wxApp::OnExit(); + } + + /** + * Function MacOpenFile + * is specific to MacOSX (not used under Linux or Windows). + * MacOSX requires it for file association. + * @see http://wiki.wxwidgets.org/WxMac-specific_topics + */ + void MacOpenFile( const wxString& aFileName ) // overload wxApp virtual + { + Pgm().MacOpenFile( aFileName ); + } +}; + +IMPLEMENT_APP( APP_SINGLE_TOP ); + + /** * Function get_kiface_getter - * returns a KIFACE_GETTER_FUNC for the current process's main implemation link image. + * returns a KIFACE_GETTER_FUNC for the current process's main implementation + * link image. * - * @param aDSOName is an absolute full path to the DSO to load and find KIFACE_GETTER_FUNC within. + * @param aDSOName is an absolute full path to the DSO to load and find + * KIFACE_GETTER_FUNC within. * - * @return KIFACE_GETTER_FUNC* - a pointer to a function which can be called to get the KIFACE - * or NULL if the getter func was not found. If not found, it is possibly not version compatible - * since the lookup is done by name and the name contains the API version. + * @return KIFACE_GETTER_FUNC* - a pointer to a function which can be called to + * get the KIFACE or NULL if the getter func was not found. If not found, + * it is possibly not version compatible since the lookup is done by name and + * the name contains the API version. */ static KIFACE_GETTER_FUNC* get_kiface_getter( const wxString& aDSOName ) { +#if defined(BUILD_KIWAY_DLL) void* addr = NULL; if( !dso.Load( aDSOName, wxDL_VERBATIM | wxDL_NOW ) ) @@ -223,6 +276,11 @@ static KIFACE_GETTER_FUNC* get_kiface_getter( const wxString& aDSOName ) } return (KIFACE_GETTER_FUNC*) addr; + +#else + return &KIFACE_GETTER; + +#endif } @@ -230,32 +288,13 @@ static KIFACE* kiface; static int kiface_version; -bool PROCESS::OnInit() + +bool PGM_SINGLE_TOP::OnPgmInit( wxApp* aWxApp ) { - // Choose to use argv command line processing in base class's OnInit(). - // That choice is not mandatory, see wx's appbase.cpp OnInit(). - if( !wxApp::OnInit() ) - return false; + // first thing: set m_wx_app + m_wx_app = aWxApp; - wxStandardPathsBase& paths = wxStandardPaths::Get(); - -#if defined(DEBUG) - wxString dir = paths.GetLocalizedResourcesDir( wxT( "de" ), - wxStandardPaths::ResourceCat_None ); - - printf( "LocalizeResourcesDir:'%s'\n", TO_UTF8( dir ) ); - - wxString dummy( _( "translate this" ) ); -#endif - - wxString absoluteArgv0 = paths.GetExecutablePath(); - -#if 0 && defined(DEBUG) - printf( "argv[0]:'%s' absoluteArgv0:'%s'\n", - TO_UTF8( wxString( argv[0] ) ), - TO_UTF8( absoluteArgv0 ) - ); -#endif + wxString absoluteArgv0 = wxStandardPaths::Get().GetExecutablePath(); if( !wxIsAbsolutePath( absoluteArgv0 ) ) { @@ -267,6 +306,9 @@ bool PROCESS::OnInit() // KIFACE has hard dependencies on subsidiary DSOs below it. SetLibEnvVar( absoluteArgv0 ); + if( !initPgm() ) + return false; + wxString dname = dso_full_path( absoluteArgv0 ); // Get the getter. @@ -279,24 +321,147 @@ bool PROCESS::OnInit() return false; } - // Get the KIFACE, and give the DSO a single chance to do its - // "process level" initialization. - kiface = getter( &kiface_version, KIFACE_VERSION, &wxGetApp() ); + // Get the KIFACE. + kiface = getter( &kiface_version, KIFACE_VERSION, this ); - // KIFACE_GETTER_FUNC function comment (API) says the non-NULL is uconditional. + // KIFACE_GETTER_FUNC function comment (API) says the non-NULL is unconditional. wxASSERT_MSG( kiface, wxT( "attempted DSO has a bug, failed to return a KIFACE*" ) ); - // Use KIFACE to create a window that the KIFACE knows about, - // pass classId=0 for now. KIFACE::CreateWindow() is a virtual - // so we don't need to link to it. - wxFrame* frame = (wxFrame*) kiface->CreateWindow( 0, &standalone ); + // Give the DSO a single chance to do its "process level" initialization. + // "Process level" specifically means stay away from any projects in there. + if( !kiface->OnKifaceStart( this ) ) + return false; - SetTopWindow( frame ); + // Use KIFACE to create a top window that the KIFACE knows about. + // TOP_FRAME is passed on compiler command line from CMake, and is one of + // the types in ID_DRAWFRAME_TYPE. + // KIFACE::CreateWindow() is a virtual so we don't need to link to it. + // Remember its in the *.kiface DSO. +#if 0 + // this pulls in EDA_DRAW_FRAME type info, which we don't want in single_top + KIWAY_PLAYER* frame = dynamic_cast( kiface->CreateWindow( + NULL, TOP_FRAME, &kiway, KFCTL_STANDALONE ) ); +#else + KIWAY_PLAYER* frame = (KIWAY_PLAYER*) kiface->CreateWindow( + NULL, TOP_FRAME, &kiway, KFCTL_STANDALONE ); +#endif - frame->Centre(); + App().SetTopWindow( frame ); // wxApp gets a face. + + // Open project or file specified on the command line: + int argc = App().argc; + + if( argc > 1 ) + { + /* + gerbview handles multiple project data files, i.e. gerber files on + cmd line. Others currently do not, they handle only one. For common + code simplicity we simply pass all the arguments in however, each + program module can do with them what they want, ignore, complain + whatever. We don't establish policy here, as this is a multi-purpose + launcher. + */ + + std::vector argSet; + + for( int i=1; iOpenProjectFiles( argSet ) ) + { + // OpenProjectFiles() API asks that it report failure to the UI. + // Nothing further to say here. + + // Fail the process startup if the file could not be opened, + // although this is an optional choice, one that can be reversed + // also in the KIFACE specific OpenProjectFiles() return value. + return false; + } + } + else + { + /* The lean single_top program launcher has no access program settings, + else it would not be lean. That kind of functionality is in the + KIFACE now, but it cannot assume that it is the only KIFACE in memory. + So this looks like a dead concept here, or an expensive one in terms + of code size. + + wxString dir; + + if( m_pgmSettings->Read( workingDirKey, &dir ) && wxDirExists( dir ) ) + { + wxSetWorkingDirectory( dir ); + } + */ + } frame->Show(); return true; } + +void PGM_SINGLE_TOP::OnPgmExit() +{ + if( kiface ) + kiface->OnKifaceEnd(); + + saveCommonSettings(); + + // write common settings to disk, and destroy everything in PGM_BASE, + // especially wxSingleInstanceCheckerImpl earlier than wxApp and earlier + // than static destruction would. + PGM_BASE::destroy(); +} + + +void PGM_SINGLE_TOP::MacOpenFile( const wxString& aFileName ) +{ + wxFileName filename( aFileName ); + + if( filename.FileExists() ) + { +#if 0 + // this pulls in EDA_DRAW_FRAME type info, which we don't want in single_top + // link image. + KIWAY_PLAYER* frame = dynamic_cast( App().GetTopWindow() ); +#else + KIWAY_PLAYER* frame = (KIWAY_PLAYER*) App().GetTopWindow(); +#endif + if( frame ) + frame->OpenProjectFiles( std::vector( 1, aFileName ) ); + } +} diff --git a/common/systemdirsappend.cpp b/common/systemdirsappend.cpp new file mode 100644 index 0000000000..0aefd88502 --- /dev/null +++ b/common/systemdirsappend.cpp @@ -0,0 +1,130 @@ + +#include + +#include +#include +#include + + +// put your best guesses in here, send the computer on a wild goose chase, its +// got nothing else to do. + +void SystemDirsAppend( SEARCH_STACK* aSearchStack ) +{ + // No clearing is done here, the most general approach is NOT to assume that + // our appends will be the only thing in the stack. This function has no + // knowledge of caller's intentions. + + // wxPathList::AddEnvList() is broken, use SEARCH_STACK::AddPaths(). + // SEARCH_STACK::AddPaths() will verify readability and existence of + // each directory before adding. + SEARCH_STACK maybe; + + // User environment variable path is the first search path. Chances are + // if the user is savvy enough to set an environment variable they know + // what they are doing. It should take precedence over anything else. + // Otherwise don't set it. + maybe.AddPaths( wxGetenv( wxT( "KICAD" ) ) ); + + // This is from CMAKE_INSTALL_PREFIX. + // Useful when KiCad is installed by `make install`. + // Use as second ranked place. + maybe.AddPaths( wxT( DEFAULT_INSTALL_PATH ) ); + + // Add the directory for the user-dependent, program specific, data files: + // Unix: ~/.appname + // Windows: C:\Documents and Settings\username\Application Data\appname + // Mac: ~/Library/Application Support/appname + maybe.AddPaths( wxStandardPaths::Get().GetUserDataDir() ); + + { + // Should be full path to this program executable. + wxString bin_dir = Pgm().GetExecutablePath(); + +#if defined(__MINGW32__) + // bin_dir uses unix path separator. So to parse with wxFileName + // use windows separator, especially important for server inclusion: + // like: \\myserver\local_path . + bin_dir.Replace( wxFileName::GetPathSeparator( wxPATH_UNIX ), + wxFileName::GetPathSeparator( wxPATH_WIN ) ); +#endif + + wxFileName bin_fn( bin_dir, wxEmptyString ); + + // Dir of the global (not user-specific), application specific, data files. + // From wx docs: + // Unix: prefix/share/appname + // Windows: the directory where the executable file is located + // Mac: appname.app/Contents/SharedSupport bundle subdirectory + wxString data_dir = wxStandardPaths::Get().GetDataDir(); + + if( bin_fn.GetPath() != data_dir ) + { + // add data_dir if it is different from the bin_dir + maybe.AddPaths( data_dir ); + } + + // Up one level relative to binary path with "share" appended below. + bin_fn.RemoveLastDir(); + maybe.AddPaths( bin_fn.GetPath() ); + } + + /* The normal OS program file install paths allow for a binary to be + * installed in a different path from the library files. This is + * useful for development purposes so the library and documentation + * files do not need to be installed separately. If someone can + * figure out a way to implement this without #ifdef, please do. + */ +#if defined(__MINGW32__) + maybe.AddPaths( wxGetenv( wxT( "PROGRAMFILES" ) ) ); +#elif __WXMAC__ + maybe.AddPaths( wxString( wxGetenv( wxT( "HOME" ) ) ) + wxT( "/Library/Application Support" ) ); + maybe.AddPaths( wxT( "/Library/Application Support" ) ); +#else + maybe.AddPaths( wxGetenv( wxT( "PATH" ) ) ); +#endif + +#if defined(DEBUG) && 0 + maybe.Show( "maybe wish list" ); +#endif + + // Append 1) kicad, 2) kicad/share, 3) share, and 4) share/kicad to each + // possible base path in 'maybe'. Since SEARCH_STACK::AddPaths() will verify + // readability and existence of each directory, not all of these will be + // actually appended. + for( unsigned i = 0; i < maybe.GetCount(); ++i ) + { + wxFileName fn( maybe[i], wxEmptyString ); + + if( fn.GetPath().AfterLast( fn.GetPathSeparator() ) == wxT( "bin" ) ) + { + fn.RemoveLastDir(); + + if( !fn.GetDirCount() ) + continue; // at least on linux + } + + aSearchStack->AddPaths( fn.GetPath() ); + + fn.AppendDir( wxT( "kicad" ) ); + aSearchStack->AddPaths( fn.GetPath() ); // add maybe[i]/kicad + + fn.AppendDir( wxT( "share" ) ); + aSearchStack->AddPaths( fn.GetPath() ); // add maybe[i]/kicad/share + + fn.RemoveLastDir(); // ../ clear share + fn.RemoveLastDir(); // ../ clear kicad + + fn.AppendDir( wxT( "share" ) ); + aSearchStack->AddPaths( fn.GetPath() ); // add maybe[i]/share + + fn.AppendDir( wxT( "kicad" ) ); + aSearchStack->AddPaths( fn.GetPath() ); // add maybe[i]/share/kicad + } + +#if defined(DEBUG) && 0 + // final results: + aSearchStack->Show( __func__ ); +#endif +} + diff --git a/common/wildcards_and_files_ext.cpp b/common/wildcards_and_files_ext.cpp index 0457830d40..e6a223c708 100644 --- a/common/wildcards_and_files_ext.cpp +++ b/common/wildcards_and_files_ext.cpp @@ -42,7 +42,7 @@ const wxString ProjectFileExtension( wxT( "pro" ) ); const wxString SchematicFileExtension( wxT( "sch" ) ); const wxString NetlistFileExtension( wxT( "net" ) ); const wxString ComponentFileExtension( wxT( "cmp" ) ); -const wxString GerberFileExtension( wxT( "pho" ) ); +const wxString GerberFileExtension( wxT( ".((gbr|(gb|gt)[alops])|pho)" ) ); const wxString LegacyPcbFileExtension( wxT( "brd" ) ); const wxString KiCadPcbFileExtension( wxT( "kicad_pcb" ) ); diff --git a/common/worksheet.cpp b/common/worksheet.cpp index db15b8b1db..215b2dd4b7 100644 --- a/common/worksheet.cpp +++ b/common/worksheet.cpp @@ -31,13 +31,13 @@ #include -#include +#include #include #include #include #include #include -#include +#include #include #include #include @@ -170,7 +170,7 @@ wxString WS_DRAW_ITEM_LIST::BuildFullText( const wxString& aTextbase ) break; case 'K': - msg += productName + wxGetApp().GetAppName(); + msg += productName + Pgm().App().GetAppName(); msg += wxT( " " ) + GetBuildVersion(); break; diff --git a/common/wxwineda.cpp b/common/wxwineda.cpp index f68fe9a19c..8ff4c2c3d3 100644 --- a/common/wxwineda.cpp +++ b/common/wxwineda.cpp @@ -90,7 +90,7 @@ wxString EDA_GRAPHIC_TEXT_CTRL::FormatSize( EDA_UNITS_T aUnit, int textSize ) if( textSize > 3000 ) textSize = 3000; - return ReturnStringFromValue( aUnit, textSize ); + return StringFromValue( aUnit, textSize ); } @@ -124,7 +124,7 @@ int EDA_GRAPHIC_TEXT_CTRL::ParseSize( const wxString& sizeText, EDA_UNITS_T aUni { int textsize; - textsize = ReturnValueFromString( aUnit, sizeText ); + textsize = ValueFromString( aUnit, sizeText ); // Limit to reasonable size if( textsize < 10 ) @@ -209,8 +209,8 @@ wxPoint EDA_POSITION_CTRL::GetValue() { wxPoint coord; - coord.x = ReturnValueFromString( m_UserUnit, m_FramePosX->GetValue() ); - coord.y = ReturnValueFromString( m_UserUnit, m_FramePosY->GetValue() ); + coord.x = ValueFromString( m_UserUnit, m_FramePosX->GetValue() ); + coord.y = ValueFromString( m_UserUnit, m_FramePosY->GetValue() ); return coord; } @@ -230,11 +230,11 @@ void EDA_POSITION_CTRL::SetValue( int x_value, int y_value ) m_Pos_To_Edit.x = x_value; m_Pos_To_Edit.y = y_value; - msg = ReturnStringFromValue( m_UserUnit, m_Pos_To_Edit.x ); + msg = StringFromValue( m_UserUnit, m_Pos_To_Edit.x ); m_FramePosX->Clear(); m_FramePosX->SetValue( msg ); - msg = ReturnStringFromValue( m_UserUnit, m_Pos_To_Edit.y ); + msg = StringFromValue( m_UserUnit, m_Pos_To_Edit.y ); m_FramePosY->Clear(); m_FramePosY->SetValue( msg ); } @@ -279,7 +279,7 @@ EDA_VALUE_CTRL::EDA_VALUE_CTRL( wxWindow* parent, const wxString& title, BoxSizer->Add( m_Text, 0, wxGROW | wxLEFT | wxRIGHT | wxTOP, 5 ); - wxString stringvalue = ReturnStringFromValue( m_UserUnit, m_Value ); + wxString stringvalue = StringFromValue( m_UserUnit, m_Value ); m_ValueCtrl = new wxTextCtrl( parent, -1, stringvalue ); BoxSizer->Add( m_ValueCtrl, @@ -301,7 +301,7 @@ int EDA_VALUE_CTRL::GetValue() int coord; wxString txtvalue = m_ValueCtrl->GetValue(); - coord = ReturnValueFromString( m_UserUnit, txtvalue ); + coord = ValueFromString( m_UserUnit, txtvalue ); return coord; } @@ -312,7 +312,7 @@ void EDA_VALUE_CTRL::SetValue( int new_value ) m_Value = new_value; - buffer = ReturnStringFromValue( m_UserUnit, m_Value ); + buffer = StringFromValue( m_UserUnit, m_Value ); m_ValueCtrl->SetValue( buffer ); } diff --git a/common/zoom.cpp b/common/zoom.cpp index b85cc0cc2a..b942a33f25 100644 --- a/common/zoom.cpp +++ b/common/zoom.cpp @@ -37,7 +37,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/cvpcb/CMakeLists.txt b/cvpcb/CMakeLists.txt index 53f39ada5e..47a5c3c111 100644 --- a/cvpcb/CMakeLists.txt +++ b/cvpcb/CMakeLists.txt @@ -1,8 +1,7 @@ -add_definitions( -DCVPCB ) -### -# Includes -### +set( MAKE_LINK_MAPS true ) + +add_definitions( -DCVPCB ) include_directories( BEFORE ${INC_BEFORE} ) include_directories( @@ -15,12 +14,13 @@ include_directories( ${INC_AFTER} ) -### -# Sources -### + set( CVPCB_DIALOGS - dialogs/dialog_cvpcb_config.cpp - dialogs/dialog_cvpcb_config_fbp.cpp + + # These 2 still use search paths, which don't exist in footprint land. +# dialogs/dialog_cvpcb_config.cpp +# dialogs/dialog_cvpcb_config_fbp.cpp + dialogs/dialog_display_options.cpp dialogs/dialog_display_options_base.cpp ../pcbnew/dialogs/dialog_fp_lib_table.cpp @@ -40,101 +40,198 @@ set( CVPCB_SRCS class_footprints_listbox.cpp class_library_listbox.cpp cvframe.cpp - cvpcb.cpp listboxes.cpp menubar.cpp readwrite_dlgs.cpp tool_cvpcb.cpp ) -### -# Windows resource file -### -if( WIN32 ) - if( MINGW ) - # CVPCB_RESOURCES variable is set by the macro. - mingw_resource_compiler( cvpcb ) - else() - set( CVPCB_RESOURCES cvpcb.rc ) - endif() + +if( MINGW ) + # CVPCB_RESOURCES variable is set by the macro. + mingw_resource_compiler( cvpcb ) endif() -### -# Apple resource files -### + if( APPLE ) set( CVPCB_RESOURCES cvpcb.icns cvpcb_doc.icns ) - set_source_files_properties( "${CMAKE_CURRENT_SOURCE_DIR}/cvpcb.icns" - PROPERTIES MACOSX_PACKAGE_LOCATION Resources ) + set_source_files_properties( "${CMAKE_CURRENT_SOURCE_DIR}/cvpcb.icns" PROPERTIES + MACOSX_PACKAGE_LOCATION Resources + ) - set_source_files_properties( "${CMAKE_CURRENT_SOURCE_DIR}/cvpcb_doc.icns" - PROPERTIES MACOSX_PACKAGE_LOCATION Resources ) + set_source_files_properties( "${CMAKE_CURRENT_SOURCE_DIR}/cvpcb_doc.icns" PROPERTIES + MACOSX_PACKAGE_LOCATION Resources + ) set( MACOSX_BUNDLE_ICON_FILE cvpcb.icns ) set( MACOSX_BUNDLE_GUI_IDENTIFIER org.kicad-eda.cvpcb ) endif() -### -# Create the cvpcb executable -### -add_executable( cvpcb WIN32 MACOSX_BUNDLE - ${CVPCB_SRCS} - ${CVPCB_DIALOGS} - ${CVPCB_RESOURCES} - ) -### -# Set properties for APPLE on cvpcb target -### -if( APPLE ) - set_target_properties( cvpcb PROPERTIES MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/Info.plist ) +if( USE_KIWAY_DLLS ) + add_executable( cvpcb WIN32 MACOSX_BUNDLE + ../common/single_top.cpp + ../common/pgm_base.cpp + ${CVPCB_RESOURCES} + ) + set_source_files_properties( ../common/single_top.cpp PROPERTIES + COMPILE_DEFINITIONS "TOP_FRAME=CVPCB_FRAME_TYPE;PGM_DATA_FILE_EXT=\"net\";BUILD_KIWAY_DLL" + ) + target_link_libraries( cvpcb + #singletop # replaces common, giving us restrictive control and link warnings. + # There's way too much crap coming in from common yet. + common + bitmaps + ${wxWidgets_LIBRARIES} + ) + if( MAKE_LINK_MAPS ) + set_target_properties( cvpcb PROPERTIES + LINK_FLAGS "${TO_LINKER},-cref ${TO_LINKER},-Map=cvpcb.map" ) + endif() + + # the main cvpcb program, in DSO form. + add_library( cvpcb_kiface MODULE + cvpcb.cpp + ${CVPCB_SRCS} + ${CVPCB_DIALOGS} +# ${CVPCB_RESOURCES} + ) + set_target_properties( cvpcb_kiface PROPERTIES + OUTPUT_NAME cvpcb + PREFIX ${KIFACE_PREFIX} + SUFFIX ${KIFACE_SUFFIX} + ) + target_link_libraries( cvpcb_kiface + 3d-viewer + pcbcommon + pcad2kicadpcb + common + bitmaps + polygon + gal + ${wxWidgets_LIBRARIES} + ${OPENGL_LIBRARIES} + ${GDI_PLUS_LIBRARIES} + ${GLEW_LIBRARIES} + ${CAIRO_LIBRARIES} + ${PIXMAN_LIBRARY} + ${OPENMP_LIBRARIES} + ) + + # Only for win32 cross compilation using MXE + if( WIN32 AND MSYS AND CMAKE_CROSSCOMPILING ) + target_link_libraries( cvpcb_kiface + opengl32 + glu32 + pixman-1 + fontconfig + freetype + bz2 + ) + endif() + + if( BUILD_GITHUB_PLUGIN ) + target_link_libraries( cvpcb_kiface github_plugin ) + endif() + + # Must follow github_plugin + target_link_libraries( cvpcb_kiface ${Boost_LIBRARIES} ) + + if( UNIX AND NOT APPLE ) + # -lrt must follow Boost + target_link_libraries( cvpcb_kiface rt ) + endif() + + if( APPLE ) + set_target_properties( cvpcb PROPERTIES + MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/Info.plist + ) + endif() + + set_source_files_properties( cvpcb.cpp PROPERTIES + # The KIFACE is in cvpcb.cpp, export it: + COMPILE_DEFINITIONS "BUILD_KIWAY_DLL;COMPILING_DLL" + ) + + if( MAKE_LINK_MAPS ) + set_target_properties( cvpcb_kiface PROPERTIES + LINK_FLAGS "${TO_LINKER},-cref ${TO_LINKER},-Map=_cvpcb.kiface.map" ) + endif() + + # if building cvpcb, then also build cvpcb_kiface if out of date. + add_dependencies( cvpcb cvpcb_kiface ) + + # these 2 binaries are a matched set, keep them together: + install( TARGETS cvpcb + DESTINATION ${KICAD_BIN} + COMPONENT binary + ) + install( TARGETS cvpcb_kiface + DESTINATION ${KICAD_BIN} + COMPONENT binary + ) + + if( APPLE ) + # copies kiface into the bundle + add_custom_target( _cvpcb_kiface_copy ALL + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/cvpcb/_cvpcb.kiface "${CMAKE_BINARY_DIR}/cvpcb/cvpcb.app/Contents/MacOS/" + DEPENDS cvpcb_kiface + COMMENT "Copying kiface into cvpcb" + ) + endif() + +else() + + add_executable( cvpcb WIN32 MACOSX_BUNDLE + ${CVPCB_SRCS} + ${CVPCB_DIALOGS} + ${CVPCB_RESOURCES} + ) + target_link_libraries( cvpcb + 3d-viewer + pcbcommon + pcad2kicadpcb + common + bitmaps + polygon + gal + ${wxWidgets_LIBRARIES} + ${OPENGL_LIBRARIES} + ${GDI_PLUS_LIBRARIES} + ${GLEW_LIBRARIES} + ${CAIRO_LIBRARIES} + ${PIXMAN_LIBRARY} + ) + + # Only for win32 cross compilation using MXE + if( WIN32 AND MSYS AND CMAKE_CROSSCOMPILING ) + target_link_libraries( cvpcb + opengl32 + glu32 + pixman-1 + fontconfig + freetype + bz2 + ) + endif() + + if( BUILD_GITHUB_PLUGIN ) + target_link_libraries( cvpcb github_plugin ) + endif() + + # Must follow github_plugin + target_link_libraries( cvpcb ${Boost_LIBRARIES} ) + + if( APPLE ) + set_target_properties( cvpcb PROPERTIES + MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/Info.plist + ) + endif() + + install( TARGETS cvpcb + DESTINATION ${KICAD_BIN} + COMPONENT binary + ) + endif() - -### -# Link executable target cvpcb with correct libraries -### -target_link_libraries( cvpcb - 3d-viewer - pcbcommon - pcad2kicadpcb - common - bitmaps - polygon - gal - ${wxWidgets_LIBRARIES} - ${OPENGL_LIBRARIES} - ${GDI_PLUS_LIBRARIES} - ${GLEW_LIBRARIES} - ${CAIRO_LIBRARIES} - ${PIXMAN_LIBRARY} - ) - -# Only for win32 cross compilation using MXE -if( WIN32 AND MSYS AND CMAKE_CROSSCOMPILING ) -target_link_libraries(cvpcb - opengl32 - glu32 - pixman-1 - fontconfig - freetype - bz2 - ) -endif() - - -if( BUILD_GITHUB_PLUGIN ) - target_link_libraries( cvpcb github_plugin ) -endif() - -# Must follow github_plugin -target_link_libraries( cvpcb ${Boost_LIBRARIES} ) - - -### -# Add cvpcb as install target -### -install( TARGETS cvpcb - DESTINATION ${KICAD_BIN} - COMPONENT binary - ) diff --git a/cvpcb/autosel.cpp b/cvpcb/autosel.cpp index f9252eddbd..2b40fa4e40 100644 --- a/cvpcb/autosel.cpp +++ b/cvpcb/autosel.cpp @@ -29,9 +29,10 @@ #include #include +#include #include #include -#include +#include #include #include @@ -87,6 +88,7 @@ void CVPCB_MAINFRAME::AssocieModule( wxCommandEvent& event ) char Line[1024]; FILE* file; size_t ii; + SEARCH_STACK& search = Prj().SchSearchS(); if( m_netlist.IsEmpty() ) return; @@ -99,17 +101,17 @@ void CVPCB_MAINFRAME::AssocieModule( wxCommandEvent& event ) if( !fn.HasExt() ) { fn.SetExt( FootprintAliasFileExtension ); - // above fails if filename have more than one point + // above fails if filename has more than one point } else { fn.SetExt( fn.GetExt() + wxT( "." ) + FootprintAliasFileExtension ); } - tmp = wxGetApp().FindLibraryPath( fn ); + tmp = search.FindValidPath( fn ); if( !tmp ) { - msg.Printf( _( "Footprint alias library file <%s> could not be found in the " + msg.Printf( _( "Footprint alias library file '%s' could not be found in the " "default search paths." ), GetChars( fn.GetFullName() ) ); wxMessageBox( msg, titleLibLoadError, wxOK | wxICON_ERROR ); diff --git a/cvpcb/cfg.cpp b/cvpcb/cfg.cpp index 6823daa777..c7b5986362 100644 --- a/cvpcb/cfg.cpp +++ b/cvpcb/cfg.cpp @@ -27,11 +27,12 @@ */ #include -#include +#include +#include #include #include #include -#include +#include #include #include #include @@ -46,24 +47,24 @@ #define GROUPEQU wxT("/cvpcb/libraries") -PARAM_CFG_ARRAY& CVPCB_MAINFRAME::GetProjectFileParameters( void ) +PARAM_CFG_ARRAY& CVPCB_MAINFRAME::GetProjectFileParameters() { if( !m_projectFileParams.empty() ) return m_projectFileParams; - m_projectFileParams.push_back( new PARAM_CFG_BASE( GROUPLIB, - PARAM_COMMAND_ERASE ) ); - m_projectFileParams.push_back( new PARAM_CFG_LIBNAME_LIST( wxT( "LibName" ), - &m_ModuleLibNames, - GROUPLIB ) ); - m_projectFileParams.push_back( new PARAM_CFG_LIBNAME_LIST( wxT( "EquName" ), - &m_AliasLibNames, - GROUPEQU ) ); - m_projectFileParams.push_back( new PARAM_CFG_WXSTRING( wxT( "NetIExt" ), - &m_NetlistFileExtension ) ); - m_projectFileParams.push_back( new PARAM_CFG_FILENAME( wxT( "LibDir" ), - &m_UserLibraryPath, - GROUPLIB ) ); + m_projectFileParams.push_back( new PARAM_CFG_BASE( GROUPLIB, PARAM_COMMAND_ERASE ) ); + + m_projectFileParams.push_back( new PARAM_CFG_LIBNAME_LIST( + wxT( "LibName" ), &m_ModuleLibNames, GROUPLIB ) ); + + m_projectFileParams.push_back( new PARAM_CFG_LIBNAME_LIST( + wxT( "EquName" ), &m_AliasLibNames, GROUPEQU ) ); + + m_projectFileParams.push_back( new PARAM_CFG_WXSTRING( + wxT( "NetIExt" ), &m_NetlistFileExtension ) ); + + m_projectFileParams.push_back( new PARAM_CFG_FILENAME( + wxT( "LibDir" ), &m_UserLibraryPath, GROUPLIB ) ); return m_projectFileParams; } @@ -71,42 +72,34 @@ PARAM_CFG_ARRAY& CVPCB_MAINFRAME::GetProjectFileParameters( void ) void CVPCB_MAINFRAME::LoadProjectFile( const wxString& aFileName ) { - wxFileName fn = aFileName; + wxFileName fn( aFileName ); + PROJECT& prj = Prj(); m_ModuleLibNames.Clear(); m_AliasLibNames.Clear(); - if( fn.GetExt() != ProjectFileExtension ) - fn.SetExt( ProjectFileExtension ); + fn.SetExt( ProjectFileExtension ); - wxGetApp().RemoveLibraryPath( m_UserLibraryPath ); - - wxGetApp().ReadProjectConfig( fn.GetFullPath(), GROUP, GetProjectFileParameters(), false ); + // was: Pgm().ReadProjectConfig( fn.GetFullPath(), GROUP, GetProjectFileParameters(), false ); + prj.ConfigLoad( prj.PcbSearchS(), fn.GetFullPath(), GROUP, GetProjectFileParameters(), false ); if( m_NetlistFileExtension.IsEmpty() ) m_NetlistFileExtension = wxT( "net" ); - // User library path takes precedent over default library search paths. - wxGetApp().InsertLibraryPath( m_UserLibraryPath, 1 ); + // empty the table, Load() it again below. + FootprintLibs()->Clear(); - delete m_footprintLibTable; + /* this is done by ConfigLoad(), and that sets the env var too. + prj.SetProjectFullName( fn.GetFullPath() ); + */ - // Attempt to load the project footprint library table if it exists. - m_footprintLibTable = new FP_LIB_TABLE(); - - if( m_DisplayFootprintFrame ) - m_DisplayFootprintFrame->SetFootprintLibTable( m_footprintLibTable ); - - wxFileName projectFpLibTableFileName; - - projectFpLibTableFileName = FP_LIB_TABLE::GetProjectFileName( fn ); - FP_LIB_TABLE::SetProjectPathEnvVariable( projectFpLibTableFileName ); + wxString projectFpLibTableFileName = prj.FootprintLibTblName(); try { - m_footprintLibTable->Load( projectFpLibTableFileName, m_globalFootprintTable ); + FootprintLibs()->Load( projectFpLibTableFileName ); } - catch( IO_ERROR ioe ) + catch( const IO_ERROR& ioe ) { DisplayError( this, ioe.errorText ); } @@ -136,5 +129,11 @@ void CVPCB_MAINFRAME::SaveProjectFile( wxCommandEvent& aEvent ) if( !IsWritable( fn ) ) return; - wxGetApp().WriteProjectConfig( fn.GetFullPath(), GROUP, GetProjectFileParameters() ); + // was: + // Pgm().WriteProjectConfig( fn.GetFullPath(), GROUP, GetProjectFileParameters() ); + + PROJECT& prj = Prj(); + SEARCH_STACK& search = prj.SchSearchS(); + + prj.ConfigSave( search, fn.GetFullPath(), GROUP, GetProjectFileParameters() ); } diff --git a/cvpcb/class_DisplayFootprintsFrame.cpp b/cvpcb/class_DisplayFootprintsFrame.cpp index 4c0b4e266a..f320465c8b 100644 --- a/cvpcb/class_DisplayFootprintsFrame.cpp +++ b/cvpcb/class_DisplayFootprintsFrame.cpp @@ -28,7 +28,7 @@ */ #include -#include +#include #include #include #include @@ -70,28 +70,25 @@ BEGIN_EVENT_TABLE( DISPLAY_FOOTPRINTS_FRAME, PCB_BASE_FRAME ) DISPLAY_FOOTPRINTS_FRAME::OnUpdateLineDrawMode ) END_EVENT_TABLE() -#define DISPLAY_FOOTPRINTS_FRAME_NAME wxT( "CmpFrame" ) - -DISPLAY_FOOTPRINTS_FRAME::DISPLAY_FOOTPRINTS_FRAME( CVPCB_MAINFRAME* parent, - const wxString& title, - const wxPoint& pos, - const wxSize& size, long style ) : - PCB_BASE_FRAME( parent, CVPCB_DISPLAY_FRAME_TYPE, title, pos, size, - style, DISPLAY_FOOTPRINTS_FRAME_NAME ) +DISPLAY_FOOTPRINTS_FRAME::DISPLAY_FOOTPRINTS_FRAME( KIWAY* aKiway, CVPCB_MAINFRAME* aParent ) : + PCB_BASE_FRAME( aKiway, aParent, CVPCB_DISPLAY_FRAME_TYPE, _( "Footprint Viewer" ), + wxDefaultPosition, wxDefaultSize, + KICAD_DEFAULT_DRAWFRAME_STYLE, FOOTPRINTVIEWER_FRAME_NAME ) { - m_FrameName = DISPLAY_FOOTPRINTS_FRAME_NAME; + m_FrameName = FOOTPRINTVIEWER_FRAME_NAME; m_showAxis = true; // true to draw axis. // Give an icon wxIcon icon; + icon.CopyFromBitmap( KiBitmap( icon_cvpcb_xpm ) ); SetIcon( icon ); SetBoard( new BOARD() ); SetScreen( new PCB_SCREEN( GetPageSizeIU() ) ); - LoadSettings(); + LoadSettings( config() ); // Initialize grid id to a default value if not found in config or bad: if( (m_LastGridSizeId <= 0) || @@ -148,8 +145,6 @@ DISPLAY_FOOTPRINTS_FRAME::~DISPLAY_FOOTPRINTS_FRAME() { delete GetScreen(); SetScreen( NULL ); // Be sure there is no double deletion - - ( (CVPCB_MAINFRAME*) wxGetApp().GetTopWindow() )->m_DisplayFootprintFrame = NULL; } @@ -438,7 +433,7 @@ void DISPLAY_FOOTPRINTS_FRAME::Show3D_Frame( wxCommandEvent& event ) return; } - m_Draw3DFrame = new EDA_3D_FRAME( this, _( "3D Viewer" ), KICAD_DEFAULT_3D_DRAWFRAME_STYLE ); + m_Draw3DFrame = new EDA_3D_FRAME( &Kiway(), this, _( "3D Viewer" ), KICAD_DEFAULT_3D_DRAWFRAME_STYLE ); m_Draw3DFrame->Show( true ); } @@ -493,7 +488,7 @@ MODULE* DISPLAY_FOOTPRINTS_FRAME::Get_Module( const wxString& aFootprintName ) wxLogDebug( wxT( "Load footprint <%s> from library <%s>." ), fpname.c_str(), nickname.c_str() ); - footprint = m_footprintLibTable->FootprintLoad( FROM_UTF8( nickname.c_str() ), FROM_UTF8( fpname.c_str() ) ); + footprint = FootprintLibs()->FootprintLoad( FROM_UTF8( nickname.c_str() ), FROM_UTF8( fpname.c_str() ) ); } catch( IO_ERROR ioe ) { diff --git a/cvpcb/class_DisplayFootprintsFrame.h b/cvpcb/class_DisplayFootprintsFrame.h index 3244d62325..b26f372565 100644 --- a/cvpcb/class_DisplayFootprintsFrame.h +++ b/cvpcb/class_DisplayFootprintsFrame.h @@ -29,6 +29,8 @@ #include +// The name (for wxWidgets) of the footprint viewer frame +#define FOOTPRINTVIEWER_FRAME_NAME wxT( "FootprintViewerFrame" ) class CVPCB_MAINFRAME; @@ -40,10 +42,7 @@ class CVPCB_MAINFRAME; class DISPLAY_FOOTPRINTS_FRAME : public PCB_BASE_FRAME { public: - DISPLAY_FOOTPRINTS_FRAME( CVPCB_MAINFRAME* father, const wxString& title, - const wxPoint& pos, const wxSize& size, - long style = KICAD_DEFAULT_DRAWFRAME_STYLE ); - + DISPLAY_FOOTPRINTS_FRAME( KIWAY* aKiway, CVPCB_MAINFRAME* aParent ); ~DISPLAY_FOOTPRINTS_FRAME(); void OnCloseWindow( wxCloseEvent& Event ); diff --git a/cvpcb/class_footprints_listbox.cpp b/cvpcb/class_footprints_listbox.cpp index fe3b38e572..d09cee580b 100644 --- a/cvpcb/class_footprints_listbox.cpp +++ b/cvpcb/class_footprints_listbox.cpp @@ -30,7 +30,7 @@ #include #include #include -#include +#include #include #include @@ -207,7 +207,7 @@ void FOOTPRINTS_LISTBOX::OnLeftClick( wxListEvent& event ) return; // If the footprint view window is displayed, update the footprint. - if( GetParent()->m_DisplayFootprintFrame ) + if( GetParent()->GetFpViewerFrame() ) GetParent()->CreateScreenCmp(); GetParent()->DisplayStatus(); diff --git a/cvpcb/cvframe.cpp b/cvpcb/cvframe.cpp index 36fb9c123a..256e12c641 100644 --- a/cvpcb/cvframe.cpp +++ b/cvpcb/cvframe.cpp @@ -29,7 +29,8 @@ #include #include -#include +#include +#include #include #include #include @@ -104,24 +105,22 @@ END_EVENT_TABLE() #define CVPCB_MAINFRAME_NAME wxT( "CvpcbFrame" ) -CVPCB_MAINFRAME::CVPCB_MAINFRAME( const wxString& title, long style ) : - EDA_BASE_FRAME( NULL, CVPCB_FRAME_TYPE, title, wxDefaultPosition, - wxDefaultSize, style, CVPCB_MAINFRAME_NAME ) + +CVPCB_MAINFRAME::CVPCB_MAINFRAME( KIWAY* aKiway, wxWindow* aParent ) : + KIWAY_PLAYER( aKiway, aParent, CVPCB_FRAME_TYPE, wxT( "CvPCB" ), wxDefaultPosition, + wxDefaultSize, KICAD_DEFAULT_DRAWFRAME_STYLE, CVPCB_MAINFRAME_NAME ) { m_FrameName = CVPCB_MAINFRAME_NAME; m_ListCmp = NULL; m_FootprintList = NULL; m_LibraryList = NULL; - m_DisplayFootprintFrame = NULL; m_mainToolBar = NULL; m_modified = false; m_isEESchemaNetlist = false; m_KeepCvpcbOpen = false; m_undefinedComponentCnt = 0; m_skipComponentSelect = false; - - m_globalFootprintTable = NULL; - m_footprintLibTable = NULL; + m_NetlistFileExtension = wxT( "net" ); /* Name of the document footprint list * usually located in share/modules/footprints_doc @@ -137,7 +136,7 @@ CVPCB_MAINFRAME::CVPCB_MAINFRAME( const wxString& title, long style ) : SetAutoLayout( true ); - LoadSettings(); + LoadSettings( config() ); if( m_FrameSize.x < FRAME_MIN_SIZE_X ) m_FrameSize.x = FRAME_MIN_SIZE_X; @@ -194,36 +193,6 @@ CVPCB_MAINFRAME::CVPCB_MAINFRAME( const wxString& title, long style ) : Right().BestSize( (int) ( m_FrameSize.x * 0.30 ), m_FrameSize.y ) ); m_auimgr.Update(); - - if( m_globalFootprintTable == NULL ) - { - try - { - m_globalFootprintTable = new FP_LIB_TABLE(); - - if( !FP_LIB_TABLE::LoadGlobalTable( *m_globalFootprintTable ) ) - { - DisplayInfoMessage( this, wxT( "You have run CvPcb for the first time using the " - "new footprint library table method of finding " - "footprints. CvPcb has either copied the default " - "table or created an empty table in your home " - "folder. You must first configure the library " - "table to include all footprint libraries not " - "included with KiCad. See the \"Footprint Library " - "Table\" section of the CvPcb documentation for " - "more information." ) ); - } - } - catch( IO_ERROR ioe ) - { - wxString msg; - msg.Printf( _( "An error occurred attempting to load the global footprint library " - "table:\n\n%s" ), GetChars( ioe.errorText ) ); - DisplayError( this, msg ); - } - - m_footprintLibTable = new FP_LIB_TABLE( m_globalFootprintTable ); - } } @@ -233,28 +202,40 @@ CVPCB_MAINFRAME::~CVPCB_MAINFRAME() } -void CVPCB_MAINFRAME::LoadSettings() +FP_LIB_TABLE* CVPCB_MAINFRAME::FootprintLibs() const { - wxASSERT( wxGetApp().GetSettings() != NULL ); + PROJECT& prj = Prj(); + FP_LIB_TABLE* tbl = dynamic_cast( prj.Elem( PROJECT::FPTBL ) ); - wxConfig* cfg = wxGetApp().GetSettings(); + if( !tbl ) + { + // Stack the project specific FP_LIB_TABLE overlay on top of the global table. + // ~FP_LIB_TABLE() will not touch the fallback table, so multiple projects may + // stack this way, all using the same global fallback table. + tbl = new FP_LIB_TABLE( &GFootprintTable ); + prj.Elem( PROJECT::FPTBL, tbl ); + } - EDA_BASE_FRAME::LoadSettings(); - cfg->Read( KeepCvpcbOpenEntry, &m_KeepCvpcbOpen, true ); - cfg->Read( FootprintDocFileEntry, &m_DocModulesFileName, + return tbl; +} + + +void CVPCB_MAINFRAME::LoadSettings( wxConfigBase* aCfg ) +{ + EDA_BASE_FRAME::LoadSettings( aCfg ); + + aCfg->Read( KeepCvpcbOpenEntry, &m_KeepCvpcbOpen, true ); + aCfg->Read( FootprintDocFileEntry, &m_DocModulesFileName, DEFAULT_FOOTPRINTS_LIST_FILENAME ); } -void CVPCB_MAINFRAME::SaveSettings() +void CVPCB_MAINFRAME::SaveSettings( wxConfigBase* aCfg ) { - wxASSERT( wxGetApp().GetSettings() != NULL ); + EDA_BASE_FRAME::SaveSettings( aCfg ); - wxConfig* cfg = wxGetApp().GetSettings(); - - EDA_BASE_FRAME::SaveSettings(); - cfg->Write( KeepCvpcbOpenEntry, m_KeepCvpcbOpen ); - cfg->Write( FootprintDocFileEntry, m_DocModulesFileName ); + aCfg->Write( KeepCvpcbOpenEntry, m_KeepCvpcbOpen ); + aCfg->Write( FootprintDocFileEntry, m_DocModulesFileName ); int state = 0; @@ -267,7 +248,7 @@ void CVPCB_MAINFRAME::SaveSettings() if( m_mainToolBar->GetToolToggled( ID_CVPCB_FOOTPRINT_DISPLAY_BY_LIBRARY_LIST ) ) state |= FOOTPRINTS_LISTBOX::BY_LIBRARY; - cfg->Write( wxT( FILTERFOOTPRINTKEY ), state ); + aCfg->Write( wxT( FILTERFOOTPRINTKEY ), state ); } @@ -321,10 +302,10 @@ void CVPCB_MAINFRAME::OnCloseWindow( wxCloseEvent& Event ) } // Close the help frame - if( wxGetApp().GetHtmlHelpController() ) + if( Pgm().GetHtmlHelpController() ) { - if( wxGetApp().GetHtmlHelpController()->GetFrame() )// returns NULL if no help frame active - wxGetApp().GetHtmlHelpController()->GetFrame()->Close( true ); + if( Pgm().GetHtmlHelpController()->GetFrame() )// returns NULL if no help frame active + Pgm().GetHtmlHelpController()->GetFrame()->Close( true ); } if( m_NetlistFileName.IsOk() ) @@ -333,8 +314,8 @@ void CVPCB_MAINFRAME::OnCloseWindow( wxCloseEvent& Event ) } // Close module display frame - if( m_DisplayFootprintFrame ) - m_DisplayFootprintFrame->Close( true ); + if( GetFpViewerFrame() ) + GetFpViewerFrame()->Close( true ); m_modified = false; @@ -460,9 +441,8 @@ void CVPCB_MAINFRAME::DelAssociations( wxCommandEvent& event ) void CVPCB_MAINFRAME::LoadNetList( wxCommandEvent& event ) { - wxString oldPath; - wxFileName newFileName; int id = event.GetId(); + wxFileName newFileName; if( id >= wxID_FILE1 && id <= wxID_FILE9 ) { @@ -483,70 +463,83 @@ void CVPCB_MAINFRAME::LoadNetList( wxCommandEvent& event ) if( newFileName == m_NetlistFileName ) return; - if( m_NetlistFileName.DirExists() ) - oldPath = m_NetlistFileName.GetPath(); + OpenProjectFiles( std::vector( 1, newFileName.GetFullPath() ) ); +} - /* Update the library search path list. */ - if( wxGetApp().GetLibraryPathList().Index( oldPath ) != wxNOT_FOUND ) - wxGetApp().GetLibraryPathList().Remove( oldPath ); - wxGetApp().GetLibraryPathList().Insert( newFileName.GetPath(), 0 ); - m_NetlistFileName = newFileName; - ReadNetListAndLinkFiles(); +bool CVPCB_MAINFRAME::OpenProjectFiles( const std::vector& aFileSet, int aCtl ) +{ + if( aFileSet.size() == 1 ) + { + m_NetlistFileName = aFileSet[0]; + ReadNetListAndLinkFiles(); - // OSX need it since some objects are "rebuild" just make aware AUI - // Fixes #1258081 - m_auimgr.Update(); + UpdateTitle(); + + // OSX need it since some objects are "rebuild" just make aware AUI + // Fixes #1258081 + m_auimgr.Update(); + + return true; + } + + return false; } void CVPCB_MAINFRAME::ConfigCvpcb( wxCommandEvent& event ) { - DIALOG_CVPCB_CONFIG ConfigFrame( this ); + /* This is showing FOOTPRINT search paths, which are obsoleted. + I am removing this for the time being, since cvpcb will soon be part of pcbnew. - ConfigFrame.ShowModal(); + DIALOG_CVPCB_CONFIG dlg( this ); + + dlg.ShowModal(); + */ } void CVPCB_MAINFRAME::OnEditFootprintLibraryTable( wxCommandEvent& aEvent ) { - bool tableChanged = false; - int r = InvokePcbLibTableEditor( this, m_globalFootprintTable, m_footprintLibTable ); + bool tableChanged = false; + int r = InvokePcbLibTableEditor( this, &GFootprintTable, FootprintLibs() ); if( r & 1 ) { + wxString fileName = FP_LIB_TABLE::GetGlobalTableFileName(); + try { - FILE_OUTPUTFORMATTER sf( FP_LIB_TABLE::GetGlobalTableFileName() ); - m_globalFootprintTable->Format( &sf, 0 ); + GFootprintTable.Save( fileName ); tableChanged = true; } - catch( IO_ERROR& ioe ) + catch( const IO_ERROR& ioe ) { - wxString msg; - msg.Printf( _( "Error occurred saving the global footprint library " - "table:\n\n%s" ), ioe.errorText.GetData() ); + wxString msg = wxString::Format( _( + "Error occurred saving the global footprint library table:\n'%s'\n%s" ), + GetChars( fileName ), + GetChars( ioe.errorText ) + ); wxMessageBox( msg, _( "File Save Error" ), wxOK | wxICON_ERROR ); } } if( r & 2 ) { - wxFileName fn = m_NetlistFileName; - fn.SetName( FP_LIB_TABLE::GetFileName() ); - fn.SetExt( wxEmptyString ); + wxString fileName = Prj().FootprintLibTblName(); try { - FILE_OUTPUTFORMATTER sf( fn.GetFullPath() ); - m_footprintLibTable->Format( &sf, 0 ); + FootprintLibs()->Save( fileName ); tableChanged = true; } - catch( IO_ERROR& ioe ) + catch( const IO_ERROR& ioe ) { - wxString msg; - msg.Printf( _( "Error occurred saving the global footprint library " - "table:\n\n%s" ), ioe.errorText.GetData() ); + wxString msg = wxString::Format( _( + "Error occurred saving the project footprint library table:\n'%s'\n%s" ), + GetChars( fileName ), + GetChars( ioe.errorText ) + ); wxMessageBox( msg, _( "File Save Error" ), wxOK | wxICON_ERROR ); } } @@ -554,7 +547,7 @@ void CVPCB_MAINFRAME::OnEditFootprintLibraryTable( wxCommandEvent& aEvent ) if( tableChanged ) { BuildLIBRARY_LISTBOX(); - m_footprints.ReadFootprintFiles( m_footprintLibTable ); + m_footprints.ReadFootprintFiles( FootprintLibs() ); } } @@ -568,7 +561,7 @@ void CVPCB_MAINFRAME::OnKeepOpenOnSave( wxCommandEvent& event ) void CVPCB_MAINFRAME::DisplayModule( wxCommandEvent& event ) { CreateScreenCmp(); - m_DisplayFootprintFrame->RedrawScreen( wxPoint( 0, 0 ), false ); + GetFpViewerFrame()->RedrawScreen( wxPoint( 0, 0 ), false ); } @@ -580,7 +573,7 @@ void CVPCB_MAINFRAME::SetLanguage( wxCommandEvent& event ) void CVPCB_MAINFRAME::DisplayDocFile( wxCommandEvent& event ) { - GetAssociatedDocument( this, m_DocModulesFileName, &wxGetApp().GetLibraryPathList() ); + GetAssociatedDocument( this, m_DocModulesFileName, &Kiface().KifaceSearch() ); } @@ -607,7 +600,9 @@ void CVPCB_MAINFRAME::OnSelectComponent( wxListEvent& event ) m_FootprintList->SetFootprints( m_footprints, libraryName, component, filter ); // Tell AuiMgr that objects are changed ! - m_auimgr.Update(); + if( m_auimgr.GetManagedWindow() ) // Be sure Aui Manager is initialized + // (could be not the case when starting CvPcb + m_auimgr.Update(); if( component == NULL ) return; @@ -646,7 +641,7 @@ void CVPCB_MAINFRAME::OnSelectComponent( wxListEvent& event ) if ( ii >= 0 ) m_FootprintList->SetSelection( ii, false ); - if( m_DisplayFootprintFrame ) + if( GetFpViewerFrame() ) { CreateScreenCmp(); } @@ -755,16 +750,17 @@ void CVPCB_MAINFRAME::DisplayStatus() bool CVPCB_MAINFRAME::LoadFootprintFiles() { + FP_LIB_TABLE* fptbl = FootprintLibs(); + // Check if there are footprint libraries in the footprint library table. - if( m_footprintLibTable == NULL || !m_footprintLibTable->GetLogicalLibs().size() ) + if( !fptbl || !fptbl->GetLogicalLibs().size() ) { wxMessageBox( _( "No PCB footprint libraries are listed in the current footprint " "library table." ), _( "Configuration Error" ), wxOK | wxICON_ERROR ); return false; } - if( m_footprintLibTable != NULL ) - m_footprints.ReadFootprintFiles( m_footprintLibTable ); + m_footprints.ReadFootprintFiles( fptbl ); if( m_footprints.GetErrorCount() ) { @@ -777,20 +773,18 @@ bool CVPCB_MAINFRAME::LoadFootprintFiles() void CVPCB_MAINFRAME::UpdateTitle() { - wxString title; + wxString title = wxString::Format( wxT( "Cvpcb %s " ), GetChars( GetBuildVersion() ) ); if( m_NetlistFileName.IsOk() && m_NetlistFileName.FileExists() ) { - title = wxGetApp().GetTitle() + wxT( " " ) + GetBuildVersion() + - wxT( " " ) + m_NetlistFileName.GetFullPath(); + title += m_NetlistFileName.GetFullPath(); if( !m_NetlistFileName.IsFileWritable() ) title += _( " [Read Only]" ); } else { - title = wxGetApp().GetTitle() + wxT( " " ) + GetBuildVersion() + - wxT( " " ) + _( " [no file]" ); + title += _( "[no file]" ); } SetTitle( title ); @@ -875,7 +869,7 @@ int CVPCB_MAINFRAME::ReadSchematicNetlist() // File header. -static char HeaderLinkFile[] = { "Cmp-Mod V01" }; +static char headerLinkFile[] = "Cmp-Mod V01"; bool CVPCB_MAINFRAME::WriteComponentLinkFile( const wxString& aFullFileName ) @@ -883,7 +877,7 @@ bool CVPCB_MAINFRAME::WriteComponentLinkFile( const wxString& aFullFileName ) COMPONENT* component; FILE* outputFile; wxFileName fn( aFullFileName ); - wxString Title = wxGetApp().GetTitle() + wxT( " " ) + GetBuildVersion(); + wxString title = wxString::Format( wxT( "Cvpcb %s " ), GetChars( GetBuildVersion() ) ); outputFile = wxFopen( fn.GetFullPath(), wxT( "wt" ) ); @@ -903,8 +897,8 @@ bool CVPCB_MAINFRAME::WriteComponentLinkFile( const wxString& aFullFileName ) * IdModule = BUS_PC; * EndCmp */ - retval |= fprintf( outputFile, "%s", HeaderLinkFile ); - retval |= fprintf( outputFile, " Created by %s", TO_UTF8( Title ) ); + retval |= fprintf( outputFile, "%s", headerLinkFile ); + retval |= fprintf( outputFile, " Created by %s", TO_UTF8( title ) ); retval |= fprintf( outputFile, " date = %s\n", TO_UTF8( DateAndTime() ) ); for( unsigned i = 0; i < m_netlist.GetCount(); i++ ) @@ -926,21 +920,17 @@ bool CVPCB_MAINFRAME::WriteComponentLinkFile( const wxString& aFullFileName ) void CVPCB_MAINFRAME::CreateScreenCmp() { - if( m_DisplayFootprintFrame == NULL ) + DISPLAY_FOOTPRINTS_FRAME* fpframe = GetFpViewerFrame(); + + if( !fpframe ) { - m_DisplayFootprintFrame = new DISPLAY_FOOTPRINTS_FRAME( this, _( "Module" ), - wxPoint( 0, 0 ), - wxSize( 600, 400 ), - KICAD_DEFAULT_DRAWFRAME_STYLE ); - - m_DisplayFootprintFrame->SetFootprintLibTable( m_footprintLibTable ); - - m_DisplayFootprintFrame->Show( true ); + fpframe = new DISPLAY_FOOTPRINTS_FRAME( &Kiway(), this ); + fpframe->Show( true ); } else { - if( m_DisplayFootprintFrame->IsIconized() ) - m_DisplayFootprintFrame->Iconize( false ); + if( fpframe->IsIconized() ) + fpframe->Iconize( false ); // The display footprint window might be buried under some other // windows, so CreateScreenCmp() on an existing window would not @@ -948,11 +938,11 @@ void CVPCB_MAINFRAME::CreateScreenCmp() // So we want to put it to front, second after our CVPCB_MAINFRAME. // We do this by a little dance of bringing it to front then the main // frame back. - m_DisplayFootprintFrame->Raise(); // Make sure that is visible. - Raise(); // .. but still we want the focus. + fpframe->Raise(); // Make sure that is visible. + Raise(); // .. but still we want the focus. } - m_DisplayFootprintFrame->InitDisplay(); + fpframe->InitDisplay(); } @@ -1039,11 +1029,11 @@ void CVPCB_MAINFRAME::BuildLIBRARY_LISTBOX() wxFONTWEIGHT_NORMAL ) ); } - if( m_footprintLibTable ) + if( FootprintLibs() ) { wxArrayString libNames; - std::vector< wxString > libNickNames = m_footprintLibTable->GetLogicalLibs(); + std::vector< wxString > libNickNames = FootprintLibs()->GetLogicalLibs(); for( unsigned ii = 0; ii < libNickNames.size(); ii++ ) libNames.Add( libNickNames[ii] ); @@ -1062,3 +1052,10 @@ COMPONENT* CVPCB_MAINFRAME::GetSelectedComponent() return NULL; } + + +DISPLAY_FOOTPRINTS_FRAME* CVPCB_MAINFRAME::GetFpViewerFrame() +{ + // returns the Footprint Viewer frame, if exists, or NULL + return (DISPLAY_FOOTPRINTS_FRAME*) wxWindow::FindWindowByName( FOOTPRINTVIEWER_FRAME_NAME ); +} diff --git a/cvpcb/cvpcb.cpp b/cvpcb/cvpcb.cpp index b2f307fb32..ebc75ad5ff 100644 --- a/cvpcb/cvpcb.cpp +++ b/cvpcb/cvpcb.cpp @@ -27,13 +27,15 @@ */ #include +#include +#include #include -#include +#include +#include #include #include #include -#include <3d_viewer.h> #include #include #include @@ -57,11 +59,13 @@ const wxString FootprintAliasFileWildcard( _( "KiCad footprint alias files (*.eq const wxString titleLibLoadError( _( "Library Load Error" ) ); +#if 0 // add this logic to OpenProjectFiles() + /* * MacOSX: Needed for file association * http://wiki.wxwidgets.org/WxMac-specific_topics */ -void EDA_APP::MacOpenFile( const wxString& aFileName ) +void PGM_BASE::MacOpenFile( const wxString& aFileName ) { wxFileName filename = aFileName; wxString oldPath; @@ -75,76 +79,258 @@ void EDA_APP::MacOpenFile( const wxString& aFileName ) oldPath = frame->m_NetlistFileName.GetPath(); // Update the library search path list. - if( wxGetApp().GetLibraryPathList().Index( oldPath ) != wxNOT_FOUND ) - wxGetApp().GetLibraryPathList().Remove( oldPath ); + if( Pgm().GetLibraryPathList().Index( oldPath ) != wxNOT_FOUND ) + Pgm().GetLibraryPathList().Remove( oldPath ); - wxGetApp().GetLibraryPathList().Insert( filename.GetPath(), 0 ); + Pgm().GetLibraryPathList().Insert( filename.GetPath(), 0 ); frame->m_NetlistFileName = filename; frame->ReadNetListAndLinkFiles(); } +#endif -// Create a new application object -IMPLEMENT_APP( EDA_APP ) +namespace CV { - -/************************************/ -/* Called to initialize the program */ -/************************************/ - -bool EDA_APP::OnInit() +static struct IFACE : public KIFACE_I { - wxFileName filename; - wxString message; - CVPCB_MAINFRAME* frame = NULL; + // Of course all are virtual overloads, implementations of the KIFACE. - InitEDA_Appl( wxT( "CvPcb" ), APP_CVPCB_T ); + IFACE( const char* aName, KIWAY::FACE_T aType ) : + KIFACE_I( aName, aType ) + {} - SetFootprintLibTablePath(); + bool OnKifaceStart( PGM_BASE* aProgram ); + + void OnKifaceEnd(); + + wxWindow* CreateWindow( wxWindow* aParent, int aClassId, KIWAY* aKiway, int aCtlBits = 0 ) + { + switch( aClassId ) + { + case CVPCB_FRAME_TYPE: + { + CVPCB_MAINFRAME* frame = new CVPCB_MAINFRAME( aKiway, aParent ); + return frame; + } + break; + + default: + ; + } + + return NULL; + } + + /** + * Function IfaceOrAddress + * return a pointer to the requested object. The safest way to use this + * is to retrieve a pointer to a static instance of an interface, similar to + * how the KIFACE interface is exported. But if you know what you are doing + * use it to retrieve anything you want. + * + * @param aDataId identifies which object you want the address of. + * + * @return void* - and must be cast into the know type. + */ + void* IfaceOrAddress( int aDataId ) + { + return NULL; + } + +} kiface( "cvpcb", KIWAY::FACE_CVPCB ); + +} // namespace + +using namespace CV; + + +static PGM_BASE* process; + + +KIFACE_I& Kiface() { return kiface; } + + +// KIFACE_GETTER's actual spelling is a substitution macro found in kiway.h. +// KIFACE_GETTER will not have name mangling due to declaration in kiway.h. +MY_API( KIFACE* ) KIFACE_GETTER( int* aKIFACEversion, int aKIWAYversion, PGM_BASE* aProgram ) +{ + process = (PGM_BASE*) aProgram; + return &kiface; +} + + +PGM_BASE& Pgm() +{ + wxASSERT( process ); // KIFACE_GETTER has already been called. + return *process; +} + + +/** + * Function set3DShapesPath + * attempts to set the environment variable given by aKiSys3Dmod to a valid path. + * (typically "KISYS3DMOD" ) + * If the environment variable is already set, + * then it left as is to respect the wishes of the user. + * + * The path is determined by attempting to find the path modules/packages3d + * files in kicad tree. + * This may or may not be the best path but it provides the best solution for + * backwards compatibility with the previous 3D shapes search path implementation. + * + * @note This must be called after #SetBinDir() is called at least on Windows. + * Otherwise, the kicad path is not known (Windows specific) + * + * @param aKiSys3Dmod = the value of environment variable, typically "KISYS3DMOD" + * @return false if the aKiSys3Dmod path is not valid. + */ +static bool set3DShapesPath( const wxString& aKiSys3Dmod ) +{ + wxString path; + + // Set the KISYS3DMOD environment variable for the current process, + // if it is not already defined in the user's environment and valid. + if( wxGetEnv( aKiSys3Dmod, &path ) && wxFileName::DirExists( path ) ) + return true; + + // Attempt to determine where the 3D shape libraries were installed using the + // legacy path: + // on Unix: /usr/local/kicad/share/modules/packages3d + // or /usr/share/kicad/modules/packages3d + // On Windows: bin../share/modules/packages3d + wxString relpath( wxT( "modules/packages3d" ) ); + +// Apple MacOSx +#ifdef __WXMAC__ + path = wxT("/Library/Application Support/kicad/modules/packages3d/"); + + if( wxFileName::DirExists( path ) ) + { + wxSetEnv( aKiSys3Dmod, path ); + return true; + } + + path = wxString( wxGetenv( wxT( "HOME" ) ) ) + wxT("/Library/Application Support/kicad/modules/packages3d/"); + + if( wxFileName::DirExists( path ) ) + { + wxSetEnv( aKiSys3Dmod, path ); + return true; + } + +#elif defined(__UNIX__) // Linux and non-Apple Unix + // Try the home directory: + path.Empty(); + wxGetEnv( wxT("HOME"), &path ); + path += wxT("/kicad/share/") + relpath; + + if( wxFileName::DirExists( path ) ) + { + wxSetEnv( aKiSys3Dmod, path ); + return true; + } + + // Try the standard install path: + path = wxT("/usr/local/kicad/share/") + relpath; + + if( wxFileName::DirExists( path ) ) + { + wxSetEnv( aKiSys3Dmod, path ); + return true; + } + + // Try the official distrib standard install path: + path = wxT("/usr/share/kicad/") + relpath; + + if( wxFileName::DirExists( path ) ) + { + wxSetEnv( aKiSys3Dmod, path ); + return true; + } + +#else // Windows + // On Windows, the install path is given by the path of executables + wxFileName fn; + fn.AssignDir( Pgm().GetExecutablePath() ); + fn.RemoveLastDir(); + path = fn.GetPathWithSep() + wxT("share/") + relpath; + + if( wxFileName::DirExists( path ) ) + { + wxSetEnv( aKiSys3Dmod, path ); + return true; + } +#endif + + return false; +} + + +//!!!!!!!!!!!!!!! This code is obsolete because of the merge into pcbnew, don't bother with it. + +FP_LIB_TABLE GFootprintTable; + + +// A short lived implementation. cvpcb will get combine into pcbnew shortly, so +// we skip setting KISYSMOD here for now. User should set the environment +// variable. + +bool IFACE::OnKifaceStart( PGM_BASE* aProgram ) +{ + // This is process level, not project level, initialization of the DSO. + + // Do nothing in here pertinent to a project! + + start_common(); // Set 3D shape path from environment variable KISYS3DMOD - Set3DShapesPath( wxT(KISYS3DMOD) ); + set3DShapesPath( wxT("KISYS3DMOD") ); - if( m_Checker && m_Checker->IsAnotherRunning() ) - { - if( !IsOK( NULL, _( "CvPcb is already running, Continue?" ) ) ) - return false; - } + /* Now that there are no *.mod files in the standard library, this function + has no utility. User should simply set the variable manually. + Looking for *.mod files which do not exist is fruitless. - if( argc > 1 ) - { - filename = argv[1]; - wxSetWorkingDirectory( filename.GetPath() ); - } - - // read current setup and reopen last directory if no filename to open in command line - bool reopenLastUsedDirectory = argc == 1; - GetSettings( reopenLastUsedDirectory ); + // SetFootprintLibTablePath(); + */ g_DrawBgColor = BLACK; - wxString Title = GetTitle() + wxT( " " ) + GetBuildVersion(); - frame = new CVPCB_MAINFRAME( Title ); - - // Show the frame - SetTopWindow( frame ); - frame->Show( true ); - frame->m_NetlistFileExtension = wxT( "net" ); - - if( filename.IsOk() && filename.FileExists() ) + try { - frame->m_NetlistFileName = filename; - frame->LoadProjectFile( filename.GetFullPath() ); + // The global table is not related to a specific project. All projects + // will use the same global table. So the KIFACE::OnKifaceStart() contract + // of avoiding anything project specific is not violated here. - if( frame->ReadNetListAndLinkFiles() ) + if( !FP_LIB_TABLE::LoadGlobalTable( GFootprintTable ) ) { - frame->m_NetlistFileExtension = filename.GetExt(); - return true; + DisplayInfoMessage( NULL, wxT( + "You have run CvPcb for the first time using the " + "new footprint library table method for finding " + "footprints. CvPcb has either copied the default " + "table or created an empty table in your home " + "folder. You must first configure the library " + "table to include all footprint libraries not " + "included with KiCad. See the \"Footprint Library " + "Table\" section of the CvPcb documentation for " + "more information." ) ); } } - - frame->UpdateTitle(); + catch( const IO_ERROR& ioe ) + { + wxString msg = wxString::Format( _( + "An error occurred attempting to load the global footprint library " + "table:\n\n%s" ), + GetChars( ioe.errorText ) + ); + DisplayError( NULL, msg ); + return false; + } return true; } + +void IFACE::OnKifaceEnd() +{ + end_common(); +} diff --git a/cvpcb/cvpcb_mainframe.h b/cvpcb/cvpcb_mainframe.h index 01e2962a0d..8cd8f5c322 100644 --- a/cvpcb/cvpcb_mainframe.h +++ b/cvpcb/cvpcb_mainframe.h @@ -35,7 +35,7 @@ #include #include -#include +#include /* Forward declarations of all top-level window classes. */ @@ -47,28 +47,22 @@ class DISPLAY_FOOTPRINTS_FRAME; class COMPONENT; class FP_LIB_TABLE; +namespace CV { struct IFACE; } /** * The CvPcb application main window. */ -class CVPCB_MAINFRAME : public EDA_BASE_FRAME +class CVPCB_MAINFRAME : public KIWAY_PLAYER { + friend struct CV::IFACE; + wxArrayString m_footprintListEntries; - /// The global footprint library table. - FP_LIB_TABLE* m_globalFootprintTable; - - /// The project footprint library table. This is a combination of the project - /// footprint library table and the global footprint table. This is the one to - /// use when finding a #MODULE. - FP_LIB_TABLE* m_footprintLibTable; - public: bool m_KeepCvpcbOpen; FOOTPRINTS_LISTBOX* m_FootprintList; LIBRARY_LISTBOX* m_LibraryList; COMPONENTS_LISTBOX* m_ListCmp; - DISPLAY_FOOTPRINTS_FRAME* m_DisplayFootprintFrame; wxAuiToolBar* m_mainToolBar; wxFileName m_NetlistFileName; wxArrayString m_ModuleLibNames; @@ -87,10 +81,24 @@ protected: // (in automatic selection/deletion of associations) PARAM_CFG_ARRAY m_projectFileParams; + CVPCB_MAINFRAME( KIWAY* aKiway, wxWindow* aParent ); + public: - CVPCB_MAINFRAME( const wxString& title, long style = KICAD_DEFAULT_DRAWFRAME_STYLE ); ~CVPCB_MAINFRAME(); + bool OpenProjectFiles( const std::vector& aFileSet, int aCtl=0 ); // overload KIWAY_PLAYER + + /** + * Function FootprintLibs + * @return the project #FP_LIB_TABLE. + */ + FP_LIB_TABLE* FootprintLibs() const; + + /** + * @return a pointer on the Footprint Viewer frame, if exists, or NULL + */ + DISPLAY_FOOTPRINTS_FRAME* GetFpViewerFrame(); + /** * Function OnSelectComponent * Called when clicking on a component in component list window @@ -226,23 +234,9 @@ public: */ void LoadProjectFile( const wxString& aFileName ); - /** - * Function LoadSettings - * loads the CvPcb main frame specific configuration settings. - * - * Don't forget to call this base method from any derived classes or the - * settings will not get loaded. - */ - virtual void LoadSettings(); + void LoadSettings( wxConfigBase* aCfg ); // override virtual - /** - * Function SaveSettings - * save the CvPcb frame specific configuration settings. - * - * Don't forget to call this base method from any derived classes or the - * settings will not get saved. - */ - virtual void SaveSettings(); + void SaveSettings( wxConfigBase* aCfg ); // override virtual /** * Function DisplayStatus diff --git a/cvpcb/dialogs/dialog_cvpcb_config.cpp b/cvpcb/dialogs/dialog_cvpcb_config.cpp index 44f263d23e..b0836502f4 100644 --- a/cvpcb/dialogs/dialog_cvpcb_config.cpp +++ b/cvpcb/dialogs/dialog_cvpcb_config.cpp @@ -29,7 +29,7 @@ #include #include -#include +#include #include #include #include @@ -43,18 +43,19 @@ #include -DIALOG_CVPCB_CONFIG::DIALOG_CVPCB_CONFIG( CVPCB_MAINFRAME* parent ) : - DIALOG_CVPCB_CONFIG_FBP( parent ) +DIALOG_CVPCB_CONFIG::DIALOG_CVPCB_CONFIG( CVPCB_MAINFRAME* aParent ) : + DIALOG_CVPCB_CONFIG_FBP( aParent ) { - wxString title; - wxFileName fn = parent->m_NetlistFileName; + wxString title; + wxFileName fn = aParent->m_NetlistFileName; + fn.SetExt( ProjectFileExtension ); - m_Parent = parent; - m_Config = wxGetApp().GetCommonSettings(); + m_Parent = aParent; + m_Config = Pgm().CommonSettings(); Init( ); - title.Format( _( "Project file: <%s>" ), GetChars( fn.GetFullPath() ) ); + title.Format( _( "Project file: '%s'" ), GetChars( fn.GetFullPath() ) ); SetTitle( title ); if( GetSizer() ) @@ -93,7 +94,7 @@ void DIALOG_CVPCB_CONFIG::Init() } // Display actual libraries paths: - wxPathList libpaths = wxGetApp().GetLibraryPathList(); + wxPathList libpaths = Pgm().GetLibraryPathList(); for( unsigned ii = 0; ii < libpaths.GetCount(); ii++ ) { @@ -112,9 +113,9 @@ void DIALOG_CVPCB_CONFIG::OnCancelClick( wxCommandEvent& event ) if( m_LibPathChanged ) { for( unsigned ii = 0; ii < m_ListLibr->GetCount(); ii++ ) - wxGetApp().RemoveLibraryPath( m_listUserPaths->GetString( ii ) ); + Pgm().RemoveLibraryPath( m_listUserPaths->GetString( ii ) ); - wxGetApp().InsertLibraryPath( m_Parent->m_UserLibraryPath, 1 ); + Pgm().InsertLibraryPath( m_Parent->m_UserLibraryPath, 1 ); } EndModal( wxID_CANCEL ); @@ -295,7 +296,8 @@ void DIALOG_CVPCB_CONFIG::OnAddOrInsertLibClick( wxCommandEvent& event ) insert = true; wildcard = FootprintAliasFileWildcard; - wxListBox * list = m_ListEquiv; + + wxListBox* list = m_ListEquiv; if( (event.GetId() == ID_ADD_LIB) || (event.GetId() == ID_INSERT_LIB) ) { @@ -317,7 +319,7 @@ void DIALOG_CVPCB_CONFIG::OnAddOrInsertLibClick( wxCommandEvent& event ) libpath = m_DefaultLibraryPathslistBox->GetStringSelection(); if( libpath.IsEmpty() ) - libpath = wxGetApp().ReturnLastVisitedLibraryPath(); + libpath = Pgm().LastVisitedLibraryPath(); wxFileDialog FilesDialog( this, _( "Footprint library files:" ), libpath, wxEmptyString, wildcard, @@ -334,7 +336,7 @@ void DIALOG_CVPCB_CONFIG::OnAddOrInsertLibClick( wxCommandEvent& event ) fn = Filenames[jj]; if( jj == 0 ) - wxGetApp().SaveLastVisitedLibraryPath( fn.GetPath() ); + Pgm().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 @@ -343,7 +345,7 @@ void DIALOG_CVPCB_CONFIG::OnAddOrInsertLibClick( wxCommandEvent& event ) * because it preserve use of default libraries paths, when the path * is a sub path of these default paths */ - libfilename = wxGetApp().ReturnFilenameWithRelativePathInLibPath( fn.GetFullPath() ); + libfilename = Pgm().FilenameWithRelativePathInSearchList( fn.GetFullPath() ); // Remove extension: fn = libfilename; @@ -372,7 +374,7 @@ void DIALOG_CVPCB_CONFIG::OnAddOrInsertLibClick( wxCommandEvent& event ) void DIALOG_CVPCB_CONFIG::OnAddOrInsertPath( wxCommandEvent& event ) { - wxString path = wxGetApp().ReturnLastVisitedLibraryPath(); + wxString path = Pgm().LastVisitedLibraryPath(); bool select = EDA_DirectorySelector( _( "Default Path for Libraries" ), path, @@ -416,10 +418,10 @@ void DIALOG_CVPCB_CONFIG::OnAddOrInsertPath( wxCommandEvent& event ) m_listUserPaths->Insert( path, ipos ); m_LibPathChanged = true; - wxGetApp().InsertLibraryPath( path, ipos + 1 ); + Pgm().InsertLibraryPath( path, ipos + 1 ); // Display actual libraries paths: - wxPathList libpaths = wxGetApp().GetLibraryPathList(); + wxPathList libpaths = Pgm().GetLibraryPathList(); m_DefaultLibraryPathslistBox->Clear(); for( unsigned ii = 0; ii < libpaths.GetCount(); ii++ ) @@ -432,7 +434,7 @@ void DIALOG_CVPCB_CONFIG::OnAddOrInsertPath( wxCommandEvent& event ) DisplayError( this, _( "Path already in use" ) ); } - wxGetApp().SaveLastVisitedLibraryPath( path ); + Pgm().SaveLastVisitedLibraryPath( path ); } @@ -445,13 +447,13 @@ void DIALOG_CVPCB_CONFIG::OnRemoveUserPath( wxCommandEvent& event ) if( ii >= 0 ) { - wxGetApp().RemoveLibraryPath( m_listUserPaths->GetStringSelection() ); + Pgm().RemoveLibraryPath( m_listUserPaths->GetStringSelection() ); m_listUserPaths->Delete( ii ); m_LibPathChanged = true; } // Display actual libraries paths: - wxPathList libpaths = wxGetApp().GetLibraryPathList(); + wxPathList libpaths = Pgm().GetLibraryPathList(); m_DefaultLibraryPathslistBox->Clear(); for( unsigned ii = 0; ii < libpaths.GetCount(); ii++ ) @@ -466,7 +468,7 @@ void DIALOG_CVPCB_CONFIG::OnBrowseModDocFile( wxCommandEvent& event ) wxString FullFileName; wxString docpath, filename; - docpath = wxGetApp().ReturnLastVisitedLibraryPath( wxT( "doc" ) ); + docpath = Pgm().LastVisitedLibraryPath( wxT( "doc" ) ); wxFileDialog FilesDialog( this, _( "Footprint document file:" ), docpath, wxEmptyString, PdfFileWildcard, @@ -485,8 +487,8 @@ void DIALOG_CVPCB_CONFIG::OnBrowseModDocFile( wxCommandEvent& event ) * a sub path of these default paths */ wxFileName fn = FullFileName; - wxGetApp().SaveLastVisitedLibraryPath( fn.GetPath() ); + Pgm().SaveLastVisitedLibraryPath( fn.GetPath() ); - filename = wxGetApp().ReturnFilenameWithRelativePathInLibPath( FullFileName ); + filename = Pgm().FilenameWithRelativePathInSearchList( FullFileName ); m_TextHelpModulesFileName->SetValue( filename ); } diff --git a/cvpcb/dialogs/dialog_cvpcb_config.h b/cvpcb/dialogs/dialog_cvpcb_config.h index a83847d874..fa9b51794c 100644 --- a/cvpcb/dialogs/dialog_cvpcb_config.h +++ b/cvpcb/dialogs/dialog_cvpcb_config.h @@ -14,8 +14,9 @@ class DIALOG_CVPCB_CONFIG : public DIALOG_CVPCB_CONFIG_FBP { private: CVPCB_MAINFRAME* m_Parent; - wxConfig * m_Config; - wxString m_UserLibDirBufferImg; + wxConfigBase* m_Config; + wxString m_UserLibDirBufferImg; + bool m_LibListChanged; bool m_LibPathChanged; diff --git a/cvpcb/menubar.cpp b/cvpcb/menubar.cpp index acd761b19b..ff9e7fa390 100644 --- a/cvpcb/menubar.cpp +++ b/cvpcb/menubar.cpp @@ -27,7 +27,8 @@ * @brief (Re)Create the menubar for CvPcb */ #include -#include +#include +#include #include #include #include @@ -74,11 +75,13 @@ void CVPCB_MAINFRAME::ReCreateMenuBar() // Add this menu to list menu managed by m_fileHistory // (the file history will be updated when adding/removing files in history if( openRecentMenu ) - wxGetApp().GetFileHistory().RemoveMenu( openRecentMenu ); + Kiface().GetFileHistory().RemoveMenu( openRecentMenu ); openRecentMenu = new wxMenu(); - wxGetApp().GetFileHistory().UseMenu( openRecentMenu ); - wxGetApp().GetFileHistory().AddFilesToMenu(); + + Kiface().GetFileHistory().UseMenu( openRecentMenu ); + Kiface().GetFileHistory().AddFilesToMenu(); + AddMenuItem( filesMenu, openRecentMenu, -1, _( "Open &Recent" ), _( "Open recent netlist" ), @@ -115,7 +118,7 @@ void CVPCB_MAINFRAME::ReCreateMenuBar() KiBitmap( library_table_xpm ) ); // Language submenu - wxGetApp().AddMenuLanguageList( preferencesMenu ); + Pgm().AddMenuLanguageList( preferencesMenu ); // Keep open on save item = new wxMenuItem( preferencesMenu, ID_CVPCB_CONFIG_KEEP_OPEN_ON_SAVE, diff --git a/cvpcb/readwrite_dlgs.cpp b/cvpcb/readwrite_dlgs.cpp index ea28775faf..6c07864ae0 100644 --- a/cvpcb/readwrite_dlgs.cpp +++ b/cvpcb/readwrite_dlgs.cpp @@ -119,6 +119,49 @@ void CVPCB_MAINFRAME::SetNewPkg( const wxString& aFootprintName ) } +/** + * Function missingLegacyLibs + * tests the list of \a aLibNames by URI to determine if any of them are missing from + * the #FP_LIB_TABLE. + * + * @note The missing legacy footprint library test is performed by using old library + * file path lookup method. If the library is found, it is compared against all + * of the URIs in the table rather than the nickname. This was done because the + * user could change the nicknames from the default table. Using the full path + * is more reliable. + * + * @param aLibNames is the list of legacy library names. + * @param aErrorMsg is a pointer to a wxString object to store the URIs of any missing + * legacy library paths. Can be NULL. + * @return true if there are missing legacy libraries. Otherwise false. + */ +static bool missingLegacyLibs( FP_LIB_TABLE* aTbl, SEARCH_STACK& aSStack, + const wxArrayString& aLibNames, wxString* aErrorMsg ) +{ + bool retv = false; + + for( unsigned i = 0; i < aLibNames.GetCount(); i++ ) + { + wxFileName fn( wxEmptyString, aLibNames[i], LegacyFootprintLibPathExtension ); + + wxString legacyLibPath = aSStack.FindValidPath( fn ); + + if( legacyLibPath.IsEmpty() ) + continue; + + if( aTbl->FindRowByURI( legacyLibPath ) == 0 ) + { + retv = true; + + if( aErrorMsg ) + *aErrorMsg += wxT( "\"" ) + legacyLibPath + wxT( "\"\n" ); + } + } + + return retv; +} + + bool CVPCB_MAINFRAME::ReadNetListAndLinkFiles() { COMPONENT* component; @@ -164,7 +207,7 @@ bool CVPCB_MAINFRAME::ReadNetListAndLinkFiles() // Check if footprint links were generated before the footprint library table was implemented. if( isLegacy ) { - if( m_footprintLibTable->MissingLegacyLibs( m_ModuleLibNames, &missingLibs ) ) + if( missingLegacyLibs( FootprintLibs(), Prj().PcbSearchS(), m_ModuleLibNames, &missingLibs ) ) { msg = wxT( "The following legacy libraries are defined in the project file " "were not found in the footprint library table:\n\n" ) + missingLibs; @@ -188,7 +231,9 @@ bool CVPCB_MAINFRAME::ReadNetListAndLinkFiles() msg.Clear(); WX_STRING_REPORTER reporter( &msg ); - if( !m_footprintLibTable->ConvertFromLegacy( m_netlist, m_ModuleLibNames, &reporter ) ) + SEARCH_STACK& search = Prj().SchSearchS(); + + if( !FootprintLibs()->ConvertFromLegacy( search, m_netlist, m_ModuleLibNames, &reporter ) ) { HTML_MESSAGE_BOX dlg( this, wxEmptyString ); @@ -270,27 +315,27 @@ int CVPCB_MAINFRAME::SaveCmpLinkFile( const wxString& aFullFileName ) fn.SetExt( ComponentFileExtension ); // Save the project specific footprint library table. - if( !m_footprintLibTable->IsEmpty( false ) ) + if( !FootprintLibs()->IsEmpty( false ) ) { - wxFileName fpLibFileName = fn; - fpLibFileName.ClearExt(); - fpLibFileName.SetName( FP_LIB_TABLE::GetFileName() ); + wxString fp_lib_tbl = Prj().FootprintLibTblName(); - if( fpLibFileName.FileExists() + if( wxFileName::FileExists( fp_lib_tbl ) && IsOK( this, _( "A footprint library table already exists in this path.\n\nDo " "you want to overwrite it?" ) ) ) { try { - m_footprintLibTable->Save( fpLibFileName ); + FootprintLibs()->Save( fp_lib_tbl ); } - catch( IO_ERROR& ioe ) + catch( const IO_ERROR& ioe ) { - DisplayError( this, - wxString::Format( _( "An error occurred attempting to save the " - "footprint library table <%s>\n\n%s" ), - GetChars( fpLibFileName.GetFullPath() ), - GetChars( ioe.errorText ) ) ); + wxString msg = wxString::Format( _( + "An error occurred attempting to save the " + "footprint library table '%s'\n\n%s" ), + GetChars( fp_lib_tbl ), + GetChars( ioe.errorText ) + ); + DisplayError( this, msg ); } } } diff --git a/cvpcb/tool_cvpcb.cpp b/cvpcb/tool_cvpcb.cpp index 47b6d78b49..a080eced69 100644 --- a/cvpcb/tool_cvpcb.cpp +++ b/cvpcb/tool_cvpcb.cpp @@ -28,7 +28,7 @@ */ #include -#include +#include #include #include @@ -41,7 +41,7 @@ void CVPCB_MAINFRAME::ReCreateHToolbar() { - wxConfig* config = wxGetApp().GetSettings(); + wxConfigBase* config = Kiface().KifaceSettings(); if( m_mainToolBar != NULL ) return; diff --git a/eeschema/CMakeLists.txt b/eeschema/CMakeLists.txt index 45411d8fae..bd04eebb7d 100644 --- a/eeschema/CMakeLists.txt +++ b/eeschema/CMakeLists.txt @@ -1,4 +1,4 @@ -set( MAKE_LINK_MAPS false ) +set( MAKE_LINK_MAPS true ) add_definitions( -DEESCHEMA ) @@ -194,11 +194,11 @@ endif() # auto-generate cmp_library_lexer.h and cmp_library_keywords.cpp for the component # library format. make_lexer( - ${CMAKE_CURRENT_SOURCE_DIR}/cmp_library.keywords - ${CMAKE_CURRENT_SOURCE_DIR}/cmp_library_lexer.h - ${CMAKE_CURRENT_SOURCE_DIR}/cmp_library_keywords.cpp - TLIB_T - ) + ${CMAKE_CURRENT_SOURCE_DIR}/cmp_library.keywords + ${CMAKE_CURRENT_SOURCE_DIR}/cmp_library_lexer.h + ${CMAKE_CURRENT_SOURCE_DIR}/cmp_library_keywords.cpp + TLIB_T + ) make_lexer( ${CMAKE_CURRENT_SOURCE_DIR}/template_fieldnames.keywords @@ -238,21 +238,35 @@ set_source_files_properties( dialogs/dialog_bom.cpp ) -# not ready for even building yet: if( USE_KIWAY_DLLS ) - add_executable( eeschema WIN32 MACOSX_BUNDLE ../common/single_top.cpp + ../common/pgm_base.cpp + ${EESCHEMA_RESOURCES} + ) + set_source_files_properties( ../common/single_top.cpp PROPERTIES + COMPILE_DEFINITIONS "TOP_FRAME=SCHEMATIC_FRAME_TYPE;PGM_DATA_FILE_EXT=\"sch\";BUILD_KIWAY_DLL" ) target_link_libraries( eeschema + #singletop # replaces common, giving us restrictive control and link warnings. + # There's way too much crap coming in from common yet. common + bitmaps ${wxWidgets_LIBRARIES} ) + # the DSO (KIFACE) housing the main eeschema code: add_library( eeschema_kiface MODULE ${EESCHEMA_SRCS} ${EESCHEMA_COMMON_SRCS} - ${EESCHEMA_RESOURCES} +# ${EESCHEMA_RESOURCES} + ) + target_link_libraries( eeschema_kiface + common + bitmaps + polygon + ${wxWidgets_LIBRARIES} + ${GDI_PLUS_LIBRARIES} ) set_target_properties( eeschema_kiface PROPERTIES # Decorate OUTPUT_NAME with PREFIX and SUFFIX, creating something like @@ -262,6 +276,14 @@ if( USE_KIWAY_DLLS ) SUFFIX ${KIFACE_SUFFIX} ) + # The KIFACE is in eeschema.cpp, export it: + set_source_files_properties( eeschema.cpp PROPERTIES + COMPILE_DEFINITIONS "BUILD_KIWAY_DLL;COMPILING_DLL" + ) + + # if building eeschema, then also build eeschema_kiface if out of date. + add_dependencies( eeschema eeschema_kiface ) + if( APPLE ) set_target_properties( eeschema_kiface PROPERTIES MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/Info.plist @@ -269,31 +291,55 @@ if( USE_KIWAY_DLLS ) endif() if( MAKE_LINK_MAPS ) - # generate a link map with cross reference + # generate link map with cross reference set_target_properties( eeschema_kiface PROPERTIES - LINK_FLAGS "-Wl,-cref -Wl,-Map=${KIFACE_PRE}eeschema.${KIFACE_EXT}.map" + LINK_FLAGS "${TO_LINKER},-cref ${TO_LINKER},-Map=${KIFACE_PREFIX}eeschema${KIFACE_SUFFIX}.map" + ) + set_target_properties( eeschema PROPERTIES + LINK_FLAGS "${TO_LINKER},-cref ${TO_LINKER},-Map=eeschema.map" ) endif() - target_link_libraries( eeschema_kiface + # these 2 binaries are a matched set, keep them together: + install( TARGETS eeschema + DESTINATION ${KICAD_BIN} + COMPONENT binary + ) + install( TARGETS eeschema_kiface + # actual filename subject to change at milestone C) + # modular-kicad blueprint. + DESTINATION ${KICAD_BIN} + COMPONENT binary + ) + + if( APPLE ) + # copies kiface into the bundle + add_custom_target( _eeschema_kiface_copy ALL + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/eeschema/_eeschema.kiface "${CMAKE_BINARY_DIR}/eeschema/eeschema.app/Contents/MacOS/" + DEPENDS eeschema_kiface + COMMENT "Copying kiface into eeschema" + ) + endif() + +else() + add_executable( eeschema WIN32 MACOSX_BUNDLE + ../common/single_top.cpp + ${EESCHEMA_SRCS} + ${EESCHEMA_COMMON_SRCS} + ${EESCHEMA_RESOURCES} + ) + + target_link_libraries( eeschema common +# lib_kicad bitmaps polygon ${wxWidgets_LIBRARIES} ${GDI_PLUS_LIBRARIES} ) - # Note that this filename is subject to change at milestone C) of - # modular-kicad blueprint. - install( TARGETS eeschema_kiface - DESTINATION ${KICAD_BIN} - COMPONENT binary - ) -else() - add_executable( eeschema WIN32 MACOSX_BUNDLE - ${EESCHEMA_SRCS} - ${EESCHEMA_COMMON_SRCS} - ${EESCHEMA_RESOURCES} + set_source_files_properties( ../common/single_top.cpp PROPERTIES + COMPILE_DEFINITIONS "TOP_FRAME=SCHEMATIC_FRAME_TYPE;PGM_DATA_FILE_EXT=\"sch\";BUILD_KIWAY_DLL" ) if( APPLE ) @@ -302,19 +348,12 @@ else() ) endif() - target_link_libraries( eeschema - common - bitmaps - polygon - ${wxWidgets_LIBRARIES} - ${GDI_PLUS_LIBRARIES} + install( TARGETS eeschema + DESTINATION ${KICAD_BIN} + COMPONENT binary ) + endif() -install( TARGETS eeschema - DESTINATION ${KICAD_BIN} - COMPONENT binary - ) - add_subdirectory( plugins ) diff --git a/eeschema/backanno.cpp b/eeschema/backanno.cpp index 2292301d6c..b72509d98b 100644 --- a/eeschema/backanno.cpp +++ b/eeschema/backanno.cpp @@ -32,7 +32,7 @@ #include #include #include -#include +#include #include #include #include @@ -145,8 +145,8 @@ bool SCH_EDIT_FRAME::LoadCmpToFootprintLinkFile() return false; wxString filename = dlg.GetPath(); - wxString title = wxGetApp().GetAppName() + wxT( " " ) + GetBuildVersion(); - title += wxT( " " ) + filename; + wxString title = wxT( "Eeschema " ) + GetBuildVersion() + wxT( ' ' ) + filename; + SetTitle( title ); int response = wxMessageBox( _( "Do you want to force all the footprint fields visibility?" ), diff --git a/eeschema/block.cpp b/eeschema/block.cpp index f4e47bffb9..98ea9e62a1 100644 --- a/eeschema/block.cpp +++ b/eeschema/block.cpp @@ -28,7 +28,7 @@ */ #include -#include +#include #include #include #include @@ -64,7 +64,7 @@ static void DrawMovingBlockOutlines( EDA_DRAW_PANEL* aPanel, wxDC* aDC, const wxPoint& aPosition, bool aErase ); -int SCH_EDIT_FRAME::ReturnBlockCommand( int key ) +int SCH_EDIT_FRAME::BlockCommand( int key ) { int cmd = BLOCK_IDLE; diff --git a/eeschema/block_libedit.cpp b/eeschema/block_libedit.cpp index 2a03cae331..e9c89d14f5 100644 --- a/eeschema/block_libedit.cpp +++ b/eeschema/block_libedit.cpp @@ -41,7 +41,7 @@ static void DrawMovingBlockOutlines( EDA_DRAW_PANEL* aPanel, wxDC* aDC, const wx bool aErase ); -int LIB_EDIT_FRAME::ReturnBlockCommand( int key ) +int LIB_EDIT_FRAME::BlockCommand( int key ) { int cmd = BLOCK_IDLE; diff --git a/eeschema/class_libentry.cpp b/eeschema/class_libentry.cpp index 4b2dcee8a9..904d7f4b86 100644 --- a/eeschema/class_libentry.cpp +++ b/eeschema/class_libentry.cpp @@ -258,7 +258,7 @@ wxString LIB_COMPONENT::GetLibraryName() } -wxString LIB_COMPONENT::ReturnSubReference( int aUnit, bool aAddSeparator ) +wxString LIB_COMPONENT::SubReference( int aUnit, bool aAddSeparator ) { wxString subRef; @@ -569,7 +569,7 @@ LIB_PIN* LIB_COMPONENT::GetPin( const wxString& aNumber, int aUnit, int aConvert { wxASSERT( pinList[i]->Type() == LIB_PIN_T ); - pinList[i]->ReturnPinStringNum( pNumber ); + pinList[i]->PinStringNum( pNumber ); if( aNumber == pNumber ) return pinList[i]; diff --git a/eeschema/class_libentry.h b/eeschema/class_libentry.h index 43fb8ccc45..a8c84ade03 100644 --- a/eeschema/class_libentry.h +++ b/eeschema/class_libentry.h @@ -664,7 +664,7 @@ public: bool IsMulti() { return m_unitCount > 1; } /** - * Function ReturnSubReference + * Function SubReference * @return the sub reference for component having multiple parts per package. * The sub reference identify the part (or unit) * @param aUnit = the part identifier ( 1 to max count) @@ -672,7 +672,7 @@ public: * by the separator symbol (if any) * Note: this is a static function. */ - static wxString ReturnSubReference( int aUnit, bool aAddSeparator = true ); + static wxString SubReference( int aUnit, bool aAddSeparator = true ); // Accessors to sub ref parameters static int GetSubpartIdSeparator() { return m_subpartIdSeparator; } diff --git a/eeschema/class_netlist_object.cpp b/eeschema/class_netlist_object.cpp index 56de1ef087..34c7333a47 100644 --- a/eeschema/class_netlist_object.cpp +++ b/eeschema/class_netlist_object.cpp @@ -259,7 +259,7 @@ void NETLIST_OBJECT::ConvertBusToNetListItems( NETLIST_OBJECT_LIST& aNetListItem i = busNumber.Find( '[' ); i++; - while( busNumber[i] != '.' && i < busNumber.Len() ) + while( i < busNumber.Len() && busNumber[i] != '.' ) { tmp.Append( busNumber[i] ); i++; @@ -267,12 +267,12 @@ void NETLIST_OBJECT::ConvertBusToNetListItems( NETLIST_OBJECT_LIST& aNetListItem tmp.ToLong( &begin ); - while( busNumber[i] == '.' && i < busNumber.Len() ) + while( i < busNumber.Len() && busNumber[i] == '.' ) i++; tmp.Empty(); - while( busNumber[i] != ']' && i < busNumber.Len() ) + while( i < busNumber.Len() && busNumber[i] != ']' ) { tmp.Append( busNumber[i] ); i++; @@ -353,7 +353,7 @@ wxString NETLIST_OBJECT::GetShortNetName() const netName = wxT("Net-("); netName << link->GetRef( &m_netNameCandidate->m_SheetPath ); netName << wxT("-Pad") - << LIB_PIN::ReturnPinStringNum( m_netNameCandidate->m_PinNum ) + << LIB_PIN::PinStringNum( m_netNameCandidate->m_PinNum ) << wxT(")"); } } diff --git a/eeschema/class_netlist_object.h b/eeschema/class_netlist_object.h index d07dcb7291..e3533a51d4 100644 --- a/eeschema/class_netlist_object.h +++ b/eeschema/class_netlist_object.h @@ -33,7 +33,7 @@ #include -#include // LIB_PIN::ReturnPinStringNum( m_PinNum ) +#include // LIB_PIN::PinStringNum( m_PinNum ) class NETLIST_OBJECT_LIST; class SCH_COMPONENT; @@ -179,7 +179,7 @@ public: wxString GetPinNumText() { // hide the ugliness in here, but do it inline. - return LIB_PIN::ReturnPinStringNum( m_PinNum ); + return LIB_PIN::PinStringNum( m_PinNum ); } /** For Pins (NET_PINS): diff --git a/eeschema/component_references_lister.cpp b/eeschema/component_references_lister.cpp index 10b67d3678..d2b553af5a 100644 --- a/eeschema/component_references_lister.cpp +++ b/eeschema/component_references_lister.cpp @@ -592,12 +592,12 @@ int SCH_REFERENCE_LIST::CheckAnnotation( wxArrayString* aMessageList ) msg.Printf( _( "Different values for %s%d%s (%s) and %s%d%s (%s)" ), GetChars( componentFlatList[ii].GetRef() ), componentFlatList[ii].m_NumRef, - GetChars( LIB_COMPONENT::ReturnSubReference( + GetChars( LIB_COMPONENT::SubReference( componentFlatList[ii].m_Unit ) ), GetChars( componentFlatList[ii].m_Value->GetText() ), GetChars( componentFlatList[next].GetRef() ), componentFlatList[next].m_NumRef, - GetChars( LIB_COMPONENT::ReturnSubReference( + GetChars( LIB_COMPONENT::SubReference( componentFlatList[next].m_Unit ) ), GetChars( componentFlatList[next].m_Value->GetText() ) ); diff --git a/eeschema/component_tree_search_container.cpp b/eeschema/component_tree_search_container.cpp index 28ef57d162..f1613b6586 100644 --- a/eeschema/component_tree_search_container.cpp +++ b/eeschema/component_tree_search_container.cpp @@ -191,7 +191,7 @@ void COMPONENT_TREE_SEARCH_CONTAINER::AddAliasList( const wxString& aNodeName, for( int u = 1; u <= a->GetComponent()->GetPartCount(); ++u ) { wxString unitName = _("Unit"); - unitName += wxT( " " ) + LIB_COMPONENT::ReturnSubReference( u, false ); + unitName += wxT( " " ) + LIB_COMPONENT::SubReference( u, false ); TREE_NODE* unit_node = new TREE_NODE( TREE_NODE::TYPE_UNIT, alias_node, a, unitName, diff --git a/eeschema/cross-probing.cpp b/eeschema/cross-probing.cpp index 9ae5e52035..dcb7788c8d 100644 --- a/eeschema/cross-probing.cpp +++ b/eeschema/cross-probing.cpp @@ -28,7 +28,7 @@ */ #include -#include +#include #include #include #include @@ -58,17 +58,11 @@ void SCH_EDIT_FRAME::ExecuteRemoteCommand( const char* cmdline ) { char line[1024]; - char* idcmd; - char* text; - wxString part_ref, msg; - SCH_EDIT_FRAME* frame; - - frame = (SCH_EDIT_FRAME*)wxGetApp().GetTopWindow(); strncpy( line, cmdline, sizeof(line) - 1 ); - idcmd = strtok( line, " \n\r" ); - text = strtok( NULL, "\"\n\r" ); + char* idcmd = strtok( line, " \n\r" ); + char* text = strtok( NULL, "\"\n\r" ); if( (idcmd == NULL) || (text == NULL) ) return; @@ -76,14 +70,14 @@ void SCH_EDIT_FRAME::ExecuteRemoteCommand( const char* cmdline ) if( strcmp( idcmd, "$PART:" ) != 0 ) return; - part_ref = FROM_UTF8( text ); + wxString part_ref = FROM_UTF8( text ); /* look for a complement */ idcmd = strtok( NULL, " \n\r" ); if( idcmd == NULL ) // component only { - frame->FindComponentAndItem( part_ref, true, FIND_COMPONENT_ONLY, wxEmptyString, false ); + FindComponentAndItem( part_ref, true, FIND_COMPONENT_ONLY, wxEmptyString, false ); return; } @@ -92,23 +86,23 @@ void SCH_EDIT_FRAME::ExecuteRemoteCommand( const char* cmdline ) if( text == NULL ) return; - msg = FROM_UTF8( text ); + wxString msg = FROM_UTF8( text ); if( strcmp( idcmd, "$REF:" ) == 0 ) { - frame->FindComponentAndItem( part_ref, true, FIND_REFERENCE, msg, false ); + FindComponentAndItem( part_ref, true, FIND_REFERENCE, msg, false ); } else if( strcmp( idcmd, "$VAL:" ) == 0 ) { - frame->FindComponentAndItem( part_ref, true, FIND_VALUE, msg, false ); + FindComponentAndItem( part_ref, true, FIND_VALUE, msg, false ); } else if( strcmp( idcmd, "$PAD:" ) == 0 ) { - frame->FindComponentAndItem( part_ref, true, FIND_PIN, msg, false ); + FindComponentAndItem( part_ref, true, FIND_PIN, msg, false ); } else { - frame->FindComponentAndItem( part_ref, true, FIND_COMPONENT_ONLY, wxEmptyString, false ); + FindComponentAndItem( part_ref, true, FIND_COMPONENT_ONLY, wxEmptyString, false ); } } @@ -126,14 +120,14 @@ void SCH_EDIT_FRAME::SendMessageToPCBNEW( EDA_ITEM* objectToSync, SCH_COMPONENT* { case SCH_FIELD_T: case LIB_FIELD_T: - { - if( LibItem == NULL ) - break; + { + if( !LibItem ) + break; - sprintf( Line, "$PART: %s", TO_UTF8( LibItem->GetField( REFERENCE )->GetText() ) ); - SendCommand( MSG_TO_PCB, Line ); - } - break; + sprintf( Line, "$PART: %s", TO_UTF8( LibItem->GetField( REFERENCE )->GetText() ) ); + SendCommand( MSG_TO_PCB, Line ); + } + break; case SCH_COMPONENT_T: LibItem = (SCH_COMPONENT*) objectToSync; @@ -142,7 +136,7 @@ void SCH_EDIT_FRAME::SendMessageToPCBNEW( EDA_ITEM* objectToSync, SCH_COMPONENT* break; case LIB_PIN_T: - if( LibItem == NULL ) + if( !LibItem ) break; Pin = (LIB_PIN*) objectToSync; @@ -150,7 +144,7 @@ void SCH_EDIT_FRAME::SendMessageToPCBNEW( EDA_ITEM* objectToSync, SCH_COMPONENT* if( Pin->GetNumber() ) { wxString pinnum; - Pin->ReturnPinStringNum( pinnum ); + Pin->PinStringNum( pinnum ); sprintf( Line, "$PIN: %s $PART: %s", TO_UTF8( pinnum ), TO_UTF8( LibItem->GetField( REFERENCE )->GetText() ) ); } diff --git a/eeschema/database.cpp b/eeschema/database.cpp index 5071a13cdc..4cf8089364 100644 --- a/eeschema/database.cpp +++ b/eeschema/database.cpp @@ -26,15 +26,15 @@ * @file database.cpp */ -#include "fctsys.h" -#include "confirm.h" -#include "eda_doc.h" -#include "kicad_string.h" -#include "wxstruct.h" +#include +#include +#include +#include +#include #include -#include "protos.h" -#include "class_library.h" -#include "dialog_helpers.h" +#include +#include +#include #include diff --git a/eeschema/dialogs/dialog_annotate.cpp b/eeschema/dialogs/dialog_annotate.cpp index c37d8a1e38..8a3c0b6a22 100644 --- a/eeschema/dialogs/dialog_annotate.cpp +++ b/eeschema/dialogs/dialog_annotate.cpp @@ -29,21 +29,20 @@ #include -#include #include #include #include #include +#include + +#define KEY_ANNOTATE_SORT_OPTION wxT( "AnnotateSortOption" ) +#define KEY_ANNOTATE_ALGO_OPTION wxT( "AnnotateAlgoOption" ) +#define KEY_ANNOTATE_AUTOCLOSE_OPTION wxT( "AnnotateAutoCloseOption" ) +#define KEY_ANNOTATE_USE_SILENTMODE wxT( "AnnotateSilentMode" ) -#define KEY_ANNOTATE_SORT_OPTION wxT( "AnnotateSortOption" ) -#define KEY_ANNOTATE_ALGO_OPTION wxT( "AnnotateAlgoOption" ) -#define KEY_ANNOTATE_AUTOCLOSE_OPTION wxT( "AnnotateAutoCloseOption" ) -#define KEY_ANNOTATE_USE_SILENTMODE wxT( "AnnotateSilentMode" ) - - -class wxConfig; +class wxConfigBase; /** @@ -57,7 +56,7 @@ public: private: SCH_EDIT_FRAME* m_Parent; - wxConfig* m_Config; + wxConfigBase* m_Config; /// Initialises member variables void InitValues(); @@ -112,7 +111,7 @@ DIALOG_ANNOTATE::DIALOG_ANNOTATE( SCH_EDIT_FRAME* parent ) void DIALOG_ANNOTATE::InitValues() { - m_Config = wxGetApp().GetSettings(); + m_Config = Kiface().KifaceSettings(); if( m_Config ) { diff --git a/eeschema/dialogs/dialog_bom.cpp b/eeschema/dialogs/dialog_bom.cpp index 105a71fc06..b293a39b17 100644 --- a/eeschema/dialogs/dialog_bom.cpp +++ b/eeschema/dialogs/dialog_bom.cpp @@ -29,7 +29,8 @@ #include -#include +#include +#include #include #include #include @@ -161,7 +162,7 @@ private: // the first is the title // the second is the command line wxArrayString m_plugins; - wxConfig* m_config; // to store the "plugins" + wxConfigBase* m_config; // to store the "plugins" public: // Constructor and destructor @@ -169,7 +170,7 @@ public: ~DIALOG_BOM(); private: - void OnPluginSelected( wxCommandEvent& event ); + void OnPluginSelected( wxCommandEvent& event ); void OnRunPlugin( wxCommandEvent& event ); void OnCancelClick( wxCommandEvent& event ); void OnHelp( wxCommandEvent& event ); @@ -177,10 +178,10 @@ private: void OnChoosePlugin( wxCommandEvent& event ); void OnRemovePlugin( wxCommandEvent& event ); void OnEditPlugin( wxCommandEvent& event ); - void OnCommandLineEdited( wxCommandEvent& event ); - void OnNameEdited( wxCommandEvent& event ); + void OnCommandLineEdited( wxCommandEvent& event ); + void OnNameEdited( wxCommandEvent& event ); - void pluginInit(); + void pluginInit(); void installPluginsList(); }; @@ -195,7 +196,7 @@ DIALOG_BOM::DIALOG_BOM( SCH_EDIT_FRAME* parent ) : DIALOG_BOM_BASE( parent ) { m_parent = parent; - m_config = wxGetApp().GetSettings(); + m_config = Kiface().KifaceSettings(); installPluginsList(); GetSizer()->SetSizeHints( this ); @@ -377,38 +378,37 @@ void DIALOG_BOM::OnAddPlugin( wxCommandEvent& event ) */ void DIALOG_BOM::OnChoosePlugin( wxCommandEvent& event ) { - wxString FullFileName, Mask, Path; + wxString mask = wxT( "*" ); + wxString path = Pgm().GetExecutablePath(); - Mask = wxT( "*" ); - Path = wxGetApp().GetExecutablePath(); - FullFileName = EDA_FileSelector( _( "Plugin files:" ), - Path, - FullFileName, + wxString fullFileName = EDA_FileSelector( _( "Plugin files:" ), + path, wxEmptyString, - Mask, + wxEmptyString, + mask, this, wxFD_OPEN, true ); - if( FullFileName.IsEmpty() ) + if( fullFileName.IsEmpty() ) return; // Creates a default command line, // suitable to run the external tool xslproc or python // The default command line depending on plugin extension, currently // "xsl" or "exe" or "py" - wxString cmdLine; - wxFileName fn( FullFileName ); - wxString ext = fn.GetExt(); + wxString cmdLine; + wxFileName fn( fullFileName ); + wxString ext = fn.GetExt(); if( ext == wxT("xsl" ) ) - cmdLine.Printf(wxT("xsltproc -o \"%%O\" \"%s\" \"%%I\""), GetChars(FullFileName) ); + cmdLine.Printf(wxT("xsltproc -o \"%%O\" \"%s\" \"%%I\""), GetChars( fullFileName ) ); else if( ext == wxT("exe" ) || ext.IsEmpty() ) - cmdLine.Printf(wxT("\"%s\" < \"%%I\" > \"%%O\""), GetChars(FullFileName) ); + cmdLine.Printf(wxT("\"%s\" < \"%%I\" > \"%%O\""), GetChars( fullFileName ) ); else if( ext == wxT("py" ) || ext.IsEmpty() ) - cmdLine.Printf(wxT("python \"%s\" \"%%I\" \"%%O\""), GetChars(FullFileName) ); + cmdLine.Printf(wxT("python \"%s\" \"%%I\" \"%%O\""), GetChars( fullFileName ) ); else - cmdLine.Printf(wxT("\"%s\""), GetChars(FullFileName) ); + cmdLine.Printf(wxT("\"%s\""), GetChars( fullFileName ) ); m_textCtrlCommand->SetValue( cmdLine ); } @@ -449,7 +449,7 @@ void DIALOG_BOM::OnEditPlugin( wxCommandEvent& event ) } } AddDelimiterString( pluginName ); - wxString editorname = wxGetApp().GetEditorName(); + wxString editorname = Pgm().GetEditorName(); if( !editorname.IsEmpty() ) ExecuteFile( this, editorname, pluginName ); diff --git a/eeschema/dialogs/dialog_color_config.cpp b/eeschema/dialogs/dialog_color_config.cpp index 7daa6988e8..1ed7ae72dc 100644 --- a/eeschema/dialogs/dialog_color_config.cpp +++ b/eeschema/dialogs/dialog_color_config.cpp @@ -4,7 +4,7 @@ #include #include -#include +#include #include #include diff --git a/eeschema/dialogs/dialog_edit_component_in_lib.cpp b/eeschema/dialogs/dialog_edit_component_in_lib.cpp index 72b4c4c69a..8866b25c1f 100644 --- a/eeschema/dialogs/dialog_edit_component_in_lib.cpp +++ b/eeschema/dialogs/dialog_edit_component_in_lib.cpp @@ -26,10 +26,11 @@ */ #include +#include #include #include #include -#include +#include #include #include @@ -435,22 +436,22 @@ bool DIALOG_EDIT_COMPONENT_IN_LIBRARY::SetUnsetConvert() void DIALOG_EDIT_COMPONENT_IN_LIBRARY::BrowseAndSelectDocFile( wxCommandEvent& event ) { - wxString FullFileName, mask; - wxString docpath, filename; + PROJECT& prj = Prj(); + SEARCH_STACK& search = prj.SchSearchS(); - docpath = wxGetApp().ReturnLastVisitedLibraryPath( wxT( "doc" ) ); + wxString docpath = prj.RPath(PROJECT::DOC).LastVisitedPath( search, wxT( "doc" ) ); + wxString mask = wxT( "*" ); - mask = wxT( "*" ); - FullFileName = EDA_FileSelector( _( "Doc Files" ), - docpath, /* Chemin par defaut */ - wxEmptyString, /* nom fichier par defaut */ - wxEmptyString, /* extension par defaut */ - mask, /* Masque d'affichage */ + wxString fullFileName = EDA_FileSelector( _( "Doc Files" ), + docpath, + wxEmptyString, + wxEmptyString, + mask, this, wxFD_OPEN, true ); - if( FullFileName.IsEmpty() ) + if( fullFileName.IsEmpty() ) return; /* If the path is already in the library search paths @@ -460,10 +461,12 @@ void DIALOG_EDIT_COMPONENT_IN_LIBRARY::BrowseAndSelectDocFile( wxCommandEvent& e * because it preserve use of default libraries paths, when the path is a sub path of * these default paths */ - wxFileName fn = FullFileName; - wxGetApp().SaveLastVisitedLibraryPath( fn.GetPath() ); + wxFileName fn = fullFileName; + + prj.RPath(PROJECT::DOC).SaveLastVisitedPath( fn.GetPath() ); + + wxString filename = search.FilenameWithRelativePathInSearchList( fullFileName ); - filename = wxGetApp().ReturnFilenameWithRelativePathInLibPath( FullFileName ); // Filenames are always stored in unix like mode, ie separator "\" is stored as "/" // to ensure files are identical under unices and windows #ifdef __WINDOWS__ diff --git a/eeschema/dialogs/dialog_edit_component_in_schematic.cpp b/eeschema/dialogs/dialog_edit_component_in_schematic.cpp index 91449c9399..9a6644d327 100644 --- a/eeschema/dialogs/dialog_edit_component_in_schematic.cpp +++ b/eeschema/dialogs/dialog_edit_component_in_schematic.cpp @@ -29,7 +29,7 @@ #include #include -#include +#include #include #include #include @@ -766,10 +766,10 @@ void DIALOG_EDIT_COMPONENT_IN_SCHEMATIC::copySelectedFieldToPanel() // top of each other. } - wxString coordText = ReturnStringFromValue( g_UserUnit, coord.x ); + wxString coordText = StringFromValue( g_UserUnit, coord.x ); posXTextCtrl->SetValue( coordText ); - coordText = ReturnStringFromValue( g_UserUnit, coord.y ); + coordText = StringFromValue( g_UserUnit, coord.y ); posYTextCtrl->SetValue( coordText ); } @@ -828,8 +828,8 @@ bool DIALOG_EDIT_COMPONENT_IN_SCHEMATIC::copyPanelToSelectedField() field.SetBold( (style & 2 ) != 0 ); wxPoint pos; - pos.x = ReturnValueFromString( g_UserUnit, posXTextCtrl->GetValue() ); - pos.y = ReturnValueFromString( g_UserUnit, posYTextCtrl->GetValue() ); + pos.x = ValueFromString( g_UserUnit, posXTextCtrl->GetValue() ); + pos.y = ValueFromString( g_UserUnit, posYTextCtrl->GetValue() ); field.SetTextPosition( pos ); return true; diff --git a/eeschema/dialogs/dialog_edit_label.cpp b/eeschema/dialogs/dialog_edit_label.cpp index fb1805e298..91fcc91cda 100644 --- a/eeschema/dialogs/dialog_edit_label.cpp +++ b/eeschema/dialogs/dialog_edit_label.cpp @@ -203,7 +203,7 @@ void DIALOG_LABEL_EDITOR::InitDialog() msg.Printf( _( "H%s x W%s" ), GetChars( units ), GetChars( units ) ); m_staticSizeUnits->SetLabel( msg ); - msg = ReturnStringFromValue( g_UserUnit, m_CurrentText->GetSize().x ); + msg = StringFromValue( g_UserUnit, m_CurrentText->GetSize().x ); m_TextSize->SetValue( msg ); if( m_CurrentText->Type() != SCH_GLOBAL_LABEL_T @@ -272,7 +272,7 @@ void DIALOG_LABEL_EDITOR::TextPropertiesAccept( wxCommandEvent& aEvent ) m_CurrentText->SetOrientation( m_TextOrient->GetSelection() ); text = m_TextSize->GetValue(); - value = ReturnValueFromString( g_UserUnit, text ); + value = ValueFromString( g_UserUnit, text ); m_CurrentText->SetSize( wxSize( value, value ) ); if( m_TextShape ) diff --git a/eeschema/dialogs/dialog_edit_libentry_fields_in_lib.cpp b/eeschema/dialogs/dialog_edit_libentry_fields_in_lib.cpp index 1e2ccb6502..4036c36cb5 100644 --- a/eeschema/dialogs/dialog_edit_libentry_fields_in_lib.cpp +++ b/eeschema/dialogs/dialog_edit_libentry_fields_in_lib.cpp @@ -27,7 +27,7 @@ #include #include -#include +#include #include #include #include @@ -675,13 +675,13 @@ void DIALOG_EDIT_LIBENTRY_FIELDS_IN_LIB::copySelectedFieldToPanel() // top of each other. } - wxString coordText = ReturnStringFromValue( g_UserUnit, coord.x ); + wxString coordText = StringFromValue( g_UserUnit, coord.x ); posXTextCtrl->SetValue( coordText ); // Note: the Y axis for components in lib is from bottom to top // and the screen axis is top to bottom: we must change the y coord sign for editing NEGATE( coord.y ); - coordText = ReturnStringFromValue( g_UserUnit, coord.y ); + coordText = StringFromValue( g_UserUnit, coord.y ); posYTextCtrl->SetValue( coordText ); } @@ -747,8 +747,8 @@ bool DIALOG_EDIT_LIBENTRY_FIELDS_IN_LIB::copyPanelToSelectedField() field.SetItalic( (style & 1 ) != 0 ); field.SetBold( (style & 2 ) != 0 ); - wxPoint pos( ReturnValueFromString( g_UserUnit, posXTextCtrl->GetValue() ), - ReturnValueFromString( g_UserUnit, posYTextCtrl->GetValue() ) ); + wxPoint pos( ValueFromString( g_UserUnit, posXTextCtrl->GetValue() ), + ValueFromString( g_UserUnit, posYTextCtrl->GetValue() ) ); // Note: the Y axis for components in lib is from bottom to top // and the screen axis is top to bottom: we must change the y coord sign for editing diff --git a/eeschema/dialogs/dialog_edit_one_field.cpp b/eeschema/dialogs/dialog_edit_one_field.cpp index af48030656..055eb77aa1 100644 --- a/eeschema/dialogs/dialog_edit_one_field.cpp +++ b/eeschema/dialogs/dialog_edit_one_field.cpp @@ -53,7 +53,7 @@ void DIALOG_EDIT_ONE_FIELD::initDlg_base() m_CommonConvert->Show(false); m_CommonUnit->Show(false); - msg = ReturnStringFromValue( g_UserUnit, m_textsize ); + msg = StringFromValue( g_UserUnit, m_textsize ); m_TextSize->SetValue( msg ); if( m_textorient == TEXT_ORIENT_VERT ) @@ -132,7 +132,7 @@ void DIALOG_EDIT_ONE_FIELD::TransfertDataToField() { m_textorient = m_Orient->GetValue() ? TEXT_ORIENT_VERT : TEXT_ORIENT_HORIZ; wxString msg = m_TextSize->GetValue(); - m_textsize = ReturnValueFromString( g_UserUnit, msg ); + m_textsize = ValueFromString( g_UserUnit, msg ); switch( m_TextHJustificationOpt->GetSelection() ) { diff --git a/eeschema/dialogs/dialog_eeschema_config.cpp b/eeschema/dialogs/dialog_eeschema_config.cpp index b3f9284067..f4f01e4043 100644 --- a/eeschema/dialogs/dialog_eeschema_config.cpp +++ b/eeschema/dialogs/dialog_eeschema_config.cpp @@ -27,10 +27,12 @@ */ #include -#include +#include +#include #include #include #include +#include #include #include @@ -40,20 +42,50 @@ #include -#include + +#include + +class SCH_EDIT_FRAME; +class EDA_DRAW_FRAME; + +class DIALOG_EESCHEMA_CONFIG : public DIALOG_EESCHEMA_CONFIG_FBP +{ +public: + DIALOG_EESCHEMA_CONFIG( SCH_EDIT_FRAME* parent, wxFrame* activeWindow ); + +private: + SCH_EDIT_FRAME* m_Parent; + bool m_LibListChanged; + bool m_LibPathChanged; + wxString m_UserLibDirBufferImg; // Copy of original g_UserLibDirBuffer + + + // event handlers, overiding the fbp handlers + void Init(); + void OnCloseWindow( wxCloseEvent& event ); + void OnRemoveLibClick( wxCommandEvent& event ); + void OnAddOrInsertLibClick( wxCommandEvent& event ); + void OnAddOrInsertPath( wxCommandEvent& event ); + void OnOkClick( wxCommandEvent& event ); + void OnCancelClick( wxCommandEvent& event ); + void OnRemoveUserPath( wxCommandEvent& event ); + void OnButtonUpClick( wxCommandEvent& event ); + void OnButtonDownClick( wxCommandEvent& event ); +}; DIALOG_EESCHEMA_CONFIG::DIALOG_EESCHEMA_CONFIG( SCH_EDIT_FRAME* aSchFrame, - EDA_DRAW_FRAME* aParent ) - : DIALOG_EESCHEMA_CONFIG_FBP( aParent ) + wxFrame* aParent ) : + DIALOG_EESCHEMA_CONFIG_FBP( aParent ) { - wxString msg; - m_Parent = aSchFrame; Init(); - msg.Printf( _( "from <%s>" ), GetChars( wxGetApp().GetCurrentOptionFile() ) ); + wxString msg = wxString::Format( + _( "from '%s'" ), + GetChars( Prj().GetProjectFullName() ) ); + SetTitle( msg ); if( GetSizer() ) @@ -74,21 +106,22 @@ void DIALOG_EESCHEMA_CONFIG::Init() m_ListLibr->InsertItems( m_Parent->GetComponentLibraries(), 0 ); // Load user libs paths: - wxStringTokenizer Token( m_UserLibDirBufferImg, wxT( ";\n\r" ) ); - while( Token.HasMoreTokens() ) + wxStringTokenizer tokenizer( m_UserLibDirBufferImg, wxT( ";\n\r" ) ); + + while( tokenizer.HasMoreTokens() ) { - wxString path = Token.GetNextToken(); + wxString path = tokenizer.GetNextToken(); if( wxFileName::DirExists( path ) ) m_listUserPaths->Append( path ); } // Display actual libraries paths: - wxPathList libpaths = wxGetApp().GetLibraryPathList(); + SEARCH_STACK& libpaths = Prj().SchSearchS(); for( unsigned ii = 0; ii < libpaths.GetCount(); ii++ ) { - m_DefaultLibraryPathslistBox->Append( libpaths[ii]); + m_DefaultLibraryPathslistBox->Append( libpaths[ii] ); } // select the first path after the current path project @@ -153,7 +186,7 @@ void DIALOG_EESCHEMA_CONFIG::OnButtonDownClick( wxCommandEvent& event ) EXCHG( libnames[jj], libnames[jj+1]); } - m_ListLibr->Set(libnames); + m_ListLibr->Set( libnames ); // Reselect previously selected names for( size_t ii = 0; ii < selections.GetCount(); ii++ ) @@ -168,13 +201,15 @@ void DIALOG_EESCHEMA_CONFIG::OnButtonDownClick( wxCommandEvent& event ) void DIALOG_EESCHEMA_CONFIG::OnCancelClick( wxCommandEvent& event ) { - // Recreate the user lib path - if ( m_LibPathChanged ) - { - for ( unsigned ii = 0; ii < m_ListLibr->GetCount(); ii++ ) - wxGetApp().RemoveLibraryPath( m_listUserPaths->GetString(ii) ); + SEARCH_STACK& lib_search = Prj().SchSearchS(); - wxGetApp().InsertLibraryPath( m_Parent->GetUserLibraryPath(), 1); + // Recreate the user lib path + if( m_LibPathChanged ) + { + for( unsigned ii = 0; ii < m_ListLibr->GetCount(); ii++ ) + lib_search.RemovePaths( m_listUserPaths->GetString(ii) ); + + lib_search.AddPaths( m_Parent->GetUserLibraryPath(), 1 ); } EndModal( wxID_CANCEL ); @@ -184,13 +219,13 @@ void DIALOG_EESCHEMA_CONFIG::OnCancelClick( wxCommandEvent& event ) void DIALOG_EESCHEMA_CONFIG::OnOkClick( wxCommandEvent& event ) { // Recreate the user lib path - if ( m_LibPathChanged ) + if( m_LibPathChanged ) { wxString path; - for ( unsigned ii = 0; ii < m_listUserPaths->GetCount(); ii++ ) + for( unsigned ii = 0; ii < m_listUserPaths->GetCount(); ii++ ) { - if ( ii > 0 ) + if( ii > 0 ) path << wxT( ";" ); path << m_listUserPaths->GetString( ii ); @@ -206,7 +241,7 @@ void DIALOG_EESCHEMA_CONFIG::OnOkClick( wxCommandEvent& event ) { wxArrayString list; - for ( unsigned ii = 0; ii < m_ListLibr->GetCount(); ii ++ ) + for( unsigned ii = 0; ii < m_ListLibr->GetCount(); ii ++ ) list.Add( m_ListLibr->GetString( ii ) ); // Recreate lib list @@ -268,10 +303,13 @@ void DIALOG_EESCHEMA_CONFIG::OnRemoveLibClick( wxCommandEvent& event ) */ void DIALOG_EESCHEMA_CONFIG::OnAddOrInsertLibClick( wxCommandEvent& event ) { - int ii; - wxString libfilename; - wxFileName fn; - wxArrayInt selections; + int ii; + wxString libfilename; + wxFileName fn; + wxArrayInt selections; + + PROJECT& prj = Prj(); + SEARCH_STACK& search = prj.SchSearchS(); m_ListLibr->GetSelections( selections ); @@ -282,28 +320,28 @@ void DIALOG_EESCHEMA_CONFIG::OnAddOrInsertLibClick( wxCommandEvent& event ) else ii = 0; - wxString libpath; - libpath = m_DefaultLibraryPathslistBox->GetStringSelection(); + wxString libpath = m_DefaultLibraryPathslistBox->GetStringSelection(); - if ( libpath.IsEmpty() ) - libpath = wxGetApp().ReturnLastVisitedLibraryPath(); + if( libpath.IsEmpty() ) + libpath = prj.RPath(PROJECT::SCH_LIB).LastVisitedPath( search ); - wxFileDialog FilesDialog( this, _( "Library files:" ), libpath, + wxFileDialog filesDialog( this, _( "Library files:" ), libpath, wxEmptyString, SchematicLibraryFileWildcard, wxFD_DEFAULT_STYLE | wxFD_MULTIPLE ); - if( FilesDialog.ShowModal() != wxID_OK ) + if( filesDialog.ShowModal() != wxID_OK ) return; - wxArrayString Filenames; - FilesDialog.GetPaths( Filenames ); + wxArrayString filenames; - for( unsigned jj = 0; jj < Filenames.GetCount(); jj++ ) + filesDialog.GetPaths( filenames ); + + for( unsigned jj = 0; jj < filenames.GetCount(); jj++ ) { - fn = Filenames[jj]; + fn = filenames[jj]; - if ( jj == 0 ) - wxGetApp().SaveLastVisitedLibraryPath( fn.GetPath() ); + if( jj == 0 ) + prj.RPath(PROJECT::SCH_LIB).SaveLastVisitedPath( fn.GetPath() ); /* If the library path is already in the library search paths * list, just add the library name to the list. Otherwise, add @@ -312,14 +350,14 @@ void DIALOG_EESCHEMA_CONFIG::OnAddOrInsertLibClick( wxCommandEvent& event ) * because it preserve use of default libraries paths, when the path * is a sub path of these default paths */ - libfilename = wxGetApp().ReturnFilenameWithRelativePathInLibPath( fn.GetFullPath() ); + libfilename = search.FilenameWithRelativePathInSearchList( fn.GetFullPath() ); // Remove extension: fn = libfilename; - fn.SetExt(wxEmptyString); + fn.SetExt( wxEmptyString ); libfilename = fn.GetFullPath(); - //Add or insert new library name, if not already in list + // Add or insert new library name, if not already in list if( m_ListLibr->FindString( libfilename, fn.IsCaseSensitive() ) == wxNOT_FOUND ) { m_LibListChanged = true; @@ -342,7 +380,9 @@ void DIALOG_EESCHEMA_CONFIG::OnAddOrInsertLibClick( wxCommandEvent& event ) void DIALOG_EESCHEMA_CONFIG::OnAddOrInsertPath( wxCommandEvent& event ) { - wxString path = wxGetApp().ReturnLastVisitedLibraryPath(); + PROJECT& prj = Prj(); + SEARCH_STACK& search = Prj().SchSearchS(); + wxString path = prj.RPath(PROJECT::SCH_LIB).LastVisitedPath( search ); bool select = EDA_DirectorySelector( _( "Default Path for Libraries" ), path, wxDD_DEFAULT_STYLE, @@ -359,14 +399,14 @@ void DIALOG_EESCHEMA_CONFIG::OnAddOrInsertPath( wxCommandEvent& event ) { int ipos = m_listUserPaths->GetCount(); - if ( event.GetId() == wxID_INSERT_PATH ) + if( event.GetId() == wxID_INSERT_PATH ) { - if ( ipos ) + if( ipos ) ipos--; int jj = m_listUserPaths->GetSelection(); - if ( jj >= 0 ) + if( jj >= 0 ) ipos = jj; } @@ -375,7 +415,8 @@ void DIALOG_EESCHEMA_CONFIG::OnAddOrInsertPath( wxCommandEvent& event ) wxYES_NO | wxICON_QUESTION, this ); if( diag == wxYES ) - { // Make it relative + { + // Make it relative wxFileName fn = path; fn.MakeRelativeTo( wxT(".") ); path = fn.GetPathWithSep() + fn.GetFullName(); @@ -383,15 +424,15 @@ void DIALOG_EESCHEMA_CONFIG::OnAddOrInsertPath( wxCommandEvent& event ) m_listUserPaths->Insert(path, ipos); m_LibPathChanged = true; - wxGetApp().InsertLibraryPath( path, ipos+1 ); + + search.AddPaths( path, ipos+1 ); // Display actual libraries paths: - wxPathList libpaths = wxGetApp().GetLibraryPathList(); m_DefaultLibraryPathslistBox->Clear(); - for( unsigned ii = 0; ii < libpaths.GetCount(); ii++ ) + for( unsigned ii = 0; ii < search.GetCount(); ii++ ) { - m_DefaultLibraryPathslistBox->Append( libpaths[ii]); + m_DefaultLibraryPathslistBox->Append( search[ii] ); } } else @@ -399,30 +440,42 @@ void DIALOG_EESCHEMA_CONFIG::OnAddOrInsertPath( wxCommandEvent& event ) DisplayError( this, _("Path already in use") ); } - wxGetApp().SaveLastVisitedLibraryPath( path ); + prj.RPath(PROJECT::SCH_LIB).SaveLastVisitedPath( path ); } void DIALOG_EESCHEMA_CONFIG::OnRemoveUserPath( wxCommandEvent& event ) { + SEARCH_STACK& lib_search = Prj().SchSearchS(); + int ii = m_listUserPaths->GetSelection(); - if ( ii < 0 ) + if( ii < 0 ) ii = m_listUserPaths->GetCount()-1; - if ( ii >= 0 ) + if( ii >= 0 ) { - wxGetApp().RemoveLibraryPath( m_listUserPaths->GetStringSelection() ); + lib_search.RemovePaths( m_listUserPaths->GetStringSelection() ); + m_listUserPaths->Delete( ii ); m_LibPathChanged = true; } // Display actual libraries paths: - wxPathList libpaths = wxGetApp().GetLibraryPathList(); m_DefaultLibraryPathslistBox->Clear(); - for( unsigned ii = 0; ii < libpaths.GetCount(); ii++ ) + for( unsigned ii = 0; ii < lib_search.GetCount(); ii++ ) { - m_DefaultLibraryPathslistBox->Append( libpaths[ii] ); + m_DefaultLibraryPathslistBox->Append( lib_search[ii] ); } } + + +int InvokeEeschemaConfig( SCH_EDIT_FRAME* aEditFrame, wxFrame* aParent ) +{ + DIALOG_EESCHEMA_CONFIG dlg( aEditFrame, aParent ); + + dlg.ShowModal(); + + return 1; +} diff --git a/eeschema/dialogs/dialog_eeschema_config.h b/eeschema/dialogs/dialog_eeschema_config.h deleted file mode 100644 index 32bc536d9d..0000000000 --- a/eeschema/dialogs/dialog_eeschema_config.h +++ /dev/null @@ -1,42 +0,0 @@ - -#ifndef _DIALOG_EESCHEMA_CONFIG_H_ -#define _DIALOG_EESCHEMA_CONFIG_H_ - - -#include - - -class SCH_EDIT_FRAME; -class EDA_DRAW_FRAME; - - -class DIALOG_EESCHEMA_CONFIG : public DIALOG_EESCHEMA_CONFIG_FBP -{ -private: - SCH_EDIT_FRAME* m_Parent; - bool m_LibListChanged; - bool m_LibPathChanged; - wxString m_UserLibDirBufferImg; // Copy of original g_UserLibDirBuffer - -private: - - // event handlers, overiding the fbp handlers - void Init(); - void OnCloseWindow( wxCloseEvent& event ); - void OnRemoveLibClick( wxCommandEvent& event ); - void OnAddOrInsertLibClick( wxCommandEvent& event ); - void OnAddOrInsertPath( wxCommandEvent& event ); - void OnOkClick( wxCommandEvent& event ); - void OnCancelClick( wxCommandEvent& event ); - void OnRemoveUserPath( wxCommandEvent& event ); - void OnButtonUpClick( wxCommandEvent& event ); - void OnButtonDownClick( wxCommandEvent& event ); - - -public: - DIALOG_EESCHEMA_CONFIG( SCH_EDIT_FRAME* parent, EDA_DRAW_FRAME* activeWindow ); - ~DIALOG_EESCHEMA_CONFIG() {}; -}; - - -#endif // _DIALOG_EESCHEMA_CONFIG_H_ diff --git a/eeschema/dialogs/dialog_eeschema_config_fbp.cpp b/eeschema/dialogs/dialog_eeschema_config_fbp.cpp index 6ef268f328..99297fb844 100644 --- a/eeschema/dialogs/dialog_eeschema_config_fbp.cpp +++ b/eeschema/dialogs/dialog_eeschema_config_fbp.cpp @@ -1,5 +1,5 @@ /////////////////////////////////////////////////////////////////////////// -// C++ code generated with wxFormBuilder (version Oct 8 2012) +// C++ code generated with wxFormBuilder (version Nov 5 2013) // http://www.wxformbuilder.org/ // // PLEASE DO "NOT" EDIT THIS FILE! @@ -9,7 +9,7 @@ /////////////////////////////////////////////////////////////////////////// -DIALOG_EESCHEMA_CONFIG_FBP::DIALOG_EESCHEMA_CONFIG_FBP( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) +DIALOG_EESCHEMA_CONFIG_FBP::DIALOG_EESCHEMA_CONFIG_FBP( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : DIALOG_SHIM( parent, id, title, pos, size, style ) { this->SetSizeHints( wxDefaultSize, wxDefaultSize ); diff --git a/eeschema/dialogs/dialog_eeschema_config_fbp.fbp b/eeschema/dialogs/dialog_eeschema_config_fbp.fbp index 0e7f0d960f..2062d5e43c 100644 --- a/eeschema/dialogs/dialog_eeschema_config_fbp.fbp +++ b/eeschema/dialogs/dialog_eeschema_config_fbp.fbp @@ -20,8 +20,10 @@ . 1 + 1 1 1 + UI 1 0 @@ -44,7 +46,7 @@ -1,-1 wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER - + DIALOG_SHIM; dialog_shim.h diff --git a/eeschema/dialogs/dialog_eeschema_config_fbp.h b/eeschema/dialogs/dialog_eeschema_config_fbp.h index d0b91eeb14..84b86341c4 100644 --- a/eeschema/dialogs/dialog_eeschema_config_fbp.h +++ b/eeschema/dialogs/dialog_eeschema_config_fbp.h @@ -1,5 +1,5 @@ /////////////////////////////////////////////////////////////////////////// -// C++ code generated with wxFormBuilder (version Oct 8 2012) +// C++ code generated with wxFormBuilder (version Nov 5 2013) // http://www.wxformbuilder.org/ // // PLEASE DO "NOT" EDIT THIS FILE! @@ -11,6 +11,9 @@ #include #include #include +class DIALOG_SHIM; + +#include "dialog_shim.h" #include #include #include @@ -28,7 +31,7 @@ /////////////////////////////////////////////////////////////////////////////// /// Class DIALOG_EESCHEMA_CONFIG_FBP /////////////////////////////////////////////////////////////////////////////// -class DIALOG_EESCHEMA_CONFIG_FBP : public wxDialog +class DIALOG_EESCHEMA_CONFIG_FBP : public DIALOG_SHIM { private: diff --git a/eeschema/dialogs/dialog_erc.cpp b/eeschema/dialogs/dialog_erc.cpp index 03a6630236..9e4bf1aae4 100644 --- a/eeschema/dialogs/dialog_erc.cpp +++ b/eeschema/dialogs/dialog_erc.cpp @@ -32,7 +32,7 @@ #include #include #include -#include +#include #include #include #include @@ -562,7 +562,7 @@ void DIALOG_ERC::TestErc( wxArrayString* aMessagesList ) if( WriteDiagnosticERC( dlg.GetPath() ) ) { Close( true ); - ExecuteFile( this, wxGetApp().GetEditorName(), QuoteFullPath( fn ) ); + ExecuteFile( this, Pgm().GetEditorName(), QuoteFullPath( fn ) ); } } } diff --git a/eeschema/dialogs/dialog_lib_edit_pin.cpp b/eeschema/dialogs/dialog_lib_edit_pin.cpp index 245ebd628b..7f3307ad83 100644 --- a/eeschema/dialogs/dialog_lib_edit_pin.cpp +++ b/eeschema/dialogs/dialog_lib_edit_pin.cpp @@ -94,10 +94,10 @@ void DIALOG_LIB_EDIT_PIN::OnPropertiesChange( wxCommandEvent& event ) if( ! IsShown() ) // do nothing at init time return; - int pinNameSize = ReturnValueFromString( g_UserUnit, GetNameTextSize() ); - int pinNumSize = ReturnValueFromString( g_UserUnit, GetPadNameTextSize()); + int pinNameSize = ValueFromString( g_UserUnit, GetNameTextSize() ); + int pinNumSize = ValueFromString( g_UserUnit, GetPadNameTextSize()); int pinOrient = LIB_PIN::GetOrientationCode( GetOrientation() ); - int pinLength = ReturnValueFromString( g_UserUnit, GetLength() ); + int pinLength = ValueFromString( g_UserUnit, GetLength() ); int pinShape = LIB_PIN::GetStyleCode( GetStyle() ); int pinType = GetElectricalType(); diff --git a/eeschema/dialogs/dialog_lib_edit_text.cpp b/eeschema/dialogs/dialog_lib_edit_text.cpp index 674b5cf820..6530175407 100644 --- a/eeschema/dialogs/dialog_lib_edit_text.cpp +++ b/eeschema/dialogs/dialog_lib_edit_text.cpp @@ -64,7 +64,7 @@ void DIALOG_LIB_EDIT_TEXT::initDlg( ) if ( m_graphicText ) { - msg = ReturnStringFromValue( g_UserUnit, m_graphicText->GetSize().x ); + msg = StringFromValue( g_UserUnit, m_graphicText->GetSize().x ); m_TextSize->SetValue( msg ); m_TextValue->SetValue( m_graphicText->GetText() ); @@ -116,7 +116,7 @@ void DIALOG_LIB_EDIT_TEXT::initDlg( ) } else { - msg = ReturnStringFromValue( g_UserUnit, m_parent->m_textSize ); + msg = StringFromValue( g_UserUnit, m_parent->m_textSize ); m_TextSize->SetValue( msg ); if ( ! m_parent->m_drawSpecificUnit ) @@ -148,7 +148,7 @@ void DIALOG_LIB_EDIT_TEXT::OnOkClick( wxCommandEvent& event ) Line = m_TextValue->GetValue(); m_parent->m_textOrientation = m_Orient->GetValue() ? TEXT_ORIENT_VERT : TEXT_ORIENT_HORIZ; wxString msg = m_TextSize->GetValue(); - m_parent->m_textSize = ReturnValueFromString( g_UserUnit, msg ); + m_parent->m_textSize = ValueFromString( g_UserUnit, msg ); m_parent->m_drawSpecificConvert = m_CommonConvert->GetValue() ? false : true; m_parent->m_drawSpecificUnit = m_CommonUnit->GetValue() ? false : true; diff --git a/eeschema/dialogs/dialog_netlist.cpp b/eeschema/dialogs/dialog_netlist.cpp index 8266c2d0c8..90a6babe90 100644 --- a/eeschema/dialogs/dialog_netlist.cpp +++ b/eeschema/dialogs/dialog_netlist.cpp @@ -39,7 +39,8 @@ */ #include -#include +#include +#include #include #include #include @@ -123,7 +124,7 @@ public: NETLIST_PAGE_DIALOG* m_PanelNetType[4 + CUSTOMPANEL_COUNTMAX]; private: - wxConfig* m_config; + wxConfigBase* m_config; public: @@ -169,17 +170,17 @@ private: } /** - * Function ReturnUserNetlistTypeName + * Function UserNetlistTypeName * to retrieve user netlist type names * @param first_item = true: return first name of the list, false = return next * @return a wxString : name of the type netlist or empty string * this function must be called first with "first_item" = true * and after with "first_item" = false to get all the other existing netlist names */ - const wxString ReturnUserNetlistTypeName( bool first_item ); + const wxString UserNetlistTypeName( bool first_item ); /** - * Function ReturnFilenamePrms + * Function FilenamePrms * returns the filename extension and the wildcard string for this curr * or a void name if there is no default name * @param aNetTypeId = the netlist type ( NET_TYPE_PCBNEW ... ) @@ -187,7 +188,7 @@ private: * @param aWildCard = reference to a wxString to return the default wildcard. * @return true for known netlist type, false for custom formats */ - bool ReturnFilenamePrms( NETLIST_TYPE_ID aNetTypeId, + bool FilenamePrms( NETLIST_TYPE_ID aNetTypeId, wxString * aExt, wxString * aWildCard ); DECLARE_EVENT_TABLE() @@ -347,7 +348,7 @@ NETLIST_DIALOG::NETLIST_DIALOG( SCH_EDIT_FRAME* parent ) : NETLIST_DIALOG_BASE( parent ) { m_Parent = parent; - m_config = wxGetApp().GetSettings(); + m_config = Kiface().KifaceSettings(); long tmp; m_config->Read( NETLIST_USE_DEFAULT_NETNAME, &tmp, 0l ); @@ -388,7 +389,7 @@ NETLIST_DIALOG::NETLIST_DIALOG( SCH_EDIT_FRAME* parent ) : } -const wxString NETLIST_DIALOG::ReturnUserNetlistTypeName( bool first_item ) +const wxString NETLIST_DIALOG::UserNetlistTypeName( bool first_item ) { static int index; wxString name, msg; @@ -448,7 +449,7 @@ void NETLIST_DIALOG::InstallCustomPages() for( ii = 0; ii < CUSTOMPANEL_COUNTMAX; ii++ ) { - title = ReturnUserNetlistTypeName( ii == 0 ? true : false ); + title = UserNetlistTypeName( ii == 0 ? true : false ); if( title.IsEmpty() ) break; // No more panel to install @@ -532,7 +533,7 @@ void NETLIST_DIALOG::OnNetlistTypeSelection( wxNotebookEvent& event ) m_cbUseDefaultNetlistName->Enable( currPage->m_IdNetType < NET_TYPE_CUSTOM1 ); wxString fileExt; - if( ReturnFilenamePrms( currPage->m_IdNetType, &fileExt, NULL ) ) + if( FilenamePrms( currPage->m_IdNetType, &fileExt, NULL ) ) { wxFileName fn = g_RootSheet->GetScreen()->GetFileName(); fn.SetExt( fileExt ); @@ -591,7 +592,7 @@ void NETLIST_DIALOG::GenNetlist( wxCommandEvent& event ) // Calculate the netlist filename fn = g_RootSheet->GetScreen()->GetFileName(); - ReturnFilenamePrms( currPage->m_IdNetType, &fileExt, &fileWildcard ); + FilenamePrms( currPage->m_IdNetType, &fileExt, &fileWildcard ); // Set some parameters switch( currPage->m_IdNetType ) @@ -653,7 +654,7 @@ void NETLIST_DIALOG::GenNetlist( wxCommandEvent& event ) } -bool NETLIST_DIALOG::ReturnFilenamePrms( NETLIST_TYPE_ID aNetTypeId, +bool NETLIST_DIALOG::FilenamePrms( NETLIST_TYPE_ID aNetTypeId, wxString * aExt, wxString * aWildCard ) { wxString fileExt; @@ -913,7 +914,7 @@ void NETLIST_DIALOG_ADD_PLUGIN::OnBrowsePlugins( wxCommandEvent& event ) wxString FullFileName, Mask, Path; Mask = wxT( "*" ); - Path = wxGetApp().GetExecutablePath(); + Path = Pgm().GetExecutablePath(); FullFileName = EDA_FileSelector( _( "Plugin files:" ), Path, FullFileName, diff --git a/eeschema/dialogs/dialog_plot_schematic.cpp b/eeschema/dialogs/dialog_plot_schematic.cpp index 1b175b625d..9390e6d6e1 100644 --- a/eeschema/dialogs/dialog_plot_schematic.cpp +++ b/eeschema/dialogs/dialog_plot_schematic.cpp @@ -29,7 +29,8 @@ */ #include -#include +#include +#include #include #include #include @@ -63,7 +64,7 @@ DIALOG_PLOT_SCHEMATIC::DIALOG_PLOT_SCHEMATIC( SCH_EDIT_FRAME* parent ) : DIALOG_PLOT_SCHEMATIC_BASE( parent ) { m_parent = parent; - m_config = wxGetApp().GetSettings(); + m_config = Kiface().KifaceSettings(); initDlg(); @@ -177,7 +178,7 @@ void DIALOG_PLOT_SCHEMATIC::getPlotOptions() m_config->Write( PLOT_HPGL_PEN_SIZE_KEY, m_HPGLPenSize/IU_PER_MM ); m_pageSizeSelect = m_PaperSizeOption->GetSelection(); - SetDefaultLineThickness( ReturnValueFromTextCtrl( *m_DefaultLineSizeCtrl ) ); + SetDefaultLineThickness( ValueFromTextCtrl( *m_DefaultLineSizeCtrl ) ); } diff --git a/eeschema/dialogs/dialog_plot_schematic.h b/eeschema/dialogs/dialog_plot_schematic.h index baa03bd4d1..df547ffbe6 100644 --- a/eeschema/dialogs/dialog_plot_schematic.h +++ b/eeschema/dialogs/dialog_plot_schematic.h @@ -46,7 +46,7 @@ class DIALOG_PLOT_SCHEMATIC : public DIALOG_PLOT_SCHEMATIC_BASE { private: SCH_EDIT_FRAME* m_parent; - wxConfig* m_config; + wxConfigBase* m_config; static int m_pageSizeSelect; // Static to keep last option for some format: // Static to keep last option: // use default size or force A or A4 size @@ -58,10 +58,10 @@ public: DIALOG_PLOT_SCHEMATIC( SCH_EDIT_FRAME* parent ); private: - void OnPlotFormatSelection( wxCommandEvent& event ); - void OnButtonPlotCurrentClick( wxCommandEvent& event ); - void OnButtonPlotAllClick( wxCommandEvent& event ); - void OnButtonCancelClick( wxCommandEvent& event ); + void OnPlotFormatSelection( wxCommandEvent& event ); + void OnButtonPlotCurrentClick( wxCommandEvent& event ); + void OnButtonPlotAllClick( wxCommandEvent& event ); + void OnButtonCancelClick( wxCommandEvent& event ); void initDlg(); diff --git a/eeschema/dialogs/dialog_print_using_printer.cpp b/eeschema/dialogs/dialog_print_using_printer.cpp index cd6548c2ca..15fbdc8055 100644 --- a/eeschema/dialogs/dialog_print_using_printer.cpp +++ b/eeschema/dialogs/dialog_print_using_printer.cpp @@ -3,7 +3,7 @@ /****************************************/ #include -#include +#include #include #include #include diff --git a/eeschema/eelibs_read_libraryfiles.cpp b/eeschema/eelibs_read_libraryfiles.cpp index 5d623767ed..8eaaafd8de 100644 --- a/eeschema/eelibs_read_libraryfiles.cpp +++ b/eeschema/eelibs_read_libraryfiles.cpp @@ -4,9 +4,10 @@ */ #include +#include #include #include -#include +#include #include #include @@ -16,18 +17,23 @@ #include -void SCH_EDIT_FRAME::LoadLibraries( void ) +void SCH_EDIT_FRAME::LoadLibraries() { - size_t ii; - wxFileName fn; - wxString msg, tmp, errMsg; - wxString libraries_not_found; - wxArrayString sortOrder; + size_t ii; + wxFileName fn; + wxString msg, tmp, errMsg; + wxString libraries_not_found; + wxArrayString sortOrder; + SEARCH_STACK& lib_search = Prj().SchSearchS(); + +#if defined(DEBUG) && 1 + lib_search.Show( __func__ ); +#endif CMP_LIBRARY_LIST::iterator i = CMP_LIBRARY::GetLibraryList().begin(); - /* Free the unwanted libraries but keep the cache library. */ - while ( i < CMP_LIBRARY::GetLibraryList().end() ) + // Free the unwanted libraries but keep the cache library. + while( i < CMP_LIBRARY::GetLibraryList().end() ) { if( i->IsCache() ) { @@ -35,26 +41,28 @@ void SCH_EDIT_FRAME::LoadLibraries( void ) continue; } + DBG(printf( "ll:%s\n", TO_UTF8( i->GetName() ) );) + if( m_componentLibFiles.Index( i->GetName(), false ) == wxNOT_FOUND ) i = CMP_LIBRARY::GetLibraryList().erase( i ); else i++; } - /* Load missing libraries. */ + // Load missing libraries. for( ii = 0; ii < m_componentLibFiles.GetCount(); ii++ ) { fn.Clear(); fn.SetName( m_componentLibFiles[ii] ); fn.SetExt( SchematicLibraryFileExtension ); - /* Skip if the file name is not valid.. */ + // Skip if the file name is not valid.. if( !fn.IsOk() ) continue; if( !fn.FileExists() ) { - tmp = wxGetApp().FindLibraryPath( fn ); + tmp = lib_search.FindValidPath( fn ); if( !tmp ) { @@ -72,24 +80,24 @@ void SCH_EDIT_FRAME::LoadLibraries( void ) if( CMP_LIBRARY::AddLibrary( fn, errMsg ) ) { - msg.Printf( _( "Library <%s> loaded" ), GetChars( tmp ) ); + msg.Printf( _( "Library '%s' loaded" ), GetChars( tmp ) ); sortOrder.Add( fn.GetName() ); } else { wxString prompt; - prompt.Printf( _( "Component library <%s> failed to load.\nError: %s" ), + prompt.Printf( _( "Component library '%s' failed to load.\nError: %s" ), GetChars( fn.GetFullPath() ), GetChars( errMsg ) ); DisplayError( this, prompt ); - msg.Printf( _( "Library <%s> error!" ), GetChars( tmp ) ); + msg.Printf( _( "Library '%s' error!" ), GetChars( tmp ) ); } PrintMsg( msg ); } - /* Print the libraries not found */ + // Print the libraries not found if( !libraries_not_found.IsEmpty() ) { HTML_MESSAGE_BOX dialog( this, _("Files not found") ); @@ -99,11 +107,11 @@ void SCH_EDIT_FRAME::LoadLibraries( void ) dialog.ShowModal(); } - /* Put the libraries in the correct order. */ + // Put the libraries in the correct order. CMP_LIBRARY::SetSortOrder( sortOrder ); CMP_LIBRARY::GetLibraryList().sort(); -#if 0 // #ifdef __WXDEBUG__ +#if 0 && defined(__WXDEBUG__) wxLogDebug( wxT( "LoadLibraries() requested component library sort order:" ) ); for( size_t i = 0; i < sortOrder.GetCount(); i++ ) @@ -118,3 +126,4 @@ void SCH_EDIT_FRAME::LoadLibraries( void ) wxLogDebug( wxT( "end LoadLibraries ()" ) ); #endif } + diff --git a/eeschema/eeschema.cpp b/eeschema/eeschema.cpp index 7b1d86cd90..c7e72dd048 100644 --- a/eeschema/eeschema.cpp +++ b/eeschema/eeschema.cpp @@ -29,12 +29,13 @@ */ #include -#include +#include +#include #include -#include #include #include #include +#include #include #include @@ -45,23 +46,65 @@ #include #include -#include - - -#if defined( USE_KIWAY_DLLS ) - #include -#include -static struct SCH_FACE : public KIFACE + +// Global variables +wxSize g_RepeatStep; +int g_RepeatDeltaLabel; +int g_DefaultBusWidth; +SCH_SHEET* g_RootSheet = NULL; + +TRANSFORM DefaultTransform = TRANSFORM( 1, 0, 0, -1 ); + + +namespace SCH { + +static struct IFACE : public KIFACE_I { - wxWindow* CreateWindow( int aClassId, KIWAY* aKIWAY, int aCtlBits = 0 ) + // Of course all are virtual overloads, implementations of the KIFACE. + + IFACE( const char* aName, KIWAY::FACE_T aType ) : + KIFACE_I( aName, aType ) + {} + + bool OnKifaceStart( PGM_BASE* aProgram ); + + void OnKifaceEnd( PGM_BASE* aProgram ) + { + end_common(); + } + + wxWindow* CreateWindow( wxWindow* aParent, int aClassId, KIWAY* aKiway, int aCtlBits = 0 ) { switch( aClassId ) { + case LIBEDITOR_FRAME_TYPE: + { + LIB_EDIT_FRAME* frame = new LIB_EDIT_FRAME( aKiway, + dynamic_cast( aParent ) ); + return frame; + } + break; + + case SCHEMATIC_FRAME_TYPE: + { + SCH_EDIT_FRAME* frame = new SCH_EDIT_FRAME( aKiway, aParent ); + + frame->Zoom_Automatique( true ); + + // Read a default config file in case no project given on command line. + frame->LoadProjectFile( wxEmptyString, true ); + + // @todo temporary + CreateServer( frame, KICAD_SCH_PORT_SERVICE_NUMBER ); + + return frame; + } + break; + default: - return new SCH_EDIT_FRAME( NULL, wxT( "Eeschema" ), - wxPoint( 0, 0 ), wxSize( 600, 400 ) ); + return NULL; } } @@ -81,139 +124,51 @@ static struct SCH_FACE : public KIFACE return NULL; } -} kiface; +} kiface( "eeschema", KIWAY::FACE_SCH ); + +} // namespace + +using namespace SCH; + +static PGM_BASE* process; + + +KIFACE_I& Kiface() { return kiface; } -static EDA_APP* process; // KIFACE_GETTER's actual spelling is a substitution macro found in kiway.h. // KIFACE_GETTER will not have name mangling due to declaration in kiway.h. -MY_API( KIFACE* ) KIFACE_GETTER( int* aKIFACEversion, int aKIWAYversion, wxApp* aProcess ) +MY_API( KIFACE* ) KIFACE_GETTER( int* aKIFACEversion, int aKiwayVersion, PGM_BASE* aProgram ) { - process = (EDA_APP*) aProcess; + process = (PGM_BASE*) aProgram; return &kiface; } -EDA_APP& wxGetApp() +PGM_BASE& Pgm() { wxASSERT( process ); // KIFACE_GETTER has already been called. return *process; } -#else -// Create a new application object: this macro will allow wxWindows to create -// the application object during program execution (it's better than using a -// static object for many reasons) and also declares the accessor function -// wxGetApp() which will return the reference of the right type (i.e. MyApp and -// not wxApp) -IMPLEMENT_APP( EDA_APP ) - -#endif - - -// Global variables -wxSize g_RepeatStep; -int g_RepeatDeltaLabel; -int g_DefaultBusWidth; -SCH_SHEET* g_RootSheet = NULL; - -TRANSFORM DefaultTransform = TRANSFORM( 1, 0, 0, -1 ); - - -/************************************/ -/* Called to initialize the program */ -/************************************/ - -/* MacOSX: Needed for file association - * http://wiki.wxwidgets.org/WxMac-specific_topics - */ -void EDA_APP::MacOpenFile( const wxString& aFileName ) +bool IFACE::OnKifaceStart( PGM_BASE* aProgram ) { - wxFileName filename = aFileName; - SCH_EDIT_FRAME* frame = ((SCH_EDIT_FRAME*) GetTopWindow()); + // This is process level, not project level, initialization of the DSO. - if( !frame ) - return; + // Do nothing in here pertinent to a project! - if( !filename.FileExists() ) - return; - - frame->LoadOneEEProject( aFileName, false ); -} - - -bool EDA_APP::OnInit() -{ - wxFileName filename; - SCH_EDIT_FRAME* frame = NULL; - bool fileReady = false; - - InitEDA_Appl( wxT( "Eeschema" ), APP_EESCHEMA_T ); - - if( argc > 1 ) - filename = argv[1]; - - if( filename.IsOk() ) - { - if( filename.GetExt() != SchematicFileExtension ) - filename.SetExt( SchematicFileExtension ); - - if( !wxGetApp().LockFile( filename.GetFullPath() ) ) - { - DisplayError( NULL, _( "This file is already open." ) ); - return false; - } - - fileReady = true; - } - - if( m_Checker && m_Checker->IsAnotherRunning() ) - { - if( !IsOK( NULL, _( "Eeschema is already running, Continue?" ) ) ) - return false; - } + start_common(); // Give a default colour for all layers // (actual color will be initialized by config) for( int ii = 0; ii < NB_SCH_LAYERS; ii++ ) SetLayerColor( DARKGRAY, ii ); - // read current setup and reopen last directory if no filename to open in - // command line - bool reopenLastUsedDirectory = argc == 1; - GetSettings( reopenLastUsedDirectory ); - - /* Must be called before creating the main frame in order to - * display the real hotkeys in menus or tool tips */ + // Must be called before creating the main frame in order to + // display the real hotkeys in menus or tool tips ReadHotkeyConfig( wxT("SchematicFrame"), s_Eeschema_Hokeys_Descr ); - // Create main frame (schematic frame) : - frame = new SCH_EDIT_FRAME( NULL, wxT( "Eeschema" ), wxPoint( 0, 0 ), wxSize( 600, 400 ) ); - - SetTopWindow( frame ); - frame->Show( true ); - - CreateServer( frame, KICAD_SCH_PORT_SERVICE_NUMBER ); - - frame->Zoom_Automatique( true ); - - // Load file specified in the command line: - if( fileReady ) - { - if( !filename.GetPath().IsEmpty() ) - // wxSetWorkingDirectory does not like empty paths - wxSetWorkingDirectory( filename.GetPath() ); - - if( frame->LoadOneEEProject( filename.GetFullName(), false ) ) - frame->GetCanvas()->Refresh( true ); - } - else - { - // Read a default config file if no file to load. - frame->LoadProjectFile( wxEmptyString, true ); - frame->GetCanvas()->Refresh( true ); - } - return true; } + diff --git a/eeschema/eeschema_config.cpp b/eeschema/eeschema_config.cpp index 4449957e0b..fe8b75b635 100644 --- a/eeschema/eeschema_config.cpp +++ b/eeschema/eeschema_config.cpp @@ -26,11 +26,13 @@ */ #include -#include +#include +#include #include #include #include #include +#include #include #include @@ -44,7 +46,6 @@ #include #include -#include #include #include @@ -117,9 +118,7 @@ EDA_COLOR_T GetInvisibleItemColor() void LIB_EDIT_FRAME::InstallConfigFrame( wxCommandEvent& event ) { - DIALOG_EESCHEMA_CONFIG CfgFrame( (SCH_EDIT_FRAME *)GetParent(), this ); - - CfgFrame.ShowModal(); + InvokeEeschemaConfig( (SCH_EDIT_FRAME *)GetParent(), this ); } @@ -194,9 +193,7 @@ void SCH_EDIT_FRAME::OnColorConfig( wxCommandEvent& aEvent ) void SCH_EDIT_FRAME::InstallConfigFrame( wxCommandEvent& event ) { - DIALOG_EESCHEMA_CONFIG CfgFrame( this, this ); - - CfgFrame.ShowModal(); + InvokeEeschemaConfig( this, this ); } @@ -212,21 +209,20 @@ void SCH_EDIT_FRAME::Process_Config( wxCommandEvent& event ) break; case ID_CONFIG_READ: - { - fn = g_RootSheet->GetScreen()->GetFileName(); - fn.SetExt( ProjectFileExtension ); + { + fn = g_RootSheet->GetScreen()->GetFileName(); + fn.SetExt( ProjectFileExtension ); - wxFileDialog dlg( this, _( "Read Project File" ), fn.GetPath(), - fn.GetFullName(), ProjectFileWildcard, - wxFD_OPEN | wxFD_FILE_MUST_EXIST ); + wxFileDialog dlg( this, _( "Read Project File" ), fn.GetPath(), + fn.GetFullName(), ProjectFileWildcard, + wxFD_OPEN | wxFD_FILE_MUST_EXIST ); - if( dlg.ShowModal() == wxID_CANCEL ) - break; - - LoadProjectFile( dlg.GetPath(), true ); - } - break; + if( dlg.ShowModal() == wxID_CANCEL ) + break; + LoadProjectFile( dlg.GetPath(), true ); + } + break; // Hotkey IDs case ID_PREFERENCES_HOTKEY_EXPORT_CONFIG: @@ -396,9 +392,10 @@ PARAM_CFG_ARRAY& SCH_EDIT_FRAME::GetProjectFileParametersList() bool SCH_EDIT_FRAME::LoadProjectFile( const wxString& aFileName, bool aForceReread ) { - wxFileName fn; - bool IsRead = true; - wxArrayString liblist_tmp = m_componentLibFiles; + wxFileName fn; + bool isRead = true; + wxArrayString liblist_tmp = m_componentLibFiles; + PROJECT& prj = Prj(); if( aFileName.IsEmpty() ) fn = g_RootSheet->GetScreen()->GetFileName(); @@ -407,18 +404,15 @@ bool SCH_EDIT_FRAME::LoadProjectFile( const wxString& aFileName, bool aForceRere m_componentLibFiles.Clear(); - /* Change the schematic file extension (.sch) to the project file - * extension (.pro). */ + // Change the schematic file extension (.sch) to the project file + // extension (.pro). fn.SetExt( ProjectFileExtension ); - wxGetApp().RemoveLibraryPath( m_userLibraryPath ); - - if( !wxGetApp().ReadProjectConfig( fn.GetFullPath(), GROUP, - GetProjectFileParametersList(), - !aForceReread ) ) + if( !prj.ConfigLoad( Kiface().KifaceSearch(), fn.GetFullPath(), GROUP, + GetProjectFileParametersList(), !aForceReread ) ) { m_componentLibFiles = liblist_tmp; - IsRead = false; + isRead = false; } // Verify some values, because the config file can be edited by hand, @@ -432,28 +426,26 @@ bool SCH_EDIT_FRAME::LoadProjectFile( const wxString& aFileName, bool aForceRere WORKSHEET_LAYOUT& pglayout = WORKSHEET_LAYOUT::GetTheInstance(); pglayout.SetPageLayout(BASE_SCREEN::m_PageLayoutDescrFileName); - // Load libraries. - // User library path takes precedent over default library search paths. - wxGetApp().InsertLibraryPath( m_userLibraryPath, 1 ); + // libraries in the *.pro file take precedence over standard library search paths, + // but not over the director of the project, which is at index 0. + prj.SchSearchS().AddPaths( m_userLibraryPath, 1 ); - /* If the list is void, force loading the library "power.lib" that is - * the "standard" library for power symbols. - */ + // If the list is empty, force loading the standard power symbol library. if( m_componentLibFiles.GetCount() == 0 ) m_componentLibFiles.Add( wxT( "power" ) ); LoadLibraries(); GetScreen()->SetGrid( ID_POPUP_GRID_LEVEL_1000 + m_LastGridSizeId ); - return IsRead; + return isRead; } void SCH_EDIT_FRAME::SaveProjectSettings( bool aAskForSave ) { - wxFileName fn; + PROJECT& prj = Prj(); + wxFileName fn = g_RootSheet->GetScreen()->GetFileName(); //ConfigFileName - fn = g_RootSheet->GetScreen()->GetFileName(); //ConfigFileName fn.SetExt( ProjectFileExtension ); if( !IsWritable( fn ) ) @@ -468,37 +460,37 @@ void SCH_EDIT_FRAME::SaveProjectSettings( bool aAskForSave ) if( dlg.ShowModal() == wxID_CANCEL ) return; - wxGetApp().WriteProjectConfig( dlg.GetPath(), GROUP, - GetProjectFileParametersList() ); + fn = dlg.GetPath(); } - else - wxGetApp().WriteProjectConfig( fn.GetFullPath(), GROUP, - GetProjectFileParametersList() ); + + prj.ConfigSave( Kiface().KifaceSearch(), + fn.GetFullPath(), GROUP, GetProjectFileParametersList() ); } -static const wxString DefaultBusWidthEntry( wxT( "DefaultBusWidth" ) ); -static const wxString DefaultDrawLineWidthEntry( wxT( "DefaultDrawLineWidth" ) ); -static const wxString ShowHiddenPinsEntry( wxT( "ShowHiddenPins" ) ); -static const wxString HorzVertLinesOnlyEntry( wxT( "HorizVertLinesOnly" ) ); -static const wxString PreviewFramePositionXEntry( wxT( "PreviewFramePositionX" ) ); -static const wxString PreviewFramePositionYEntry( wxT( "PreviewFramePositionY" ) ); -static const wxString PreviewFrameWidthEntry( wxT( "PreviewFrameWidth" ) ); -static const wxString PreviewFrameHeightEntry( wxT( "PreviewFrameHeight" ) ); -static const wxString PrintDialogPositionXEntry( wxT( "PrintDialogPositionX" ) ); -static const wxString PrintDialogPositionYEntry( wxT( "PrintDialogPositionY" ) ); -static const wxString PrintDialogWidthEntry( wxT( "PrintDialogWidth" ) ); -static const wxString PrintDialogHeightEntry( wxT( "PrintDialogHeight" ) ); -static const wxString FindDialogPositionXEntry( wxT( "FindDialogPositionX" ) ); -static const wxString FindDialogPositionYEntry( wxT( "FindDialogPositionY" ) ); -static const wxString FindDialogWidthEntry( wxT( "FindDialogWidth" ) ); -static const wxString FindDialogHeightEntry( wxT( "FindDialogHeight" ) ); -static const wxString FindReplaceFlagsEntry( wxT( "LastFindReplaceFlags" ) ); -static const wxString FindStringEntry( wxT( "LastFindString" ) ); -static const wxString ReplaceStringEntry( wxT( "LastReplaceString" ) ); -static const wxString FindStringHistoryEntry( wxT( "FindStringHistoryList%d" ) ); -static const wxString ReplaceStringHistoryEntry( wxT( "ReplaceStringHistoryList%d" ) ); -static const wxString FieldNamesEntry( wxT( "FieldNames" ) ); -static const wxString SimulatorCommandEntry( wxT( "SimCmdLine" ) ); + +static const wxChar DefaultBusWidthEntry[] = wxT( "DefaultBusWidth" ); +static const wxChar DefaultDrawLineWidthEntry[] = wxT( "DefaultDrawLineWidth" ); +static const wxChar ShowHiddenPinsEntry[] = wxT( "ShowHiddenPins" ); +static const wxChar HorzVertLinesOnlyEntry[] = wxT( "HorizVertLinesOnly" ); +static const wxChar PreviewFramePositionXEntry[] = wxT( "PreviewFramePositionX" ); +static const wxChar PreviewFramePositionYEntry[] = wxT( "PreviewFramePositionY" ); +static const wxChar PreviewFrameWidthEntry[] = wxT( "PreviewFrameWidth" ); +static const wxChar PreviewFrameHeightEntry[] = wxT( "PreviewFrameHeight" ); +static const wxChar PrintDialogPositionXEntry[] = wxT( "PrintDialogPositionX" ); +static const wxChar PrintDialogPositionYEntry[] = wxT( "PrintDialogPositionY" ); +static const wxChar PrintDialogWidthEntry[] = wxT( "PrintDialogWidth" ); +static const wxChar PrintDialogHeightEntry[] = wxT( "PrintDialogHeight" ); +static const wxChar FindDialogPositionXEntry[] = wxT( "FindDialogPositionX" ); +static const wxChar FindDialogPositionYEntry[] = wxT( "FindDialogPositionY" ); +static const wxChar FindDialogWidthEntry[] = wxT( "FindDialogWidth" ); +static const wxChar FindDialogHeightEntry[] = wxT( "FindDialogHeight" ); +static const wxChar FindReplaceFlagsEntry[] = wxT( "LastFindReplaceFlags" ); +static const wxChar FindStringEntry[] = wxT( "LastFindString" ); +static const wxChar ReplaceStringEntry[] = wxT( "LastReplaceString" ); +static const wxChar FindStringHistoryEntry[] = wxT( "FindStringHistoryList%d" ); +static const wxChar ReplaceStringHistoryEntry[] = wxT( "ReplaceStringHistoryList%d" ); +static const wxChar FieldNamesEntry[] = wxT( "FieldNames" ); +static const wxChar SimulatorCommandEntry[] = wxT( "SimCmdLine" ); PARAM_CFG_ARRAY& SCH_EDIT_FRAME::GetConfigurationSettings( void ) @@ -590,64 +582,62 @@ PARAM_CFG_ARRAY& SCH_EDIT_FRAME::GetConfigurationSettings( void ) } -void SCH_EDIT_FRAME::LoadSettings() +void SCH_EDIT_FRAME::LoadSettings( wxConfigBase* aCfg ) { - wxASSERT( wxGetApp().GetSettings() != NULL ); + EDA_DRAW_FRAME::LoadSettings( aCfg ); long tmp; - wxConfig* cfg = wxGetApp().GetSettings(); - - EDA_DRAW_FRAME::LoadSettings(); - - wxGetApp().ReadCurrentSetupValues( GetConfigurationSettings() ); + wxConfigLoadSetups( aCfg, GetConfigurationSettings() ); // This is required until someone gets rid of the global variable s_layerColor. m_GridColor = GetLayerColor( LAYER_GRID ); - SetDefaultBusThickness( cfg->Read( DefaultBusWidthEntry, 12l ) ); - SetDefaultLineThickness( cfg->Read( DefaultDrawLineWidthEntry, 6l ) ); - cfg->Read( ShowHiddenPinsEntry, &m_showAllPins, false ); - cfg->Read( HorzVertLinesOnlyEntry, &m_forceHVLines, true ); + SetDefaultBusThickness( aCfg->Read( DefaultBusWidthEntry, 12l ) ); + SetDefaultLineThickness( aCfg->Read( DefaultDrawLineWidthEntry, 6l ) ); + aCfg->Read( ShowHiddenPinsEntry, &m_showAllPins, false ); + aCfg->Read( HorzVertLinesOnlyEntry, &m_forceHVLines, true ); // Load print preview window session settings. - cfg->Read( PreviewFramePositionXEntry, &tmp, -1 ); + aCfg->Read( PreviewFramePositionXEntry, &tmp, -1 ); m_previewPosition.x = (int) tmp; - cfg->Read( PreviewFramePositionYEntry, &tmp, -1 ); + aCfg->Read( PreviewFramePositionYEntry, &tmp, -1 ); m_previewPosition.y = (int) tmp; - cfg->Read( PreviewFrameWidthEntry, &tmp, -1 ); + aCfg->Read( PreviewFrameWidthEntry, &tmp, -1 ); m_previewSize.SetWidth( (int) tmp ); - cfg->Read( PreviewFrameHeightEntry, &tmp, -1 ); + aCfg->Read( PreviewFrameHeightEntry, &tmp, -1 ); m_previewSize.SetHeight( (int) tmp ); // Load print dialog session settings. - cfg->Read( PrintDialogPositionXEntry, &tmp, -1 ); + aCfg->Read( PrintDialogPositionXEntry, &tmp, -1 ); m_printDialogPosition.x = (int) tmp; - cfg->Read( PrintDialogPositionYEntry, &tmp, -1 ); + aCfg->Read( PrintDialogPositionYEntry, &tmp, -1 ); m_printDialogPosition.y = (int) tmp; - cfg->Read( PrintDialogWidthEntry, &tmp, -1 ); + aCfg->Read( PrintDialogWidthEntry, &tmp, -1 ); m_printDialogSize.SetWidth( (int) tmp ); - cfg->Read( PrintDialogHeightEntry, &tmp, -1 ); + aCfg->Read( PrintDialogHeightEntry, &tmp, -1 ); m_printDialogSize.SetHeight( (int) tmp ); // Load netlists options: - cfg->Read( SimulatorCommandEntry, &m_simulatorCommand ); + aCfg->Read( SimulatorCommandEntry, &m_simulatorCommand ); // Load find dialog session setting. - cfg->Read( FindDialogPositionXEntry, &tmp, -1 ); + aCfg->Read( FindDialogPositionXEntry, &tmp, -1 ); m_findDialogPosition.x = (int) tmp; - cfg->Read( FindDialogPositionYEntry, &tmp, -1 ); + aCfg->Read( FindDialogPositionYEntry, &tmp, -1 ); m_findDialogPosition.y = (int) tmp; - cfg->Read( FindDialogWidthEntry, &tmp, -1 ); + aCfg->Read( FindDialogWidthEntry, &tmp, -1 ); m_findDialogSize.SetWidth( (int) tmp ); - cfg->Read( FindDialogHeightEntry, &tmp, -1 ); + aCfg->Read( FindDialogHeightEntry, &tmp, -1 ); m_findDialogSize.SetHeight( (int) tmp ); + wxASSERT_MSG( m_findReplaceData, wxT( "Find dialog data settings object not created. Bad programmer!" ) ); - cfg->Read( FindReplaceFlagsEntry, &tmp, (long) wxFR_DOWN ); + + aCfg->Read( FindReplaceFlagsEntry, &tmp, (long) wxFR_DOWN ); m_findReplaceData->SetFlags( (wxUint32) tmp & ~FR_REPLACE_ITEM_FOUND ); - m_findReplaceData->SetFindString( cfg->Read( FindStringEntry, wxEmptyString ) ); - m_findReplaceData->SetReplaceString( cfg->Read( ReplaceStringEntry, wxEmptyString ) ); + m_findReplaceData->SetFindString( aCfg->Read( FindStringEntry, wxEmptyString ) ); + m_findReplaceData->SetReplaceString( aCfg->Read( ReplaceStringEntry, wxEmptyString ) ); // Load the find and replace string history list. for( int i = 0; i < FR_HISTORY_LIST_CNT; ++i ) @@ -655,19 +645,19 @@ void SCH_EDIT_FRAME::LoadSettings() wxString tmpHistory; wxString entry; entry.Printf( FindStringHistoryEntry, i ); - tmpHistory = cfg->Read( entry, wxEmptyString ); + tmpHistory = aCfg->Read( entry, wxEmptyString ); if( !tmpHistory.IsEmpty() ) m_findStringHistoryList.Add( tmpHistory ); entry.Printf( ReplaceStringHistoryEntry, i ); - tmpHistory = cfg->Read( entry, wxEmptyString ); + tmpHistory = aCfg->Read( entry, wxEmptyString ); if( !tmpHistory.IsEmpty() ) m_replaceStringHistoryList.Add( tmpHistory ); } - wxString templateFieldNames = cfg->Read( FieldNamesEntry, wxEmptyString ); + wxString templateFieldNames = aCfg->Read( FieldNamesEntry, wxEmptyString ); if( !templateFieldNames.IsEmpty() ) { @@ -686,47 +676,43 @@ void SCH_EDIT_FRAME::LoadSettings() } -void SCH_EDIT_FRAME::SaveSettings() +void SCH_EDIT_FRAME::SaveSettings( wxConfigBase* aCfg ) { - wxASSERT( wxGetApp().GetSettings() != NULL ); + EDA_DRAW_FRAME::SaveSettings( aCfg ); - wxConfig* cfg = wxGetApp().GetSettings(); + wxConfigSaveSetups( aCfg, GetConfigurationSettings() ); - EDA_DRAW_FRAME::SaveSettings(); - - wxGetApp().SaveCurrentSetupValues( GetConfigurationSettings() ); - - cfg->Write( DefaultBusWidthEntry, (long) GetDefaultBusThickness() ); - cfg->Write( DefaultDrawLineWidthEntry, (long) GetDefaultLineThickness() ); - cfg->Write( ShowHiddenPinsEntry, m_showAllPins ); - cfg->Write( HorzVertLinesOnlyEntry, GetForceHVLines() ); + aCfg->Write( DefaultBusWidthEntry, (long) GetDefaultBusThickness() ); + aCfg->Write( DefaultDrawLineWidthEntry, (long) GetDefaultLineThickness() ); + aCfg->Write( ShowHiddenPinsEntry, m_showAllPins ); + aCfg->Write( HorzVertLinesOnlyEntry, GetForceHVLines() ); // Save print preview window session settings. - cfg->Write( PreviewFramePositionXEntry, m_previewPosition.x ); - cfg->Write( PreviewFramePositionYEntry, m_previewPosition.y ); - cfg->Write( PreviewFrameWidthEntry, m_previewSize.GetWidth() ); - cfg->Write( PreviewFrameHeightEntry, m_previewSize.GetHeight() ); + aCfg->Write( PreviewFramePositionXEntry, m_previewPosition.x ); + aCfg->Write( PreviewFramePositionYEntry, m_previewPosition.y ); + aCfg->Write( PreviewFrameWidthEntry, m_previewSize.GetWidth() ); + aCfg->Write( PreviewFrameHeightEntry, m_previewSize.GetHeight() ); // Save print dialog session settings. - cfg->Write( PrintDialogPositionXEntry, m_printDialogPosition.x ); - cfg->Write( PrintDialogPositionYEntry, m_printDialogPosition.y ); - cfg->Write( PrintDialogWidthEntry, m_printDialogSize.GetWidth() ); - cfg->Write( PrintDialogHeightEntry, m_printDialogSize.GetHeight() ); + aCfg->Write( PrintDialogPositionXEntry, m_printDialogPosition.x ); + aCfg->Write( PrintDialogPositionYEntry, m_printDialogPosition.y ); + aCfg->Write( PrintDialogWidthEntry, m_printDialogSize.GetWidth() ); + aCfg->Write( PrintDialogHeightEntry, m_printDialogSize.GetHeight() ); // Save netlists options: - cfg->Write( SimulatorCommandEntry, m_simulatorCommand ); + aCfg->Write( SimulatorCommandEntry, m_simulatorCommand ); // Save find dialog session setting. - cfg->Write( FindDialogPositionXEntry, m_findDialogPosition.x ); - cfg->Write( FindDialogPositionYEntry, m_findDialogPosition.y ); - cfg->Write( FindDialogWidthEntry, m_findDialogSize.GetWidth() ); - cfg->Write( FindDialogHeightEntry, m_findDialogSize.GetHeight() ); + aCfg->Write( FindDialogPositionXEntry, m_findDialogPosition.x ); + aCfg->Write( FindDialogPositionYEntry, m_findDialogPosition.y ); + aCfg->Write( FindDialogWidthEntry, m_findDialogSize.GetWidth() ); + aCfg->Write( FindDialogHeightEntry, m_findDialogSize.GetHeight() ); wxASSERT_MSG( m_findReplaceData, wxT( "Find dialog data settings object not created. Bad programmer!" ) ); - cfg->Write( FindReplaceFlagsEntry, + aCfg->Write( FindReplaceFlagsEntry, (long) m_findReplaceData->GetFlags() & ~FR_REPLACE_ITEM_FOUND ); - cfg->Write( FindStringEntry, m_findReplaceData->GetFindString() ); - cfg->Write( ReplaceStringEntry, m_findReplaceData->GetReplaceString() ); + aCfg->Write( FindStringEntry, m_findReplaceData->GetFindString() ); + aCfg->Write( ReplaceStringEntry, m_findReplaceData->GetReplaceString() ); // Save the find and replace string history list. unsigned i; @@ -736,13 +722,13 @@ void SCH_EDIT_FRAME::SaveSettings() for( i = 0; i < m_findStringHistoryList.GetCount() && i < FR_HISTORY_LIST_CNT; i++ ) { entry.Printf( FindStringHistoryEntry, i ); - cfg->Write( entry, m_findStringHistoryList[ i ] ); + aCfg->Write( entry, m_findStringHistoryList[ i ] ); } for( i = 0; i < m_replaceStringHistoryList.GetCount() && i < FR_HISTORY_LIST_CNT; i++ ) { entry.Printf( ReplaceStringHistoryEntry, i ); - cfg->Write( entry, m_replaceStringHistoryList[ i ] ); + aCfg->Write( entry, m_replaceStringHistoryList[ i ] ); } // Save template fieldnames @@ -756,5 +742,5 @@ void SCH_EDIT_FRAME::SaveSettings() record.Replace( wxT("\n"), wxT(""), true ); // strip all newlines record.Replace( wxT(" "), wxT(" "), true ); // double space to single - cfg->Write( FieldNamesEntry, record ); + aCfg->Write( FieldNamesEntry, record ); } diff --git a/eeschema/eeschema_config.h b/eeschema/eeschema_config.h index 0c9135066c..8bdfa54ec6 100644 --- a/eeschema/eeschema_config.h +++ b/eeschema/eeschema_config.h @@ -2,7 +2,7 @@ * @file eeschema_config.h */ -#include +#include #define GROUP wxT( "/eeschema" ) #define GROUPCOMMON wxT( "/common" ) diff --git a/eeschema/files-io.cpp b/eeschema/files-io.cpp index fa6f17b91e..a94761d038 100644 --- a/eeschema/files-io.cpp +++ b/eeschema/files-io.cpp @@ -33,7 +33,7 @@ #include #include #include -#include +#include #include #include @@ -243,14 +243,15 @@ bool SCH_EDIT_FRAME::LoadCacheLibrary( const wxString& aFilename ) } -bool SCH_EDIT_FRAME::LoadOneEEProject( const wxString& aFileName, bool aIsNew ) +bool SCH_EDIT_FRAME::OpenProjectFiles( const std::vector& aFileSet, int aCtl ) { SCH_SCREEN* screen; - wxString FullFileName, msg; - bool LibCacheExist = false; - SCH_SCREENS ScreenList; + wxString fullFileName( aFileSet[0] ); + wxString msg; + bool libCacheExist = false; + SCH_SCREENS screenList; - for( screen = ScreenList.GetFirst(); screen != NULL; screen = ScreenList.GetNext() ) + for( screen = screenList.GetFirst(); screen != NULL; screen = screenList.GetNext() ) { if( screen->IsModify() ) break; @@ -258,10 +259,12 @@ bool SCH_EDIT_FRAME::LoadOneEEProject( const wxString& aFileName, bool aIsNew ) if( screen ) { - int response = YesNoCancelDialog( this, _( "The current schematic has been modified. Do " - "you wish to save the changes?" ), - wxEmptyString, - _( "Save and Load" ), _( "Load Without Saving" ) ); + 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 ) { @@ -274,9 +277,8 @@ bool SCH_EDIT_FRAME::LoadOneEEProject( const wxString& aFileName, bool aIsNew ) } } - FullFileName = aFileName; - - if( FullFileName.IsEmpty() && !aIsNew ) +/* + if( fullFileName.IsEmpty() && !aIsNew ) { wxFileDialog dlg( this, _( "Open Schematic" ), wxGetCwd(), wxEmptyString, SchematicFileWildcard, @@ -287,16 +289,17 @@ bool SCH_EDIT_FRAME::LoadOneEEProject( const wxString& aFileName, bool aIsNew ) FullFileName = dlg.GetPath(); } +*/ - wxFileName fn = FullFileName; + wxFileName fn = fullFileName; if( fn.IsRelative() ) { fn.MakeAbsolute(); - FullFileName = fn.GetFullPath(); + fullFileName = fn.GetFullPath(); } - if( !wxGetApp().LockFile( FullFileName ) ) + if( !Pgm().LockFile( fullFileName ) ) { DisplayError( this, _( "This file is already open." ) ); return false; @@ -312,16 +315,19 @@ bool SCH_EDIT_FRAME::LoadOneEEProject( const wxString& aFileName, bool aIsNew ) CreateScreens(); screen = GetScreen(); - wxLogDebug( wxT( "Loading schematic " ) + FullFileName ); + wxLogDebug( wxT( "Loading schematic " ) + fullFileName ); + + // @todo: this is bad: wxSetWorkingDirectory( fn.GetPath() ); - screen->SetFileName( FullFileName ); - g_RootSheet->SetFileName( FullFileName ); + screen->SetFileName( fullFileName ); + g_RootSheet->SetFileName( fullFileName ); SetStatusText( wxEmptyString ); ClearMsgPanel(); screen->ClrModify(); +#if 0 if( aIsNew ) { /* SCH_SCREEN constructor does this now @@ -347,9 +353,10 @@ bool SCH_EDIT_FRAME::LoadOneEEProject( const wxString& aFileName, bool aIsNew ) m_canvas->Refresh(); return true; } +#endif // Reloading configuration. - msg.Printf( _( "Ready\nWorking dir: <%s>\n" ), GetChars( wxGetCwd() ) ); + msg.Printf( _( "Ready\nWorking dir: '%s'\n" ), GetChars( wxGetCwd() ) ); PrintMsg( msg ); LoadProjectFile( wxEmptyString, false ); @@ -361,38 +368,46 @@ bool SCH_EDIT_FRAME::LoadOneEEProject( const wxString& aFileName, bool aIsNew ) // Delete old caches. CMP_LIBRARY::RemoveCacheLibrary(); - LibCacheExist = LoadCacheLibrary( g_RootSheet->GetScreen()->GetFileName() ); - - if( !wxFileExists( g_RootSheet->GetScreen()->GetFileName() ) && !LibCacheExist ) + if( !wxFileExists( g_RootSheet->GetScreen()->GetFileName() ) ) { Zoom_Automatique( false ); - msg.Printf( _( "File <%s> not found." ), - GetChars( g_RootSheet->GetScreen()->GetFileName() ) ); - DisplayInfoMessage( this, msg ); - return false; + + if( aCtl == 0 ) + { + msg.Printf( _( "File '%s' not found." ), + GetChars( g_RootSheet->GetScreen()->GetFileName() ) ); + DisplayInfoMessage( this, msg ); + } + + return true; // do not close Eeschema if the file if not found: + // we may have to create a new schematic file. } // load the project. + libCacheExist = LoadCacheLibrary( g_RootSheet->GetScreen()->GetFileName() ); g_RootSheet->SetScreen( NULL ); bool diag = g_RootSheet->Load( this ); SetScreen( m_CurrentSheet->LastScreen() ); UpdateFileHistory( g_RootSheet->GetScreen()->GetFileName() ); - /* Redraw base screen (ROOT) if necessary. */ + // Redraw base screen (ROOT) if necessary. GetScreen()->SetGrid( ID_POPUP_GRID_LEVEL_1000 + m_LastGridSizeId ); Zoom_Automatique( false ); SetSheetNumberAndCount(); m_canvas->Refresh( true ); - return diag; + +// return diag; + return true; // do not close Eeschema if the file if not found: + // we may have to create a new schematic file. } bool SCH_EDIT_FRAME::AppendOneEEProject() { SCH_SCREEN* screen; - wxString FullFileName; - wxString msg; + wxString fullFileName; + wxString msg; screen = GetScreen(); @@ -410,22 +425,22 @@ bool SCH_EDIT_FRAME::AppendOneEEProject() if( dlg.ShowModal() == wxID_CANCEL ) return false; - FullFileName = dlg.GetPath(); + fullFileName = dlg.GetPath(); - wxFileName fn = FullFileName; + wxFileName fn = fullFileName; if( fn.IsRelative() ) { fn.MakeAbsolute(); - FullFileName = fn.GetFullPath(); + fullFileName = fn.GetFullPath(); } - LoadCacheLibrary( FullFileName ); + LoadCacheLibrary( fullFileName ); - wxLogDebug( wxT( "Importing schematic " ) + FullFileName ); + wxLogDebug( wxT( "Importing schematic " ) + fullFileName ); // load the project - bool success = LoadOneEEFile( screen, FullFileName, true ); + bool success = LoadOneEEFile( screen, fullFileName, true ); if( success ) { // load sub-sheets diff --git a/eeschema/find.cpp b/eeschema/find.cpp index ed52efe966..d29cd4aba8 100644 --- a/eeschema/find.cpp +++ b/eeschema/find.cpp @@ -34,7 +34,7 @@ * in current sheet or whole the project */ #include -#include +#include #include #include #include diff --git a/eeschema/getpart.cpp b/eeschema/getpart.cpp index 200b29bcd3..fa1f083860 100644 --- a/eeschema/getpart.cpp +++ b/eeschema/getpart.cpp @@ -29,7 +29,7 @@ */ #include -#include +#include #include #include #include @@ -59,12 +59,13 @@ wxString SCH_BASE_FRAME::SelectComponentFromLibBrowser( LIB_ALIAS* aPreselectedA wxString cmpname; // Close the current Lib browser, if open, and open a new one, in "modal" mode: - LIB_VIEW_FRAME * viewlibFrame = LIB_VIEW_FRAME::GetActiveLibraryViewer();; + LIB_VIEW_FRAME* viewlibFrame = LIB_VIEW_FRAME::GetActiveLibraryViewer( this ); if( viewlibFrame ) viewlibFrame->Destroy(); - viewlibFrame = new LIB_VIEW_FRAME( this, NULL, &semaphore, - KICAD_DEFAULT_DRAWFRAME_STYLE | wxFRAME_FLOAT_ON_PARENT ); + viewlibFrame = new LIB_VIEW_FRAME( &Kiway(), this, NULL, &semaphore, + KICAD_DEFAULT_DRAWFRAME_STYLE | wxFRAME_FLOAT_ON_PARENT ); + if ( aPreselectedAlias ) { viewlibFrame->SetSelectedLibrary( aPreselectedAlias->GetLibraryName() ); diff --git a/eeschema/invoke_sch_dialog.h b/eeschema/invoke_sch_dialog.h index 4cd27be957..b2a8fba3f8 100644 --- a/eeschema/invoke_sch_dialog.h +++ b/eeschema/invoke_sch_dialog.h @@ -75,5 +75,6 @@ int InvokeDialogCreateBOM( SCH_EDIT_FRAME* aCaller ); #define NET_PLUGIN_CHANGE 1 int InvokeDialogNetList( SCH_EDIT_FRAME* aCaller ); +int InvokeEeschemaConfig( SCH_EDIT_FRAME* aEditFrame, wxFrame* aParent ); #endif // INVOKE_SCH_DIALOG_H_ diff --git a/eeschema/lib_arc.cpp b/eeschema/lib_arc.cpp index a93ecae90f..df4fb03f0d 100644 --- a/eeschema/lib_arc.cpp +++ b/eeschema/lib_arc.cpp @@ -555,7 +555,7 @@ void LIB_ARC::GetMsgPanelInfo( std::vector< MSG_PANEL_ITEM >& aList ) LIB_ITEM::GetMsgPanelInfo( aList ); - msg = ReturnStringFromValue( g_UserUnit, m_Width, true ); + msg = StringFromValue( g_UserUnit, m_Width, true ); aList.push_back( MSG_PANEL_ITEM( _( "Line width" ), msg, BLUE ) ); diff --git a/eeschema/lib_bezier.cpp b/eeschema/lib_bezier.cpp index 1d4601950a..b58e11cb6b 100644 --- a/eeschema/lib_bezier.cpp +++ b/eeschema/lib_bezier.cpp @@ -411,7 +411,7 @@ void LIB_BEZIER::GetMsgPanelInfo( std::vector< MSG_PANEL_ITEM >& aList ) LIB_ITEM::GetMsgPanelInfo( aList ); - msg = ReturnStringFromValue( g_UserUnit, m_Width, true ); + msg = StringFromValue( g_UserUnit, m_Width, true ); aList.push_back( MSG_PANEL_ITEM( _( "Line width" ), msg, BLUE ) ); diff --git a/eeschema/lib_circle.cpp b/eeschema/lib_circle.cpp index 2110f42bf8..204db95d5f 100644 --- a/eeschema/lib_circle.cpp +++ b/eeschema/lib_circle.cpp @@ -270,11 +270,11 @@ void LIB_CIRCLE::GetMsgPanelInfo( MSG_PANEL_ITEMS& aList ) LIB_ITEM::GetMsgPanelInfo( aList ); - msg = ReturnStringFromValue( g_UserUnit, m_Width, true ); + msg = StringFromValue( g_UserUnit, m_Width, true ); aList.push_back( MSG_PANEL_ITEM( _( "Line width" ), msg, BLUE ) ); - msg = ReturnStringFromValue( g_UserUnit, m_Radius, true ); + msg = StringFromValue( g_UserUnit, m_Radius, true ); aList.push_back( MSG_PANEL_ITEM( _( "Radius" ), msg, RED ) ); msg.Printf( wxT( "(%d, %d, %d, %d)" ), bBox.GetOrigin().x, diff --git a/eeschema/lib_field.cpp b/eeschema/lib_field.cpp index 4e924a5333..392daecc8c 100644 --- a/eeschema/lib_field.cpp +++ b/eeschema/lib_field.cpp @@ -27,7 +27,7 @@ */ #include -#include +#include #include #include #include @@ -517,7 +517,7 @@ wxString LIB_FIELD::GetFullText( int unit ) text << wxT( "?" ); if( GetParent()->IsMulti() ) - text << LIB_COMPONENT::ReturnSubReference( unit ); + text << LIB_COMPONENT::SubReference( unit ); return text; } @@ -763,10 +763,10 @@ void LIB_FIELD::GetMsgPanelInfo( MSG_PANEL_ITEMS& aList ) msg = GetTextStyleName(); aList.push_back( MSG_PANEL_ITEM( _( "Style" ), msg, MAGENTA ) ); - msg = ReturnStringFromValue( g_UserUnit, m_Size.x, true ); + msg = StringFromValue( g_UserUnit, m_Size.x, true ); aList.push_back( MSG_PANEL_ITEM( _( "Size X" ), msg, BLUE ) ); - msg = ReturnStringFromValue( g_UserUnit, m_Size.y, true ); + msg = StringFromValue( g_UserUnit, m_Size.y, true ); aList.push_back( MSG_PANEL_ITEM( _( "Size Y" ), msg, BLUE ) ); // Display field name (ref, value ...) diff --git a/eeschema/lib_pin.cpp b/eeschema/lib_pin.cpp index 481c083c6f..b8e8f7897a 100644 --- a/eeschema/lib_pin.cpp +++ b/eeschema/lib_pin.cpp @@ -27,7 +27,7 @@ */ #include -#include +#include #include #include #include @@ -602,7 +602,7 @@ bool LIB_PIN::Save( OUTPUTFORMATTER& aFormatter ) break; } - ReturnPinStringNum( StringPinNum ); + PinStringNum( StringPinNum ); if( StringPinNum.IsEmpty() ) StringPinNum = wxT( "~" ); @@ -824,7 +824,7 @@ void LIB_PIN::drawGraphic( EDA_DRAW_PANEL* aPanel, DrawPinText = false; /* Calculate pin orient taking in account the component orientation. */ - int orient = ReturnPinDrawOrient( aTransform ); + int orient = PinDrawOrient( aTransform ); /* Calculate the pin position */ wxPoint pos1 = aTransform.TransformCoordinate( m_position ) + aOffset; @@ -1102,7 +1102,7 @@ void LIB_PIN::DrawPinTexts( EDA_DRAW_PANEL* panel, GetLayerColor( LAYER_PINNUM ) : Color ); /* Create the pin num string */ - ReturnPinStringNum( StringPinNum ); + PinStringNum( StringPinNum ); x1 = pin_pos.x; y1 = pin_pos.y; @@ -1396,7 +1396,7 @@ void LIB_PIN::PlotPinTexts( PLOTTER* plotter, NumColor = GetLayerColor( LAYER_PINNUM ); /* Create the pin num string */ - ReturnPinStringNum( StringPinNum ); + PinStringNum( StringPinNum ); x1 = pin_pos.x; y1 = pin_pos.y; @@ -1565,7 +1565,7 @@ void LIB_PIN::PlotPinTexts( PLOTTER* plotter, } -wxPoint LIB_PIN::ReturnPinEndPoint() const +wxPoint LIB_PIN::PinEndPoint() const { wxPoint pos = m_position; @@ -1592,7 +1592,7 @@ wxPoint LIB_PIN::ReturnPinEndPoint() const } -int LIB_PIN::ReturnPinDrawOrient( const TRANSFORM& aTransform ) const +int LIB_PIN::PinDrawOrient( const TRANSFORM& aTransform ) const { int orient; wxPoint end; // position of pin end starting at 0,0 according to its orientation, length = 1 @@ -1637,13 +1637,13 @@ int LIB_PIN::ReturnPinDrawOrient( const TRANSFORM& aTransform ) const } -void LIB_PIN::ReturnPinStringNum( wxString& aStringBuffer ) const +void LIB_PIN::PinStringNum( wxString& aStringBuffer ) const { - aStringBuffer = ReturnPinStringNum( m_number ); + aStringBuffer = PinStringNum( m_number ); } -wxString LIB_PIN::ReturnPinStringNum( long aPinNum ) +wxString LIB_PIN::PinStringNum( long aPinNum ) { char ascii_buf[5]; @@ -1714,7 +1714,7 @@ void LIB_PIN::SetOffset( const wxPoint& aOffset ) bool LIB_PIN::Inside( EDA_RECT& rect ) const { - wxPoint end = ReturnPinEndPoint(); + wxPoint end = PinEndPoint(); return rect.Contains( m_position.x, -m_position.y ) || rect.Contains( end.x, -end.y ); } @@ -1809,7 +1809,7 @@ void LIB_PIN::Plot( PLOTTER* plotter, const wxPoint& offset, bool fill, if( ! IsVisible() ) return; - int orient = ReturnPinDrawOrient( aTransform ); + int orient = PinDrawOrient( aTransform ); wxPoint pos = aTransform.TransformCoordinate( m_position ) + offset; @@ -1842,7 +1842,7 @@ void LIB_PIN::GetMsgPanelInfo( MSG_PANEL_ITEMS& aList ) if( m_number == 0 ) Text = wxT( "?" ); else - ReturnPinStringNum( Text ); + PinStringNum( Text ); aList.push_back( MSG_PANEL_ITEM( _( "Number" ), Text, DARKCYAN ) ); @@ -1860,7 +1860,7 @@ void LIB_PIN::GetMsgPanelInfo( MSG_PANEL_ITEMS& aList ) aList.push_back( MSG_PANEL_ITEM( _( "Visible" ), Text, DARKGREEN ) ); // Display pin length - Text = ReturnStringFromValue( g_UserUnit, m_length, true ); + Text = StringFromValue( g_UserUnit, m_length, true ); aList.push_back( MSG_PANEL_ITEM( _( "Length" ), Text, MAGENTA ) ); Text = wxGetTranslation( pin_orientation_names[ GetOrientationCodeIndex( m_orientation ) ] ); @@ -1937,7 +1937,7 @@ const EDA_RECT LIB_PIN::GetBoundingBox() const } // Now, calculate boundary box corners position for the actual pin orientation - int orient = ReturnPinDrawOrient( DefaultTransform ); + int orient = PinDrawOrient( DefaultTransform ); /* Calculate the pin position */ switch( orient ) diff --git a/eeschema/lib_pin.h b/eeschema/lib_pin.h index c89538a216..bf4c504776 100644 --- a/eeschema/lib_pin.h +++ b/eeschema/lib_pin.h @@ -142,20 +142,20 @@ public: const EDA_RECT GetBoundingBox() const; // Virtual /** - * Function ReturnPinEndPoint + * Function PinEndPoint * * @return The pin end position for a component in the normal orientation. */ - wxPoint ReturnPinEndPoint() const; + wxPoint PinEndPoint() const; /** - * Function ReturnPinDrawOrient + * Function PinDrawOrient * returns the pin real orientation (PIN_UP, PIN_DOWN, PIN_RIGHT, PIN_LEFT), * according to its orientation and the matrix transform (rot, mirror) \a aTransform * * @param aTransform Transform matrix */ - int ReturnPinDrawOrient( const TRANSFORM& aTransform ) const; + int PinDrawOrient( const TRANSFORM& aTransform ) const; /** * Fill a string buffer with pin number. @@ -165,20 +165,20 @@ public: * * @param aStringBuffer - the wxString to store the pin num as an unicode string */ - void ReturnPinStringNum( wxString& aStringBuffer ) const; + void PinStringNum( wxString& aStringBuffer ) const; long GetNumber() const { return m_number; } - wxString GetNumberString() const { return ReturnPinStringNum( m_number ); } + wxString GetNumberString() const { return PinStringNum( m_number ); } /** - * Function ReturnPinStringNum (static function) + * Function PinStringNum (static function) * Pin num is coded as a long or 4 ascii chars * @param aPinNum = a long containing a pin num * @return aStringBuffer = the wxString to store the pin num as an * unicode string */ - static wxString ReturnPinStringNum( long aPinNum ); + static wxString PinStringNum( long aPinNum ); /** * Function SetPinNumFromString diff --git a/eeschema/lib_polyline.cpp b/eeschema/lib_polyline.cpp index 49aa1daf42..5b4b1ba49c 100644 --- a/eeschema/lib_polyline.cpp +++ b/eeschema/lib_polyline.cpp @@ -400,7 +400,7 @@ void LIB_POLYLINE::GetMsgPanelInfo( MSG_PANEL_ITEMS& aList ) LIB_ITEM::GetMsgPanelInfo( aList ); - msg = ReturnStringFromValue( g_UserUnit, m_Width, true ); + msg = StringFromValue( g_UserUnit, m_Width, true ); aList.push_back( MSG_PANEL_ITEM( _( "Line width" ), msg, BLUE ) ); diff --git a/eeschema/lib_rectangle.cpp b/eeschema/lib_rectangle.cpp index 4ba9ab959e..7efdb3dbf1 100644 --- a/eeschema/lib_rectangle.cpp +++ b/eeschema/lib_rectangle.cpp @@ -250,7 +250,7 @@ void LIB_RECTANGLE::GetMsgPanelInfo( MSG_PANEL_ITEMS& aList ) LIB_ITEM::GetMsgPanelInfo( aList ); - msg = ReturnStringFromValue( g_UserUnit, m_Width, true ); + msg = StringFromValue( g_UserUnit, m_Width, true ); aList.push_back( MSG_PANEL_ITEM( _( "Line width" ), msg, BLUE ) ); } diff --git a/eeschema/lib_text.cpp b/eeschema/lib_text.cpp index a197b9251a..d52acdda97 100644 --- a/eeschema/lib_text.cpp +++ b/eeschema/lib_text.cpp @@ -423,7 +423,7 @@ void LIB_TEXT::GetMsgPanelInfo( MSG_PANEL_ITEMS& aList ) LIB_ITEM::GetMsgPanelInfo( aList ); - msg = ReturnStringFromValue( g_UserUnit, m_Thickness, true ); + msg = StringFromValue( g_UserUnit, m_Thickness, true ); aList.push_back( MSG_PANEL_ITEM( _( "Line width" ), msg, BLUE ) ); } diff --git a/eeschema/libedit.cpp b/eeschema/libedit.cpp index 9236467b6d..82afe32532 100644 --- a/eeschema/libedit.cpp +++ b/eeschema/libedit.cpp @@ -29,9 +29,10 @@ */ #include +#include #include #include -#include +#include #include #include #include @@ -320,8 +321,13 @@ bool LIB_EDIT_FRAME::SaveActiveLibrary( bool newFile ) } if( newFile ) - { // Get a new name for the library - wxString default_path = wxGetApp().ReturnLastVisitedLibraryPath(); + { + PROJECT& prj = Prj(); + SEARCH_STACK& search = prj.SchSearchS(); + + // Get a new name for the library + wxString default_path = prj.RPath(PROJECT::SCH_LIB).LastVisitedPath( search ); + wxFileDialog dlg( this, _( "Component Library Name:" ), default_path, wxEmptyString, SchematicLibraryFileExtension, wxFD_SAVE | wxFD_OVERWRITE_PROMPT ); @@ -336,7 +342,7 @@ bool LIB_EDIT_FRAME::SaveActiveLibrary( bool newFile ) if( fn.GetExt().IsEmpty() ) fn.SetExt( SchematicLibraryFileExtension ); - wxGetApp().SaveLastVisitedLibraryPath( fn.GetPath() ); + prj.RPath(PROJECT::SCH_LIB).SaveLastVisitedPath( fn.GetPath() ); } else { @@ -404,6 +410,7 @@ bool LIB_EDIT_FRAME::SaveActiveLibrary( bool newFile ) if( docFileName.FileExists() ) { backupFileName.SetExt( wxT( "bck" ) ); + if( backupFileName.FileExists() ) wxRemoveFile( backupFileName.GetFullPath() ); diff --git a/eeschema/libedit_plot_component.cpp b/eeschema/libedit_plot_component.cpp index 45bf13a412..39d3dbafcb 100644 --- a/eeschema/libedit_plot_component.cpp +++ b/eeschema/libedit_plot_component.cpp @@ -29,7 +29,7 @@ #include #include -#include +#include #include #include #include diff --git a/eeschema/libeditframe.cpp b/eeschema/libeditframe.cpp index b608513916..0eaa7aca20 100644 --- a/eeschema/libeditframe.cpp +++ b/eeschema/libeditframe.cpp @@ -29,7 +29,8 @@ */ #include -#include +#include +#include #include #include #include @@ -188,15 +189,11 @@ END_EVENT_TABLE() #define LIB_EDIT_FRAME_NAME wxT( "LibeditFrame" ) -LIB_EDIT_FRAME::LIB_EDIT_FRAME( SCH_EDIT_FRAME* aParent, - const wxString& title, - const wxPoint& pos, - const wxSize& size, - long style ) : - SCH_BASE_FRAME( aParent, LIBEDITOR_FRAME_TYPE, title, pos, size, - style, GetLibEditFrameName() ) +LIB_EDIT_FRAME::LIB_EDIT_FRAME( KIWAY* aKiway, SCH_EDIT_FRAME* aParent ) : + SCH_BASE_FRAME( aKiway, aParent, LIBEDITOR_FRAME_TYPE, _( "Library Editor" ), + wxDefaultPosition, wxDefaultSize, KICAD_DEFAULT_DRAWFRAME_STYLE, GetLibEditFrameName() ) { - wxASSERT( aParent ); + wxASSERT( aParent ); // LIB_EDIT_FRAME needs a parent, since it peeks up there. m_FrameName = GetLibEditFrameName(); m_showAxis = true; // true to draw axis @@ -219,7 +216,7 @@ LIB_EDIT_FRAME::LIB_EDIT_FRAME( SCH_EDIT_FRAME* aParent, SetCrossHairPosition( wxPoint( 0, 0 ) ); - LoadSettings(); + LoadSettings( config() ); // Ensure m_LastGridSizeId is an offset inside the allowed schematic range if( m_LastGridSizeId < ID_POPUP_GRID_LEVEL_50 - ID_POPUP_GRID_LEVEL_1000 ) @@ -302,17 +299,29 @@ LIB_EDIT_FRAME* LIB_EDIT_FRAME::GetActiveLibraryEditor() } -void LIB_EDIT_FRAME::LoadSettings() +void LIB_EDIT_FRAME::LoadSettings( wxConfigBase* aCfg ) { - wxConfig* cfg; +#if 0 // original + + wxConfigBase* cfg; EDA_DRAW_FRAME::LoadSettings(); wxConfigPathChanger cpc( wxGetApp().GetSettings(), m_configPath ); - cfg = wxGetApp().GetSettings(); + cfg = Pgm().GetSettings(); +#else - m_lastLibExportPath = cfg->Read( lastLibExportPathEntry, ::wxGetCwd() ); - m_lastLibImportPath = cfg->Read( lastLibImportPathEntry, ::wxGetCwd() ); + EDA_DRAW_FRAME::LoadSettings( aCfg ); + + wxConfigPathChanger cpc( aCfg, m_configPath ); + + m_lastLibExportPath = aCfg->Read( lastLibExportPathEntry, ::wxGetCwd() ); + m_lastLibImportPath = aCfg->Read( lastLibImportPathEntry, ::wxGetCwd() ); + +#endif + + m_lastLibExportPath = aCfg->Read( lastLibExportPathEntry, ::wxGetCwd() ); + m_lastLibImportPath = aCfg->Read( lastLibImportPathEntry, ::wxGetCwd() ); } @@ -323,17 +332,14 @@ void LIB_EDIT_FRAME::SetDrawItem( LIB_ITEM* drawItem ) -void LIB_EDIT_FRAME::SaveSettings() +void LIB_EDIT_FRAME::SaveSettings( wxConfigBase* aCfg ) { - wxConfig* cfg; + EDA_DRAW_FRAME::SaveSettings( aCfg ); - EDA_DRAW_FRAME::SaveSettings(); + wxConfigPathChanger cpc( aCfg, m_configPath ); - wxConfigPathChanger cpc( wxGetApp().GetSettings(), m_configPath ); - cfg = wxGetApp().GetSettings(); - - cfg->Write( lastLibExportPathEntry, m_lastLibExportPath ); - cfg->Write( lastLibImportPathEntry, m_lastLibImportPath ); + aCfg->Write( lastLibExportPathEntry, m_lastLibExportPath ); + aCfg->Write( lastLibImportPathEntry, m_lastLibImportPath ); } @@ -464,7 +470,7 @@ void LIB_EDIT_FRAME::UpdatePartSelectList() { for( int i = 0; i < m_component->GetPartCount(); i++ ) { - wxString sub = LIB_COMPONENT::ReturnSubReference( i+1, false ); + wxString sub = LIB_COMPONENT::SubReference( i+1, false ); wxString part = wxString::Format( _( "Unit %s" ), GetChars( sub ) ); m_partSelectBox->Append( part ); } @@ -613,15 +619,19 @@ void LIB_EDIT_FRAME::OnViewEntryDoc( wxCommandEvent& event ) if( m_component == NULL ) return; - wxString fileName; - LIB_ALIAS* alias = m_component->GetAlias( m_aliasName ); + wxString fileName; + LIB_ALIAS* alias = m_component->GetAlias( m_aliasName ); wxCHECK_RET( alias != NULL, wxT( "Alias not found." ) ); fileName = alias->GetDocFileName(); if( !fileName.IsEmpty() ) - GetAssociatedDocument( this, fileName, &wxGetApp().GetLibraryPathList() ); + { + SEARCH_STACK* lib_search = &Prj().SchSearchS(); + + GetAssociatedDocument( this, fileName, lib_search ); + } } diff --git a/eeschema/libeditframe.h b/eeschema/libeditframe.h index 16802af6b0..45582f34d8 100644 --- a/eeschema/libeditframe.h +++ b/eeschema/libeditframe.h @@ -45,16 +45,15 @@ class LIB_ALIAS; class LIB_FIELD; class DIALOG_LIB_EDIT_TEXT; - /** * The component library editor main window. */ class LIB_EDIT_FRAME : public SCH_BASE_FRAME { - LIB_COMPONENT* m_tempCopyComponent; ///< Temporary copy of current component during edit. - LIB_COLLECTOR m_collectedItems; // Used for hit testing. - wxComboBox* m_partSelectBox; // a Box to select a part to edit (if any) - wxComboBox* m_aliasSelectBox; // a box to select the alias to edit (if any) + LIB_COMPONENT* m_tempCopyComponent; ///< Temporary copy of current component during edit. + LIB_COLLECTOR m_collectedItems; ///< Used for hit testing. + wxComboBox* m_partSelectBox; ///< a Box to select a part to edit (if any) + wxComboBox* m_aliasSelectBox; ///< a box to select the alias to edit (if any) wxString m_configPath; wxString m_lastLibImportPath; @@ -122,9 +121,8 @@ class LIB_EDIT_FRAME : public SCH_BASE_FRAME LIB_ITEM* locateItem( const wxPoint& aPosition, const KICAD_T aFilterList[] ); public: - LIB_EDIT_FRAME( SCH_EDIT_FRAME* aParent, const wxString& aTitle, - const wxPoint& aPosition, const wxSize& aSize, - long aStyle = KICAD_DEFAULT_DRAWFRAME_STYLE ); + + LIB_EDIT_FRAME( KIWAY* aKiway, SCH_EDIT_FRAME* aParent ); ~LIB_EDIT_FRAME(); @@ -294,23 +292,9 @@ public: void GeneralControl( wxDC* aDC, const wxPoint& aPosition, int aHotKey = 0 ); - /** - * Function LoadSettings - * loads the library editor frame specific configuration settings. - * - * Don't forget to call this method from any derived classes or the settings will not - * get loaded. - */ - void LoadSettings(); + void LoadSettings( wxConfigBase* aCfg ); - /** - * Function SaveSettings - * saves the library editor frame specific configuration settings. - * - * Don't forget to call this base method from any derived classes or the settings will - * not get saved. - */ - void SaveSettings(); + void SaveSettings( wxConfigBase* aCfg ); /** * Function CloseWindow @@ -575,11 +559,11 @@ public: /* Block commands: */ /** - * Function ReturnBlockCommand + * Function BlockCommand * returns the block command (BLOCK_MOVE, BLOCK_COPY...) corresponding to * the \a aKey (ALT, SHIFT ALT ..) */ - virtual int ReturnBlockCommand( int aKey ); + virtual int BlockCommand( int aKey ); /** * Function HandleBlockPlace diff --git a/eeschema/menubar.cpp b/eeschema/menubar.cpp index 61f8e22256..58ed11c90d 100644 --- a/eeschema/menubar.cpp +++ b/eeschema/menubar.cpp @@ -29,7 +29,8 @@ */ #include -#include +#include +#include #include #include @@ -83,11 +84,13 @@ void SCH_EDIT_FRAME::ReCreateMenuBar() // Add this menu to list menu managed by m_fileHistory // (the file history will be updated when adding/removing files in history if( openRecentMenu ) - wxGetApp().GetFileHistory().RemoveMenu( openRecentMenu ); + Kiface().GetFileHistory().RemoveMenu( openRecentMenu ); openRecentMenu = new wxMenu(); - wxGetApp().GetFileHistory().UseMenu( openRecentMenu ); - wxGetApp().GetFileHistory().AddFilesToMenu( openRecentMenu ); + + Kiface().GetFileHistory().UseMenu( openRecentMenu ); + Kiface().GetFileHistory().AddFilesToMenu( openRecentMenu ); + AddMenuItem( fileMenu, openRecentMenu, wxID_ANY, _( "Open &Recent" ), _( "Open a recent opened schematic project" ), @@ -424,7 +427,7 @@ void SCH_EDIT_FRAME::ReCreateMenuBar() // Language submenu - wxGetApp().AddMenuLanguageList( preferencesMenu ); + Pgm().AddMenuLanguageList( preferencesMenu ); // Hotkey submenu AddHotkeyConfigMenu( preferencesMenu ); diff --git a/eeschema/menubar_libedit.cpp b/eeschema/menubar_libedit.cpp index eba56c6188..1671b0769e 100644 --- a/eeschema/menubar_libedit.cpp +++ b/eeschema/menubar_libedit.cpp @@ -28,7 +28,7 @@ * @brief (Re)Create the main menubar for the component editor frame (LibEdit) */ #include -#include +#include #include #include @@ -239,7 +239,7 @@ void LIB_EDIT_FRAME::ReCreateMenuBar() KiBitmap( palette_xpm ) ); // Language submenu - wxGetApp().AddMenuLanguageList( preferencesMenu ); + Pgm().AddMenuLanguageList( preferencesMenu ); // Hotkey submenu AddHotkeyConfigMenu( preferencesMenu ); diff --git a/eeschema/netform.cpp b/eeschema/netform.cpp index a0665d675f..3a97b08849 100644 --- a/eeschema/netform.cpp +++ b/eeschema/netform.cpp @@ -32,7 +32,7 @@ #include #include #include -#include +#include #include #include @@ -644,8 +644,7 @@ XNODE* NETLIST_EXPORT_TOOL::makeGenericDesignHeader() xdesign->AddChild( node( wxT( "date" ), DateAndTime() ) ); // which Eeschema tool - xdesign->AddChild( node( wxT( "tool" ), wxGetApp().GetAppName() + wxChar(' ') + - GetBuildVersion() ) ); + xdesign->AddChild( node( wxT( "tool" ), wxT( "Eeschema " ) + GetBuildVersion() ) ); /* @todo might do a list of schematic pages @@ -1727,13 +1726,13 @@ bool NETLIST_EXPORT_TOOL::WriteNetListCADSTAR( FILE* f ) wxString footprint; SCH_SHEET_PATH* sheet; EDA_ITEM* DrawList; - SCH_COMPONENT* Component; - wxString Title = wxGetApp().GetAppName() + wxT( " " ) + GetBuildVersion(); + SCH_COMPONENT* component; + wxString title = wxT( "Eeschema " ) + GetBuildVersion(); ret |= fprintf( f, "%sHEA\n", TO_UTF8( StartLine ) ); ret |= fprintf( f, "%sTIM %s\n", TO_UTF8( StartLine ), TO_UTF8( DateAndTime() ) ); ret |= fprintf( f, "%sAPP ", TO_UTF8( StartLine ) ); - ret |= fprintf( f, "\"%s\"\n", TO_UTF8( Title ) ); + ret |= fprintf( f, "\"%s\"\n", TO_UTF8( title ) ); ret |= fprintf( f, "\n" ); // Prepare list of nets generation @@ -1749,27 +1748,27 @@ bool NETLIST_EXPORT_TOOL::WriteNetListCADSTAR( FILE* f ) { for( DrawList = sheet->LastDrawList(); DrawList != NULL; DrawList = DrawList->Next() ) { - DrawList = Component = findNextComponentAndCreatePinList( DrawList, sheet ); + DrawList = component = findNextComponentAndCreatePinList( DrawList, sheet ); - if( Component == NULL ) + if( component == NULL ) break; /* doing nothing with footprint - if( !Component->GetField( FOOTPRINT )->IsVoid() ) + if( !component->GetField( FOOTPRINT )->IsVoid() ) { - footprint = Component->GetField( FOOTPRINT )->m_Text; + footprint = component->GetField( FOOTPRINT )->m_Text; footprint.Replace( wxT( " " ), wxT( "_" ) ); } else footprint = wxT( "$noname" ); */ - msg = Component->GetRef( sheet ); + msg = component->GetRef( sheet ); ret |= fprintf( f, "%s ", TO_UTF8( StartCmpDesc ) ); ret |= fprintf( f, "%s", TO_UTF8( msg ) ); - msg = Component->GetField( VALUE )->GetText(); + msg = component->GetField( VALUE )->GetText(); msg.Replace( wxT( " " ), wxT( "_" ) ); ret |= fprintf( f, " \"%s\"", TO_UTF8( msg ) ); ret |= fprintf( f, "\n" ); @@ -1836,18 +1835,18 @@ bool NETLIST_EXPORT_TOOL::writeListOfNetsCADSTAR( FILE* f ) switch( print_ter ) { case 0: - { - char buf[5]; - wxString str_pinnum; - strncpy( buf, (char*) &nitem->m_PinNum, 4 ); - buf[4] = 0; - str_pinnum = FROM_UTF8( buf ); - InitNetDescLine.Printf( wxT( "\n%s %s %.4s %s" ), - GetChars( InitNetDesc ), - GetChars( refstr ), - GetChars( str_pinnum ), - GetChars( netcodeName ) ); - } + { + char buf[5]; + wxString str_pinnum; + strncpy( buf, (char*) &nitem->m_PinNum, 4 ); + buf[4] = 0; + str_pinnum = FROM_UTF8( buf ); + InitNetDescLine.Printf( wxT( "\n%s %s %.4s %s" ), + GetChars( InitNetDesc ), + GetChars( refstr ), + GetChars( str_pinnum ), + GetChars( netcodeName ) ); + } print_ter++; break; diff --git a/eeschema/operations_on_items_lists.cpp b/eeschema/operations_on_items_lists.cpp index e897d8d735..28464a0ec6 100644 --- a/eeschema/operations_on_items_lists.cpp +++ b/eeschema/operations_on_items_lists.cpp @@ -5,7 +5,7 @@ */ #include -#include +#include #include #include diff --git a/eeschema/pinedit.cpp b/eeschema/pinedit.cpp index eee9cf5dca..202a7d691f 100644 --- a/eeschema/pinedit.cpp +++ b/eeschema/pinedit.cpp @@ -86,13 +86,13 @@ void LIB_EDIT_FRAME::OnEditPin( wxCommandEvent& event ) LIB_PIN::GetElectricalTypeSymbols() ); dlg.SetElectricalType( pin->GetType() ); dlg.SetName( pin->GetName() ); - dlg.SetNameTextSize( ReturnStringFromValue( g_UserUnit, pin->GetNameTextSize() ) ); + dlg.SetNameTextSize( StringFromValue( g_UserUnit, pin->GetNameTextSize() ) ); dlg.SetNameTextSizeUnits( units ); dlg.SetPadName( pin->GetNumberString() ); - dlg.SetPadNameTextSize( ReturnStringFromValue( g_UserUnit, pin->GetNumberTextSize() ) ); + dlg.SetPadNameTextSize( StringFromValue( g_UserUnit, pin->GetNumberTextSize() ) ); dlg.SetPadNameTextSizeUnits( units ); - dlg.SetLength( ReturnStringFromValue( g_UserUnit, pin->GetLength() ) ); + dlg.SetLength( StringFromValue( g_UserUnit, pin->GetLength() ) ); dlg.SetLengthUnits( units ); dlg.SetAddToAllParts( pin->GetUnit() == 0 ); dlg.SetAddToAllBodyStyles( pin->GetConvert() == 0 ); @@ -120,10 +120,10 @@ void LIB_EDIT_FRAME::OnEditPin( wxCommandEvent& event ) } // Save the pin properties to use for the next new pin. - LastPinNameSize = ReturnValueFromString( g_UserUnit, dlg.GetNameTextSize() ); - LastPinNumSize = ReturnValueFromString( g_UserUnit, dlg.GetPadNameTextSize() ); + LastPinNameSize = ValueFromString( g_UserUnit, dlg.GetNameTextSize() ); + LastPinNumSize = ValueFromString( g_UserUnit, dlg.GetPadNameTextSize() ); LastPinOrient = LIB_PIN::GetOrientationCode( dlg.GetOrientation() ); - LastPinLength = ReturnValueFromString( g_UserUnit, dlg.GetLength() ); + LastPinLength = ValueFromString( g_UserUnit, dlg.GetLength() ); LastPinShape = LIB_PIN::GetStyleCode( dlg.GetStyle() ); LastPinType = dlg.GetElectricalType(); LastPinCommonConvert = dlg.GetAddToAllBodyStyles(); @@ -546,7 +546,7 @@ void LIB_EDIT_FRAME::RepeatPinItem( wxDC* DC, LIB_PIN* SourcePin ) IncrementLabelMember( nextName ); Pin->SetName( nextName ); - Pin->ReturnPinStringNum( msg ); + Pin->PinStringNum( msg ); IncrementLabelMember( msg ); Pin->SetPinNumFromString( msg ); @@ -644,11 +644,11 @@ void LIB_EDIT_FRAME::OnCheckComponent( wxCommandEvent& event ) continue; dup_error++; - Pin->ReturnPinStringNum( stringPinNum ); + Pin->PinStringNum( stringPinNum ); /* TODO I dare someone to find a way to make happy translators on this thing! Lorenzo */ - curr_pin->ReturnPinStringNum( stringCurrPinNum ); + curr_pin->PinStringNum( stringCurrPinNum ); msg.Printf( _( "Duplicate pin %s \"%s\" at location (%.3f, \ %.3f) conflicts with pin %s \"%s\" at location (%.3f, %.3f)" ), GetChars( stringCurrPinNum ), @@ -692,7 +692,8 @@ void LIB_EDIT_FRAME::OnCheckComponent( wxCommandEvent& event ) // A pin is found here off grid offgrid_error++; wxString stringPinNum; - Pin->ReturnPinStringNum( stringPinNum ); + Pin->PinStringNum( stringPinNum ); + msg.Printf( _( "Off grid pin %s \"%s\" at location (%.3f, %.3f)" ), GetChars( stringPinNum ), GetChars( Pin->GetName() ), diff --git a/eeschema/plot_schematic_HPGL.cpp b/eeschema/plot_schematic_HPGL.cpp index b520cced70..f1a4dff409 100644 --- a/eeschema/plot_schematic_HPGL.cpp +++ b/eeschema/plot_schematic_HPGL.cpp @@ -97,7 +97,7 @@ static const wxChar* plot_sheet_list( int aSize ) void DIALOG_PLOT_SCHEMATIC::SetHPGLPenWidth() { - m_HPGLPenSize = ReturnValueFromTextCtrl( *m_penHPGLWidthCtrl ); + m_HPGLPenSize = ValueFromTextCtrl( *m_penHPGLWidthCtrl ); if( m_HPGLPenSize > Millimeter2iu( 2 ) ) m_HPGLPenSize = Millimeter2iu( 2 ); diff --git a/eeschema/plot_schematic_SVG.cpp b/eeschema/plot_schematic_SVG.cpp index de1ffb0466..050bad1105 100644 --- a/eeschema/plot_schematic_SVG.cpp +++ b/eeschema/plot_schematic_SVG.cpp @@ -28,7 +28,7 @@ */ #include -#include +#include #include #include #include @@ -80,12 +80,12 @@ void DIALOG_PLOT_SCHEMATIC::createSVGFile( bool aPrintAll, bool aPrintFrameRef ) if( !success ) { - msg.Printf( _( "Error creating file <%s>\n" ), + msg.Printf( _( "Error creating file <%s>\n" ), GetChars( fn.GetFullPath() ) ); } else { - msg.Printf( _( "File <%s> OK\n" ), + msg.Printf( _( "File <%s> OK\n" ), GetChars( fn.GetFullPath() ) ); } diff --git a/eeschema/sch_base_frame.cpp b/eeschema/sch_base_frame.cpp index 891a1c1f29..686efce6de 100644 --- a/eeschema/sch_base_frame.cpp +++ b/eeschema/sch_base_frame.cpp @@ -27,24 +27,25 @@ #include #include -SCH_BASE_FRAME::SCH_BASE_FRAME( wxWindow* aParent, - ID_DRAWFRAME_TYPE aWindowType, - const wxString& aTitle, - const wxPoint& aPosition, const wxSize& aSize, - long aStyle, const wxString & aFrameName ) : - EDA_DRAW_FRAME( aParent, aWindowType, aTitle, aPosition, aSize, aStyle, aFrameName ) + +SCH_BASE_FRAME::SCH_BASE_FRAME( KIWAY* aKiway, wxWindow* aParent, + ID_DRAWFRAME_TYPE aWindowType, const wxString& aTitle, + const wxPoint& aPosition, const wxSize& aSize, long aStyle, + const wxString& aFrameName ) : + EDA_DRAW_FRAME( aKiway, aParent, aWindowType, aTitle, aPosition, + aSize, aStyle, aFrameName ) { } void SCH_BASE_FRAME::OnOpenLibraryViewer( wxCommandEvent& event ) { - LIB_VIEW_FRAME * viewlibFrame = LIB_VIEW_FRAME::GetActiveLibraryViewer();; + LIB_VIEW_FRAME* viewlibFrame = LIB_VIEW_FRAME::GetActiveLibraryViewer( this ); if( viewlibFrame ) viewlibFrame->Show( true ); else - new LIB_VIEW_FRAME( this ); + new LIB_VIEW_FRAME( &Kiway(), this ); } diff --git a/eeschema/sch_component.cpp b/eeschema/sch_component.cpp index 3575075845..90903a582a 100644 --- a/eeschema/sch_component.cpp +++ b/eeschema/sch_component.cpp @@ -28,7 +28,7 @@ */ #include -#include +#include #include #include #include diff --git a/eeschema/sch_field.cpp b/eeschema/sch_field.cpp index 71886a0205..942bf820e8 100644 --- a/eeschema/sch_field.cpp +++ b/eeschema/sch_field.cpp @@ -104,7 +104,7 @@ const wxString SCH_FIELD::GetFullyQualifiedText() const wxT( "No component associated with field" ) + text ); if( component->GetPartCount() > 1 ) - text << LIB_COMPONENT::ReturnSubReference( component->GetUnit() ); + text << LIB_COMPONENT::SubReference( component->GetUnit() ); } return text; @@ -419,7 +419,7 @@ bool SCH_FIELD::Matches( wxFindReplaceData& aSearchData, void* aAuxData, wxPoint text = component->GetRef( (SCH_SHEET_PATH*) aAuxData ); if( component->GetPartCount() > 1 ) - text << LIB_COMPONENT::ReturnSubReference( component->GetUnit() ); + text << LIB_COMPONENT::SubReference( component->GetUnit() ); } match = SCH_ITEM::Matches( text, aSearchData ); @@ -457,7 +457,7 @@ bool SCH_FIELD::Replace( wxFindReplaceData& aSearchData, void* aAuxData ) text = component->GetRef( (SCH_SHEET_PATH*) aAuxData ); // if( component->GetPartCount() > 1 ) - // text << LIB_COMPONENT::ReturnSubReference( component->GetUnit() ); + // text << LIB_COMPONENT::SubReference( component->GetUnit() ); isReplaced = EDA_ITEM::Replace( aSearchData, text ); @@ -598,7 +598,7 @@ void SCH_FIELD::Plot( PLOTTER* aPlotter ) else /* We plot the reference, for a multiple parts per package */ { /* Adding A, B ... to the reference */ - wxString Text = m_Text + LIB_COMPONENT::ReturnSubReference( parent->GetUnit() ); + wxString Text = m_Text + LIB_COMPONENT::SubReference( parent->GetUnit() ); aPlotter->Text( textpos, color, Text, orient, m_Size, hjustify, vjustify, thickness, m_Italic, m_Bold ); diff --git a/eeschema/sch_screen.cpp b/eeschema/sch_screen.cpp index 52d512a78a..86a8ed9727 100644 --- a/eeschema/sch_screen.cpp +++ b/eeschema/sch_screen.cpp @@ -34,7 +34,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/eeschema/sch_sheet.cpp b/eeschema/sch_sheet.cpp index dd54465b99..95c268dcaa 100644 --- a/eeschema/sch_sheet.cpp +++ b/eeschema/sch_sheet.cpp @@ -636,9 +636,9 @@ const EDA_RECT SCH_SHEET::GetBoundingBox() const // Determine length of texts wxString text = wxT( "Sheet: " ) + m_name; - int textlen = ReturnGraphicTextWidth( text, m_sheetNameSize, false, lineWidth ); + int textlen = GraphicTextWidth( text, m_sheetNameSize, false, lineWidth ); text = wxT( "File: " ) + m_fileName; - int textlen2 = ReturnGraphicTextWidth( text, m_fileNameSize, false, lineWidth ); + int textlen2 = GraphicTextWidth( text, m_fileNameSize, false, lineWidth ); // Calculate bounding box X size: textlen = std::max( textlen, textlen2 ); diff --git a/eeschema/sch_text.cpp b/eeschema/sch_text.cpp index 90f932cf2d..7893abfa5f 100644 --- a/eeschema/sch_text.cpp +++ b/eeschema/sch_text.cpp @@ -795,7 +795,7 @@ void SCH_TEXT::GetMsgPanelInfo( MSG_PANEL_ITEMS& aList ) } // Display text size (X or Y value, with are the same value in Eeschema) - msg = ReturnStringFromValue( g_UserUnit, m_Size.x, true ); + msg = StringFromValue( g_UserUnit, m_Size.x, true ); aList.push_back( MSG_PANEL_ITEM( _( "Size" ), msg, RED ) ); } diff --git a/eeschema/schedit.cpp b/eeschema/schedit.cpp index 9bcf60ed0b..8706b5c4b5 100644 --- a/eeschema/schedit.cpp +++ b/eeschema/schedit.cpp @@ -28,8 +28,9 @@ */ #include +#include #include -#include +#include #include #include #include @@ -294,8 +295,9 @@ void SCH_EDIT_FRAME::Process_Special_Functions( wxCommandEvent& event ) if( LibEntry && LibEntry->GetDocFileName() != wxEmptyString ) { - GetAssociatedDocument( this, LibEntry->GetDocFileName(), - &wxGetApp().GetLibraryPathList() ); + SEARCH_STACK* lib_search = &Prj().SchSearchS(); + + GetAssociatedDocument( this, LibEntry->GetDocFileName(), lib_search ); } } break; diff --git a/eeschema/schframe.cpp b/eeschema/schframe.cpp index 808c3044c5..fa7cb5c5df 100644 --- a/eeschema/schframe.cpp +++ b/eeschema/schframe.cpp @@ -27,7 +27,9 @@ */ #include -#include +#include +#include +#include #include #include #include @@ -173,12 +175,9 @@ END_EVENT_TABLE() #define SCH_EDIT_FRAME_NAME wxT( "SchematicFrame" ) - -SCH_EDIT_FRAME::SCH_EDIT_FRAME( wxWindow* aParent, const wxString& aTitle, - const wxPoint& aPosition, const wxSize& aSize, - long aStyle ) : - SCH_BASE_FRAME( aParent, SCHEMATIC_FRAME_TYPE, aTitle, aPosition, aSize, - aStyle, SCH_EDIT_FRAME_NAME ), +SCH_EDIT_FRAME::SCH_EDIT_FRAME( KIWAY* aKiway, wxWindow* aParent ): + SCH_BASE_FRAME( aKiway, aParent, SCHEMATIC_FRAME_TYPE, wxT( "Eeschema" ), + wxDefaultPosition, wxDefaultSize, KICAD_DEFAULT_DRAWFRAME_STYLE, SCH_EDIT_FRAME_NAME ), m_item_to_repeat( 0 ) { m_FrameName = SCH_EDIT_FRAME_NAME; @@ -212,8 +211,7 @@ SCH_EDIT_FRAME::SCH_EDIT_FRAME( wxWindow* aParent, const wxString& aTitle, // Initialize grid id to the default value (50 mils): m_LastGridSizeId = ID_POPUP_GRID_LEVEL_50 - ID_POPUP_GRID_LEVEL_1000; - /* Get config */ - LoadSettings(); + LoadSettings( config() ); // Ensure m_LastGridSizeId is an offset inside the allowed schematic range if( m_LastGridSizeId < ID_POPUP_GRID_LEVEL_50 - ID_POPUP_GRID_LEVEL_1000 ) @@ -448,7 +446,7 @@ void SCH_EDIT_FRAME::OnCloseWindow( wxCloseEvent& aEvent ) if( libeditFrame && !libeditFrame->Close() ) // Can close component editor? return; - LIB_VIEW_FRAME * viewlibFrame = LIB_VIEW_FRAME::GetActiveLibraryViewer();; + LIB_VIEW_FRAME* viewlibFrame = LIB_VIEW_FRAME::GetActiveLibraryViewer( this ); if( viewlibFrame && !viewlibFrame->Close() ) // Can close component viewer? return; @@ -716,12 +714,10 @@ void SCH_EDIT_FRAME::OnFindDialogClose( wxFindDialogEvent& event ) void SCH_EDIT_FRAME::OnLoadFile( wxCommandEvent& event ) { - wxString fn; + wxString fn = GetFileFromHistory( event.GetId(), _( "Schematic" ) ); - fn = GetFileFromHistory( event.GetId(), _( "Schematic" ) ); - - if( fn != wxEmptyString ) - LoadOneEEProject( fn, false ); + if( fn.size() ) + OpenProjectFiles( std::vector( 1, fn ) ); } @@ -734,13 +730,29 @@ void SCH_EDIT_FRAME::OnLoadCmpToFootprintLinkFile( wxCommandEvent& event ) void SCH_EDIT_FRAME::OnNewProject( wxCommandEvent& event ) { - LoadOneEEProject( wxEmptyString, true ); + wxFileDialog dlg( this, _( "New Schematic" ), wxGetCwd(), + wxEmptyString, SchematicFileWildcard, + wxFD_SAVE ); + + if( dlg.ShowModal() != wxID_CANCEL ) + { + OpenProjectFiles( std::vector( 1, dlg.GetPath() ), 1 ); + } } void SCH_EDIT_FRAME::OnLoadProject( wxCommandEvent& event ) { - LoadOneEEProject( wxEmptyString, false ); + // LoadOneEEProject( wxEmptyString, false ); + + wxFileDialog dlg( this, _( "Open Schematic" ), wxGetCwd(), + wxEmptyString, SchematicFileWildcard, + wxFD_OPEN | wxFD_FILE_MUST_EXIST ); + + if( dlg.ShowModal() != wxID_CANCEL ) + { + OpenProjectFiles( std::vector( 1, dlg.GetPath() ) ); + } } @@ -797,7 +809,7 @@ void SCH_EDIT_FRAME::OnOpenLibraryEditor( wxCommandEvent& event ) component = (SCH_COMPONENT*) item; } - LIB_EDIT_FRAME * libeditFrame = LIB_EDIT_FRAME::GetActiveLibraryEditor();; + LIB_EDIT_FRAME* libeditFrame = LIB_EDIT_FRAME::GetActiveLibraryEditor();; if( libeditFrame ) { if( libeditFrame->IsIconized() ) @@ -807,10 +819,8 @@ void SCH_EDIT_FRAME::OnOpenLibraryEditor( wxCommandEvent& event ) } else { - libeditFrame = new LIB_EDIT_FRAME( this, - wxT( "Library Editor" ), - wxPoint( -1, -1 ), - wxSize( 600, 400 ) ); + wxWindow* w = Kiface().CreateWindow( this, LIBEDITOR_FRAME_TYPE, &Kiway() ); + libeditFrame = dynamic_cast( w ); } if( component ) @@ -850,13 +860,15 @@ void SCH_EDIT_FRAME::OnPrint( wxCommandEvent& event ) fn = g_RootSheet->GetScreen()->GetFileName(); - wxString default_name = NAMELESS_PROJECT; - default_name += wxT( ".sch" ); + wxString default_name = NAMELESS_PROJECT wxT( ".sch" ); if( fn.GetFullName() != default_name ) { fn.SetExt( ProjectFileExtension ); - wxGetApp().WriteProjectConfig( fn.GetFullPath(), GROUP, GetProjectFileParametersList() ); + + // was: wxGetApp().WriteProjectConfig( fn.GetFullPath(), GROUP, GetProjectFileParametersList() ); + Prj().ConfigSave( Kiface().KifaceSearch(), + fn.GetFullPath(), GROUP, GetProjectFileParametersList() ); } } diff --git a/eeschema/selpart.cpp b/eeschema/selpart.cpp index 6368deedc8..22fa518c9b 100644 --- a/eeschema/selpart.cpp +++ b/eeschema/selpart.cpp @@ -5,7 +5,7 @@ #include #include #include -#include +#include #include #include diff --git a/eeschema/sheet.cpp b/eeschema/sheet.cpp index ab9730b3ea..3dbb135fc1 100644 --- a/eeschema/sheet.cpp +++ b/eeschema/sheet.cpp @@ -50,10 +50,10 @@ bool SCH_EDIT_FRAME::EditSheet( SCH_SHEET* aSheet, wxDC* aDC ) wxString units = GetUnitsLabel( g_UserUnit ); dlg.SetFileName( aSheet->GetFileName() ); - dlg.SetFileNameTextSize( ReturnStringFromValue( g_UserUnit, aSheet->GetFileNameSize() ) ); + dlg.SetFileNameTextSize( StringFromValue( g_UserUnit, aSheet->GetFileNameSize() ) ); dlg.SetFileNameTextSizeUnits( units ); dlg.SetSheetName( aSheet->GetName() ); - dlg.SetSheetNameTextSize( ReturnStringFromValue( g_UserUnit, aSheet->GetSheetNameSize() ) ); + dlg.SetSheetNameTextSize( StringFromValue( g_UserUnit, aSheet->GetSheetNameSize() ) ); dlg.SetSheetNameTextSizeUnits( units ); dlg.SetSheetTimeStamp( wxString::Format( wxT("%8.8lX"), (unsigned long) aSheet->GetTimeStamp() ) ); @@ -213,9 +213,9 @@ bool SCH_EDIT_FRAME::EditSheet( SCH_SHEET* aSheet, wxDC* aDC ) else if( loadFromFile ) aSheet->Load( this ); - aSheet->SetFileNameSize( ReturnValueFromString( g_UserUnit, dlg.GetFileNameTextSize() ) ); + aSheet->SetFileNameSize( ValueFromString( g_UserUnit, dlg.GetFileNameTextSize() ) ); aSheet->SetName( dlg.GetSheetName() ); - aSheet->SetSheetNameSize( ReturnValueFromString( g_UserUnit, dlg.GetSheetNameTextSize() ) ); + aSheet->SetSheetNameSize( ValueFromString( g_UserUnit, dlg.GetSheetNameTextSize() ) ); if( aSheet->GetName().IsEmpty() ) aSheet->SetName( wxString::Format( wxT( "Sheet%8.8lX" ), aSheet->GetTimeStamp() ) ); diff --git a/eeschema/sheetlab.cpp b/eeschema/sheetlab.cpp index b644e76849..f9043a226d 100644 --- a/eeschema/sheetlab.cpp +++ b/eeschema/sheetlab.cpp @@ -56,9 +56,9 @@ int SCH_EDIT_FRAME::EditSheetPin( SCH_SHEET_PIN* aSheetPin, wxDC* aDC ) DIALOG_SCH_EDIT_SHEET_PIN dlg( this ); dlg.SetLabelName( aSheetPin->GetText() ); - dlg.SetTextHeight( ReturnStringFromValue( g_UserUnit, aSheetPin->GetSize().y ) ); + dlg.SetTextHeight( StringFromValue( g_UserUnit, aSheetPin->GetSize().y ) ); dlg.SetTextHeightUnits( GetUnitsLabel( g_UserUnit ) ); - dlg.SetTextWidth( ReturnStringFromValue( g_UserUnit, aSheetPin->GetSize().x ) ); + dlg.SetTextWidth( StringFromValue( g_UserUnit, aSheetPin->GetSize().x ) ); dlg.SetTextWidthUnits( GetUnitsLabel( g_UserUnit ) ); dlg.SetConnectionType( aSheetPin->GetShape() ); @@ -84,8 +84,8 @@ int SCH_EDIT_FRAME::EditSheetPin( SCH_SHEET_PIN* aSheetPin, wxDC* aDC ) } aSheetPin->SetText( dlg.GetLabelName() ); - aSheetPin->SetSize( wxSize( ReturnValueFromString( g_UserUnit, dlg.GetTextHeight() ), - ReturnValueFromString( g_UserUnit, dlg.GetTextWidth() ) ) ); + aSheetPin->SetSize( wxSize( ValueFromString( g_UserUnit, dlg.GetTextHeight() ), + ValueFromString( g_UserUnit, dlg.GetTextWidth() ) ) ); aSheetPin->SetShape( dlg.GetConnectionType() ); if( aDC ) diff --git a/eeschema/symbdraw.cpp b/eeschema/symbdraw.cpp index 619db5b46b..79d80f3491 100644 --- a/eeschema/symbdraw.cpp +++ b/eeschema/symbdraw.cpp @@ -69,7 +69,7 @@ void LIB_EDIT_FRAME::EditGraphicSymbol( wxDC* DC, LIB_ITEM* DrawItem ) dialog.SetWidthUnits( ReturnUnitSymbol( g_UserUnit ) ); - wxString val = ReturnStringFromValue( g_UserUnit, DrawItem->GetWidth() ); + wxString val = StringFromValue( g_UserUnit, DrawItem->GetWidth() ); dialog.SetWidth( val ); dialog.SetApplyToAllUnits( DrawItem->GetUnit() == 0 ); dialog.EnableApplyToAllUnits( component && component->GetPartCount() > 1 ); @@ -83,7 +83,7 @@ void LIB_EDIT_FRAME::EditGraphicSymbol( wxDC* DC, LIB_ITEM* DrawItem ) // Init default values (used to create a new draw item) val = dialog.GetWidth(); - m_drawLineWidth = ReturnValueFromString( g_UserUnit, val ); + m_drawLineWidth = ValueFromString( g_UserUnit, val ); m_drawSpecificConvert = !dialog.GetApplyToAllConversions(); m_drawSpecificUnit = !dialog.GetApplyToAllUnits(); diff --git a/eeschema/symbedit.cpp b/eeschema/symbedit.cpp index 95309e6757..a5dc98738d 100644 --- a/eeschema/symbedit.cpp +++ b/eeschema/symbedit.cpp @@ -29,7 +29,8 @@ */ #include -#include +#include +#include #include #include #include @@ -54,9 +55,12 @@ void LIB_EDIT_FRAME::LoadOneSymbol() if( m_component == NULL || ( m_drawItem && m_drawItem->GetFlags() ) ) return; + PROJECT& prj = Prj(); + SEARCH_STACK& search = prj.SchSearchS(); + m_canvas->SetIgnoreMouseEvents( true ); - wxString default_path = wxGetApp().ReturnLastVisitedLibraryPath(); + wxString default_path = prj.RPath(PROJECT::SCH_LIB).LastVisitedPath( search ); wxFileDialog dlg( this, _( "Import Symbol Drawings" ), default_path, wxEmptyString, SchematicSymbolFileWildcard, @@ -70,13 +74,14 @@ void LIB_EDIT_FRAME::LoadOneSymbol() m_canvas->SetIgnoreMouseEvents( false ); wxFileName fn = dlg.GetPath(); - wxGetApp().SaveLastVisitedLibraryPath( fn.GetPath() ); + + prj.RPath(PROJECT::SCH_LIB).SaveLastVisitedPath( fn.GetPath() ); Lib = new CMP_LIBRARY( LIBRARY_TYPE_SYMBOL, fn ); if( !Lib->Load( err ) ) { - msg.Printf( _( "Error <%s> occurred loading symbol library <%s>." ), + msg.Printf( _( "Error '%s' occurred loading symbol library '%s'." ), GetChars( err ), GetChars( fn.GetName() ) ); DisplayError( this, msg ); delete Lib; @@ -85,7 +90,7 @@ void LIB_EDIT_FRAME::LoadOneSymbol() if( Lib->IsEmpty() ) { - msg.Printf( _( "No components found in symbol library <%s>." ), + msg.Printf( _( "No components found in symbol library '%s'." ), GetChars( fn.GetName() ) ); delete Lib; return; @@ -93,7 +98,7 @@ void LIB_EDIT_FRAME::LoadOneSymbol() if( Lib->GetCount() > 1 ) { - msg.Printf( _( "More than one part in symbol file <%s>." ), + msg.Printf( _( "More than one part in symbol file '%s'." ), GetChars( fn.GetName() ) ); wxMessageBox( msg, _( "Warning" ), wxOK | wxICON_EXCLAMATION, this ); } @@ -131,12 +136,14 @@ void LIB_EDIT_FRAME::LoadOneSymbol() void LIB_EDIT_FRAME::SaveOneSymbol() { - wxString msg; + wxString msg; + PROJECT& prj = Prj(); + SEARCH_STACK& search = prj.SchSearchS(); if( m_component->GetDrawItemList().empty() ) return; - wxString default_path = wxGetApp().ReturnLastVisitedLibraryPath(); + wxString default_path = prj.RPath(PROJECT::SCH_LIB).LastVisitedPath( search ); wxFileDialog dlg( this, _( "Export Symbol Drawings" ), default_path, m_component->GetName(), SchematicSymbolFileWildcard, @@ -152,9 +159,9 @@ void LIB_EDIT_FRAME::SaveOneSymbol() if( fn.GetExt().IsEmpty() ) fn.SetExt( SchematicSymbolFileExtension ); - wxGetApp().SaveLastVisitedLibraryPath( fn.GetPath() ); + prj.RPath(PROJECT::SCH_LIB).SaveLastVisitedPath( fn.GetPath() ); - msg.Printf( _( "Saving symbol in <%s>" ), GetChars( fn.GetPath() ) ); + msg.Printf( _( "Saving symbol in '%s'" ), GetChars( fn.GetPath() ) ); SetStatusText( msg ); wxString line; @@ -220,7 +227,7 @@ void LIB_EDIT_FRAME::SaveOneSymbol() } catch( IO_ERROR ioe ) { - msg.Printf( _( "An error occurred attempting to save symbol file <%s>" ), + msg.Printf( _( "An error occurred attempting to save symbol file '%s'" ), GetChars( fn.GetFullPath() ) ); DisplayError( this, msg ); } diff --git a/eeschema/viewlib_frame.cpp b/eeschema/viewlib_frame.cpp index b6a3b296a6..3963b03dbf 100644 --- a/eeschema/viewlib_frame.cpp +++ b/eeschema/viewlib_frame.cpp @@ -28,7 +28,8 @@ */ #include -#include +#include +#include #include #include #include @@ -94,10 +95,10 @@ static wxAcceleratorEntry accels[] = #define ACCEL_TABLE_CNT ( sizeof( accels ) / sizeof( wxAcceleratorEntry ) ) #define LIB_VIEW_FRAME_NAME wxT( "ViewlibFrame" ) -LIB_VIEW_FRAME::LIB_VIEW_FRAME( SCH_BASE_FRAME* aParent, CMP_LIBRARY* aLibrary, - wxSemaphore* aSemaphore, long aStyle ) : - SCH_BASE_FRAME( aParent, VIEWER_FRAME_TYPE, _( "Library Browser" ), - wxDefaultPosition, wxDefaultSize, aStyle, GetLibViewerFrameName() ) +LIB_VIEW_FRAME::LIB_VIEW_FRAME( KIWAY* aKiway, SCH_BASE_FRAME* aParent, + CMP_LIBRARY* aLibrary, wxSemaphore* aSemaphore, long aStyle ) : + SCH_BASE_FRAME( aKiway, aParent, VIEWER_FRAME_TYPE, _( "Library Browser" ), + wxDefaultPosition, wxDefaultSize, aStyle, GetLibViewerFrameName() ) { wxAcceleratorTable table( ACCEL_TABLE_CNT, accels ); @@ -122,7 +123,7 @@ LIB_VIEW_FRAME::LIB_VIEW_FRAME( SCH_BASE_FRAME* aParent, CMP_LIBRARY* aLibrary, SetScreen( new SCH_SCREEN() ); GetScreen()->m_Center = true; // Axis origin centered on screen. - LoadSettings(); + LoadSettings( config() ); SetSize( m_FramePos.x, m_FramePos.y, m_FrameSize.x, m_FrameSize.y ); @@ -242,9 +243,9 @@ const wxChar* LIB_VIEW_FRAME::GetLibViewerFrameName() } -LIB_VIEW_FRAME* LIB_VIEW_FRAME::GetActiveLibraryViewer() +LIB_VIEW_FRAME* LIB_VIEW_FRAME::GetActiveLibraryViewer( const wxWindow* aParent ) { - return (LIB_VIEW_FRAME*) wxWindow::FindWindowByName(GetLibViewerFrameName()); + return (LIB_VIEW_FRAME*) wxWindow::FindWindowByName( GetLibViewerFrameName(), aParent ); } @@ -484,17 +485,14 @@ void LIB_VIEW_FRAME::ExportToSchematicLibraryPart( wxCommandEvent& event ) #define CMPLIST_WIDTH_KEY wxT( "ViewCmplistWidth" ) -void LIB_VIEW_FRAME::LoadSettings( ) +void LIB_VIEW_FRAME::LoadSettings( wxConfigBase* aCfg ) { - wxConfig* cfg ; + EDA_DRAW_FRAME::LoadSettings( aCfg ); - EDA_DRAW_FRAME::LoadSettings(); + wxConfigPathChanger cpc( aCfg, m_configPath ); - wxConfigPathChanger cpc( wxGetApp().GetSettings(), m_configPath ); - cfg = wxGetApp().GetSettings(); - - cfg->Read( LIBLIST_WIDTH_KEY, &m_libListWidth, 100 ); - cfg->Read( CMPLIST_WIDTH_KEY, &m_cmpListWidth, 100 ); + aCfg->Read( LIBLIST_WIDTH_KEY, &m_libListWidth, 100 ); + aCfg->Read( CMPLIST_WIDTH_KEY, &m_cmpListWidth, 100 ); // Set parameters to a reasonable value. if( m_libListWidth > m_FrameSize.x/2 ) @@ -505,23 +503,20 @@ void LIB_VIEW_FRAME::LoadSettings( ) } -void LIB_VIEW_FRAME::SaveSettings() +void LIB_VIEW_FRAME::SaveSettings( wxConfigBase* aCfg ) { - wxConfig* cfg; + EDA_DRAW_FRAME::SaveSettings( aCfg ); - EDA_DRAW_FRAME::SaveSettings(); + wxConfigPathChanger cpc( aCfg, m_configPath ); - wxConfigPathChanger cpc( wxGetApp().GetSettings(), m_configPath ); - cfg = wxGetApp().GetSettings(); - - if( m_libListWidth && m_libList) + if( m_libListWidth && m_libList ) { m_libListWidth = m_libList->GetSize().x; - cfg->Write( LIBLIST_WIDTH_KEY, m_libListWidth ); + aCfg->Write( LIBLIST_WIDTH_KEY, m_libListWidth ); } m_cmpListWidth = m_cmpList->GetSize().x; - cfg->Write( CMPLIST_WIDTH_KEY, m_cmpListWidth ); + aCfg->Write( CMPLIST_WIDTH_KEY, m_cmpListWidth ); } diff --git a/eeschema/viewlib_frame.h b/eeschema/viewlib_frame.h index f5b4a05f85..bdb304a312 100644 --- a/eeschema/viewlib_frame.h +++ b/eeschema/viewlib_frame.h @@ -48,9 +48,9 @@ class CMP_LIBRARY; class LIB_VIEW_FRAME : public SCH_BASE_FRAME { public: - LIB_VIEW_FRAME( SCH_BASE_FRAME* aParent, CMP_LIBRARY* aLibrary = NULL, - wxSemaphore* aSemaphore = NULL, - long aStyle = KICAD_DEFAULT_DRAWFRAME_STYLE ); + LIB_VIEW_FRAME( KIWAY* aKiway, SCH_BASE_FRAME* aParent, + CMP_LIBRARY* aLibrary = NULL, wxSemaphore* aSemaphore = NULL, + long aStyle = KICAD_DEFAULT_DRAWFRAME_STYLE ); ~LIB_VIEW_FRAME(); @@ -66,7 +66,7 @@ public: * @return a reference to the current opened Library viewer * or NULL if no Library viewer currently opened */ - static LIB_VIEW_FRAME* GetActiveLibraryViewer(); + static LIB_VIEW_FRAME* GetActiveLibraryViewer( const wxWindow* aParent ); void OnSize( wxSizeEvent& event ); @@ -93,23 +93,8 @@ public: void GeneralControl( wxDC* aDC, const wxPoint& aPosition, int aHotKey = 0 ); - /** - * Function LoadSettings - * loads the library viewer frame specific configuration settings. - * - * Don't forget to call this base method from any derived classes or the - * settings will not get loaded. - */ - void LoadSettings(); - - /** - * Function SaveSettings - * save library viewer frame specific configuration settings. - * - * Don't forget to call this base method from any derived classes or the - * settings will not get saved. - */ - void SaveSettings(); + void LoadSettings( wxConfigBase* aCfg ); + void SaveSettings( wxConfigBase* aCfg ); /** * Set the selected library in the library window. diff --git a/eeschema/viewlibs.cpp b/eeschema/viewlibs.cpp index 289b37a1d9..15e76c8941 100644 --- a/eeschema/viewlibs.cpp +++ b/eeschema/viewlibs.cpp @@ -3,8 +3,9 @@ */ #include +#include #include -#include +#include #include #include #include @@ -51,8 +52,11 @@ void LIB_VIEW_FRAME::Process_Special_Functions( wxCommandEvent& event ) LibEntry = CMP_LIBRARY::FindLibraryEntry( m_entryName, m_libraryName ); if( LibEntry && ( !LibEntry->GetDocFileName().IsEmpty() ) ) - GetAssociatedDocument( this, LibEntry->GetDocFileName(), - &wxGetApp().GetLibraryPathList() ); + { + SEARCH_STACK& lib_search = Prj().SchSearchS(); + + GetAssociatedDocument( this, LibEntry->GetDocFileName(), &lib_search ); + } break; case ID_LIBVIEW_DE_MORGAN_NORMAL_BUTT: diff --git a/gerbview/CMakeLists.txt b/gerbview/CMakeLists.txt index c34b979deb..685c826a1d 100644 --- a/gerbview/CMakeLists.txt +++ b/gerbview/CMakeLists.txt @@ -1,10 +1,8 @@ +set( MAKE_LINK_MAPS true ) + add_definitions(-DGERBVIEW) -### -# Includes -### - -include_directories(BEFORE ${INC_BEFORE}) +include_directories( BEFORE ${INC_BEFORE} ) include_directories( ../pcbnew dialogs @@ -14,11 +12,7 @@ include_directories( ) -### -# Sources -### - -set(DIALOGS_SRCS +set( DIALOGS_SRCS dialogs/gerbview_dialog_display_options_frame_base.cpp dialogs/gerbview_dialog_display_options_frame.cpp dialogs/dialog_layers_select_to_pcb_base.cpp @@ -29,7 +23,7 @@ set(DIALOGS_SRCS dialogs/dialog_show_page_borders_base.cpp ) -set(GERBVIEW_SRCS +set( GERBVIEW_SRCS block.cpp class_am_param.cpp class_aperture_macro.cpp @@ -47,7 +41,6 @@ set(GERBVIEW_SRCS excellon_read_drill_file.cpp export_to_pcbnew.cpp files.cpp - gerbview.cpp gerbview_config.cpp gerbview_frame.cpp hotkeys.cpp @@ -65,10 +58,7 @@ set(GERBVIEW_SRCS toolbars_gerber.cpp ) -### -# We need some extra sources from common and pcbnew -### -set(GERBVIEW_EXTRA_SRCS +set( GERBVIEW_EXTRA_SRCS ../common/base_screen.cpp ../common/base_units.cpp ../common/eda_text.cpp @@ -78,58 +68,125 @@ set(GERBVIEW_EXTRA_SRCS ../pcbnew/printout_controler.cpp ) -### -# Windows resource file -### -if(WIN32) - if(MINGW) - # GERBVIEW_RESOURCES variable is set by the macro. - mingw_resource_compiler(gerbview) - else(MINGW) - set(GERBVIEW_RESOURCES gerbview.rc) - endif(MINGW) -endif(WIN32) +if( MINGW ) + # GERBVIEW_RESOURCES variable is set by the macro. + mingw_resource_compiler( gerbview ) +endif() -### -# Apple resource files -### -if(APPLE) + +if( APPLE ) set(GERBVIEW_RESOURCES gerbview.icns gerbview_doc.icns) - set_source_files_properties("${CMAKE_CURRENT_SOURCE_DIR}/gerbview.icns" - PROPERTIES MACOSX_PACKAGE_LOCATION Resources) - set_source_files_properties("${CMAKE_CURRENT_SOURCE_DIR}/gerbview_doc.icns" - PROPERTIES MACOSX_PACKAGE_LOCATION Resources) - set(MACOSX_BUNDLE_ICON_FILE gerbview.icns) - set(MACOSX_BUNDLE_GUI_IDENTIFIER org.kicad-eda.gerbview) -endif(APPLE) + set_source_files_properties("${CMAKE_CURRENT_SOURCE_DIR}/gerbview.icns" PROPERTIES + MACOSX_PACKAGE_LOCATION Resources + ) + set_source_files_properties("${CMAKE_CURRENT_SOURCE_DIR}/gerbview_doc.icns" PROPERTIES + MACOSX_PACKAGE_LOCATION Resources + ) + set( MACOSX_BUNDLE_ICON_FILE gerbview.icns ) + set( MACOSX_BUNDLE_GUI_IDENTIFIER org.kicad-eda.gerbview ) +endif() -### -# Create the gerbview executable -### -add_executable(gerbview WIN32 MACOSX_BUNDLE - ${GERBVIEW_SRCS} - ${DIALOGS_SRCS} - ${GERBVIEW_EXTRA_SRCS} - ${GERBVIEW_RESOURCES}) +if( USE_KIWAY_DLLS ) -### -# Set properties for APPLE on gerbview target -### -if(APPLE) - set_target_properties(gerbview PROPERTIES MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/Info.plist) -endif(APPLE) + add_executable( gerbview WIN32 MACOSX_BUNDLE + ../common/single_top.cpp + ../common/pgm_base.cpp + ${GERBVIEW_RESOURCES} + ) + set_source_files_properties( ../common/single_top.cpp PROPERTIES + COMPILE_DEFINITIONS "TOP_FRAME=GERBER_FRAME_TYPE;BUILD_KIWAY_DLL" + ) + target_link_libraries( gerbview + #singletop # replaces common, giving us restrictive control and link warnings. + # There's way too much crap coming in from common yet. + common + bitmaps + ${wxWidgets_LIBRARIES} + ) + if( MAKE_LINK_MAPS ) + set_target_properties( gerbview PROPERTIES + LINK_FLAGS "${TO_LINKER},-cref ${TO_LINKER},-Map=gerbview.map" ) + endif() -### -# Link executable target gerbview with correct libraries -### -target_link_libraries(gerbview common polygon bitmaps - ${OPENGL_LIBRARIES} - ${wxWidgets_LIBRARIES} - ${GDI_PLUS_LIBRARIES}) + # the main gerbview program, in DSO form. + add_library( gerbview_kiface MODULE + gerbview.cpp + ${GERBVIEW_SRCS} + ${DIALOGS_SRCS} + ${GERBVIEW_EXTRA_SRCS} +# ${GERBVIEW_RESOURCES} + ) + set_target_properties( gerbview_kiface PROPERTIES + OUTPUT_NAME gerbview + PREFIX ${KIFACE_PREFIX} + SUFFIX ${KIFACE_SUFFIX} + ) + target_link_libraries( gerbview_kiface + common + polygon + bitmaps + ${OPENGL_LIBRARIES} + ${wxWidgets_LIBRARIES} + ${GDI_PLUS_LIBRARIES} + ) + set_source_files_properties( gerbview.cpp PROPERTIES + # The KIFACE is in gerbview.cpp, export it: + COMPILE_DEFINITIONS "BUILD_KIWAY_DLL;COMPILING_DLL" + ) + if( MAKE_LINK_MAPS ) + set_target_properties( gerbview_kiface PROPERTIES + LINK_FLAGS "${TO_LINKER},-cref ${TO_LINKER},-Map=_gerbview.kiface.map" ) + endif() -### -# Add gerbview as install target -### -install(TARGETS gerbview + # if building gerbview, then also build gerbview_kiface if out of date. + add_dependencies( gerbview gerbview_kiface ) + + # these 2 binaries are a matched set, keep them together + install( TARGETS gerbview DESTINATION ${KICAD_BIN} - COMPONENT binary) + COMPONENT binary + ) + install( TARGETS gerbview_kiface + DESTINATION ${KICAD_BIN} + COMPONENT binary + ) + + if( APPLE ) + # copies kiface into the bundle + add_custom_target( _gerbview_kiface_copy ALL + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/gerbview/_gerbview.kiface "${CMAKE_BINARY_DIR}/gerbview/gerbview.app/Contents/MacOS/" + DEPENDS gerbview_kiface + COMMENT "Copying kiface into gerbview" + ) + endif() + +else() + + add_executable( gerbview WIN32 MACOSX_BUNDLE + gerbview.cpp + ${GERBVIEW_SRCS} + ${DIALOGS_SRCS} + ${GERBVIEW_EXTRA_SRCS} + ${GERBVIEW_RESOURCES} + ) + target_link_libraries( gerbview + common + polygon + bitmaps + ${OPENGL_LIBRARIES} + ${wxWidgets_LIBRARIES} + ${GDI_PLUS_LIBRARIES} + ) + install( TARGETS gerbview + DESTINATION ${KICAD_BIN} + COMPONENT binary + ) + +endif() + +if( APPLE ) + set_target_properties( gerbview PROPERTIES + MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/Info.plist) +endif() + + diff --git a/gerbview/block.cpp b/gerbview/block.cpp index d973ac9a03..912113538a 100644 --- a/gerbview/block.cpp +++ b/gerbview/block.cpp @@ -46,7 +46,7 @@ static void DrawMovingBlockOutlines( EDA_DRAW_PANEL* aPanel, wxDC* aDC, const wx bool erase ); -int GERBVIEW_FRAME::ReturnBlockCommand( int key ) +int GERBVIEW_FRAME::BlockCommand( int key ) { int cmd = 0; diff --git a/gerbview/class_DCodeSelectionbox.cpp b/gerbview/class_DCodeSelectionbox.cpp index 32969313f6..84cf9cdc54 100644 --- a/gerbview/class_DCodeSelectionbox.cpp +++ b/gerbview/class_DCodeSelectionbox.cpp @@ -3,7 +3,7 @@ /*****************************************************************/ #include -#include +#include #include #include #include diff --git a/gerbview/class_GERBER.cpp b/gerbview/class_GERBER.cpp index 9d7b7302ea..5ae04d5083 100644 --- a/gerbview/class_GERBER.cpp +++ b/gerbview/class_GERBER.cpp @@ -225,7 +225,7 @@ bool GERBER_IMAGE::HasNegativeItems() return m_hasNegativeItems == 1; } -int GERBER_IMAGE::ReturnUsedDcodeNumber() +int GERBER_IMAGE::UsedDcodeNumber() { int count = 0; diff --git a/gerbview/class_GERBER.h b/gerbview/class_GERBER.h index 19fba78fd0..632ac6487c 100644 --- a/gerbview/class_GERBER.h +++ b/gerbview/class_GERBER.h @@ -141,7 +141,7 @@ public: GERBER_IMAGE( GERBVIEW_FRAME* aParent, int layer ); virtual ~GERBER_IMAGE(); void Clear_GERBER_IMAGE(); - int ReturnUsedDcodeNumber(); + int UsedDcodeNumber(); virtual void ResetDefaultValues(); /** @@ -211,8 +211,8 @@ public: wxPoint ReadIJCoord( char*& Text ); // functions to read G commands or D commands: - int ReturnGCodeNumber( char*& Text ); - int ReturnDCodeNumber( char*& Text ); + int GCodeNumber( char*& Text ); + int DCodeNumber( char*& Text ); // functions to execute G commands or D commands: bool Execute_G_Command( char*& text, int G_command ); diff --git a/gerbview/class_excellon.h b/gerbview/class_excellon.h index 86c9f356ca..07d2800b0d 100644 --- a/gerbview/class_excellon.h +++ b/gerbview/class_excellon.h @@ -101,9 +101,9 @@ private: bool Execute_EXCELLON_G_Command( char*& text ); bool Execute_Drill_Command( char*& text ); - int ReturnTCodeNumber( char*& Text ) + int TCodeNumber( char*& Text ) { - return ReturnDCodeNumber( Text ); + return DCodeNumber( Text ); } diff --git a/gerbview/dialogs/dialog_print_using_printer.cpp b/gerbview/dialogs/dialog_print_using_printer.cpp index da67c4989b..3f9f338416 100644 --- a/gerbview/dialogs/dialog_print_using_printer.cpp +++ b/gerbview/dialogs/dialog_print_using_printer.cpp @@ -6,7 +6,8 @@ #define wxTEST_POSTSCRIPT_IN_MSW 1 #include -#include +//#include +#include #include #include #include @@ -40,7 +41,7 @@ class DIALOG_PRINT_USING_PRINTER : public DIALOG_PRINT_USING_PRINTER_BASE { private: GERBVIEW_FRAME* m_Parent; - wxConfig* m_Config; + wxConfigBase* m_Config; wxCheckBox* m_BoxSelectLayer[32]; public: @@ -100,7 +101,7 @@ DIALOG_PRINT_USING_PRINTER::DIALOG_PRINT_USING_PRINTER( GERBVIEW_FRAME* parent ) /*************************************************************************************/ { m_Parent = parent; - m_Config = wxGetApp().GetSettings(); + m_Config = Kiface().KifaceSettings(); InitValues( ); GetSizer()->SetSizeHints( this ); diff --git a/gerbview/events_called_functions.cpp b/gerbview/events_called_functions.cpp index 6efd44786d..a1021c1fab 100644 --- a/gerbview/events_called_functions.cpp +++ b/gerbview/events_called_functions.cpp @@ -4,7 +4,7 @@ */ #include -#include +#include #include #include #include @@ -256,7 +256,7 @@ void GERBVIEW_FRAME::OnShowGerberSourceFile( wxCommandEvent& event ) if( gerber_layer ) { - wxString editorname = wxGetApp().GetEditorName(); + wxString editorname = Pgm().GetEditorName(); if( !editorname.IsEmpty() ) { wxFileName fn( gerber_layer->m_FileName ); diff --git a/gerbview/excellon_read_drill_file.cpp b/gerbview/excellon_read_drill_file.cpp index a16843f1f0..952d89c8d3 100644 --- a/gerbview/excellon_read_drill_file.cpp +++ b/gerbview/excellon_read_drill_file.cpp @@ -543,7 +543,7 @@ bool EXCELLON_IMAGE::Execute_Drill_Command( char*& text ) bool EXCELLON_IMAGE::Select_Tool( char*& text ) { - int tool_id = ReturnTCodeNumber( text ); + int tool_id = TCodeNumber( text ); if( tool_id >= 0 ) { diff --git a/gerbview/gerbview.cpp b/gerbview/gerbview.cpp index b1537bb0d1..4e52f3937a 100644 --- a/gerbview/gerbview.cpp +++ b/gerbview/gerbview.cpp @@ -27,7 +27,8 @@ */ #include -#include +#include +#include #include #include #include @@ -62,83 +63,103 @@ const wxChar* g_GerberPageSizeList[] = { GERBER_IMAGE* g_GERBER_List[32]; -IMPLEMENT_APP( EDA_APP ) +namespace GERBV { -/* MacOSX: Needed for file association - * http://wiki.wxwidgets.org/WxMac-specific_topics - */ -void EDA_APP::MacOpenFile( const wxString& aFileName ) +static struct IFACE : public KIFACE_I { - wxFileName filename = aFileName; - GERBVIEW_FRAME * frame = ((GERBVIEW_FRAME*)GetTopWindow()); + // Of course all are virtual overloads, implementations of the KIFACE. - if( !filename.FileExists() ) - return; + IFACE( const char* aName, KIWAY::FACE_T aType ) : + KIFACE_I( aName, aType ) + {} - frame->LoadGerberFiles( aFileName ); + bool OnKifaceStart( PGM_BASE* aProgram ); + + void OnKifaceEnd(); + + wxWindow* CreateWindow( wxWindow* aParent, int aClassId, KIWAY* aKiway, int aCtlBits = 0 ) + { + switch( aClassId ) + { + case GERBER_FRAME_TYPE: + { + GERBVIEW_FRAME* frame = new GERBVIEW_FRAME( aKiway, aParent ); + + /* Is this really needed since at this point there is no open file? + frame->Zoom_Automatique( true ); // Zoom fit in frame + + if so, why is the constructor not doing it? + */ + + return frame; + } + break; + + default: + ; + } + + return NULL; + } + + /** + * Function IfaceOrAddress + * return a pointer to the requested object. The safest way to use this + * is to retrieve a pointer to a static instance of an interface, similar to + * how the KIFACE interface is exported. But if you know what you are doing + * use it to retrieve anything you want. + * + * @param aDataId identifies which object you want the address of. + * + * @return void* - and must be cast into the know type. + */ + void* IfaceOrAddress( int aDataId ) + { + return NULL; + } + +} kiface( "gerbview", KIWAY::FACE_GERBVIEW ); + +} // namespace + +using namespace GERBV; + +static PGM_BASE* process; + +KIFACE_I& Kiface() { return kiface; } + + +// KIFACE_GETTER's actual spelling is a substitution macro found in kiway.h. +// KIFACE_GETTER will not have name mangling due to declaration in kiway.h. +MY_API( KIFACE* ) KIFACE_GETTER( int* aKIFACEversion, int aKiwayVersion, PGM_BASE* aProgram ) +{ + process = (PGM_BASE*) aProgram; + return &kiface; } -bool EDA_APP::OnInit() +PGM_BASE& Pgm() { - wxFileName fn; - GERBVIEW_FRAME* frame = NULL; + wxASSERT( process ); // KIFACE_GETTER has already been called. + return *process; +} - InitEDA_Appl( wxT( "GerbView" ), APP_GERBVIEW_T ); - if( m_Checker && m_Checker->IsAnotherRunning() ) - { - if( !IsOK( NULL, _( "GerbView is already running. Continue?" ) ) ) - return false; - } +bool IFACE::OnKifaceStart( PGM_BASE* aProgram ) +{ + start_common(); - // read current setup and reopen last directory if no filename to open in - // command line - bool reopenLastUsedDirectory = argc == 1; - GetSettings( reopenLastUsedDirectory ); + // Must be called before creating the main frame in order to + // display the real hotkeys in menus or tool tips + ReadHotkeyConfig( wxT("GerberFrame"), s_Gerbview_Hokeys_Descr ); g_DrawBgColor = BLACK; - /* Must be called before creating the main frame in order to - * display the real hotkeys in menus or tool tips */ - ReadHotkeyConfig( wxT("GerberFrame"), s_Gerbview_Hokeys_Descr ); - - frame = new GERBVIEW_FRAME( NULL, wxT( "GerbView" ), wxPoint( 0, 0 ), wxSize( 600, 400 ) ); - - /* Gerbview mainframe title */ - frame->SetTitle( GetTitle() + wxT( " " ) + GetBuildVersion() ); - - SetTopWindow( frame ); // Set GerbView mainframe on top - frame->Show( true ); // Show GerbView mainframe - frame->Zoom_Automatique( true ); // Zoom fit in frame - frame->GetScreen()->m_FirstRedraw = false; - - - if( argc <= 1 ) - return true; - - fn = argv[1]; - - if( fn.IsOk() ) - { - if( fn.DirExists() ) - wxSetWorkingDirectory( fn.GetPath() ); - - // Load all files specified on the command line. - LAYER_NUM jj = FIRST_LAYER; - - for( LAYER_NUM ii = LAYER_N_2; ii < argc && ii <= NB_GERBER_LAYERS; ++ii ) - { - fn = wxFileName( argv[ii] ); - - if( fn.FileExists() ) - { - frame->setActiveLayer( jj ); - ++jj; - frame->LoadGerberFiles( fn.GetFullPath() ); - } - } - } - return true; } + + +void IFACE::OnKifaceEnd() +{ + end_common(); +} diff --git a/gerbview/gerbview_config.cpp b/gerbview/gerbview_config.cpp index f3a06de0b2..db1ed29f3e 100644 --- a/gerbview/gerbview_config.cpp +++ b/gerbview/gerbview_config.cpp @@ -34,7 +34,7 @@ #include #include #include -#include +#include #include #include diff --git a/gerbview/gerbview_frame.cpp b/gerbview/gerbview_frame.cpp index 62fdf0c130..1e2b073e8d 100644 --- a/gerbview/gerbview_frame.cpp +++ b/gerbview/gerbview_frame.cpp @@ -27,7 +27,8 @@ */ #include -#include +//#include +#include #include #include #include @@ -63,11 +64,9 @@ static const wxString cfgShowBorderAndTitleBlock( wxT( "ShowBorderAndTitleBloc #define GERBVIEW_FRAME_NAME wxT( "GerberFrame" ) -GERBVIEW_FRAME::GERBVIEW_FRAME( wxWindow* aParent, const wxString& aTitle, - const wxPoint& aPosition, const wxSize& aSize, - long aStyle ) : - EDA_DRAW_FRAME( aParent, GERBER_FRAME_TYPE, aTitle, aPosition, aSize, - aStyle, GERBVIEW_FRAME_NAME ) +GERBVIEW_FRAME::GERBVIEW_FRAME( KIWAY* aKiway, wxWindow* aParent ): + EDA_DRAW_FRAME( aKiway, aParent, GERBER_FRAME_TYPE, wxT( "GerbView" ), + wxDefaultPosition, wxDefaultSize, KICAD_DEFAULT_DRAWFRAME_STYLE, GERBVIEW_FRAME_NAME ) { m_colorsSettings = &g_ColorsSettings; m_gerberLayout = NULL; @@ -109,7 +108,8 @@ GERBVIEW_FRAME::GERBVIEW_FRAME( wxWindow* aParent, const wxString& aTitle, // LoadSettings() *after* creating m_LayersManager, because LoadSettings() // initialize parameters in m_LayersManager - LoadSettings(); + LoadSettings( config() ); + SetSize( m_FramePos.x, m_FramePos.y, m_FrameSize.x, m_FrameSize.y ); if( m_LastGridSizeId < 0 ) @@ -171,7 +171,6 @@ GERBVIEW_FRAME::GERBVIEW_FRAME( wxWindow* aParent, const wxString& aTitle, GERBVIEW_FRAME::~GERBVIEW_FRAME() { - wxGetApp().SaveCurrentSetupValues( m_configSettings ); } @@ -181,6 +180,26 @@ void GERBVIEW_FRAME::OnCloseWindow( wxCloseEvent& Event ) } +bool GERBVIEW_FRAME::OpenProjectFiles( const std::vector& aFileSet, int aCtl ) +{ + const unsigned limit = std::min( unsigned( aFileSet.size() ), unsigned( NB_GERBER_LAYERS ) ); + + LAYER_NUM layer = FIRST_LAYER; + + for( unsigned i=0; im_Drawings; @@ -202,26 +221,22 @@ double GERBVIEW_FRAME::BestZoom() } -void GERBVIEW_FRAME::LoadSettings() +void GERBVIEW_FRAME::LoadSettings( wxConfigBase* aCfg ) { - wxConfig* config = wxGetApp().GetSettings(); + EDA_DRAW_FRAME::LoadSettings( aCfg ); - if( config == NULL ) - return; - - EDA_DRAW_FRAME::LoadSettings(); - - wxGetApp().ReadCurrentSetupValues( GetConfigurationSettings() ); + // was: wxGetApp().ReadCurrentSetupValues( GetConfigurationSettings() ); + wxConfigLoadSetups( aCfg, GetConfigurationSettings() ); PAGE_INFO pageInfo( wxT( "GERBER" ) ); - config->Read( cfgShowBorderAndTitleBlock, &m_showBorderAndTitleBlock, false ); + aCfg->Read( cfgShowBorderAndTitleBlock, &m_showBorderAndTitleBlock, false ); if( m_showBorderAndTitleBlock ) { wxString pageType; - config->Read( cfgShowPageSizeOption, &pageType, wxT( "GERBER" ) ); + aCfg->Read( cfgShowPageSizeOption, &pageType, wxT( "GERBER" ) ); pageInfo.SetType( pageType ); } @@ -231,16 +246,16 @@ void GERBVIEW_FRAME::LoadSettings() GetScreen()->InitDataPoints( pageInfo.GetSizeIU() ); bool tmp; - config->Read( cfgShowDCodes, &tmp, true ); + aCfg->Read( cfgShowDCodes, &tmp, true ); SetElementVisibility( DCODES_VISIBLE, tmp ); - config->Read( cfgShowNegativeObjects, &tmp, false ); + aCfg->Read( cfgShowNegativeObjects, &tmp, false ); SetElementVisibility( NEGATIVE_OBJECTS_VISIBLE, tmp ); // because we have 2 file historues, we must read this one // using a specific path - config->SetPath( wxT( "drl_files" ) ); - m_drillFileHistory.Load( *config ); - config->SetPath( wxT( ".." ) ); + aCfg->SetPath( wxT( "drl_files" ) ); + m_drillFileHistory.Load( *aCfg ); + aCfg->SetPath( wxT( ".." ) ); // WxWidgets 2.9.1 seems call setlocale( LC_NUMERIC, "" ) // when reading doubles in config, @@ -249,29 +264,25 @@ void GERBVIEW_FRAME::LoadSettings() } -void GERBVIEW_FRAME::SaveSettings() +void GERBVIEW_FRAME::SaveSettings( wxConfigBase* aCfg ) { - wxConfig* config = wxGetApp().GetSettings(); + EDA_DRAW_FRAME::SaveSettings( aCfg ); - if( config == NULL ) - return; + // was: wxGetApp().SaveCurrentSetupValues( GetConfigurationSettings() ); + wxConfigSaveSetups( aCfg, GetConfigurationSettings() ); - EDA_DRAW_FRAME::SaveSettings(); - - wxGetApp().SaveCurrentSetupValues( GetConfigurationSettings() ); - - config->Write( cfgShowPageSizeOption, GetPageSettings().GetType() ); - config->Write( cfgShowBorderAndTitleBlock, m_showBorderAndTitleBlock ); - config->Write( cfgShowDCodes, IsElementVisible( DCODES_VISIBLE ) ); - config->Write( cfgShowNegativeObjects, + aCfg->Write( cfgShowPageSizeOption, GetPageSettings().GetType() ); + aCfg->Write( cfgShowBorderAndTitleBlock, m_showBorderAndTitleBlock ); + aCfg->Write( cfgShowDCodes, IsElementVisible( DCODES_VISIBLE ) ); + aCfg->Write( cfgShowNegativeObjects, IsElementVisible( NEGATIVE_OBJECTS_VISIBLE ) ); // Save the drill file history list. // Because we have 2 file histories, we must save this one // in a specific path - config->SetPath( wxT( "drl_files" ) ); - m_drillFileHistory.Save( *config ); - config->SetPath( wxT( ".." ) ); + aCfg->SetPath( wxT( "drl_files" ) ); + m_drillFileHistory.Save( *aCfg ); + aCfg->SetPath( wxT( ".." ) ); } @@ -394,7 +405,7 @@ void GERBVIEW_FRAME::Liste_D_Codes() if( gerber == NULL ) continue; - if( gerber->ReturnUsedDcodeNumber() == 0 ) + if( gerber->UsedDcodeNumber() == 0 ) continue; if( layer == curr_layer ) diff --git a/gerbview/gerbview_frame.h b/gerbview/gerbview_frame.h index 9cabd38b16..f703ece8ee 100644 --- a/gerbview/gerbview_frame.h +++ b/gerbview/gerbview_frame.h @@ -31,8 +31,8 @@ #define WX_GERBER_STRUCT_H -#include -#include +#include +#include #include #include @@ -201,15 +201,15 @@ private: // An array sting to store warning messages when reaging a gerber file. wxArrayString m_Messages; -public: - GERBVIEW_FRAME( wxWindow* aParent, const wxString& aTitle, - const wxPoint& aPosition, const wxSize& aSize, - long aStyle = KICAD_DEFAULT_DRAWFRAME_STYLE ); +public: + GERBVIEW_FRAME( KIWAY* aKiway, wxWindow* aParent ); ~GERBVIEW_FRAME(); void OnCloseWindow( wxCloseEvent& Event ); + bool OpenProjectFiles( const std::vector& aFileSet, int aCtl ); // overload KIWAY_PLAYER + // Virtual basic functions: void RedrawActiveWindow( wxDC* DC, bool EraseBg ); void ReCreateHToolbar(); @@ -458,28 +458,9 @@ public: */ PARAM_CFG_ARRAY& GetConfigurationSettings( void ); - /** - * Load applications settings specific to the Pcbnew. - * - * This overrides the base class EDA_DRAW_FRAME::LoadSettings() to - * handle settings specific common to the PCB layout application. It - * calls down to the base class to load settings common to all - * EDA_DRAW_FRAME type drawing frames. - * Please put your application settings for Pcbnew here - * to avoid having application settings loaded all over the place. - */ - virtual void LoadSettings(); + void LoadSettings( wxConfigBase* aCfg ); // override virtual - /** - * Save applications settings common to PCB draw frame objects. - * - * This overrides the base class EDA_DRAW_FRAME::SaveSettings() to - * save settings specific to the gerbview application main window. It - * calls down to the base class to save settings common to all - * drawing frames. Please put your application settings for Gerbview here - * to avoid having application settings saved all over the place. - */ - virtual void SaveSettings(); + void SaveSettings( wxConfigBase* aCfg ); // override virtual /** * Function SetLanguage @@ -556,11 +537,11 @@ public: void OnUpdateLayerSelectBox( wxUpdateUIEvent& aEvent ); /** - * Function ReturnBlockCommand + * Function BlockCommand * returns the block command (BLOCK_MOVE, BLOCK_COPY...) corresponding to * the \a aKey (ALT, SHIFT ALT ..) */ - virtual int ReturnBlockCommand( int key ); + virtual int BlockCommand( int key ); /** * Function HandleBlockPlace diff --git a/gerbview/menubar.cpp b/gerbview/menubar.cpp index 6ea327a46b..fd2b6c0abf 100644 --- a/gerbview/menubar.cpp +++ b/gerbview/menubar.cpp @@ -29,15 +29,15 @@ */ #include -#include - +#include +#include #include #include #include #include -void GERBVIEW_FRAME::ReCreateMenuBar( void ) +void GERBVIEW_FRAME::ReCreateMenuBar() { // Create and try to get the current menubar wxMenuBar* menuBar = GetMenuBar(); @@ -77,11 +77,13 @@ void GERBVIEW_FRAME::ReCreateMenuBar( void ) // Add this menu to list menu managed by m_fileHistory // (the file history will be updated when adding/removing files in history if( openRecentGbrMenu ) - wxGetApp().GetFileHistory().RemoveMenu( openRecentGbrMenu ); + Kiface().GetFileHistory().RemoveMenu( openRecentGbrMenu ); openRecentGbrMenu = new wxMenu(); - wxGetApp().GetFileHistory().UseMenu( openRecentGbrMenu ); - wxGetApp().GetFileHistory().AddFilesToMenu(); + + Kiface().GetFileHistory().UseMenu( openRecentGbrMenu ); + Kiface().GetFileHistory().AddFilesToMenu(); + AddMenuItem( fileMenu, openRecentGbrMenu, wxID_ANY, _( "Open &Recent Gerber File" ), @@ -166,9 +168,8 @@ void GERBVIEW_FRAME::ReCreateMenuBar( void ) KiBitmap( preference_xpm ) ); #endif // __WXMAC__ - // Language submenu - wxGetApp().AddMenuLanguageList( configMenu ); + Pgm().AddMenuLanguageList( configMenu ); // Hotkey submenu AddHotkeyConfigMenu( configMenu ); diff --git a/gerbview/readgerb.cpp b/gerbview/readgerb.cpp index 01ae04cb4f..ac374bb5c7 100644 --- a/gerbview/readgerb.cpp +++ b/gerbview/readgerb.cpp @@ -97,13 +97,13 @@ bool GERBVIEW_FRAME::Read_GERBER_File( const wxString& GERBER_FullFileName, break; case 'G': /* Line type Gxx : command */ - G_command = gerber->ReturnGCodeNumber( text ); + G_command = gerber->GCodeNumber( text ); gerber->Execute_G_Command( text, G_command ); break; case 'D': /* Line type Dxx : Tool selection (xx > 0) or * command if xx = 0..9 */ - D_commande = gerber->ReturnDCodeNumber( text ); + D_commande = gerber->DCodeNumber( text ); gerber->Execute_DCODE_Command( text, D_commande ); break; diff --git a/gerbview/rs274d.cpp b/gerbview/rs274d.cpp index 838f1a9b39..7023d63930 100644 --- a/gerbview/rs274d.cpp +++ b/gerbview/rs274d.cpp @@ -406,7 +406,7 @@ static void fillArcPOLY( GERBER_DRAW_ITEM* aGbrItem, /* Read the Gnn sequence and returns the value nn. */ -int GERBER_IMAGE::ReturnGCodeNumber( char*& Text ) +int GERBER_IMAGE::GCodeNumber( char*& Text ) { int ii = 0; char* text; @@ -429,7 +429,7 @@ int GERBER_IMAGE::ReturnGCodeNumber( char*& Text ) /* Get the sequence Dnn and returns the value nn */ -int GERBER_IMAGE::ReturnDCodeNumber( char*& Text ) +int GERBER_IMAGE::DCodeNumber( char*& Text ) { int ii = 0; char* text; @@ -491,7 +491,7 @@ bool GERBER_IMAGE::Execute_G_Command( char*& text, int G_command ) case GC_SELECT_TOOL: { - int D_commande = ReturnDCodeNumber( text ); + int D_commande = DCodeNumber( text ); if( D_commande < FIRST_DCODE ) return false; if( D_commande > (TOOLS_MAX_COUNT - 1) ) diff --git a/gerbview/select_layers_to_pcb.cpp b/gerbview/select_layers_to_pcb.cpp index 6583e578ae..058dfd5d54 100644 --- a/gerbview/select_layers_to_pcb.cpp +++ b/gerbview/select_layers_to_pcb.cpp @@ -27,7 +27,8 @@ */ #include -#include +//#include +#include #include #include #include @@ -301,7 +302,7 @@ void LAYERS_MAP_DIALOG::OnResetClick( wxCommandEvent& event ) */ void LAYERS_MAP_DIALOG::OnStoreSetup( wxCommandEvent& event ) { - wxConfig* config = wxGetApp().GetSettings(); + wxConfigBase* config = Kiface().KifaceSettings(); config->Write( wxT("BrdLayersCount"), m_exportBoardCopperLayersCount ); wxString key; @@ -314,7 +315,7 @@ void LAYERS_MAP_DIALOG::OnStoreSetup( wxCommandEvent& event ) void LAYERS_MAP_DIALOG::OnGetSetup( wxCommandEvent& event ) { - wxConfig* config = wxGetApp().GetSettings(); + wxConfigBase* config = Kiface().KifaceSettings(); config->Read( wxT("BrdLayersCount"), &m_exportBoardCopperLayersCount ); normalizeBrdLayersCount(); diff --git a/include/appl_wxstruct.h b/include/appl_wxstruct.h deleted file mode 100644 index afb2b91ed8..0000000000 --- a/include/appl_wxstruct.h +++ /dev/null @@ -1,491 +0,0 @@ -/* - * This program source code file is part of KiCad, a free EDA CAD application. - * - * Copyright (C) 2004 Jean-Pierre Charras, jaen-pierre.charras@gipsa-lab.inpg.com - * Copyright (C) 2008-2011 Wayne Stambaugh - * Copyright (C) 1992-2011 KiCad Developers, see AUTHORS.txt for contributors. - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, you may find one here: - * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html - * or you may search the http://www.gnu.org website for the version 2 license, - * or you may write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA - */ - -/** - * @file appl_wxstruct.h - * @brief Base class implementation for all KiCad applications. - */ - -#ifndef APPL_WXSTRUCT_H -#define APPL_WXSTRUCT_H - -/* Use wxFileHistory for most recently used file handling. */ -#include -#include -#include -#include - - -enum EDA_APP_T { - APP_UNKNOWN_T, - APP_EESCHEMA_T, - APP_PCBNEW_T, - APP_CVPCB_T, - APP_GERBVIEW_T, - APP_KICAD_T, - APP_PL_EDITOR_T -}; - -class wxConfigBase; -class wxFileConfig; -class wxSingleInstanceChecker; -class wxHtmlHelpController; - - -/** - * Class EDA_APP - * is the base class representing all of KiCad applications. - */ -class EDA_APP : public wxApp -{ -protected: - /// Used mainly to handle default paths libs m_Id = APP_EESCHEMA_T, APP_PCBNEW_T ... - EDA_APP_T m_Id; - - /// Used to prevent multiple instances of an application from being run at the same time. - wxSingleInstanceChecker* m_Checker; - - /// Used to prevent opening the same file multiple times. - wxSingleInstanceChecker* m_oneInstancePerFileChecker; - - wxString m_Project; - - /// The application specific configuration settings. - wxConfig* m_settings; - - /// The configuration settings common to all KiCad applications. - wxConfig* m_commonSettings; - - /// The current project specific settings. - wxFileConfig* m_projectSettings; - - /// KiCad executable path. - wxString m_BinDir; - - /// The KICAD system environment variable. - wxString m_KicadEnv; - - /// The current locale. - wxLocale* m_Locale; - - /// The current language setting. - int m_LanguageId; - - void setLanguageId( int aId ) { m_LanguageId = aId; } - - /// The file name of the the program selected for browsing pdf files. - wxString m_PdfBrowser; - /// true to use the selected PDF browser, if exists, or false to use the default - bool m_useSystemPdfBrowser; - - wxPathList m_searchPaths; - wxFileHistory m_fileHistory; - wxString m_HelpFileName; - wxString m_EditorName; - wxString m_CurrentOptionFile; - wxString m_CurrentOptionFileDateAndTime; - wxPoint m_HelpPos; - wxSize m_HelpSize; - wxString m_Title; - wxPathList m_libSearchPaths; - wxFileName m_projectFileName; - wxString m_LastVisitedLibPath; - - /// last visited module library in the module editor or viewer - wxString m_module_nickname; - - wxHtmlHelpController* m_HtmlCtrl; - -public: - EDA_APP(); - ~EDA_APP(); - - /** - * Function OnInit - * this is the first executed function (like main() ) - * @return true if the application can be started. - */ - bool OnInit(); // should this be virtual - - wxHtmlHelpController* GetHtmlHelpController() { return m_HtmlCtrl; } - - void SetHtmlHelpController( wxHtmlHelpController* aController ); - - wxString GetHelpFileName() const { return m_HelpFileName; } - void SetHelpFileName( const wxString& aFileName ) { m_HelpFileName = aFileName; } - - wxConfig* GetSettings() { return m_settings; } - - wxConfig* GetCommonSettings() { return m_commonSettings; } - - wxString GetEditorName() const { return m_EditorName; } - void SetEditorName( const wxString& aFileName ) { m_EditorName = aFileName; } - - wxString GetCurrentOptionFile() const { return m_CurrentOptionFile; } - - bool IsKicadEnvVariableDefined() const { return !m_KicadEnv.IsEmpty(); } - - wxString GetKicadEnvVariable() const { return m_KicadEnv; } - - wxString GetExecutablePath() const { return m_BinDir; } - - wxLocale* GetLocale() { return m_Locale; } - - /** - * @return the full file name of the prefered PDF browser - * ( the file name is empty if no prefered there is no PDF browser selected - */ - wxString GetPdfBrowserFileName() const { return m_PdfBrowser; } - - /** - * Set the name of a prefered PDF browser, which could be an alternate browser - * to the system PDF browser. - */ - void SetPdfBrowserFileName( const wxString& aFileName ) { m_PdfBrowser = aFileName; } - - /** - * @return true if the PDF browser is the default (system) PDF browser - * and false if the PDF browser is the prefered (selected) browser - * returns false if there is no selected browser - */ - bool UseSystemPdfBrowser() const { return m_useSystemPdfBrowser || m_PdfBrowser.IsEmpty(); } - - /** - * force the use of system PDF browser, even if a preferend PDF browser is set - */ - void ForceSystemPdfBrowser( bool aFlg ) { m_useSystemPdfBrowser = aFlg; } - - wxFileHistory& GetFileHistory() { return m_fileHistory; } - - /** - * Function SetBinDir - * finds the path to the executable and store it in EDA_APP::m_BinDir - * - * @return TODO - */ - bool SetBinDir(); - - /** - * Function SetDefaultSearchPaths - * sets search paths for libraries, modules, internationalization files, etc. - */ - void SetDefaultSearchPaths( void ); - - /** - * Function MacOpenFile - * Specific to MacOSX. Not used under Linux or Windows - * MacOSX: Needed for file association - * http://wiki.wxwidgets.org/WxMac-specific_topics - */ - virtual void MacOpenFile( const wxString& aFileName ); - - /** - * Function InitEDA_Appl - * initialize some general parameters - * - Default paths (help, libs, bin)and configuration files names - * - Language and locale - * - fonts - * @param aName : used as paths in configuration files - * @param aId = flag : LIBRARY_TYPE_EESCHEMA or LIBRARY_TYPE_PCBNEW - * used to choose what default library path must be used - */ - void InitEDA_Appl( const wxString& aName, EDA_APP_T aId = APP_UNKNOWN_T ); - - /** - * Function SetLanguage - * sets the dictionary file name for internationalization. - *

- * The files are in kicad/internat/xx or kicad/internat/xx_XX and are named kicad.mo - *

- * @param first_time must be set to true the first time this funct is - * called, false otherwise - * @return true if the language can be set (i.e. if the locale is available) - */ - bool SetLanguage( bool first_time = false ); - - /** - * Function AddMenuLanguageList - * creates a menu list for language choice, and add it as submenu to \a MasterMenu. - * - * @param MasterMenu The main menu. The sub menu list will be accessible from the menu - * item with id ID_LANGUAGE_CHOICE - */ - void AddMenuLanguageList( wxMenu* MasterMenu ); - - /** - * Function SetLanguageIdentifier - * sets in .m_LanguageId member the wxWidgets language identifier Id from - * the KiCad menu id (internal menu identifier). - * - * @param menu_id The KiCad menuitem id (returned by Menu Event, when - * clicking on a menu item) - */ - void SetLanguageIdentifier( int menu_id ); - - void SetLanguagePath( void ); - - /** - * Function InitOnLineHelp - * initializes KiCad's online help. - */ - void InitOnLineHelp(); - - /** - * Function GetSettings - * gets the application settings. - * @param aReopenLastUsedDirectory True to switch to last opened directory, false - * to use current CWD - */ - void GetSettings( bool aReopenLastUsedDirectory ); - - /** - * Function SaveSettings - * saves the application settings. - */ - void SaveSettings(); - - /** - * Function WriteProjectConfig - * Save the current "project" parameters - * saved parameters are parameters that have the .m_Setup member set to false - * saving file is the .pro file project - */ - void WriteProjectConfig( const wxString& fileName, - const wxString& GroupName, - const PARAM_CFG_ARRAY& params ); - - /** - * Function SaveCurrentSetupValues - * saves the current setup values in m_settings. - * Saved parameters are parameters that have the .m_Setup member set to - * true. - * @param aList = array of PARAM_CFG_BASE pointers - */ - void SaveCurrentSetupValues( const PARAM_CFG_ARRAY& aList ); - - /** - * Function ReadCurrentSetupValues - * reads the current setup values previously saved, from m_settings. - * Saved parameters are parameters that have the .m_Setup member set to - * true. - * @param aList = array of PARAM_CFG_BASE pointers - */ - void ReadCurrentSetupValues( const PARAM_CFG_ARRAY& aList ); - - /** - * Function ReadProjectConfig - * Read the current "project" parameters - * Parameters are parameters that have the .m_Setup member set to false - * read file is the .pro file project - * - * if Load_Only_if_New == true, this file is read only if it differs from - * the current config (different dates ) - * - * @return true if read. - * Also set: - * wxGetApp().m_CurrentOptionFileDateAndTime - * wxGetApp().m_CurrentOptionFile - */ - bool ReadProjectConfig( const wxString& local_config_filename, - const wxString& GroupName, - PARAM_CFG_BASE** List, - bool Load_Only_if_New ); - bool ReadProjectConfig( const wxString& local_config_filename, - const wxString& GroupName, - const PARAM_CFG_ARRAY& List, - bool Load_Only_if_New ); - - /** - * Creates or recreates the KiCad project file. (filename.pro) - * Initialize: - * G_Prj_Config - * G_Prj_Config_LocalFilename - * G_Prj_Default_Config_FullFilename - * Return: - * True if local config - * False if default config - */ - bool ReCreatePrjConfig( const wxString& local_config_filename, - const wxString& GroupName, - bool ForceUseLocalConfig ); - - /** - * Function ReadPdfBrowserInfos - * read the PDF browser choice from the common configuration. - */ - void ReadPdfBrowserInfos(); - - /* Function WritePdfBrowserInfos - * save the PDF browser choice to the common configuration. - */ - void WritePdfBrowserInfos(); - - /** - * Function FindFileInSearchPaths - * looks in search paths for \a filename. - */ - wxString FindFileInSearchPaths( const wxString& filename, - const wxArrayString* subdirs = NULL ); - - /** - * Function GetHelpFile - * get the help file path. - *

- * Return the KiCad help file with path. The base paths defined in - * m_searchPaths are tested for a valid file. The path returned can - * be relative depending on the paths added to m_searchPaths. See the - * documentation for wxPathList for more information. If the help file - * for the current locale is not found, an attempt to find the English - * version of the help file is made. - * wxEmptyString is returned if help file not found. - * Help file is searched in directories in this order: - * help/\ like help/en_GB - * help/\ like help/en - * help/en - *

- */ - wxString GetHelpFile( void ); - - /** - * Return the preferred editor name. - */ - wxString& GetEditorName(); - - const wxString& GetTitle() { return m_Title; } - void SetTitle( const wxString& aTitle ) { m_Title = aTitle; } - - wxPathList& GetLibraryPathList() { return m_libSearchPaths; } - wxString FindLibraryPath( const wxString& fileName ); - - /** - * Function FindLibraryPath - * KiCad saves user defined library files that are not in the standard - * library search path list with the full file path. Calling the library - * search path list with a user library file will fail. This helper method - * solves that problem. - * @param fileName - * @return a wxEmptyString if library file is not found. - */ - wxString FindLibraryPath( const wxFileName& fileName ) - { - return FindLibraryPath( fileName.GetFullPath() ); - } - - - /** - * Function ReturnLastVisitedLibraryPath - * returns the last visited library directory, or (if void) the first - * path in lib path list ( but not the CWD ) - * - * @param aSubPathToSearch = Preferred sub path to search in path list - */ - wxString ReturnLastVisitedLibraryPath( const wxString& aSubPathToSearch = wxEmptyString ); - - void SaveLastVisitedLibraryPath( const wxString& aPath ); - - /** - * Function ReturnFilenameWithRelativePathInLibPath - * @return a short filename (with extension) with only a relative path if - * this filename can be found in library paths - * @param aFullFilename The filename with path and extension. - */ - wxString ReturnFilenameWithRelativePathInLibPath( const wxString& aFullFilename ); - - /** - * Function RemoveLibraryPath - * Removes the given path(s) from the library path list - * @param aPaths = path or path list to remove. paths must be separated by - * ";" - */ - void RemoveLibraryPath( const wxString& aPaths ); - - /** - * Function InsertLibraryPath - * insert path(s) int lib paths list. - * @param aPaths = path or path list to add. paths must be separated by ";" - * @param aIndex = insertion point - */ - void InsertLibraryPath( const wxString& aPaths, size_t aIndex ); - - /** - * Function LockFile - * Locks the access to a file. - * @param fileName = full path to the file. - * @return false if the file was already locked, true otherwise. - */ - bool LockFile( const wxString& fileName ); - - /** - * Function SetFootprintLibTableEnv - * attempts set the KISYSMOD environment variable to the best possible path. - * - * The path is determined by attempting to find the path with the most footprint library - * files. This may or may not be the best path but it provides the best solution for - * backwards compatibility with the previous library search path implementation. If the - * KISYSMOD environment variable is already set, then it left as is to respect the wishes - * of the user. - * - * @note This must be called after #SetDefaultSearchPaths() is called. Otherwise, the - * list of library search paths will be empty and KISYSMOD will be undefined making - * it impossible for the footprint libraries to be loaded from the footprint library - * table. - * - * @return false if the KISYSMOD path is not valid. - */ - bool SetFootprintLibTablePath(); - - /** - * Function Set3DShapesPath - * attempts set the environment variable given by aKiSys3Dmod to a valid path. - * (typically "KISYS3DMOD" ) - * If the environment variable is already set, - * then it left as is to respect the wishes of the user. - * - * The path is determined by attempting to find the path modules/packages3d - * files in kicad tree. - * This may or may not be the best path but it provides the best solution for - * backwards compatibility with the previous 3D shapes search path implementation. - * - * @note This must be called after #SetBinDir() is called at least on Windows. - * Otherwise, the kicad path is not known (Windows specific) - * - * @param aKiSys3Dmod = the value of environment variable, typically "KISYS3DMOD" - * @return false if the aKiSys3Dmod path is not valid. - */ - bool Set3DShapesPath( const wxString& aKiSys3Dmod ); - - const wxString& GetModuleLibraryNickname() { return m_module_nickname; } - void SetModuleLibraryNickname( const wxString& aNickname ) { m_module_nickname = aNickname; } -}; - - -/* - * Use wxGetApp() to access EDA_APP. It is not necessary to keep copies - * of the application pointer all over the place or worse yet in a global - * variable. - */ -DECLARE_APP( EDA_APP ) - -#endif // APPL_WXSTRUCT_H diff --git a/include/base_units.h b/include/base_units.h index b8492deafe..2858cc7388 100644 --- a/include/base_units.h +++ b/include/base_units.h @@ -108,7 +108,7 @@ wxString AngleToStringDegrees( double aAngle ); wxString LengthDoubleToString( double aValue, bool aConvertToMils = false ); /** - * Function ReturnStringFromValue + * Function StringFromValue * returns the string from \a aValue according to units (inch, mm ...) for display, * and the initial unit for value. * @@ -126,7 +126,7 @@ wxString LengthDoubleToString( double aValue, bool aConvertToMils = false ); * @param aAddUnitSymbol = true to add symbol unit to the string value * @return A wxString object containing value and optionally the symbol unit (like 2.000 mm) */ -wxString ReturnStringFromValue( EDA_UNITS_T aUnit, int aValue, bool aAddUnitSymbol = false ); +wxString StringFromValue( EDA_UNITS_T aUnit, int aValue, bool aAddUnitSymbol = false ); /** * Operator << overload @@ -153,17 +153,17 @@ void PutValueInLocalUnits( wxTextCtrl& aTextCtr, int aValue ); double From_User_Unit( EDA_UNITS_T aUnit, double aValue ); /** - * Function ReturnValueFromString + * Function ValueFromString * converts \a aTextValue in \a aUnits to internal units used by the application. * * @param aUnits The units of \a aTextValue. * @param aTextValue A reference to a wxString object containing the string to convert. * @return The string from Value, according to units (inch, mm ...) for display, */ -int ReturnValueFromString( EDA_UNITS_T aUnits, const wxString& aTextValue ); +int ValueFromString( EDA_UNITS_T aUnits, const wxString& aTextValue ); /** - * Function ReturnValueFromString + * Function ValueFromString * converts \a aTextValue in \a aUnits to internal units used by the application, * unit type will be obtained from g_UserUnit. @@ -172,12 +172,12 @@ int ReturnValueFromString( EDA_UNITS_T aUnits, const wxString& aTextValue ); * @return The string from Value, according to units (inch, mm ...) for display, */ -int ReturnValueFromString( const wxString& aTextValue ); +int ValueFromString( const wxString& aTextValue ); /** * Convert the number Value in a string according to the internal units * and the selected unit (g_UserUnit) and put it in the wxTextCtrl TextCtrl */ -int ReturnValueFromTextCtrl( const wxTextCtrl& aTextCtr ); +int ValueFromTextCtrl( const wxTextCtrl& aTextCtr ); #endif // _BASE_UNITS_H_ diff --git a/include/bin_mod.h b/include/bin_mod.h new file mode 100644 index 0000000000..edfc9cf8e7 --- /dev/null +++ b/include/bin_mod.h @@ -0,0 +1,64 @@ +#ifndef BIN_MOD_H_ +#define BIN_MOD_H_ + +/* + * This program source code file is part of KiCad, a free EDA CAD application. + * + * Copyright (C) 2014 KiCad Developers, see AUTHORS.txt for contributors. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, you may find one here: + * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html + * or you may search the http://www.gnu.org website for the version 2 license, + * or you may write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + */ + +#if 0 + #include // wx 3.0: +#else + #include +#endif + +#include + +#include + +class wxConfigBase; + +/** + * Struct BIN_MOD + * pertains to a single program module, either an EXE or a DSO/DLL ("bin_mod"). + * It manages miscellaneous configuration file information pertinent to one bin_mod. + * Because it serves in both DSO/DLLs and in EXEs, its name is neutral. + *

+ * Accessors are in containing (wrapper) classes. + */ +struct BIN_MOD +{ + BIN_MOD( const char* aName ); + ~BIN_MOD(); + + void Init(); + void End(); + + const char* m_name; ///< name of this binary module, static C string. + + wxConfigBase* m_config; ///< maybe from $HOME/.${m_name} + wxFileHistory m_history; + wxString m_help_file; + + SEARCH_STACK m_search; +}; + +#endif // BIN_MOD_H_ diff --git a/include/class_board_design_settings.h b/include/class_board_design_settings.h index a651e982fc..31ebfccfe5 100644 --- a/include/class_board_design_settings.h +++ b/include/class_board_design_settings.h @@ -7,7 +7,7 @@ #include // NB_COLORS #include -#include +#include /** diff --git a/include/class_layer_box_selector.h b/include/class_layer_box_selector.h index 27d19b8a18..4a130c8654 100644 --- a/include/class_layer_box_selector.h +++ b/include/class_layer_box_selector.h @@ -5,7 +5,7 @@ #include // EDA_COLOR_T definition #include -class EDA_HOTKEY_CONFIG; +struct EDA_HOTKEY_CONFIG; /* Basic class to build a layer list. * this is an basic abstract class to build a layer list selector. diff --git a/include/colors.h b/include/colors.h index a1bd0c8fdf..c7dfa1fd2d 100644 --- a/include/colors.h +++ b/include/colors.h @@ -2,8 +2,8 @@ /* colors.h */ /************/ -#ifndef _COLORS_H -#define _COLORS_H +#ifndef COLORS_H_ +#define COLORS_H_ #include @@ -195,4 +195,4 @@ inline wxColour MakeColour( EDA_COLOR_T aColor ) ); } -#endif /* ifndef _COLORS_H */ +#endif // COLORS_H_ diff --git a/include/common.h b/include/common.h index ca40fca2b5..a6b282df08 100644 --- a/include/common.h +++ b/include/common.h @@ -44,6 +44,8 @@ class wxAboutDialogInfo; +class SEARCH_STACK; + // Flag for special keys #define GR_KB_RIGHTSHIFT 0x10000000 /* Keybd states: right @@ -579,4 +581,12 @@ unsigned GetRunningMicroSecs(); */ wxString FormatDateLong( const wxDateTime &aDate ); +/** + * Function SystemDirsAppend + * appends system places to aSearchStack in a platform specific way, and pertinent + * to KiCad programs. It seems to be a place to collect bad ideas and keep them + * out of view. + */ +void SystemDirsAppend( SEARCH_STACK* aSearchStack ); + #endif // INCLUDE__COMMON_H_ diff --git a/include/param_config.h b/include/config_params.h similarity index 69% rename from include/param_config.h rename to include/config_params.h index fdb98fc18f..a8002e0a9e 100644 --- a/include/param_config.h +++ b/include/config_params.h @@ -1,10 +1,34 @@ -/** - * The common library - * @file param_config.h +#ifndef CONFIG_PARAMS_H_ +#define CONFIG_PARAMS_H_ +/* + * This program source code file is part of KiCad, a free EDA CAD application. + * + * Copyright (C) 2004 Jean-Pierre Charras, jaen-pierre.charras@gipsa-lab.inpg.com + * Copyright (C) 2008-2011 Wayne Stambaugh + * Copyright (C) 1992-2011 KiCad Developers, see AUTHORS.txt for contributors. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, you may find one here: + * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html + * or you may search the http://www.gnu.org website for the version 2 license, + * or you may write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ -#ifndef PARAM_CONFIG_H_ -#define PARAM_CONFIG_H_ +/** + * The common library + * @file config_params.h + */ #include #include @@ -13,6 +37,9 @@ #include +#define CONFIG_VERSION 1 +#define FORCE_LOCAL_CONFIG true + /** * Function ConfigBaseWriteDouble @@ -258,6 +285,67 @@ public: /** A list of parameters type */ -typedef boost::ptr_vector PARAM_CFG_ARRAY; +//typedef boost::ptr_vector PARAM_CFG_ARRAY; +class PARAM_CFG_ARRAY : public boost::ptr_vector +{ +}; -#endif // PARAM_CONFIG_H_ + +/** + * Function wxConfigSaveSetups + * writes @a aList of PARAM_CFG_ARRAY elements to save configuration values + * to @a aCfg. Only elements with m_Setup set true will be saved, hence the + * function name. + * + * @param aCfg where to save + * @param aList holds some configuration parameters, not all of which will + * necessarily be saved. + */ +void wxConfigSaveSetups( wxConfigBase* aCfg, const PARAM_CFG_ARRAY& aList ); + +/** + * Function wxConfigSaveParams + * writes @a aList of PARAM_CFG_ARRAY elements to save configuration values + * to @a aCfg. Only elements with m_Setup set false will be saved, hence the + * function name. + * + * @param aCfg where to save + * @param aList holds some configuration parameters, not all of which will + * necessarily be saved. + * @param aGroup indicates in which group the value should be saved, + * unless the PARAM_CFG_ARRAY element provides its own group, in which case it will + * take precedence. aGroup may be empty. + */ +void wxConfigSaveParams( wxConfigBase* aCfg, + const PARAM_CFG_ARRAY& aList, const wxString& aGroup ); + +/** + * Function wxConfigLoadSetups + * uses @a aList of PARAM_CFG_ARRAY elements to load configuration values + * from @a aCfg. Only elements whose m_Setup field is true will be loaded. + * + * @param aCfg where to load from. + * @param aList holds some configuration parameters, not all of which will + * necessarily be loaded. + */ +void wxConfigLoadSetups( wxConfigBase* aCfg, const PARAM_CFG_ARRAY& aList ); + +/** + * Function wxConfigLoadParams + * uses @a aList of PARAM_CFG_ARRAY elements to load configuration values + * from @a aCfg. Only elements whose m_Setup field is false will be loaded. + * + * @param aCfg where to load from. + * + * @param aList holds some configuration parameters, not all of which will + * necessarily be loaded. + * + * @param aGroup indicates in which group the value should be saved, + * unless the PARAM_CFG_ARRAY element provides its own group, in which case it will + * take precedence. aGroup may be empty. + */ +void wxConfigLoadParams( wxConfigBase* aCfg, + const PARAM_CFG_ARRAY& aList, const wxString& aGroup ); + + +#endif // CONFIG_PARAMS_H_ diff --git a/include/dialog_hotkeys_editor.h b/include/dialog_hotkeys_editor.h index d8b671cd3d..81c523f935 100644 --- a/include/dialog_hotkeys_editor.h +++ b/include/dialog_hotkeys_editor.h @@ -18,7 +18,7 @@ #include #include -#include +#include #include <../common/dialogs/dialog_hotkeys_editor_base.h> class HOTKEYS_EDITOR_DIALOG : public HOTKEYS_EDITOR_DIALOG_BASE diff --git a/include/dialog_shim.h b/include/dialog_shim.h index 56e30253fb..cab1d5f0f7 100644 --- a/include/dialog_shim.h +++ b/include/dialog_shim.h @@ -27,6 +27,7 @@ #include #include +#include #if wxMINOR_VERSION == 8 && defined(__WXGTK__) #define DLGSHIM_USE_SETFOCUS 1 @@ -44,7 +45,7 @@ *
* in the dialog window's properties. **/ -class DIALOG_SHIM : public wxDialog +class DIALOG_SHIM : public wxDialog, public KIWAY_HOLDER { public: @@ -57,6 +58,7 @@ public: bool Show( bool show ); // overload wxDialog::Show + protected: std::string m_hash_key; // alternate for class_map when classname re-used. @@ -64,8 +66,6 @@ protected: private: void onInit( wxInitDialogEvent& aEvent ); #endif - - }; #endif // DIALOG_SHIM_ diff --git a/include/draw_frame.h b/include/draw_frame.h new file mode 100644 index 0000000000..c8067de3d7 --- /dev/null +++ b/include/draw_frame.h @@ -0,0 +1,676 @@ +#ifndef EDA_DRAW_FRAME_H_ +#define EDA_DRAW_FRAME_H_ +/* + * This program source code file is part of KiCad, a free EDA CAD application. + * + * Copyright (C) 2009 Jean-Pierre Charras, jaen-pierre.charras@gipsa-lab.inpg.com + * Copyright (C) 2011 Wayne Stambaugh + * Copyright (C) 1992-2011 KiCad Developers, see AUTHORS.txt for contributors. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, you may find one here: + * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html + * or you may search the http://www.gnu.org website for the version 2 license, + * or you may write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + */ + +#include +#include + + +/** + * Class EDA_DRAW_FRAME + * is the base class for create windows for drawing purpose. The Eeschema, Pcbnew and + * GerbView main windows are just a few examples of classes derived from EDA_DRAW_FRAME. + */ +class EDA_DRAW_FRAME : public KIWAY_PLAYER +{ + /// Let the #EDA_DRAW_PANEL object have access to the protected data since + /// it is closely tied to the #EDA_DRAW_FRAME. + friend class EDA_DRAW_PANEL; + + ///< Id of active button on the vertical toolbar. + int m_toolId; + + BASE_SCREEN* m_currentScreen; ///< current used SCREEN + + bool m_snapToGrid; ///< Indicates if cursor should be snapped to grid. + bool m_galCanvasActive; ///< whether to use new GAL engine + + EDA_DRAW_PANEL_GAL* m_galCanvas; + +protected: + EDA_HOTKEY_CONFIG* m_HotkeysZoomAndGridList; + int m_LastGridSizeId; // the command id offset (>= 0) of the last selected grid + // 0 is for the grid corresponding to + // a wxCommand ID = ID_POPUP_GRID_LEVEL_1000. + bool m_DrawGrid; // hide/Show grid + EDA_COLOR_T m_GridColor; // Grid color + + /// The area to draw on. + EDA_DRAW_PANEL* m_canvas; + + /// Tool ID of previously active draw tool bar button. + int m_lastDrawToolId; + + /// The shape of the KiCad cursor. The default value (0) is the normal cross + /// hair cursor. Set to non-zero value to draw the full screen cursor. + /// @note This is not the system mouse cursor. + int m_cursorShape; + + /// True shows the X and Y axis indicators. + bool m_showAxis; + + /// True shows the grid axis indicators. + bool m_showGridAxis; + + /// True shows the origin axis used to indicate the coordinate offset for + /// drill, gerber, and component position files. + bool m_showOriginAxis; + + /// True shows the drawing border and title block. + bool m_showBorderAndTitleBlock; + + /// Choice box to choose the grid size. + wxComboBox* m_gridSelectBox; + + /// Choice box to choose the zoom value. + wxComboBox* m_zoomSelectBox; + + /// The tool bar that contains the buttons for quick access to the application draw + /// tools. It typically is located on the right side of the main window. + wxAuiToolBar* m_drawToolBar; + + /// The options tool bar typcially located on the left edge of the main window. + wxAuiToolBar* m_optionsToolBar; + + /// Panel used to display information at the bottom of the main window. + EDA_MSG_PANEL* m_messagePanel; + + int m_MsgFrameHeight; + +#ifdef USE_WX_OVERLAY + // MAC Uses overlay to workaround the wxINVERT and wxXOR miss + wxOverlay m_overlay; +#endif + + void SetScreen( BASE_SCREEN* aScreen ) { m_currentScreen = aScreen; } + + /** + * Function unitsChangeRefresh + * is called when when the units setting has changed to allow for any derived classes + * to handle refreshing and controls that have units based measurements in them. The + * default version only updates the status bar. Don't forget to call the default + * in your derived class or the status bar will not get updated properly. + */ + virtual void unitsChangeRefresh(); + +public: + EDA_DRAW_FRAME( KIWAY* aKiway, wxWindow* aParent, + ID_DRAWFRAME_TYPE aFrameType, + const wxString& aTitle, + const wxPoint& aPos, const wxSize& aSize, + long aStyle, + const wxString& aFrameName ); + + ~EDA_DRAW_FRAME(); + + virtual void SetPageSettings( const PAGE_INFO& aPageSettings ) = 0; + virtual const PAGE_INFO& GetPageSettings() const = 0; + + /** + * Function GetPageSizeIU + * works off of GetPageSettings() to return the size of the paper page in + * the internal units of this particular view. + */ + virtual const wxSize GetPageSizeIU() const = 0; + + /** + * Function GetAuxOrigin + * returns the origin of the axis used for plotting and various exports. + */ + virtual const wxPoint& GetAuxOrigin() const = 0; + virtual void SetAuxOrigin( const wxPoint& aPosition ) = 0; + + /** + * Function GetGridOrigin + * returns the absolute coordinates of the origin of the snap grid. This is + * treated as a relative offset, and snapping will occur at multiples of the grid + * size relative to this point. + */ + virtual const wxPoint& GetGridOrigin() const = 0; + virtual void SetGridOrigin( const wxPoint& aPosition ) = 0; + + //----------------------------------------------- + /** + * Function GetCrossHairPosition + * return the current cross hair position in logical (drawing) coordinates. + * @param aInvertY Inverts the Y axis position. + * @return The cross hair position in drawing coordinates. + */ + wxPoint GetCrossHairPosition( bool aInvertY = false ) const; + + /** + * Function SetCrossHairPosition + * sets the screen cross hair position to \a aPosition in logical (drawing) units. + * @param aPosition The new cross hair position. + * @param aSnapToGrid Sets the cross hair position to the nearest grid position to + * \a aPosition. + * + */ + void SetCrossHairPosition( const wxPoint& aPosition, bool aSnapToGrid = true ); + + /** + * Function GetCursorPosition + * returns the current cursor position in logical (drawing) units. + * @param aOnGrid Returns the nearest grid position at the current cursor position. + * @param aGridSize Custom grid size instead of the current grid size. Only valid + * if \a aOnGrid is true. + * @return The current cursor position. + */ + wxPoint GetCursorPosition( bool aOnGrid, wxRealPoint* aGridSize = NULL ) const; + + /** + * Function GetNearestGridPosition + * returns the nearest \a aGridSize location to \a aPosition. + * @param aPosition The position to check. + * @param aGridSize The grid size to locate to if provided. If NULL then the current + * grid size is used. + * @return The nearst grid position. + */ + wxPoint GetNearestGridPosition( const wxPoint& aPosition, wxRealPoint* aGridSize = NULL ) const; + + /** + * Function GetCursorScreenPosition + * returns the cross hair position in device (display) units.b + * @return The current cross hair position. + */ + wxPoint GetCrossHairScreenPosition() const; + + void SetMousePosition( const wxPoint& aPosition ); + + /** + * Function RefPos + * Return the reference position, coming from either the mouse position + * or the cursor position. + * + * @param useMouse If true, return mouse position, else cursor's. + * + * @return wxPoint - The reference point, either the mouse position or + * the cursor position. + */ + wxPoint RefPos( bool useMouse ) const; + + const wxPoint& GetScrollCenterPosition() const; + void SetScrollCenterPosition( const wxPoint& aPoint ); + + //---------------------------------------------- + + + virtual const TITLE_BLOCK& GetTitleBlock() const = 0; + virtual void SetTitleBlock( const TITLE_BLOCK& aTitleBlock ) = 0; + + int GetCursorShape() const { return m_cursorShape; } + + void SetCursorShape( int aCursorShape ) { m_cursorShape = aCursorShape; } + + bool GetShowBorderAndTitleBlock() const { return m_showBorderAndTitleBlock; } + + void SetShowBorderAndTitleBlock( bool aShow ) { m_showBorderAndTitleBlock = aShow; } + + EDA_DRAW_PANEL* GetCanvas() { return m_canvas; } + + virtual wxString GetScreenDesc() const; + + /** + * Function GetScreen + * returns a pointer to a BASE_SCREEN or one of its + * derivatives. It is overloaded by derived classes to return + * SCH_SCREEN or PCB_SCREEN. + */ + virtual BASE_SCREEN* GetScreen() const { return m_currentScreen; } + + /** + * Execute a remote command send via a socket to the application, + * port KICAD_PCB_PORT_SERVICE_NUMBER (currently 4242) + * It called by EDA_DRAW_FRAME::OnSockRequest(). + * this is a virtual function becuse the actual commands depends on the + * application. + * the basic function do nothing + * @param cmdline = received command from socket + */ + virtual void ExecuteRemoteCommand( const char* cmdline ){} + + void OnMenuOpen( wxMenuEvent& event ); + void OnMouseEvent( wxMouseEvent& event ); + + /** function SkipNextLeftButtonReleaseEvent + * after calling this function, if the left mouse button + * is down, the next left mouse button release event will be ignored. + * It is is usefull for instance when closing a dialog on a mouse click, + * to skip the next mouse left button release event + * by the parent window, because the mouse button + * clicked on the dialog is often released in the parent frame, + * and therefore creates a left button released mouse event + * which can be unwanted in some cases + */ + void SkipNextLeftButtonReleaseEvent(); + + virtual void OnHotKey( wxDC* aDC, int aHotKey, const wxPoint& aPosition, + EDA_ITEM* aItem = NULL ); + + /** + * Function AddMenuZoomAndGrid (virtual) + * Add standard zoom commands and submenu zoom and grid selection to a popup menu + * uses zoom hotkeys info base to add hotkeys info to menu commands + * @param aMasterMenu = the menu to populate. + */ + virtual void AddMenuZoomAndGrid( wxMenu* aMasterMenu ); + + void EraseMsgBox(); + void Process_PageSettings( wxCommandEvent& event ); + + /** + * Function SetLanguage + * called on a language menu selection + * when using a derived function, do not forget to call this one + */ + virtual void SetLanguage( wxCommandEvent& event ); + + virtual void ReCreateHToolbar() = 0; + virtual void ReCreateVToolbar() = 0; + virtual void ReCreateMenuBar(); + virtual void ReCreateAuxiliaryToolbar(); + + /** + * Function SetToolID + * sets the tool command ID to \a aId and sets the cursor to \a aCursor. The + * command ID must be greater or equal ::ID_NO_TOOL_SELECTED. If the command + * ID is less than ::ID_NO_TOOL_SELECTED, the tool command ID is set to + * ::ID_NO_TOOL_SELECTED. On debug builds, an assertion will be raised when + * \a aId is invalid. + * @param aId New tool command ID if greater than or equal to ::ID_NO_TOOL_SELECTED. + If less than zero, the current tool command ID is retained. + * @param aCursor Sets the cursor shape if greater than or equal to zero. + * @param aToolMsg The tool message to set in the status bar. + */ + virtual void SetToolID( int aId, int aCursor, const wxString& aToolMsg ); + + int GetToolId() const { return m_toolId; } + + /* These 4 functions provide a basic way to show/hide grid + * and /get/set grid color. + * These parameters are saved in KiCad config for each main frame + */ + /** + * Function IsGridVisible() , virtual + * @return true if the grid must be shown + */ + virtual bool IsGridVisible() const + { + return m_DrawGrid; + } + + /** + * Function SetGridVisibility() , virtual + * It may be overloaded by derived classes + * @param aVisible = true if the grid must be shown + */ + virtual void SetGridVisibility( bool aVisible ) + { + m_DrawGrid = aVisible; + } + + /** + * Function GetGridColor() , virtual + * @return the color of the grid + */ + virtual EDA_COLOR_T GetGridColor() const + { + return m_GridColor; + } + + /** + * Function SetGridColor() , virtual + * @param aColor = the new color of the grid + */ + virtual void SetGridColor( EDA_COLOR_T aColor ) + { + m_GridColor = aColor; + } + + /** + * Function GetGridPosition + * returns the nearest grid position to \a aPosition if a screen is defined and snap to + * grid is enabled. Otherwise, the original positions is returned. + * @see m_snapToGrid and m_BaseScreen members. + * @param aPosition The position to test. + * @return The wxPoint of the appropriate cursor position. + */ + wxPoint GetGridPosition( const wxPoint& aPosition ) const; + + /** + * Function SetNextGrid() + * changes the grid size settings to the next one available. + */ + virtual void SetNextGrid(); + + /** + * Function SetPrevGrid() + * changes the grid size settings to the previous one available. + */ + virtual void SetPrevGrid(); + + /** + * Command event handler for selecting grid sizes. + * + * All commands that set the grid size should eventually end up here. + * This is where the application setting is saved. If you override + * this method, make sure you call down to the base class. + * + * @param event - Command event passed by selecting grid size from the + * grid size combobox on the toolbar. + */ + virtual void OnSelectGrid( wxCommandEvent& event ); + + /** + * Functions OnSelectZoom + * sets the zoom factor when selected by the zoom list box in the main tool bar. + * @note List position 0 is fit to page + * List position >= 1 = zoom (1 to zoom max) + * Last list position is custom zoom not in zoom list. + */ + virtual void OnSelectZoom( wxCommandEvent& event ); + + // Command event handlers shared by all applications derived from EDA_DRAW_FRAME. + void OnToggleGridState( wxCommandEvent& aEvent ); + void OnSelectUnits( wxCommandEvent& aEvent ); + void OnToggleCrossHairStyle( wxCommandEvent& aEvent ); + + // Update user interface event handlers shared by all applications derived from + // EDA_DRAW_FRAME. + void OnUpdateUndo( wxUpdateUIEvent& aEvent ); + void OnUpdateRedo( wxUpdateUIEvent& aEvent ); + void OnUpdateGrid( wxUpdateUIEvent& aEvent ); + void OnUpdateUnits( wxUpdateUIEvent& aEvent ); + void OnUpdateCrossHairStyle( wxUpdateUIEvent& aEvent ); + + /** + * Function GeneralControl + * performs application specific control using \a aDC at \a aPosition in logical units. + *

+ * Override this function for application specific control. This function gets + * called on every mouse and key event. + *

+ * @param aDC A device context. + * @param aPosition The current cursor position in logical (drawing) units. + * @param aHotKey A key event used for application specific control if not zero. + */ + virtual void GeneralControl( wxDC* aDC, const wxPoint& aPosition, int aHotKey = 0 ) { } + + /** + * Function OnSize + * recalculates the size of toolbars and display panel when the frame size changes. + */ + virtual void OnSize( wxSizeEvent& event ); + + void OnEraseBackground( wxEraseEvent& SizeEvent ); + + virtual void OnZoom( wxCommandEvent& event ); + + /** + * Function SetNextZoom() + * changes the zoom to the next one available. + */ + void SetNextZoom(); + + /** + * Function SetPrevZoom() + * changes the zoom to the previous one available. + */ + void SetPrevZoom(); + + /** + * Function RedrawScreen + * redraws the entire screen area by updating the scroll bars and mouse pointer in + * order to have \a aCenterPoint at the center of the screen. + * @param aCenterPoint The position in logical units to center the scroll bars. + * @param aWarpPointer Moves the mouse cursor to \a aCenterPoint if true. + */ + void RedrawScreen( const wxPoint& aCenterPoint, bool aWarpPointer ); + + /** + * Function RedrawScreen2 + * puts the crosshair back to the screen position it had before zooming + * @param posBefore screen position of the crosshair before zooming + */ + void RedrawScreen2( const wxPoint& posBefore ); + + /** + * Function Zoom_Automatique + * redraws the screen with best zoom level and the best centering + * that shows all the page or the board + */ + void Zoom_Automatique( bool aWarpPointer ); + + /* Set the zoom level to show the area Rect */ + void Window_Zoom( EDA_RECT& Rect ); + + /** Return the zoom level which displays the full page on screen */ + virtual double BestZoom() = 0; + + /** + * Function GetZoom + * @return The current zoom level. + */ + double GetZoom(); + + /** + * Function DrawWorkSheet + * Draws on screen the page layout with the frame and the basic inscriptions. + * @param aDC The device context. + * @param aScreen screen to draw + * @param aLineWidth The pen width to use to draw the layout. + * @param aScale The mils to Iu conversion factor. + * @param aFilename The filename to display in basic inscriptions. + */ + void DrawWorkSheet( wxDC* aDC, BASE_SCREEN* aScreen, int aLineWidth, + double aScale, const wxString &aFilename ); + + void DisplayToolMsg( const wxString& msg ); + virtual void RedrawActiveWindow( wxDC* DC, bool EraseBg ) = 0; + virtual void OnLeftClick( wxDC* DC, const wxPoint& MousePos ) = 0; + virtual void OnLeftDClick( wxDC* DC, const wxPoint& MousePos ); + virtual bool OnRightClick( const wxPoint& MousePos, wxMenu* PopMenu ) = 0; + virtual void ToolOnRightClick( wxCommandEvent& event ); + void AdjustScrollBars( const wxPoint& aCenterPosition ); + + /** + * Function OnActivate (virtual) + * is called when activating the frame. + * In derived classes with a overriding OnActivate function, + * do not forget to call this EDA_DRAW_FRAME::OnActivate( event ) basic function. + */ + virtual void OnActivate( wxActivateEvent& event ); + + /** + * Function UpdateStatusBar + * updates the status bar information. + * + * The base method updates the absolute and relative coordinates and the + * zoom information. If you override this virtual method, make sure to call + * this subclassed method. The status bar can draw itself. This is not + * a drawing function per se, but rather updates lines of text held by + * the components within the status bar which is owned by the wxFrame. + *

+ * On a MAC, be careful about calling this function when there is an + * existing wxDC in existence on a sibling window. + */ + virtual void UpdateStatusBar(); + + /** + * Function DisplayUnitsMsg + * displays current unit pane on the status bar. + */ + void DisplayUnitsMsg(); + + /* Handlers for block commands */ + virtual void InitBlockPasteInfos(); + + /** + * Function HandleBlockBegin + * initializes the block command including the command type, initial position, + * and other variables. + */ + virtual bool HandleBlockBegin( wxDC* aDC, int aKey, const wxPoint& aPosition ); + + /** + * Function BlockCommand + * Returns the block command code (BLOCK_MOVE, BLOCK_COPY...) corresponding to the + * keys pressed (ALT, SHIFT, SHIFT ALT ..) when block command is started by dragging + * the mouse. + * + * @param aKey = the key modifiers (Alt, Shift ...) + * @return the block command id (BLOCK_MOVE, BLOCK_COPY...) + */ + virtual int BlockCommand( int aKey ); + + /** + * Function HandleBlockPlace( ) + * Called after HandleBlockEnd, when a block command needs to be + * executed after the block is moved to its new place + * (bloc move, drag, copy .. ) + * Parameters must be initialized in GetScreen()->m_BlockLocate + */ + virtual void HandleBlockPlace( wxDC* DC ); + + /** + * Function HandleBlockEnd( ) + * Handle the "end" of a block command, + * i.e. is called at the end of the definition of the area of a block. + * depending on the current block command, this command is executed + * or parameters are initialized to prepare a call to HandleBlockPlace + * in GetScreen()->m_BlockLocate + * @return false if no item selected, or command finished, + * true if some items found and HandleBlockPlace must be called later + */ + virtual bool HandleBlockEnd( wxDC* DC ); + + /** + * Function CopyToClipboard + * copies the current page or the current block to the clipboard. + */ + void CopyToClipboard( wxCommandEvent& event ); + + /* interprocess communication */ + void OnSockRequest( wxSocketEvent& evt ); + void OnSockRequestServer( wxSocketEvent& evt ); + + void LoadSettings( wxConfigBase* aCfg ); // override virtual + + void SaveSettings( wxConfigBase* aCfg ); // override virtual + + /** + * Append a message to the message panel. + * + * This helper method checks to make sure the message panel exists in + * the frame and appends a message to it using the message panel + * AppendMessage() method. + * + * @param textUpper - The message upper text. + * @param textLower - The message lower text. + * @param color - A color ID from the KiCad color list (see colors.h). + * @param pad - Number of spaces to pad between messages (default = 4). + */ + void AppendMsgPanel( const wxString& textUpper, const wxString& textLower, + EDA_COLOR_T color, int pad = 6 ); + + /** + * Clear all messages from the message panel. + */ + void ClearMsgPanel( void ); + + /** + * Function SetMsgPanel + * clears the message panel and populates it with the contents of \a aList. + * + * @param aList is the list of #MSG_PANEL_ITEM objects to fill the message panel. + */ + void SetMsgPanel( const std::vector< MSG_PANEL_ITEM >& aList ); + + void SetMsgPanel( EDA_ITEM* aItem ); + + /** + * Function PrintPage + * used to print a page + * Print the page pointed by current screen, set by the calling print function + * @param aDC = wxDC given by the calling print function + * @param aPrintMask = not used here + * @param aPrintMirrorMode = not used here (Set when printing in mirror mode) + * @param aData = a pointer on an auxiliary data (not always used, NULL if not used) + */ + virtual void PrintPage( wxDC* aDC, LAYER_MSK aPrintMask, bool aPrintMirrorMode, void* aData = NULL ); + + /** + * Function CoordinateToString + * is a helper to convert the \a integer coordinate \a aValue to a string in inches or mm + * according to the current user units setting. + * @param aValue The coordinate to convert. + * @param aConvertToMils Convert inch values to mils if true. This setting has no effect if + * the current user unit is millimeters. + * @return The converted string for display in user interface elements. + */ + wxString CoordinateToString( int aValue, bool aConvertToMils = false ) const; + + /** + * Function LengthDoubleToString + * is a helper to convert the \a double value \a aValue to a string in inches or mm + * according to the current user units setting. + * @param aValue The coordinate to convert. + * @param aConvertToMils Convert inch values to mils if true. This setting has no effect if + * the current user unit is millimeters. + * @return The converted string for display in user interface elements. + */ + wxString LengthDoubleToString( double aValue, bool aConvertToMils = false ) const; + + /** + * Function UseGalCanvas + * used to switch between standard and GAL-based canvas. + * + * @param aEnable True for GAL-based canvas, false for standard canvas. + */ + virtual void UseGalCanvas( bool aEnable ); + + /** + * Function IsGalCanvasActive + * is used to check which canvas (GAL-based or standard) is currently in use. + * + * @return True for GAL-based canvas, false for standard canvas. + */ + bool IsGalCanvasActive() const { return m_galCanvasActive; } + void SetGalCanvasActive( bool aState ) { m_galCanvasActive = aState; } + + /** + * Function GetGalCanvas + * returns a pointer to GAL-based canvas of given EDA draw frame. + * + * @return Pointer to GAL-based canvas. + */ + EDA_DRAW_PANEL_GAL* GetGalCanvas() const { return m_galCanvas; } + void SetGalCanvas( EDA_DRAW_PANEL_GAL* aPanel ) { m_galCanvas = aPanel; } + + DECLARE_EVENT_TABLE() +}; + +#endif // EDA_DRAW_FRAME_H_ diff --git a/include/drawtxt.h b/include/drawtxt.h index b2d898e99a..d830f164c5 100644 --- a/include/drawtxt.h +++ b/include/drawtxt.h @@ -50,11 +50,11 @@ int Clamp_Text_PenSize( int aPenSize, wxSize aSize, bool aBold = true ); int GetPenSizeForBold( int aTextSize ); /** - * Function ReturnGraphicTextWidth + * Function GraphicTextWidth * @return the X size of the graphic text - * the full X size is ReturnGraphicTextWidth + the thickness of graphic lines + * the full X size is GraphicTextWidth + the thickness of graphic lines */ -int ReturnGraphicTextWidth( const wxString& aText, int size_h, bool italic, bool bold ); +int GraphicTextWidth( const wxString& aText, int size_h, bool italic, bool bold ); /** * Function NegableTextLength diff --git a/include/fp_lib_table.h b/include/fp_lib_table.h index 5ce7d5236f..e4f589e53d 100644 --- a/include/fp_lib_table.h +++ b/include/fp_lib_table.h @@ -30,11 +30,9 @@ #include #include #include - - +#include #define FP_LATE_ENVVAR 1 ///< late=1/early=0 environment variable expansion -#define KISYSMOD "KISYSMOD" class wxFileName; class OUTPUTFORMATTER; @@ -42,7 +40,7 @@ class MODULE; class FP_LIB_TABLE_LEXER; class NETLIST; class REPORTER; - +class SEARCH_STACK; /** * Class FP_LIB_TABLE @@ -85,7 +83,7 @@ class REPORTER; * * @author Wayne Stambaugh */ -class FP_LIB_TABLE +class FP_LIB_TABLE : public PROJECT::_ELEM { friend class DIALOG_FP_LIB_TABLE; @@ -271,6 +269,13 @@ public: */ FP_LIB_TABLE( FP_LIB_TABLE* aFallBackTable = NULL ); + /// Delete all rows. + void Clear() + { + rows.clear(); + nickIndex.clear(); + } + bool operator==( const FP_LIB_TABLE& r ) const { if( rows.size() == r.rows.size() ) @@ -352,8 +357,6 @@ public: */ void Format( OUTPUTFORMATTER* out, int nestLevel ) const throw( IO_ERROR ); - void Save( const wxFileName& aPath ) const throw( IO_ERROR ); - /** * Function GetLogicalLibs * returns the logical library names, all of them that are pertinent to @@ -496,27 +499,9 @@ public: */ bool IsEmpty( bool aIncludeFallback = true ); - /** - * Function MissingLegacyLibs - * tests the list of \a aLibNames by URI to determine if any of them are missing from - * the #FP_LIB_TABLE. - * - * @note The missing legacy footprint library test is performed by using old library - * file path lookup method. If the library is found, it is compared against all - * of the URIs in the table rather than the nickname. This was done because the - * user could change the nicknames from the default table. Using the full path - * is more reliable. - * - * @param aLibNames is the list of legacy library names. - * @param aErrorMsg is a pointer to a wxString object to store the URIs of any missing - * legacy library paths. Can be NULL. - * @return true if there are missing legacy libraries. Otherwise false. - */ - bool MissingLegacyLibs( const wxArrayString& aLibNames, wxString* aErrorMsg = NULL ); - /** * Function ConvertFromLegacy - * converts the footprint names in \a aNetList from the legacy fromat to the #FPID format. + * converts the footprint names in \a aNetList from the legacy format to the #FPID format. * * @param aNetList is the #NETLIST object to convert. * @param aLibNames is the list of legacy footprint library names from the currently loaded @@ -524,11 +509,11 @@ public: * @param aReporter is the #REPORTER object to dump messages into. * @return true if all footprint names were successfully converted to a valid FPID. */ - bool ConvertFromLegacy( NETLIST& aNetList, const wxArrayString& aLibNames, - REPORTER* aReporter = NULL ) throw( IO_ERROR ); + bool ConvertFromLegacy( SEARCH_STACK& aSStack, NETLIST& aNetList, + const wxArrayString& aLibNames, REPORTER* aReporter = NULL ) throw( IO_ERROR ); /** - * Function ExpandEnvSubsitutions + * Function ExpandSubstitutions * replaces any environment variable references with their values and is * here to fully embellish the ROW::uri in a platform independent way. * This enables (fp_lib_table)s to have platform dependent environment @@ -557,20 +542,13 @@ public: */ static wxString GetGlobalTableFileName(); +#if 0 /** * Function GetFileName * @return the footprint library file name. */ - static const wxString& GetFileName(); - - static void SetProjectPathEnvVariable( const wxFileName& aPath ); - - /** - * Function ProjectPathEnvVarVariableName - * returns the name of the environment variable used to hold the directory of - * the current project on program startup. - */ - static const wxString ProjectPathEnvVariableName(); + static const wxString GetFileName(); +#endif /** * Function GlobalPathEnvVarVariableName @@ -582,19 +560,24 @@ public: */ static const wxString GlobalPathEnvVariableName(); - static wxString GetProjectFileName( const wxFileName& aPath ); - /** * Function Load * loads the footprint library table using the path defined in \a aFileName with * \a aFallBackTable. * - * @param aFileName contains the path and possible the file name and extension. - * @param aFallBackTable the fall back footprint library table which can be NULL. + * @param aFileName contains the full path to the s-expression file. + * * @throw IO_ERROR if an error occurs attempting to load the footprint library * table. */ - void Load( const wxFileName& aFileName, FP_LIB_TABLE* aFallBackTable ) throw( IO_ERROR ); + void Load( const wxString& aFileName ) throw( IO_ERROR ); + + /** + * Function Save + * writes this table to aFileName in s-expression form. + * @param aFileName is the name of the file to write to. + */ + void Save( const wxString& aFileName ) const throw( IO_ERROR ); protected: @@ -640,4 +623,7 @@ protected: FP_LIB_TABLE* fallBack; }; + +extern FP_LIB_TABLE GFootprintTable; // KIFACE scope. + #endif // FP_LIB_TABLE_H_ diff --git a/include/gestfich.h b/include/gestfich.h index 4d6403e29d..324a767eb0 100644 --- a/include/gestfich.h +++ b/include/gestfich.h @@ -112,7 +112,7 @@ void AddDelimiterString( wxString& string ); wxString FindKicadHelpPath(); /** - * Function ReturnKicadDatasPath + * Function KicadDatasPath * returns the data path common to KiCad. * If environment variable KICAD is defined (KICAD = path to kicad) * Returns \ /; @@ -122,7 +122,7 @@ wxString FindKicadHelpPath(); * Note: * The \\ are replaced by / (a la Unix) */ -wxString ReturnKicadDatasPath(); +wxString KicadDatasPath(); /** * Function FindKicadFile diff --git a/include/hotkey_grid_table.h b/include/hotkey_grid_table.h index 8856a18520..27fbbcfb9c 100644 --- a/include/hotkey_grid_table.h +++ b/include/hotkey_grid_table.h @@ -10,7 +10,7 @@ #include #include -#include +#include #include #include diff --git a/include/hotkeys_basic.h b/include/hotkeys_basic.h index f070441de4..cbae182e39 100644 --- a/include/hotkeys_basic.h +++ b/include/hotkeys_basic.h @@ -113,7 +113,7 @@ void AddHotkeyConfigMenu( wxMenu* menu ); void HandleHotkeyConfigMenuSelection( EDA_DRAW_FRAME* frame, int id ); /** - * Function ReturnKeyNameFromKeyCode + * Function KeyNameFromKeyCode * return the key name from the key code * * Only some wxWidgets key values are handled for function key ( see * s_Hotkey_Name_List[] ) @@ -121,32 +121,33 @@ void HandleHotkeyConfigMenuSelection( EDA_DRAW_FRAME* frame, int id ); * @param aIsFound = a pointer to a bool to return true if found, or false. an be NULL default) * @return the key name in a wxString */ -wxString ReturnKeyNameFromKeyCode( int aKeycode, bool * aIsFound = NULL ); +wxString KeyNameFromKeyCode( int aKeycode, bool * aIsFound = NULL ); /** - * Function ReturnKeyNameFromCommandId + * Function KeyNameFromCommandId * return the key name from the Command id value ( m_Idcommand member value) * @param aList = pointer to a EDA_HOTKEY list of commands * @param aCommandId = Command Id value * @return the key name in a wxString */ -wxString ReturnKeyNameFromCommandId( EDA_HOTKEY** aList, int aCommandId ); +wxString KeyNameFromCommandId( EDA_HOTKEY** aList, int aCommandId ); /** - * Function ReturnKeyCodeFromKeyName + * Function KeyCodeFromKeyName * return the key code from its key name * Only some wxWidgets key values are handled for function key * @param keyname = wxString key name to find in s_Hotkey_Name_List[], * like F2 or space or an usual (ascii) char. * @return the key code */ -int ReturnKeyCodeFromKeyName( const wxString& keyname ); +int KeyCodeFromKeyName( const wxString& keyname ); -/* An helper enum for AddHotkeyName function - * In menus we can an a hot key, or an accelerator , or sometimes just a comment +/** + * An helper enum for AddHotkeyName function + * In menus we can add a hot key, or an accelerator , or sometimes just a comment * Hot keys can perform actions using the current mouse cursor position - * Accelerators performs the same action as the associated menu + * Accelerators perform the same action as the associated menu * A comment is used in tool tips for some tools (zoom ..) * to show the hot key that performs this action */ diff --git a/include/import_export.h b/include/import_export.h index eed48fb797..57de9f9ef7 100644 --- a/include/import_export.h +++ b/include/import_export.h @@ -24,7 +24,9 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ -// macros which export functions from a DLL/DSO. + +/// Macros which export functions from a DLL/DSO. +/// See: http://gcc.gnu.org/wiki/Visibility #if defined(__MINGW32__) #define APIEXPORT __declspec(dllexport) @@ -32,6 +34,7 @@ #define APILOCAL #elif defined(__GNUC__) && __GNUC__ >= 4 + // On ELF, we compile with hidden visibility, so unwrap that for specific symbols: #define APIEXPORT __attribute__ ((visibility("default"))) #define APIIMPORT __attribute__ ((visibility("default"))) #define APILOCAL __attribute__ ((visibility("hidden"))) @@ -44,8 +47,9 @@ #endif -#if defined(test_EXPORTS) || defined(COMPILING_DLL) - // above defined by CMake magically when compiling implementation. +#if defined(COMPILING_DLL) + // Be sure and define COMPILING_DLL when compiling implementation, and NOT when + // compiling the client. #define MY_API(rettype) APIEXPORT rettype #else #define MY_API(rettype) APIIMPORT rettype diff --git a/include/kiface_i.h b/include/kiface_i.h new file mode 100644 index 0000000000..23f89dffbf --- /dev/null +++ b/include/kiface_i.h @@ -0,0 +1,141 @@ +#ifndef KIFACE_I_H_ +#define KIFACE_I_H_ + +/* + * This program source code file is part of KiCad, a free EDA CAD application. + * + * Copyright (C) 1992-2014 KiCad Developers, see AUTHORS.txt for contributors. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, you may find one here: + * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html + * or you may search the http://www.gnu.org website for the version 2 license, + * or you may write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + */ + + +#include +#include + + +/** + * Class KIFACE_I + * is a KIFACE (I)mplementation, + * with some features useful for DSOs which implement a KIFACE. + * It is abstract, a few functions must be implemented in derivations. + */ +class KIFACE_I : public KIFACE +{ +public: + + //--------------------------------------------------------------- + + // see base class KIFACE in kiway.h for doxygen docs + + VTBL_ENTRY bool OnKifaceStart( PGM_BASE* aProgram ) = 0; + /* + { + typically call start_common() in your overload + return start_common(); + } + */ + + VTBL_ENTRY void OnKifaceEnd() + { + // overload this if you want, end_common() may be handy. + end_common(); + } + + VTBL_ENTRY wxWindow* CreateWindow( wxWindow* aParent, + int aClassId, KIWAY* aKIWAY, int aCtlBits = 0 ) = 0; + + VTBL_ENTRY void* IfaceOrAddress( int aDataId ) = 0; + + //-------------------------------------------------------------- + + // The remainder are DSO specific helpers, not part of the KIFACE API + + /** + * Constructor + * + * @param aKifaceName should point to a C string in permanent storage, + * which contains the name of the DSO. Examples: "eeschema", "pcbnew", etc. + * This controls the name of the wxConfigBase established in m_bm, + * so it should be lowercase. + */ + KIFACE_I( const char* aKifaceName, KIWAY::FACE_T aId ) : + m_id( aId ), + m_bm( aKifaceName ) + { + } + + // ~KIFACE_I(); + +protected: + + /// Common things to do for a top program module, during OnKifaceStart(). + bool start_common(); + + /// Common things to do for a top program module, during OnKifaceEnd(); + void end_common(); + + // From here down should probably not be in a KIFACE, even though they + // are DSO specific, they have nothing to do with KIWAY's use of KIFACE, + // so its a questionable choice to put non KIWAY client code in this class. + +public: + + const wxString Name() { return wxString::FromUTF8( m_bm.m_name ); } + + wxConfigBase* KifaceSettings() const { return m_bm.m_config; } + + const wxString& GetHelpFileName() const { return m_bm.m_help_file; } + void SetHelpFileName( const wxString& aFileName ) { m_bm.m_help_file = aFileName; } + + /** + * Function GetHelpFile + * gets the help file path. + *

+ * Return the KiCad help file with path. The base paths defined in + * m_searchPaths are tested for a valid file. The path returned can + * be relative depending on the paths added to m_searchPaths. See the + * documentation for wxPathList for more information. If the help file + * for the current locale is not found, an attempt to find the English + * version of the help file is made. + * wxEmptyString is returned if help file not found. + * Help file is searched in directories in this order: + * help/\ like help/en_GB + * help/\ like help/en + * help/en + *

+ */ + wxString GetHelpFile(); + + wxFileHistory& GetFileHistory() { return m_bm.m_history; } + + /// Only for DSO specific 'non-library' files. + /// (The library search path is in the PROJECT class.) + SEARCH_STACK& KifaceSearch() { return m_bm.m_search; } + +private: + KIWAY::FACE_T m_id; + + BIN_MOD m_bm; +}; + + +/// Global KIFACE_I "get" accessor. +KIFACE_I& Kiface(); + +#endif // KIFACE_I_H_ diff --git a/include/kiway.h b/include/kiway.h index efef894340..b13f8b88e4 100644 --- a/include/kiway.h +++ b/include/kiway.h @@ -99,21 +99,18 @@ as such! As such, it is OK to use UTF8 characters: #include #include #include +#include +#include #define VTBL_ENTRY virtual -#define KIFACE_VERSION 1 -#define KIFACE_GETTER KIFACE_1 +#define KIFACE_VERSION 1 +#define KIFACE_GETTER KIFACE_1 // The KIFACE acquistion function is declared extern "C" so its name should not -// be mangled (much). Windows has leading underscore for our C function. -// Keep the trailing version number in sync with the KIFACE_GETTER define above. -#if defined(__MINGW32__) - #define KIFACE_INSTANCE_NAME_AND_VERSION "_KIFACE_1" -#else - #define KIFACE_INSTANCE_NAME_AND_VERSION "KIFACE_1" -#endif +// be mangled. +#define KIFACE_INSTANCE_NAME_AND_VERSION "KIFACE_1" #if defined(__linux__) @@ -127,40 +124,17 @@ as such! As such, it is OK to use UTF8 characters: #endif -/** - * Class PROJECT - * holds project specific data. Because it is in the neutral program top, which - * is not linked to by subsidiarly DSOs, any functions in this interface must - * be VTBL_ENTRYs. - */ -class PROJECT -{ - -public: - -#if 0 - /// Derive PROJECT elements from this, it has a virtual destructor, and - /// Elem*() functions can work with it. - class ELEM_BASE - { - public: - virtual ~ELEM_BASE() {} - }; - - VTBL_ENTRY int ElemAllocNdx(); - VTBL_ENTRY void ElemSet( int aIndex, ELEMENT_BASE* aBlock ); - VTBL_ENTRY ELEM_BASE* ElemGet( int aIndex ) -#endif -}; +class wxConfigBase; class KIWAY; class wxWindow; -class wxApp; +class PGM_BASE; +class wxConfigBase; /** - * Struct KIFACE + * Class KIFACE * is used by a participant in the KIWAY alchemy. KIWAY is a minimalistic * software bus for communications between various DLLs/DSOs (DSOs) within the same * KiCad process. It makes it possible to call between DSOs without having to link @@ -173,36 +147,71 @@ class wxApp; */ struct KIFACE { - // Do not change the order of functions in this listing, add new ones at - // the end, unless you recompile all of KiCad. + // The order of functions establishes the vtable sequence, do not change the + // order of functions in this listing unless you recompile all clients of + // this interface. + + /** + * Function OnKifaceStart + * is called just once shortly after the DSO is loaded. It is the second + * function called, immediately after the KIFACE_GETTER(). However before + * either of those, static C++ constructors are called. The DSO implementation + * should do process level initialization here, not project specific since there + * will be multiple projects open eventually. + * + * @param aProgram is the process block: PGM_BASE* + * + * @return bool - true if DSO initialized OK, false if not. When returning + * false, the loader may optionally decide to terminate the process or not, + * but will not put out any UI because that is the duty of this function to say + * why it is returning false. Never return false without having reported + * to the UI why. + */ + VTBL_ENTRY bool OnKifaceStart( PGM_BASE* aProgram ) = 0; + + /** + * Function OnKifaceEnd + * is called just once just before the DSO is to be unloaded. It is called + * before static C++ destructors are called. A default implementation is supplied. + */ + VTBL_ENTRY void OnKifaceEnd() = 0; #define KFCTL_STANDALONE (1<<0) ///< Am running as a standalone Top. /** * Function CreateWindow - * creates a wxTopLevelWindow for the current project. The caller + * creates a wxWindow for the current project. The caller * must cast the return value into the known type. * - * @param aClassId identifies which wxFrame or wxDialog to retrieve. + * @param aParent may be NULL, or is otherwise the parent to connect under. If NULL + * then caller may want to connect the returned wxWindow into some hierarchy after + * this function returns. + * + * @param aClassId identifies which wxFrame or wxDialog to retrieve, using a value + * known to the implementing KIFACE. * * @param aKIWAY tells the window which KIWAY (and PROJECT) it is a participant in. * - * @param aCtlBits consists of bit flags from the set KFCTL_* #defined above. + * @param aCtlBits consists of bit flags from the set of KFCTL_* \#defines above. * - * @return wxWindow* - and if not NULL, should be cast into the known type. + * @return wxWindow* - and if not NULL, should be cast into the known type using + * and old school cast. dynamic_cast is problemenatic since it needs typeinfo probably + * not contained in the caller's link image. */ - VTBL_ENTRY wxWindow* CreateWindow( int aClassId, KIWAY* aKIWAY, int aCtlBits = 0 ) = 0; + VTBL_ENTRY wxWindow* CreateWindow( wxWindow* aParent, int aClassId, + KIWAY* aKIWAY, int aCtlBits = 0 ) = 0; /** * Function IfaceOrAddress - * return a pointer to the requested object. The safest way to use this + * returns a pointer to the requested object. The safest way to use this * is to retrieve a pointer to a static instance of an interface, similar to * how the KIFACE interface is exported. But if you know what you are doing - * use it to retrieve anything you want. + * use it to retrieve anything you want. Segfaults are your fault. * - * @param aDataId identifies which object you want the address of. + * @param aDataId identifies which object you want the address of, and consists + * of choices known in advance by the implementing KIFACE. * - * @return void* - and must be cast into the know type. + * @return void* - and must be cast into the known type. */ VTBL_ENTRY void* IfaceOrAddress( int aDataId ) = 0; }; @@ -213,17 +222,23 @@ struct KIFACE * is a minimalistic software bus for communications between various * DLLs/DSOs (DSOs) within the same KiCad process. It makes it possible * to call between DSOs without having to link them together, and without - * having to link to the top process module which houses the KIWAY(s). It also - * makes it possible to send custom wxEvents between DSOs and from the top + * having to link to the top process module which houses the KIWAY(s). More importantly + * it makes it possible to send custom wxEvents between DSOs and from the top * process module down into the DSOs. The latter capability is thought useful * for driving the lower DSOs from a python test rig or for demo (automaton) purposes. *

- * Most all calls are via virtual functions which means C++ vtables + * Most all calls are via virtual functions, which means C++ vtables * are used to hold function pointers and eliminate the need to link to specific * object code libraries, speeding development and encouraging clearly defined - * interface design. There is one KIWAY in the launching portion of the process - * for each open KiCad project. Each project has its own KIWAY. Within a KIWAY - * is an actual PROJECT data structure. + * interface design. Unlike Microsoft COM, which is a multi-vendor design supporting + * DLL's built at various points in time, the KIWAY alchemy is single project, with + * all components being built at the same time. So one should expect solid compatibility + * between all KiCad components, as long at they are compiled at the same time. + *

+ * There is one KIWAY in the launching portion of the process + * for each open KiCad project. Each project has its own KIWAY. Available to + * each KIWAY is an actual PROJECT data structure. If you have a KIWAY, you + * can get to the PROJECT using KIWAY::Prj(). *

* In summary, a KIWAY facilitates communicating between DSOs, where the topic * of the communication is project specific. Here a "project" means a BOARD @@ -237,35 +252,56 @@ public: /// DSO players on *this* KIWAY enum FACE_T { - FACE_SCH, ///< _eeschema DSO + FACE_SCH, ///< eeschema DSO // FACE_LIB, - FACE_PCB, ///< _pcbnew DSO + FACE_PCB, ///< pcbnew DSO // FACE_MOD, + FACE_CVPCB, + FACE_BMP2CMP, + FACE_GERBVIEW, + FACE_PL_EDITOR, + FACE_PCB_CALCULATOR, - FACE_COUNT ///< how many KIWAY player types + FACE_COUNT, ///< how many KIWAY player types }; + /* from edaappl.h, now pgm_base.h, obsoleted by above FACE_T enum. + enum PGM_BASE_T + { + APP_UNKNOWN, + APP_EESCHEMA, + APP_PCBNEW, + APP_CVPCB, + APP_GERBVIEW, + APP_KICAD, + APP_PL_EDITOR, + APP_BM2CMP, + }; + */ + // Don't change the order of these VTBL_ENTRYs, add new ones at the end, // unless you recompile all of KiCad. VTBL_ENTRY KIFACE* KiFACE( FACE_T aFaceId, bool doLoad ); - VTBL_ENTRY PROJECT& Project(); + VTBL_ENTRY PROJECT& Prj() const; KIWAY(); private: + /* /// Get the name of the DSO holding the requested FACE_T. static const wxString dso_name( FACE_T aFaceId ); + */ // one for each FACE_T static wxDynamicLibrary s_sch_dso; static wxDynamicLibrary s_pcb_dso; - //static wxDynamicLibrary s_cvpcb_dso; // will get merged into pcbnew + //static wxDynamicLibrary s_cvpcb_dso; // will get merged into pcbnew - KIFACE* m_dso_players[FACE_COUNT]; + KIFACE* m_kiface[FACE_COUNT]; - PROJECT m_project; + PROJECT m_project; // do not assume this is here, use Prj(). }; @@ -273,19 +309,18 @@ private: * Function Pointer KIFACE_GETTER_FUNC * points to the one and only KIFACE export. The export's address * is looked up via symbolic string and should be extern "C" to avoid name - * mangling. That function can also implement process initialization functionality, - * things to do once per process that is DSO resident. This function will only be - * called one time. The DSO itself however may be asked to support multiple - * Top windows, i.e. multiple projects within its lifetime. + * mangling. This function will only be called one time. The DSO itself however + * may be asked to support multiple Top windows, i.e. multiple projects + * within its lifetime. * * @param aKIFACEversion is where to put the API version implemented by the KIFACE. * @param aKIWAYversion tells the KIFACE what KIWAY version will be available. - * @param aProcess is a pointer to the basic wxApp for this process. - * @return KIFACE* - unconditionally. + * @param aProgram is a pointer to the PGM_BASE for this process. + * @return KIFACE* - unconditionally, cannot fail. */ -typedef KIFACE* KIFACE_GETTER_FUNC( int* aKIFACEversion, int aKIWAYversion, wxApp* aProcess ); +typedef KIFACE* KIFACE_GETTER_FUNC( int* aKIFACEversion, int aKIWAYversion, PGM_BASE* aProgram ); -/// No name mangling. Each TOPMOD will implement this once. -extern "C" KIFACE* KIFACE_GETTER( int* aKIFACEversion, int aKIWAYversion, wxApp* aProcess ); +/// No name mangling. Each KIFACE (DSO/DLL) will implement this once. +extern "C" KIFACE* KIFACE_GETTER( int* aKIFACEversion, int aKIWAYversion, PGM_BASE* aProgram ); #endif // KIWAY_H_ diff --git a/include/kiway_player.h b/include/kiway_player.h new file mode 100644 index 0000000000..b61b6f195c --- /dev/null +++ b/include/kiway_player.h @@ -0,0 +1,169 @@ +#ifndef KIWAY_PLAYER_H_ +#define KIWAY_PLAYER_H_ + +/* + * This program source code file is part of KiCad, a free EDA CAD application. + * + * Copyright (C) 2014 SoftPLC Corporation, Dick Hollenbeck + * Copyright (C) 2014 KiCad Developers, see change_log.txt for contributors. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, you may find one here: + * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html + * or you may search the http://www.gnu.org website for the version 2 license, + * or you may write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + */ + +#include +#include +#include + + +class KIWAY; +class PROJECT; +struct KIFACE; +class KIFACE_I; + + +/** + * Class KIWAY_HOLDER + * is a mix in class which holds the location of a wxWindow's KIWAY. It allows + * calls to Kiway() and SetKiway(). + * + * Known to be used in at least DIALOG_SHIM and KIWAY_PLAYER classes. + */ +class KIWAY_HOLDER +{ +public: + KIWAY_HOLDER( KIWAY* aKiway ) : + m_kiway( aKiway ) + {} + + /** + * Function Kiway + * returns a reference to the KIWAY that this object has an opportunity + * to participate in. A KIWAY_HOLDER is not necessarily a KIWAY_PLAYER. + */ + KIWAY& Kiway() const + { + wxASSERT( m_kiway ); // smoke out bugs in Debug build, then Release runs fine. + return *m_kiway; + } + + /** + * Function Prj + * returns a reference to the PROJECT "associated with" this KIWAY. + */ + PROJECT& Prj() const; + + /** + * Function SetKiway + * + * @param aDest is the recipient of aKiway pointer. + * It is only used for debugging, since "this" is not a wxWindow*. "this" is + * a KIWAY_HOLDER mix-in. + * + * @param aKiway is often from a parent window, or from KIFACE::CreateWindow(). + */ + void SetKiway( wxWindow* aDest, KIWAY* aKiway ); + +private: + // private, all setting is done through SetKiway(). + KIWAY* m_kiway; // no ownership. +}; + + +/** + * Class KIWAY_PLAYER + * is a wxFrame capable of the OpenProjectFiles function, meaning it can load + * a portion of a KiCad project. Because this class provides a dummy implementation, + * it is not a certainty that all classes which inherit from this clas intend to + * participate in a KIWAY. Those that do must actually interact with the provided + * KIWAY*. + *

+ * EDA_BASE_FRAME would not have sufficed because BM2CMP_FRAME_BASE is not + * derived from it. + */ +class KIWAY_PLAYER : public EDA_BASE_FRAME, public KIWAY_HOLDER +{ +public: + KIWAY_PLAYER( KIWAY* aKiway, wxWindow* aParent, ID_DRAWFRAME_TYPE aFrameType, + const wxString& aTitle, const wxPoint& aPos, const wxSize& aSize, + long aStyle, const wxString& aWdoName = wxFrameNameStr ) : + EDA_BASE_FRAME( aParent, aFrameType, aTitle, aPos, aSize, aStyle, aWdoName ), + KIWAY_HOLDER( aKiway ) + {} + + /// Don't use this one, only wxformbuilder uses it, and it must be augmented with + /// a SetKiway() early in derived constructor. + KIWAY_PLAYER( wxWindow* aParent, wxWindowID aId, const wxString& aTitle, + const wxPoint& aPos, const wxSize& aSize, long aStyle, + const wxString& aWdoName = wxFrameNameStr ) : + EDA_BASE_FRAME( aParent, (ID_DRAWFRAME_TYPE) aId, aTitle, aPos, aSize, aStyle, aWdoName ), + KIWAY_HOLDER( 0 ) + {} + + + // For the aCtl argument of OpenProjectFiles() +#define KICTL_OPEN_APPEND (1<<0) ///< append the data file, rather than replace +#define KICTL_EAGLE_BRD (1<<1) ///< chosen *.brd file is Eagle according to user. + + /** + * Function OpenProjectFiles + * is abstract, and opens a project or set of files given by @a aFileList. + * This is generalized in the direction of worst case. In a typical case + * @a aFileList will only hold a single file, like "myboard.kicad_pcb", + * because any KIWAY_PLAYER is only in one KIWAY and the KIWAY owns the + * PROJECT. Therefore opening files from multiple projects into the same + * KIWAY_PLAYER is precluded. + *

+ * Each derived class should handle this in a way specific to its needs. + * No prompting is done inside here for any file or project. There should be + * need to call this with aFileList which is empty. However, calling it with + * a single filename which does not exist should indicate to the implementor + * that a new session is being started and that the given name is the desired + * name for the data file at time of save. + *

+ * Therefore, one of the first things an implementation should do is test for + * existence of the first file in the list, and if it does not exist, treat + * it as a new session, possibly with a UI notification to that effect. + *

+ * After loading the window should update its Title as part of this operation. + * If the KIWAY_PLAYER needs to, it can load the *.pro file as part of this operation. + *

+ * If the KIWAY_PLAYER cannot load any of the file(s) in the list, then it + * should say why through some GUI interface, and return false. + * + * @param aFileList includes files that this frame should open + * according to the knowledge in the derived wxFrame. In almost every case, + * the list will have only a single file in it. + * + * @param aCtl is a set of bit flags ORed together from the set of KICTL_* \#defined above. + * + * @return bool - true if all requested files were opened OK, else false. + */ + virtual bool OpenProjectFiles( const std::vector& aFileList, int aCtl = 0 ) + { + // overload me for your wxFrame type. + + // Any overload should probably do this also: + // Prj().MaybeLoadProjectSettings(); + + // Then update the window title. + + return false; + } +}; + +#endif // KIWAY_PLAYER_H_ diff --git a/include/layers_id_colors_and_visibility.h b/include/layers_id_colors_and_visibility.h index 50aa5fa832..5b73d4f266 100644 --- a/include/layers_id_colors_and_visibility.h +++ b/include/layers_id_colors_and_visibility.h @@ -63,6 +63,8 @@ typedef int LAYER_NUM; #define NB_COPPER_LAYERS (LAST_COPPER_LAYER - FIRST_COPPER_LAYER + 1) #define FIRST_NON_COPPER_LAYER 16 +#define FIRST_TECHNICAL_LAYER 16 +#define FIRST_USER_LAYER 24 #define ADHESIVE_N_BACK 16 #define ADHESIVE_N_FRONT 17 #define SOLDERPASTE_N_BACK 18 @@ -77,6 +79,8 @@ typedef int LAYER_NUM; #define ECO2_N 27 #define EDGE_N 28 #define LAST_NON_COPPER_LAYER 28 +#define LAST_TECHNICAL_LAYER 23 +#define LAST_USER_LAYER 27 #define NB_PCB_LAYERS (LAST_NON_COPPER_LAYER + 1) #define UNUSED_LAYER_29 29 #define UNUSED_LAYER_30 30 @@ -128,13 +132,16 @@ typedef unsigned LAYER_MSK; #define ALL_CU_LAYERS 0x0000FFFF #define INTERNAL_CU_LAYERS 0x00007FFE #define EXTERNAL_CU_LAYERS 0x00008001 -#define FRONT_AUX_LAYERS (SILKSCREEN_LAYER_FRONT | SOLDERMASK_LAYER_FRONT \ +#define FRONT_TECH_LAYERS (SILKSCREEN_LAYER_FRONT | SOLDERMASK_LAYER_FRONT \ | ADHESIVE_LAYER_FRONT | SOLDERPASTE_LAYER_FRONT) -#define BACK_AUX_LAYERS (SILKSCREEN_LAYER_BACK | SOLDERMASK_LAYER_BACK \ +#define BACK_TECH_LAYERS (SILKSCREEN_LAYER_BACK | SOLDERMASK_LAYER_BACK \ | ADHESIVE_LAYER_BACK | SOLDERPASTE_LAYER_BACK) -#define ALL_AUX_LAYERS (FRONT_AUX_LAYERS | BACK_AUX_LAYERS) -#define BACK_LAYERS (LAYER_BACK | BACK_AUX_LAYERS) -#define FRONT_LAYERS (LAYER_FRONT | FRONT_AUX_LAYERS) +#define ALL_TECH_LAYERS (FRONT_TECH_LAYERS | BACK_TECH_LAYERS) +#define BACK_LAYERS (LAYER_BACK | BACK_TECH_LAYERS) +#define FRONT_LAYERS (LAYER_FRONT | FRONT_TECH_LAYERS) + +#define ALL_USER_LAYERS (DRAW_LAYER | COMMENT_LAYER |\ + ECO1_LAYER | ECO2_LAYER ) #define NO_LAYERS 0x00000000 @@ -330,8 +337,18 @@ inline bool IsCopperLayer( LAYER_NUM aLayer ) */ inline bool IsNonCopperLayer( LAYER_NUM aLayer ) { - return aLayer >= FIRST_NON_COPPER_LAYER - && aLayer <= LAST_NON_COPPER_LAYER; + return aLayer >= FIRST_NON_COPPER_LAYER && aLayer <= LAST_NON_COPPER_LAYER; +} + +/** + * Function IsUserLayer + * tests whether a layer is a non copper and a non tech layer + * @param aLayer = Layer to test + * @return true if aLayer is a user layer + */ +inline bool IsUserLayer( LAYER_NUM aLayer ) +{ + return aLayer >= FIRST_USER_LAYER && aLayer <= LAST_USER_LAYER; } /* IMPORTANT: If a layer is not a front layer not necessarily is true @@ -369,7 +386,7 @@ inline bool IsBackLayer( LAYER_NUM aLayer ) } /** - * Function ReturnFlippedLayerNumber + * Function FlippedLayerNumber * @return the layer number after flipping an item * some (not all) layers: external copper, Mask, Paste, and solder * are swapped between front and back sides diff --git a/include/pgm_base.h b/include/pgm_base.h new file mode 100644 index 0000000000..9ffd028fc7 --- /dev/null +++ b/include/pgm_base.h @@ -0,0 +1,288 @@ +/* + * This program source code file is part of KiCad, a free EDA CAD application. + * + * Copyright (C) 2004 Jean-Pierre Charras, jaen-pierre.charras@gipsa-lab.inpg.com + * Copyright (C) 2008-2011 Wayne Stambaugh + * Copyright (C) 1992-2011 KiCad Developers, see AUTHORS.txt for contributors. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, you may find one here: + * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html + * or you may search the http://www.gnu.org website for the version 2 license, + * or you may write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + */ + +/** + * @file pgm_base.h + * @brief see class PGM_BASE + */ + +#ifndef PGM_BASE_H_ +#define PGM_BASE_H_ + +#include +#include +#include + + +class wxConfigBase; +class wxSingleInstanceChecker; +class wxHtmlHelpController; +class wxApp; +class wxMenu; + +// inter program module calling +#define VTBL_ENTRY virtual + + +/** + * Class PGM_BASE + * keeps program (whole process) data for KiCad programs. + * The VTBL_ENTRY functions are VTBL_ENTRY so we can do cross module calls + * without linking to them. This used to be a wxApp derivative, but that + * is difficult under wxPython which shapes the wxApp. So now this is a "side-car" + * (like a motorcycle side-car) object with a back pointer into the wxApp + * which initializes it. + *

+ * OnPgmStart() is virtual, may be overridden, and parallels + * wxApp::OnInit(), from where it should called. + *

+ * OnPgmEnd() is virtual, may be overridden, and parallels wxApp::OnExit(), + * from where it should be called. + */ +class PGM_BASE +{ +public: + PGM_BASE(); + ~PGM_BASE(); + + /** + * Function OnPgmInit + * this is the first executed function (like main() ) + * @return true if the application can be started. + */ + virtual bool OnPgmInit( wxApp* aWxApp ) = 0; // call this from wxApp::OnInit() + + virtual void OnPgmExit() = 0; // call this from wxApp::OnExit() + + /** + * Function MacOpenFile + * is specific to MacOSX (not used under Linux or Windows). + * MacOSX requires it for file association. + * @see http://wiki.wxwidgets.org/WxMac-specific_topics + */ + virtual void MacOpenFile( const wxString& aFileName ) = 0; + + //--------------------------------------------------------- + + VTBL_ENTRY wxHtmlHelpController* GetHtmlHelpController() { return m_html_ctrl; } + + VTBL_ENTRY void SetHtmlHelpController( wxHtmlHelpController* aController ); + + VTBL_ENTRY wxConfigBase* CommonSettings() const { return m_common_settings; } + + VTBL_ENTRY void SetEditorName( const wxString& aFileName ); + + /** + * Return the preferred editor name. + */ + VTBL_ENTRY const wxString& GetEditorName(); + + VTBL_ENTRY bool IsKicadEnvVariableDefined() const { return !m_kicad_env.IsEmpty(); } + + VTBL_ENTRY const wxString& GetKicadEnvVariable() const { return m_kicad_env; } + + VTBL_ENTRY const wxString& GetExecutablePath() const { return m_bin_dir; } + + VTBL_ENTRY wxLocale* GetLocale() { return m_locale; } + + VTBL_ENTRY const wxString& GetPdfBrowserName() const { return m_pdf_browser; } + + VTBL_ENTRY void SetPdfBrowserName( const wxString& aFileName ) { m_pdf_browser = aFileName; } + + /** + * Function UseSystemPdfBrowser + * returns true if the PDF browser is the default (system) PDF browser + * and false if the PDF browser is the prefered (selected) browser, else + * returns false if there is no selected browser + */ + VTBL_ENTRY bool UseSystemPdfBrowser() const + { + return m_use_system_pdf_browser || m_pdf_browser.IsEmpty(); + } + + /** + * Function ForceSystemPdfBrowser + * forces the use of system PDF browser, even if a preferend PDF browser is set. + */ + VTBL_ENTRY void ForceSystemPdfBrowser( bool aFlg ) { m_use_system_pdf_browser = aFlg; } + + /** + * Function SetLanguage + * sets the dictionary file name for internationalization. + *

+ * The files are in kicad/internat/xx or kicad/internat/xx_XX and are named kicad.mo + *

+ * @param first_time must be set to true the first time this funct is + * called, false otherwise + * @return true if the language can be set (i.e. if the locale is available) + */ + VTBL_ENTRY bool SetLanguage( bool first_time = false ); + + /** + * Function AddMenuLanguageList + * creates a menu list for language choice, and add it as submenu to \a MasterMenu. + * + * @param MasterMenu The main menu. The sub menu list will be accessible from the menu + * item with id ID_LANGUAGE_CHOICE + */ + VTBL_ENTRY void AddMenuLanguageList( wxMenu* MasterMenu ); + + /** + * Function SetLanguageIdentifier + * sets in .m_language_id member the wxWidgets language identifier Id from + * the KiCad menu id (internal menu identifier). + * + * @param menu_id The KiCad menuitem id (returned by Menu Event, when + * clicking on a menu item) + */ + VTBL_ENTRY void SetLanguageIdentifier( int menu_id ); + + VTBL_ENTRY void SetLanguagePath(); + + /** + * Function InitOnLineHelp + * initializes KiCad's online help. + */ + VTBL_ENTRY void InitOnLineHelp(); + + /** + * Function ReadPdfBrowserInfos + * reads the PDF browser choice from the common configuration. + */ + VTBL_ENTRY void ReadPdfBrowserInfos(); + + /** + * Function WritePdfBrowserInfos + * saves the PDF browser choice to the common configuration. + */ + VTBL_ENTRY void WritePdfBrowserInfos(); + + /** + * Function LockFile + * marks a file as being in use. + * @param aFileName = full path to the file. + * @return false if the file was already locked, true otherwise. + */ + VTBL_ENTRY bool LockFile( const wxString& aFileName ); + + /** + * Function App + * returns a bare naked wxApp, which may come from wxPython, SINGLE_TOP, or kicad.exe. + * Use this function instead of wxGetApp(). + */ + VTBL_ENTRY wxApp& App() + { + wxASSERT( m_wx_app ); + return *m_wx_app; + } + + //-------------------------------------------------------- + + static const wxChar workingDirKey[]; + +protected: + + /** + * Function initPgm + * initializes this program (process) in a KiCad standard way, + * using some generalized techniques. + * - Default paths (help, libs, bin) and configuration file names + * - Language and locale + * - fonts + *

+ * But nothing relating to DSOs or projects. + * @return bool - true if success, false if failure and program is to terminate. + */ + bool initPgm(); + + /** + * Function loadCommonSettings + * loads the program (process) settings subset which are stored in .kicad_common + */ + void loadCommonSettings(); + + /** + * Function saveCommonSettings + * saves the program (process) settings subset which are stored .kicad_common + */ + void saveCommonSettings(); + + /// prevents multiple instances of a program from being run at the same time. + wxSingleInstanceChecker* m_pgm_checker; + + /// prevents opening the same file multiple times. + wxSingleInstanceChecker* m_file_checker; + + /// Configuration settings common to all KiCad program modules, + /// like as in $HOME/.kicad_common + wxConfigBase* m_common_settings; + + /// full path to this program + wxString m_bin_dir; + + /// The KICAD system environment variable. + wxString m_kicad_env; + + /// The current locale. + wxLocale* m_locale; + + /// The current language setting. + int m_language_id; + + /// true to use the selected PDF browser, if exists, or false to use the default + bool m_use_system_pdf_browser; + + /// Trap all changes in here, simplifies debugging + void setLanguageId( int aId ) { m_language_id = aId; } + + /** + * Function setExecutablePath + * finds the path to the executable and stores it in PGM_BASE::m_bin_dir + * @return bool - true if success, else false. + */ + bool setExecutablePath(); + + /// The file name of the the program selected for browsing pdf files. + wxString m_pdf_browser; + wxString m_editor_name; + wxSize m_help_size; + + wxHtmlHelpController* m_html_ctrl; + + wxApp* m_wx_app; + + // The PGM_* classes can have difficulties at termination if they + // are not destroyed soon enough. Relying on a static destructor can be + // too late for contained objects like wxSingleInstanceChecker. + void destroy(); +}; + + +#if !defined(PGM_KICAD_H_) // PGM_KICAD has an alternate +/// The global Program "get" accessor. +extern PGM_BASE& Pgm(); +#endif + +#endif // PGM_BASE_H_ diff --git a/include/project.h b/include/project.h new file mode 100644 index 0000000000..202d957eb8 --- /dev/null +++ b/include/project.h @@ -0,0 +1,262 @@ +#ifndef PROJECT_H_ +#define PROJECT_H_ +/* + * This program source code file is part of KiCad, a free EDA CAD application. + * + * Copyright (C) 2014 KiCad Developers, see CHANGELOG.TXT for contributors. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, you may find one here: + * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html + * or you may search the http://www.gnu.org website for the version 2 license, + * or you may write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + */ + +#include +#include +#include +#include + +/// A variable name whose value holds the current project directory. +/// Currently an environment variable, eventually a project variable. +#define PROJECT_VAR_NAME wxT( "KIPRJMOD" ) + + +class wxConfigBase; +class PARAM_CFG_ARRAY; + + +#define VTBL_ENTRY virtual + +/** + * Class PROJECT + * holds project specific data. Because it is in the neutral program top, which + * is not linked to by subsidiarly DSOs, any functions in this interface must + * be VTBL_ENTRYs. + */ +class PROJECT +{ +public: + + /// Derive PROJECT elements from this, it has a virtual destructor, and + /// Elem*() functions can work with it. Implementation is opaque in + /// class PROJECT. If find you have to include derived class headers in this + /// file, you are doing something wrong. Keep knowledge of derived classes + /// opaque to class PROJECT please. + class _ELEM + { + public: + virtual ~_ELEM() {} + }; + + PROJECT(); + ~PROJECT(); + + // VTBL_ENTRY bool MaybeLoadProjectSettings( const std::vector& aFileSet ); + + /** + * Function SetProjectFullName + * sets the: + * 1) full directory, 2) basename, and 3) extension of the project. This is + * the name of the *.pro file with full absolute path and it also defines + * the name of the project. The project name and the *.pro file names are + * exactly the same, providing the *.pro filename is absolute. + */ + VTBL_ENTRY void SetProjectFullName( const wxString& aFullPathAndName ); + + /** + * Function GetProjectFullName + * returns the full path and name of the project. This is the same as the + * name of the *.pro file and will always be an absolute path. + */ + VTBL_ENTRY const wxString GetProjectFullName() const; + + /** + * Function FootprintLibTblName + * returns the path and filename of this project's fp-lib-table, + * i.e. the project specific one, not the global one. + */ + VTBL_ENTRY const wxString FootprintLibTblName() const; + + /** + * Function ConfigSave + * saves the current "project" parameters into the wxConfigBase* derivative. + * Then the wxConfigBase derivative is written to the *.pro file for the project. + * + * @param aSearchS a SEARCH_STACK + * @param aFileName is where to save the *.pro file. + * @param aGroupName + * @param aParams is a ptr vector of PARAM_CFG_BASE derivatives. + * Saved parameters are the subset in this array having the .m_Setup member + * set to false. + */ + VTBL_ENTRY void ConfigSave( const SEARCH_STACK& aSearchS, const wxString& aFileName, + const wxString& aGroupName, const PARAM_CFG_ARRAY& aParams ); + + /** + * Function ConfigLoad + * reads a subset of parameters from the "project" file. Parameters are the + * subset of variables given in @a aParams array which have the .m_Setup member + * set to false. The file which is read in and then extracted from is the + * '*.pro' file for the project. + *

+ * set: + * m_pro_date_and_time + * m_pro_name + * + * @param aSearchS a SEARCH_STACK where a kicad.pro template file may be found. + * @param aLocalConfigFileName + * @param aGroupName + * @param aParams is ptr vector of PARAM_CFG_BASE derivatives. + * @param doLoadOnlyIfNew if true, then this file is read only if it differs from + * the current config on date (different dates), else the *.pro file is read and + * extracted from unconditionally. + * + * @return bool - true if loaded OK. + */ + VTBL_ENTRY bool ConfigLoad( const SEARCH_STACK& aSearchS, const wxString& aLocalConfigFileName, + const wxString& aGroupName, const PARAM_CFG_ARRAY& aParams, bool doLoadOnlyIfNew ); + + /// Accessor for Eeschema search stack. + VTBL_ENTRY SEARCH_STACK& SchSearchS() { return m_sch_search; } + + /** + * Function PcbSearchS + * returns the obsolete footprint library search stack. + * Projects created before the FP_LIB_TABLE support will have footprint + * search paths in the *.pro files. Projects created after the FP_LIB_TABLE + * support will not. This stack is used for conversion from old to new only. + */ + VTBL_ENTRY SEARCH_STACK& PcbSearchS() { return m_pcb_search; } + + VTBL_ENTRY wxString GetModuleLibraryNickname() { return m_module_library_nickname; } + VTBL_ENTRY void SetModuleLibraryNickname( const wxString& aNickName ) { m_module_library_nickname = aNickName; } + + /// Retain a number of paths for user convienience, enumerated here: + enum RETPATH_T + { + DOC, + SCH_LIB, + PCB_LIB, + VIEWER_3D, + + RPATH_COUNT + }; + + /// Give acess to a RETAINED_PATH using enum RETPATH_T + VTBL_ENTRY RETAINED_PATH& RPath( RETPATH_T aPath ); + + /** + * Enum ELEM_T + * is the set of _ELEMs that a PROJECT can hold. + */ + enum ELEM_T + { + FPTBL, + + ELEM_COUNT + }; + + /** + * A PROJECT can hold stuff it knows nothing about, in the form of + * _ELEM derivatives. This function gives access to a PROJECT::_ELEM using + * enum ELEM_T as an index. + *

+ * Acts as setter iff aElem is not NULL, else getter. + *

+ * Typically wrapped somewhere else in a more meaningful function wrapper. + * This is a cross module API, therefore the _ELEM destructor is virtual and + * can point to a destructor function in another link image. Be careful that + * that program module is resident at time of destruction. + *

+ * Summary: 1) cross module API, 2) PROJECT knows nothing about _ELEM objects, + * except how to delete them and set and get pointers to them. + */ + VTBL_ENTRY _ELEM* Elem( ELEM_T aIndex, _ELEM* aElem = NULL ); + +private: + + /** + * Function configCreate + * creates or recreates the KiCad project file and wxConfigBase: + * + * .pro + * + * @param aFilename is a local configuration file path and basename. + * + * Initializes ? + * G_Prj_Config + * G_Prj_Config_LocalFilename + * G_Prj_Default_Config_FullFilename + * : + */ + wxConfigBase* configCreate( const SEARCH_STACK& aSearchS, + const wxString& aFilename, const wxString& aGroupName, + bool aForceUseLocalConfig ); + + SEARCH_STACK m_sch_search; ///< Eeschema's search paths + SEARCH_STACK m_pcb_search; ///< Pcbnew's obsolete footprint search paths, see comment above. + + wxFileName m_project_name; ///< /.pro + wxString m_pro_date_and_time; + + wxString m_module_library_nickname; ///< @todo move this into m_rpaths[] + + /// @see this::RPath() and enum RETPATH_T. + RETAINED_PATH m_rpaths[RPATH_COUNT]; + + /// @see this::Elem() and enum ELEM_T. + _ELEM* m_elems[ELEM_COUNT]; +}; + + +//-------------------------------------------------------------- + +#if 0 + VTBL_ENTRY int ElemAllocNdx(); + VTBL_ENTRY void ElemSet( int aIndex, ELEMENT_BASE* aBlock ); + VTBL_ENTRY ELEM_BASE* ElemGet( int aIndex ) + + /** + * Function Value + * fetches a project variable @a aVariable and returns true if that variable was + * found, else false. If not found, aFetchedValue is not touched. Any environment + * variable is also a project variable. + * + * @param aVariable is the property or option to look for. + * @param aFetchedValue is where to put the value of the property if it exists + * and aFetchedValue is not NULL. + * @return bool - true if variable was found, else false. + */ + VTBL_ENTRY bool Value( const wxString& aVariable, wxString* aFetchedValue = NULL ); + + /** + * Function Substitute + * replaces any project variable references found within @a aString with their + * values. Any referenced variable is first sought in the PROJECT space, and if + * not found, then sought in the environment. + */ + VTBL_ENTRY const wxString Substitute( const wxString& aString ); + + /** + * Function SubstituteAndEvaluate + * replaces any project variable references found within @a aString with their + * values, and evaluates aString as an expression. + * Any referenced variable is first sought in the PROJECT space, and if + * not found, then sought in the environment. + */ + VTBL_ENTRY const wxString SubstituteAndEvaluate( const wxString& aString ); +#endif + +#endif // PROJECT_H_ diff --git a/include/richio.h b/include/richio.h index 6440fda7b0..64c842fcb2 100644 --- a/include/richio.h +++ b/include/richio.h @@ -155,7 +155,7 @@ struct IO_ERROR // : std::exception /** - * Class PARSE_ERROR + * Struct PARSE_ERROR * contains a filename or source description, a problem input line, a line number, * a byte offset, and an error message which contains the the caller's report and his * call site information: CPP source file, function, and line number. diff --git a/include/sch_base_frame.h b/include/sch_base_frame.h index b598df3944..27a4193446 100644 --- a/include/sch_base_frame.h +++ b/include/sch_base_frame.h @@ -24,7 +24,7 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ -#include +#include #include class PAGE_INFO; @@ -46,7 +46,7 @@ class LIB_ALIAS; class SCH_BASE_FRAME : public EDA_DRAW_FRAME { public: - SCH_BASE_FRAME( wxWindow* aParent, + SCH_BASE_FRAME( KIWAY* aKiway, wxWindow* aParent, ID_DRAWFRAME_TYPE aWindowType, const wxString& aTitle, const wxPoint& aPosition, const wxSize& aSize, diff --git a/include/search_stack.h b/include/search_stack.h new file mode 100644 index 0000000000..29cf8af7b5 --- /dev/null +++ b/include/search_stack.h @@ -0,0 +1,118 @@ +#ifndef SEARCH_STACK_H_ +#define SEARCH_STACK_H_ + +#include +#include + + +/** + * Class SEARCH_STACK + * looks for files in a number of places. Augments wxPathList. + * I chose the name because it sounded like a stack of work, as a reminder + * that anything you put in here means searching work at some point in time. + * (An alternative is to simply know where something is.) + */ +class SEARCH_STACK : public wxPathList +{ +public: + +#if defined(DEBUG) + void Show( const char* aPrefix ) const; +#endif + + /** + * Function FilenameWithRelativePathInSearchList + * @return a short filename (with extension) with only a relative path if + * this filename can be found in library paths + * @param aFullFilename The filename with path and extension. + */ + wxString FilenameWithRelativePathInSearchList( const wxString& aFullFilename ); + + wxString FindValidPath( const wxString& aFileName ) const + { +#if 1 // might not be needed + + if( wxFileName::FileExists( aFileName ) ) + return aFileName; + else +#endif + return wxPathList::FindValidPath( aFileName ); + } + + /** + * Function FindValidPath + * KiCad saves user defined library files that are not in the standard + * library search path list with the full file path. Calling the library + * search path list with a user library file will fail. This helper method + * solves that problem. + * @param fileName + * @return a wxEmptyString if library file is not found. + */ + wxString FindValidPath( const wxFileName& aFileName ) const + { + // call wxPathList::FindValidPath( const wxString& ); + return wxPathList::FindValidPath( aFileName.GetFullPath() ); + } + + /** + * Function AddPaths + * insert or append path(s) + * + * @param aPaths = path or path list to add. paths must be + * separated by ";" on windows, or ":" | ";" on unix. + * + * @param aIndex = insertion point, -1 for append. + */ + void AddPaths( const wxString& aPaths, int aIndex = -1 ); + + /** + * Function RemovePaths + * removes the given path(s) from the library path list + * @param aPaths = path or list of paths to remove. If list, paths must be separated by + * ";" on windows, or ":" | ";" on unix. + */ + void RemovePaths( const wxString& aPaths ); + + /** + * Function FindFileInSearchPaths + * looks in "this" for \a aFilename, but first modifies every search + * path by appending a list of path fragments from aSubdirs. That modification + * is not rentative. + */ + wxString FindFileInSearchPaths( const wxString& aFilename, + const wxArrayString* aSubdirs = NULL ); +}; + + +/** + * Class RETAINED_PATH + * is a glamorous way to save a path you might need in the future. + * It is simply a container for the two functions, if you can figure them out. + * This whole concept is awkward, and the two function might have better been + * non-member functions, simply globals. + */ +class RETAINED_PATH +{ +public: + + /** + * Function LastVisitedPath + * returns the last visited directory, or aSubPathToSearch is empty, the first + * path in lib path list ( but not the CWD ). + * @todo add more here if you can figure it out. + * + * @param aSearchStack gives the set of directories to consider. + * @param aSubPathToSearch is the preferred sub path to search in path list + */ + wxString LastVisitedPath( const SEARCH_STACK& aSStack, + const wxString& aSubPathToSearch = wxEmptyString ); + + void SaveLastVisitedPath( const wxString& aPath ); + + void Clear(); + +private: + wxString m_retained_path; +}; + +#endif // SEARCH_STACK_H_ diff --git a/include/ttl/ttl.h b/include/ttl/ttl.h index 7d7c655843..7de2e7b08d 100644 --- a/include/ttl/ttl.h +++ b/include/ttl/ttl.h @@ -357,7 +357,7 @@ private: ForwardIterator it; for (it = first; it != last; ++it) { - bool status = insertNode(dart, **it); + insertNode(dart, **it); } } @@ -1914,13 +1914,4 @@ passes: }; // End of ttl namespace scope (but other files may also contain functions for ttl) - - //------------------------------------------------------------------------------------------------ - // ----------------------------- Constrained Triangulation Group -------------------------------- - //------------------------------------------------------------------------------------------------ - - // Still namespace ttl - -#include - #endif // _TTL_H_ diff --git a/include/ttl/ttl_constr.h b/include/ttl/ttl_constr.h deleted file mode 100644 index 125bddeb23..0000000000 --- a/include/ttl/ttl_constr.h +++ /dev/null @@ -1,635 +0,0 @@ -/* - * Copyright (C) 1998, 2000-2007, 2010, 2011, 2012, 2013 SINTEF ICT, - * Applied Mathematics, Norway. - * - * Contact information: E-mail: tor.dokken@sintef.no - * SINTEF ICT, Department of Applied Mathematics, - * P.O. Box 124 Blindern, - * 0314 Oslo, Norway. - * - * This file is part of TTL. - * - * TTL is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * TTL is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public - * License along with TTL. If not, see - * . - * - * In accordance with Section 7(b) of the GNU Affero General Public - * License, a covered work must retain the producer line in every data - * file that is created or manipulated using TTL. - * - * Other Usage - * You can be released from the requirements of the license by purchasing - * a commercial license. Buying such a license is mandatory as soon as you - * develop commercial activities involving the TTL library without - * disclosing the source code of your own applications. - * - * This file may be used in accordance with the terms contained in a - * written agreement between you and SINTEF ICT. - */ - -#ifndef _TTL_CONSTR_H_ -#define _TTL_CONSTR_H_ - - -#include -#include - - -// Debugging -#ifdef DEBUG_TTL_CONSTR_PLOT - #include - static ofstream ofile_constr("qweCons.dat"); -#endif - -/** \brief Constrained Delaunay triangulation -* -* Basic generic algorithms in TTL for inserting a constrained edge between two existing nodes.\n -* -* See documentation for the namespace ttl for general requirements and assumptions. -* -* \author -* �yvind Hjelle, oyvindhj@ifi.uio.no -*/ - -namespace ttl_constr { - - // ??? A constant used to evluate a numerical expression against a user spesified - // roundoff-zero number -#ifdef DEBUG_TTL_CONSTR - static const double ROUNDOFFZERO = 0.0; // 0.1e-15; -#endif - - -class ConstrainedTriangulation -{ - public: - //------------------------------------------------------------------------------------------------ - /* Checks if \e dart has start and end points in \e dstart and \e dend. - * - * \param dart - * The dart that should be controlled to see if it's the constraint - * - * \param dstart - * A CCW dart with the startnode of the constraint as the startnode - * - * \param dend - * A CCW dart with the endnode of the constraint as the startnode - * - * \retval bool - * A bool confirming that it's the constraint or not - * - * \using - * same_0_orbit - */ - template - static bool isTheConstraint(const DartType& dart, const DartType& dstart, const DartType& dend) { - DartType d0 = dart; - d0.alpha0(); // CW - if ((ttl::TriangulationHelper::same_0_orbit(dstart, dart) && ttl::TriangulationHelper::same_0_orbit(dend, d0)) || - (ttl::TriangulationHelper::same_0_orbit(dstart, d0) && ttl::TriangulationHelper::same_0_orbit(dend, dart))) { - return true; - } - return false; - } - - - //------------------------------------------------------------------------------------------------ - /* Checks if \e d1 and \e d2 are on the same side of the line between \e dstart and \e dend. - * (The start nodes of \e d1 and \e d2 represent an edge). - * - * \param dstart - * A CCW dart with the start node of the constraint as the source node of the dart. - * - * \param dend - * A CCW dart with the end node of the constraint as the source node of the dart. - * - * \param d1 - * A CCW dart with the first node as the start node of the dart. - * - * \param d2 - * A CCW dart with the other node as the start node of the dart. - * - * \using - * TraitsType::orient2d - */ - template - static bool crossesConstraint(DartType& dstart, DartType& dend, DartType& d1, DartType& d2) { - - typename TraitsType::real_type orient_1 = TraitsType::orient2d(dstart,d1,dend); - typename TraitsType::real_type orient_2 = TraitsType::orient2d(dstart,d2,dend); - // ??? Should we refine this? e.g. find if (dstart,dend) (d1,d2) represent the same edge - if ((orient_1 <= 0 && orient_2 <= 0) || (orient_1 >= 0 && orient_2 >= 0)) - return false; - - return true; - } - - - //------------------------------------------------------------------------------------------------ - /* Return the dart \e d making the smallest non-negative angle, - * as calculated with: orient2d(dstart, d.alpha0(), dend), - * at the 0-orbit of dstart. - * If (dstart,dend) is a CCW boundary edge \e d will be CW, otherwise CCW (since CCW in) - * at the 0-orbit of dstart. - * - * \par Assumes: - * - CCW dstart and dend, but returned dart can be CW at the boundary. - * - Boundary is convex? - * - * \param dstart - * A CCW dart dstart - * - * \param dend - * A CCW dart dend - * - * \retval DartType - * The dart \e d making the smallest positive (or == 0) angle - * - * \using - * isBoundaryNode - * positionAtNextBoundaryEdge - * TraitsType::orient2d - */ - template - static DartType getAtSmallestAngle(const DartType& dstart, const DartType& dend) { - - // - Must boundary be convex??? - // - Handle the case where the constraint is already present??? - // - Handle dstart and/or dend at the boundary - // (dstart and dend may define a boundary edge) - - DartType d_iter = dstart; - if (ttl::TriangulationHelper::isBoundaryNode(d_iter)) { - d_iter.alpha1(); // CW - ttl::TriangulationHelper::positionAtNextBoundaryEdge(d_iter); // CCW (was rotated CW to the boundary) - } - - // assume convex boundary; see comments - - DartType d0 = d_iter; - d0.alpha0(); - bool ccw = true; // the rotation later - typename TraitsType::real_type o_iter = TraitsType::orient2d(d_iter, d0, dend); - if (o_iter == 0) { // collinear BUT can be on "back side" - d0.alpha1().alpha0(); // CW - if (TraitsType::orient2d(dstart, dend, d0) > 0) - return d_iter; //(=dstart) collinear - else { - // collinear on "back side" - d_iter.alpha1().alpha2(); // assume convex boundary - ccw = true; - } - } - else if (o_iter < 0) { - // Prepare for rotating CW and with d_iter CW - d_iter.alpha1(); - ccw = false; - } - - // Set first angle - d0 = d_iter; d0.alpha0(); - o_iter = TraitsType::orient2d(dstart, d0, dend); - - typename TraitsType::real_type o_next; - - // Rotate towards the constraint CCW or CW. - // Here we assume that the boundary is convex. - DartType d_next = d_iter; - for (;;) { - d_next.alpha1(); // CW !!! (if ccw == true) - d0 = d_next; d0.alpha0(); - o_next = TraitsType::orient2d(dstart, d0, dend); - - if (ccw && o_next < 0) // and o_iter > 0 - return d_iter; - else if (!ccw && o_next > 0) - return d_next; // CCW - else if (o_next == 0) { - if (ccw) - return d_next.alpha2(); // also ok if boundary - else - return d_next; - } - - // prepare next - d_next.alpha2(); // CCW if ccw - d_iter = d_next; // also ok if boundary CCW if ccw == true - } - } - - - //------------------------------------------------------------------------------------------------ - /* This function finds all the edges in the triangulation crossing - * the spesified constraint and puts them in a list. - * In the case of collinearity, an attempt is made to detect this. - * The first collinear node between dstart and dend is then returned. - * - * Strategy: - * - Iterate such that \e d_iter is always strictly "below" the constraint - * as seen with \e dstart to the left and \e dend to the right. - * - Add CCW darts, whose edges intersect the constrait, to a list. - * These edges are found by the orient2d predicate: - * If two nodes of an edge are on opposite sides of the constraint, - * the edge between them intersect. - * - Must handle collinnear cases, i.e., if a node falls on the constraint, - * and possibly restarting collection of edges. Detecting collinearity - * heavily relies on the orient2d predicate which is provided by the - * traits class. - * - * Action: - * 1) Find cone/opening angle containing \e dstart and \e dend - * 2) Find first edge from the first 0-orbit that intersects - * 3) Check which of the two opposite that intersects - * - * 1) - * Rotate CCW and find the (only) case where \e d_iter and \e d_next satisfy: - * - orient2d(d_iter, d_iter.alpha0(), dend) > 0 - * - orient2d(d_next, d_next.alpha0(), dend) < 0 - * - * - check if we are done, i.e., if (d_next.alpha0() == my_dend) - * - Note also the situation if, e.g., the constraint is a boundary edge in which case - * \e my_dend wil be CW - * - * \param dstart - * A CCW dart with the startnode of the constraint as the startnode - * - * \param dend - * A CCW dart with the endnode of the constraint as the startnode - * - * \param elist - * A list where all the edges crossing the spesified constraint will be put - * - * \retval dartType - * Returns the next "collinear" starting node such that dend is returned when done. - */ - template - static DartType findCrossingEdges(const DartType& dstart, const DartType& dend, ListType& elist) { - - const DartType my_start = getAtSmallestAngle(dstart, dend); - DartType my_end = getAtSmallestAngle(dend, dstart); - - DartType d_iter = my_start; - if (d_iter.alpha0().alpha2() == my_end) - return d_iter; // The constraint is an existing edge and we are done - - // Facts/status so far: - // - my_start and my_end are now both CCW and the constraint is not a boundary edge. - // - Further, the constraint is not one single existing edge, but it might be a collection - // of collinear edges in which case we return the current collinear edge - // and calling this function until all are collected. - - my_end.alpha1(); // CW! // ??? this is probably ok for testing now? - - d_iter = my_start; - d_iter.alpha0().alpha1(); // alpha0 is downwards or along the constraint - - // Facts: - // - d_iter is guaranteed to intersect, but can be in start point. - // - d_iter.alpha0() is not at dend yet - typename TraitsType::real_type orient = TraitsType::orient2d(dstart, d_iter, dend); - - // Use round-off error/tolerance or rely on the orient2d predicate ??? - // Make a warning message if orient != exact 0 - if (orient == 0) - return d_iter; - -#ifdef DEBUG_TTL_CONSTR - else if (fabs(orient) <= ROUNDOFFZERO) { - cout << "The darts are not exactly colinear, but |d1 x d2| <= " << ROUNDOFFZERO << endl; - return d_iter; // collinear, not done (and not collect in the list) - } -#endif - - // Collect intersecting edges - // -------------------------- - elist.push_back(d_iter); // The first with interior intersection point - - // Facts, status so far: - // - The first intersecting edge is now collected - // (- d_iter.alpha0() is still not at dend) - - // d_iter should always be the edge that intersects and be below or on the constraint - // One of the two edges opposite to d_iter must intersect, or we have collinearity - - // Note: Almost collinear cases can be handled on the - // application side with orient2d. We should probably - // return an int and the application will set it to zero - for(;;) { - // assume orient have been calc. and collinearity has been tested, - // above the first time and below later - d_iter.alpha2().alpha1(); // 2a same node - - DartType d0 = d_iter; - d0.alpha0(); // CW - if (d0 == my_end) - return dend; // WE ARE DONE (but can we enter an endless loop???) - - // d_iter or d_iter.alpha0().alpha1() must intersect - orient = TraitsType::orient2d(dstart, d0, dend); - - if (orient == 0) - return d0.alpha1(); - -#ifdef DEBUG_TTL_CONSTR - else if (fabs(orient) <= ROUNDOFFZERO) { - return d0.alpha1(); // CCW, collinear - } -#endif - - else if (orient > 0) { // orient > 0 and still below - // This one must intersect! - d_iter = d0.alpha1(); - } - elist.push_back(d_iter); - } - } - - - //------------------------------------------------------------------------------------------------ - /* This function recives a constrained edge and a list of all the edges crossing a constraint. - * It then swaps the crossing edges away from the constraint. This is done according to a - * scheme suggested by Dyn, Goren & Rippa (slightly modified). - * The resulting triangulation is a constrained one, but not necessarily constrained Delaunay. - * In other to run optimization later to obtain a constrained Delaunay triangulation, - * the swapped edges are maintained in a list. - * - * Strategy : - * - Situation A: Run through the list and swap crossing edges away from the constraint. - * All the swapped edges are moved to the end of the list, and are "invisible" to this procedure. - * - Situation B: We may come in a situation where none of the crossing edges can be swapped away - * from the constraint. - * Then we follow the strategy of Dyn, Goren & Rippa and allow edges to be swapped, - * even if they are not swapped away from the constraint. - * These edges are NOT moved to the end of the list. They are later swapped to none-crossing - * edges when the locked situation is solved. - * - We keep on swapping edges in Situation B until we have iterated trough the list. - * We then resume Situation A. - * - This is done until the list is virtualy empty. The resulting \c elist has the constraint - * as the last element. - * - * \param dstart - * A CCW dart dstart - * - * \param dend - * A CCW dart dend - * - * \param elist - * A list containing all the edges crossing the spesified constraint - * - * \using - * swappableEdge - * swapEdgeInList - * crossesConstraint - * isTheConstraint - */ - template - void transformToConstraint(ttl::TriangulationHelper helper, DartType& dstart, DartType& dend, - std::list& elist) const { - - typename std::list::iterator it, used; - - // We may enter in a situation where dstart and dend are altered because of a swap. - // (The general rule is that darts inside the actual quadrilateral can be changed, - // but not those outside.) - // So, we need some look-ahead strategies for dstart and dend and change these - // after a swap if necessary. - - int dartsInList = (int)elist.size(); - if (dartsInList == 0) - return; - - bool erase; // indicates if an edge is swapped away from the constraint such that it can be - // moved to the back of the list - bool locked = false; - do { - int noswap = 0; - it = elist.begin(); - - // counts how many edges that have been swapped per list-cycle - int counter = 1; - while(it != elist.end()) { // ??? change this test with counter > dartsInList - erase = false; - // Check if our virtual end of the list has been crossed. It breaks the - // while and starts all over again in the do-while loop - if (counter > dartsInList) - break; - - if (ttl::TriangulationHelper::swappableEdge(*it, true)) { - // Dyn & Goren & Rippa 's notation: - // The node assosiated with dart *it is denoted u_m. u_m has edges crossing the constraint - // named w_1, ... , w_r . The other node to the edge assosiated with dart *it is w_s. - // We want to swap from edge u_m<->w_s to edge w_{s-1}<->w_{s+1}. - DartType op1 = *it; - DartType op2 = op1; - op1.alpha1().alpha0(); //finds dart with node w_{s-1} - op2.alpha2().alpha1().alpha0(); // (CW) finds dart with node w_{s+1} - DartType tmp = *it; tmp.alpha0(); // Dart with assosiated node opposite to node of *it allong edge - // If there is a locked situation we swap, even if the result is crossing the constraint - // If there is a looked situation, but we do an ordinary swap, it should be treated as - // if we were not in a locked situation!! - - // The flag swap_away indicates if the edge is swapped away from the constraint such that - // it does not cross the constraint. - bool swap_away = (crossesConstraint(dstart, dend, *it, tmp) && - !crossesConstraint(dstart, dend, op1, op2)); - if (swap_away || locked) { - // Do a look-ahead to see if dstart and/or dend are in the quadrilateral - // If so, we mark it with a flag to make sure we update them after the swap - // (they may have been changed during the swap according to the general rule!) - bool start = false; - bool end = false; - - DartType d = *it; - if (d.alpha1().alpha0() == dstart) - start = true; - d = *it; - if (d.alpha2().alpha1().alpha0().alpha1() == dend) - end = true; - - // This is the only place swapping is called when inserting a constraint - helper.swapEdgeInList(it,elist); - - // If we, during look-ahead, found that dstart and/or dend were in the quadrilateral, - // we update them. - if (end) - dend = *it; - if (start) { - dstart = *it; - dstart.alpha0().alpha2(); - } - - if (swap_away) { // !locked || //it should be sufficient with swap_away ??? - noswap++; - erase = true; - } - - if (isTheConstraint(*it, dstart, dend)) { - // Move the constraint to the end of the list - DartType the_constraint = *it; - elist.erase(it); - elist.push_back(the_constraint); - return; - } //endif - } //endif - } //endif "swappable edge" - - - // Move the edge to the end of the list if it was swapped away from the constraint - if (erase) { - used = it; - elist.push_back(*it); - ++it; - elist.erase(used); - --dartsInList; - } - else { - ++it; - ++counter; - } - - } //end while - - if (noswap == 0) - locked = true; - - } while (dartsInList != 0); - - -#ifdef DEBUG_TTL_CONSTR - // We will never enter here. (If elist is empty, we return above). - cout << "??????? ERROR 2, should never enter here ????????????????????????? SKIP ???? " << endl; - exit(-1); -#endif - - } - -}; // End of ConstrainedTriangulation class - -}; // End of ttl_constr namespace scope - - -namespace ttl { // (extension) - - /** @name Constrained (Delaunay) Triangulation */ - //@{ - - //------------------------------------------------------------------------------------------------ - /** Inserts a constrained edge between two existing nodes in a triangulation. - * If the constraint falls on one or more existing nodes and this is detected by the - * predicate \c TraitsType::orient2d, which should return zero in this case, the - * constraint is split. Otherwise a degenerate triangle will be made along - * the constraint. - * - * \param dstart - * A CCW dart with the start node of the constraint as the source node - * - * \param dend - * A CCW dart with the end node of the constraint as the source node - * - * \param optimize_delaunay - * If set to \c true, the resulting triangulation will be - * a \e constrained \e Delaunay \e triangulation. If set to \c false, the resulting - * triangulation will not necessarily be of constrained Delaunay type. - * - * \retval DartType - * A dart representing the constrained edge. - * - * \require - * - \ref hed::TTLtraits::orient2d "TraitsType::orient2d" (DartType&, DartType&, PointType&) - * - \ref hed::TTLtraits::swapEdge "TraitsType::swapEdge" (DartType&) - * - * \using - * - optimizeDelaunay if \e optimize_delaunay is set to \c true - * - * \par Assumes: - * - The constrained edge must be inside the existing triangulation (and it cannot - * cross the boundary of the triangulation). - */ - template - DartType TriangulationHelper::insertConstraint(DartType& dstart, DartType& dend, bool optimize_delaunay) { - - // Assumes: - // - It is the users responsibility to avoid crossing constraints - // - The constraint cannot cross the boundary, i.e., the boundary must be - // convex in the area of crossing edges. - // - dtart and dend are preserved (same node associated.) - - - // Find edges crossing the constraint and put them in elist. - // If findCrossingEdges reaches a Node lying on the constraint, this function - // calls itself recursively. - - // RECURSION - std::list elist; - DartType next_start = ttl_constr::ConstrainedTriangulation::findCrossingEdges(dstart, dend, elist); - - // If there are no crossing edges (elist is empty), we assume that the constraint - // is an existing edge. - // In this case, findCrossingEdges returns the constraint. - // Put the constraint in the list to fit with the procedures below - // (elist can also be empty in the case of invalid input data (the constraint is in - // a non-convex area) but this is the users responsibility.) - - //by Thomas Sevaldrud if (elist.size() == 0) - //by Thomas Sevaldrud elist.push_back(next_start); - - // findCrossingEdges stops if it finds a node lying on the constraint. - // A dart with this node as start node is returned - // We call insertConstraint recursivly until the received dart is dend - if (!same_0_orbit(next_start, dend)) { - -#ifdef DEBUG_TTL_CONSTR_PLOT - cout << "RECURSION due to collinearity along constraint" << endl; -#endif - - insertConstraint(next_start, dend, optimize_delaunay); - } - - // Swap edges such that the constraint edge is present in the transformed triangulation. - if (elist.size() > 0) // by Thomas Sevaldrud - ttl_constr::ConstrainedTriangulation::transformToConstraint(dstart, next_start, elist); - -#ifdef DEBUG_TTL_CONSTR_PLOT - cout << "size of elist = " << elist.size() << endl; - if (elist.size() > 0) { - DartType the_constraint = elist.back(); - ofile_constr << the_constraint.x() << " " << the_constraint.y() << " " << 0 << endl; - the_constraint.alpha0(); - ofile_constr << the_constraint.x() << " " << the_constraint.y() << " " << 0 << endl << endl; - } -#endif - - // Optimize to constrained Delaunay triangulation if required. - typename std::list::iterator end_opt = elist.end(); - if (optimize_delaunay) { - - // Indicate that the constrained edge, which is the last element in the list, - // should not be swapped - --end_opt; - optimizeDelaunay(elist, end_opt); - } - - if(elist.size() == 0) // by Thomas Sevaldrud - return next_start; // by Thomas Sevaldrud - - // Return the constraint, which is still the last element in the list - end_opt = elist.end(); - --end_opt; - return *end_opt; - } - - //@} // End of Constrained Triangulation Group - -}; // End of ttl namespace scope (extension) - -#endif // _TTL_CONSTR_H_ diff --git a/include/wxBasePcbFrame.h b/include/wxBasePcbFrame.h index 6f8c226e90..d6ed9b0ba8 100644 --- a/include/wxBasePcbFrame.h +++ b/include/wxBasePcbFrame.h @@ -34,7 +34,7 @@ #include -#include +#include #include #include // EDA_DRAW_MODE_T #include @@ -86,11 +86,6 @@ protected: BOARD* m_Pcb; GENERAL_COLLECTOR* m_Collector; - /// The project footprint library table. This is a combination of the project - /// footprint library table and the global footprint table. This is the one to - /// use when finding a #MODULE. - FP_LIB_TABLE* m_footprintLibTable; - /// Auxiliary tool bar typically shown below the main tool bar at the top of the /// main window. wxAuiToolBar* m_auxiliaryToolBar; @@ -108,7 +103,7 @@ protected: * * @param aFootprintId is the #FPID of component footprint to load. * @return the #MODULE if found or NULL if \a aFootprintId not found in any of the - * libraries in #m_footprintLibTable. + * libraries in the table returned from #FootprintLibs(). * @throw IO_ERROR if an I/O error occurs or a #PARSE_ERROR if a file parsing error * occurs while reading footprint library files. */ @@ -120,10 +115,9 @@ protected: static const LAYER_NUM GAL_LAYER_ORDER[]; public: - PCB_BASE_FRAME( wxWindow* aParent, ID_DRAWFRAME_TYPE aFrameType, - const wxString& aTitle, - const wxPoint& aPos, const wxSize& aSize, - long aStyle, const wxString & aFrameName ); + PCB_BASE_FRAME( KIWAY* aKiway, wxWindow* aParent, ID_DRAWFRAME_TYPE aFrameType, + const wxString& aTitle, const wxPoint& aPos, const wxSize& aSize, + long aStyle, const wxString& aFrameName ); ~PCB_BASE_FRAME(); @@ -133,7 +127,7 @@ public: * * @param aFootprintId is the #FPID of component footprint to load. * @return the #MODULE if found or NULL if \a aFootprintId not found in any of the - * libraries in #m_footprintLibTable. + * libraries in table returned from #FootprintLibs(). */ MODULE* LoadFootprint( const FPID& aFootprintId ); @@ -191,17 +185,6 @@ public: return m_Pcb; } - /** - * Function SetFootprintLibTable - * set the footprint library table to \a aFootprintLibTable. - * - * @param aFootprintLibTable is a pointer to the #FP_LIB_TABLE object. - */ - void SetFootprintLibTable( FP_LIB_TABLE* aFootprintLibTable ) - { - m_footprintLibTable = aFootprintLibTable; - } - // General virtual void OnCloseWindow( wxCloseEvent& Event ) = 0; virtual void RedrawActiveWindow( wxDC* DC, bool EraseBg ) { } @@ -481,12 +464,10 @@ public: wxString SelectFootprintFromLibBrowser(); /** - * Function GetFootprintLibraryTable - * @return the project #FP_LIB_TABLE so programs can find footprints. + * Function FootprintLibs + * @return the project #FP_LIB_TABLE. */ - FP_LIB_TABLE* GetFootprintLibraryTable() { return m_footprintLibTable; } - - void SetFootprintLibraryTable( FP_LIB_TABLE* aTable ) { m_footprintLibTable = aTable; } + FP_LIB_TABLE* FootprintLibs() const; // ratsnest functions /** @@ -642,36 +623,15 @@ public: virtual void SwitchLayer( wxDC* DC, LAYER_NUM layer ); - /** - * Load applications settings common to PCB draw frame objects. - * - * This overrides the base class EDA_DRAW_FRAME::LoadSettings() to - * handle settings common to the PCB layout application and footprint - * editor main windows. It calls down to the base class to load - * settings common to all drawing frames. Please put your application - * settings common to all pcb drawing frames here to avoid having - * application settings loaded all over the place. - */ - virtual void LoadSettings(); + void LoadSettings( wxConfigBase* aCfg ); // override virtual + void SaveSettings( wxConfigBase* aCfg ); // override virtual bool InvokeDialogGrid(); - /** - * Save applications settings common to PCB draw frame objects. - * - * This overrides the base class EDA_DRAW_FRAME::SaveSettings() to - * save settings common to the PCB layout application and footprint - * editor main windows. It calls down to the base class to save - * settings common to all drawing frames. Please put your application - * settings common to all pcb drawing frames here to avoid having - * application settings saved all over the place. - */ - virtual void SaveSettings(); - void OnTogglePolarCoords( wxCommandEvent& aEvent ); void OnTogglePadDrawMode( wxCommandEvent& aEvent ); - /* User interface update event handlers. */ + // User interface update event handlers. void OnUpdateCoordType( wxUpdateUIEvent& aEvent ); void OnUpdatePadDrawMode( wxUpdateUIEvent& aEvent ); void OnUpdateSelectGrid( wxUpdateUIEvent& aEvent ); diff --git a/include/wxEeschemaStruct.h b/include/wxEeschemaStruct.h index 61eebdf8eb..5f22c1fab7 100644 --- a/include/wxEeschemaStruct.h +++ b/include/wxEeschemaStruct.h @@ -31,7 +31,7 @@ #define WX_EESCHEMA_STRUCT_H #include -#include +#include #include #include #include @@ -66,7 +66,7 @@ class wxFindDialogEvent; class wxFindReplaceData; -/* enum used in RotationMiroir() */ +/// enum used in RotationMiroir() enum COMPONENT_ORIENTATION_T { CMP_NORMAL, // Normal orientation, no rotation or mirror CMP_ROTATE_CLOCKWISE, // Rotate -90 @@ -115,6 +115,7 @@ enum SCH_SEARCH_T { class SCH_EDIT_FRAME : public SCH_BASE_FRAME { private: + SCH_SHEET_PATH* m_CurrentSheet; ///< which sheet we are presently working on. wxString m_DefaultSchematicFileName; int m_TextFieldSize; @@ -197,10 +198,7 @@ protected: void updateFindReplaceView( wxFindDialogEvent& aEvent ); public: - SCH_EDIT_FRAME( wxWindow* aParent, const wxString& aTitle, - const wxPoint& aPosition, const wxSize& aSize, - long aStyle = KICAD_DEFAULT_DRAWFRAME_STYLE ); - + SCH_EDIT_FRAME( KIWAY* aKiway, wxWindow* aParent ); ~SCH_EDIT_FRAME(); SCH_SCREEN* GetScreen() const; // overload SCH_BASE_FRAME @@ -338,8 +336,8 @@ public: */ PARAM_CFG_ARRAY& GetConfigurationSettings( void ); - void LoadSettings(); - void SaveSettings(); + void LoadSettings( wxConfigBase* aCfg ); + void SaveSettings( wxConfigBase* aCfg ); void RedrawActiveWindow( wxDC* DC, bool EraseBg ); @@ -639,23 +637,23 @@ public: void OnSaveProject( wxCommandEvent& aEvent ); /** - * Function LoadOneEEProject - * load an entire project into the schematic editor. + * Function OpenProjectFiles + * loads an entire project into the schematic editor. * * This function loads schematic root file and it's subhierarchies, the project * configuration, and the component libraries which are not already loaded. * - * @param aFileName The full path an file name to load. - * @param aIsNew True indicates that this is a new project and the default project - * template is loaded. - * @return True if the project loaded properly. + * @param aFileSet is a list of one file, the top level schematic. + * + * @return bool - true if the project loaded properly, else false. */ - bool LoadOneEEProject( const wxString& aFileName, bool aIsNew ); + //bool LoadOneEEProject( const wxString& aFileName, bool aIsNew ); + bool OpenProjectFiles( const std::vector& aFileSet, int aCtl = 0 ); // virtual from KIWAY_PLAYER /** * Function AppendOneEEProject - * read an entire project and loads it into the schematic editor *whitout* replacing the - * existing contents. + * read an entire project and loads it into the schematic editor *without* + * replacing the existing contents. * @return True if the project was imported properly. */ bool AppendOneEEProject(); @@ -1152,14 +1150,14 @@ public: void InitBlockPasteInfos(); /** - * Function ReturnBlockCommand + * Function BlockCommand * Returns the block command internat code (BLOCK_MOVE, BLOCK_COPY...) * corresponding to the keys pressed (ALT, SHIFT, SHIFT ALT ..) when * block command is started by dragging the mouse. * @param aKey = the key modifiers (Alt, Shift ...) * @return the block command id (BLOCK_MOVE, BLOCK_COPY...) */ - virtual int ReturnBlockCommand( int aKey ); + virtual int BlockCommand( int aKey ); /** * Function HandleBlockPlace diff --git a/include/wxPcbStruct.h b/include/wxPcbStruct.h index 022a591930..f382658ee3 100644 --- a/include/wxPcbStruct.h +++ b/include/wxPcbStruct.h @@ -31,7 +31,7 @@ #include -#include +#include #include #include #include @@ -61,18 +61,21 @@ class BOARD_ITEM; class PCB_LAYER_BOX_SELECTOR; class NETLIST; class REPORTER; -class PARSE_ERROR; -class IO_ERROR; +struct PARSE_ERROR; +struct IO_ERROR; class FP_LIB_TABLE; +namespace PCB { struct IFACE; } // KIFACE_I is in pcbnew.cpp + /** - * class PCB_EDIT_FRAME - * the main frame for Pcbnew + * Class PCB_EDIT_FRAME + * is the main frame for Pcbnew. * * See also class PCB_BASE_FRAME(): Basic class for Pcbnew and GerbView. */ class PCB_EDIT_FRAME : public PCB_BASE_FRAME { + friend class PCB::IFACE; friend class PCB_LAYER_WIDGET; void updateTraceWidthSelectBox(); @@ -84,9 +87,6 @@ class PCB_EDIT_FRAME : public PCB_BASE_FRAME /// The auxiliary right vertical tool bar used to access the microwave tools. wxAuiToolBar* m_microWaveToolBar; - /// The global footprint library table. - FP_LIB_TABLE* m_globalFootprintTable; - /// User defined rotation angle (in tenths of a degree). int m_rotationAngle; @@ -186,6 +186,9 @@ protected: */ void duplicateZone( wxDC* aDC, ZONE_CONTAINER* aZone ); + // protected so that PCB::IFACE::CreateWindow() is the only factory. + PCB_EDIT_FRAME( KIWAY* aKiway, wxWindow* aParent ); + public: PCB_LAYER_BOX_SELECTOR* m_SelLayerBox; // a combo box to display and select active layer wxComboBox* m_SelTrackWidthBox; // a combo box to display and select current track width @@ -194,10 +197,6 @@ public: bool m_show_microwave_tools; bool m_show_layer_manager_tools; - PCB_EDIT_FRAME( wxWindow* father, const wxString& title, - const wxPoint& pos, const wxSize& size, - long style = KICAD_DEFAULT_DRAWFRAME_STYLE ); - virtual ~PCB_EDIT_FRAME(); void OnQuit( wxCommandEvent& event ); @@ -368,29 +367,9 @@ public: */ PARAM_CFG_ARRAY& GetConfigurationSettings(); - /** - * Function LoadSettings - * loads applications settings specific to Pcbnew. - * - * This overrides the base class PCB_BASE_FRAME::LoadSettings() to - * handle settings specific common to the PCB layout application. It - * calls down to the base class to load settings common to all PCB type - * drawing frames. Please put your application settings for Pcbnew here - * to avoid having application settings loaded all over the place. - */ - virtual void LoadSettings(); + void LoadSettings( wxConfigBase* aCfg ); // override virtual - /** - * Function SaveSettings - * saves applications settings common to Pcbnew. - * - * This overrides the base class PCB_BASE_FRAME::SaveSettings() to - * save settings specific to the PCB layout application main window. It - * calls down to the base class to save settings common to all PCB type - * drawing frames. Please put your application settings for Pcbnew here - * to avoid having application settings saved all over the place. - */ - virtual void SaveSettings(); + void SaveSettings( wxConfigBase* aCfg ); // override virtual /** * Get the last net list read with the net list dialog box. @@ -717,14 +696,14 @@ public: /* Block operations: */ /** - * Function ReturnBlockCommand + * Function BlockCommand * Returns the block command internat code (BLOCK_MOVE, BLOCK_COPY...) * corresponding to the keys pressed (ALT, SHIFT, SHIFT ALT ..) when * block command is started by dragging the mouse. * @param aKey = the key modifiers (Alt, Shift ...) * @return the block command id (BLOCK_MOVE, BLOCK_COPY...) */ - virtual int ReturnBlockCommand( int aKey ); + virtual int BlockCommand( int aKey ); /** * Function HandleBlockPlace() @@ -857,20 +836,20 @@ public: void Files_io( wxCommandEvent& event ); /** - * Function LoadOnePcbFile - * loads a KiCad board (.brd) from \a aFileName. + * Function OpenProjectFiles (was LoadOnePcbFile) + * loads a KiCad board (.kicad_pcb) from \a aFileName. * - * @param aFileName - File name including path. If empty, a file dialog will - * be displayed. - * @param aAppend - Append board file aFileName to the currently loaded file if true. - * Default = false. - * @param aForceFileDialog - Display the file open dialog even if aFullFileName is - * valid if true; Default = false. + * @param aFileSet - hold the BOARD file to load, a vector of one element. * - * @return False if file load fails or is canceled by the user, otherwise true. - */ + * @param aCtl - KICTL_ bits, one to indicate that an append of the board file + * aFileName to the currently loaded file is desired. + * @see #KIWAY_PLAYER for bit defines. + * + * @return bool - false if file load fails, otherwise true. bool LoadOnePcbFile( const wxString& aFileName, bool aAppend = false, bool aForceFileDialog = false ); + */ + bool OpenProjectFiles( const std::vector& aFileSet, int aCtl = 0 ); /** * Function ReadPcbFile @@ -991,12 +970,20 @@ public: /** * Function ExporttoSPECCTRA - * will export the current BOARD to a specctra dsn file. See - * See http://www.autotraxeda.com/docs/SPECCTRA/SPECCTRA.pdf for the - * specification. + * Ask for a filename and call ExportSpecctraFile to export the current BOARD + * to a specctra dsn file. */ void ExportToSpecctra( wxCommandEvent& event ); + /** + * Function ExportSpecctraFile + * will export the current BOARD to a specctra dsn file. + * See http://www.autotraxeda.com/docs/SPECCTRA/SPECCTRA.pdf for the + * specification. + * @return true if OK + */ + bool ExportSpecctraFile( const wxString& aFullFilename ); + /** * Function ImportSpecctraSession * will import a specctra *.ses file and use it to relocate MODULEs and @@ -1697,4 +1684,18 @@ public: }; +/** + * Function AskBoardFileName + * puts up a wxFileDialog asking for a BOARD filename to open. + * + * @param aParent is a wxFrame passed to wxFileDialog. + * @param aCtl is where to put the OpenProjectFiles() control bits. + * + * @param aFileName on entry is a probable choice, on return is the chosen filename. + * + * @return bool - true if chosen, else false if user aborted. + */ +bool AskBoardFileName( wxWindow* aParent, int* aCtl, wxString* aFileName ); + + #endif // WXPCB_STRUCT_H_ diff --git a/include/wxstruct.h b/include/wxstruct.h index 1047a04302..fb79aae9a7 100644 --- a/include/wxstruct.h +++ b/include/wxstruct.h @@ -80,6 +80,7 @@ enum id_librarytype { LIBRARY_TYPE_SYMBOL }; + enum ID_DRAWFRAME_TYPE { NOT_INIT_FRAME_TYPE = 0, @@ -108,9 +109,12 @@ extern const wxChar traceAutoSave[]; * Class EDA_BASE_FRAME * is the base frame for deriving all KiCad main window classes. This class is not * intended to be used directly. It provides support for automatic calls to - * a virtual SaveSettings() function. SaveSettings() for a derived class can choose + * a SaveSettings() function. SaveSettings() for a derived class can choose * to do nothing, or rely on basic SaveSettings() support in this base class to do * most of the work by calling it from the derived class's SaveSettings(). + *

+ * This class is not a KIWAY_PLAYER because KICAD_MANAGER_FRAME is derived from it + * and that class is not a player. */ class EDA_BASE_FRAME : public wxFrame { @@ -175,12 +179,17 @@ protected: */ virtual bool doAutoSave(); + /** + * Function config + * returns the wxConfigBase used in SaveSettings(), and is overloaded in + * KICAD_MANAGER_FRAME + */ + virtual wxConfigBase* config(); + public: EDA_BASE_FRAME( wxWindow* aParent, ID_DRAWFRAME_TYPE aFrameType, - const wxString& aTitle, - const wxPoint& aPos, const wxSize& aSize, - long aStyle, - const wxString & aFrameName ); + const wxString& aTitle, const wxPoint& aPos, const wxSize& aSize, + long aStyle, const wxString& aFrameName ); ~EDA_BASE_FRAME(); @@ -223,24 +232,23 @@ public: void AddHelpVersionInfoMenuEntry( wxMenu* aMenu ); /** - * Load common frame parameters from configuration. + * Function LoadSettings + * loads common frame parameters from a configuration file. * - * The method is virtual so you can override it to load frame specific - * parameters. Don't forget to call the base method or your frames won't + * Don't forget to call the base method or your frames won't * remember their positions and sizes. */ - virtual void LoadSettings(); + virtual void LoadSettings( wxConfigBase* aCfg ); /** - * Save common frame parameters to configuration data file. + * Function SaveSettings + * saves common frame parameters to a configuration data file. * - * The method is virtual so you can override it to save frame specific - * parameters. Don't forget to call the base class's SaveSettings() from + * Don't forget to call the base class's SaveSettings() from * your derived SaveSettings() otherwise the frames won't remember their - * positions and sizes. The virtual call to SaveSettings is done safely - * only in EDA_BASE_FRAME::Show( bool ). + * positions and sizes. */ - virtual void SaveSettings(); + virtual void SaveSettings( wxConfigBase* aCfg ); /** * Function SaveProjectSettings @@ -396,665 +404,6 @@ public: }; -/** - * Class EDA_DRAW_FRAME - * is the base class for create windows for drawing purpose. The Eeschema, Pcbnew and - * GerbView main windows are just a few examples of classes derived from EDA_DRAW_FRAME. - */ -class EDA_DRAW_FRAME : public EDA_BASE_FRAME -{ - /// Let the #EDA_DRAW_PANEL object have access to the protected data since - /// it is closely tied to the #EDA_DRAW_FRAME. - friend class EDA_DRAW_PANEL; - - ///< Id of active button on the vertical toolbar. - int m_toolId; - - BASE_SCREEN* m_currentScreen; ///< current used SCREEN - - bool m_snapToGrid; ///< Indicates if cursor should be snapped to grid. - bool m_galCanvasActive; ///< whether to use new GAL engine - - EDA_DRAW_PANEL_GAL* m_galCanvas; - -protected: - EDA_HOTKEY_CONFIG* m_HotkeysZoomAndGridList; - int m_LastGridSizeId; // the command id offset (>= 0) of the last selected grid - // 0 is for the grid corresponding to - // a wxCommand ID = ID_POPUP_GRID_LEVEL_1000. - bool m_DrawGrid; // hide/Show grid - EDA_COLOR_T m_GridColor; // Grid color - - /// The area to draw on. - EDA_DRAW_PANEL* m_canvas; - - /// Tool ID of previously active draw tool bar button. - int m_lastDrawToolId; - - /// The shape of the KiCad cursor. The default value (0) is the normal cross - /// hair cursor. Set to non-zero value to draw the full screen cursor. - /// @note This is not the system mouse cursor. - int m_cursorShape; - - /// True shows the X and Y axis indicators. - bool m_showAxis; - - /// True shows the grid axis indicators. - bool m_showGridAxis; - - /// True shows the origin axis used to indicate the coordinate offset for - /// drill, gerber, and component position files. - bool m_showOriginAxis; - - /// True shows the drawing border and title block. - bool m_showBorderAndTitleBlock; - - /// Choice box to choose the grid size. - wxComboBox* m_gridSelectBox; - - /// Choice box to choose the zoom value. - wxComboBox* m_zoomSelectBox; - - /// The tool bar that contains the buttons for quick access to the application draw - /// tools. It typically is located on the right side of the main window. - wxAuiToolBar* m_drawToolBar; - - /// The options tool bar typcially located on the left edge of the main window. - wxAuiToolBar* m_optionsToolBar; - - /// Panel used to display information at the bottom of the main window. - EDA_MSG_PANEL* m_messagePanel; - - int m_MsgFrameHeight; - -#ifdef USE_WX_OVERLAY - // MAC Uses overlay to workaround the wxINVERT and wxXOR miss - wxOverlay m_overlay; -#endif - - void SetScreen( BASE_SCREEN* aScreen ) { m_currentScreen = aScreen; } - - /** - * Function unitsChangeRefresh - * is called when when the units setting has changed to allow for any derived classes - * to handle refreshing and controls that have units based measurements in them. The - * default version only updates the status bar. Don't forget to call the default - * in your derived class or the status bar will not get updated properly. - */ - virtual void unitsChangeRefresh(); - -public: - EDA_DRAW_FRAME( wxWindow* aParent, - ID_DRAWFRAME_TYPE aFrameType, - const wxString& aTitle, - const wxPoint& aPos, const wxSize& aSize, - long aStyle, - const wxString & aFrameName ); - - ~EDA_DRAW_FRAME(); - - virtual void SetPageSettings( const PAGE_INFO& aPageSettings ) = 0; - virtual const PAGE_INFO& GetPageSettings() const = 0; - - /** - * Function GetPageSizeIU - * works off of GetPageSettings() to return the size of the paper page in - * the internal units of this particular view. - */ - virtual const wxSize GetPageSizeIU() const = 0; - - /** - * Function GetAuxOrigin - * returns the origin of the axis used for plotting and various exports. - */ - virtual const wxPoint& GetAuxOrigin() const = 0; - virtual void SetAuxOrigin( const wxPoint& aPosition ) = 0; - - /** - * Function GetGridOrigin - * returns the absolute coordinates of the origin of the snap grid. This is - * treated as a relative offset, and snapping will occur at multiples of the grid - * size relative to this point. - */ - virtual const wxPoint& GetGridOrigin() const = 0; - virtual void SetGridOrigin( const wxPoint& aPosition ) = 0; - - //----------------------------------------------- - /** - * Function GetCrossHairPosition - * return the current cross hair position in logical (drawing) coordinates. - * @param aInvertY Inverts the Y axis position. - * @return The cross hair position in drawing coordinates. - */ - wxPoint GetCrossHairPosition( bool aInvertY = false ) const; - - /** - * Function SetCrossHairPosition - * sets the screen cross hair position to \a aPosition in logical (drawing) units. - * @param aPosition The new cross hair position. - * @param aSnapToGrid Sets the cross hair position to the nearest grid position to - * \a aPosition. - * - */ - void SetCrossHairPosition( const wxPoint& aPosition, bool aSnapToGrid = true ); - - /** - * Function GetCursorPosition - * returns the current cursor position in logical (drawing) units. - * @param aOnGrid Returns the nearest grid position at the current cursor position. - * @param aGridSize Custom grid size instead of the current grid size. Only valid - * if \a aOnGrid is true. - * @return The current cursor position. - */ - wxPoint GetCursorPosition( bool aOnGrid, wxRealPoint* aGridSize = NULL ) const; - - /** - * Function GetNearestGridPosition - * returns the nearest \a aGridSize location to \a aPosition. - * @param aPosition The position to check. - * @param aGridSize The grid size to locate to if provided. If NULL then the current - * grid size is used. - * @return The nearst grid position. - */ - wxPoint GetNearestGridPosition( const wxPoint& aPosition, wxRealPoint* aGridSize = NULL ) const; - - /** - * Function GetCursorScreenPosition - * returns the cross hair position in device (display) units.b - * @return The current cross hair position. - */ - wxPoint GetCrossHairScreenPosition() const; - - void SetMousePosition( const wxPoint& aPosition ); - - /** - * Function RefPos - * Return the reference position, coming from either the mouse position - * or the cursor position. - * - * @param useMouse If true, return mouse position, else cursor's. - * - * @return wxPoint - The reference point, either the mouse position or - * the cursor position. - */ - wxPoint RefPos( bool useMouse ) const; - - const wxPoint& GetScrollCenterPosition() const; - void SetScrollCenterPosition( const wxPoint& aPoint ); - - //---------------------------------------------- - - - virtual const TITLE_BLOCK& GetTitleBlock() const = 0; - virtual void SetTitleBlock( const TITLE_BLOCK& aTitleBlock ) = 0; - - int GetCursorShape() const { return m_cursorShape; } - - void SetCursorShape( int aCursorShape ) { m_cursorShape = aCursorShape; } - - bool GetShowBorderAndTitleBlock() const { return m_showBorderAndTitleBlock; } - - void SetShowBorderAndTitleBlock( bool aShow ) { m_showBorderAndTitleBlock = aShow; } - - EDA_DRAW_PANEL* GetCanvas() { return m_canvas; } - - virtual wxString GetScreenDesc() const; - - /** - * Function GetScreen - * returns a pointer to a BASE_SCREEN or one of its - * derivatives. It is overloaded by derived classes to return - * SCH_SCREEN or PCB_SCREEN. - */ - virtual BASE_SCREEN* GetScreen() const { return m_currentScreen; } - - /** - * Execute a remote command send via a socket to the application, - * port KICAD_PCB_PORT_SERVICE_NUMBER (currently 4242) - * It called by EDA_DRAW_FRAME::OnSockRequest(). - * this is a virtual function becuse the actual commands depends on the - * application. - * the basic function do nothing - * @param cmdline = received command from socket - */ - virtual void ExecuteRemoteCommand( const char* cmdline ){} - - void OnMenuOpen( wxMenuEvent& event ); - void OnMouseEvent( wxMouseEvent& event ); - - /** function SkipNextLeftButtonReleaseEvent - * after calling this function, if the left mouse button - * is down, the next left mouse button release event will be ignored. - * It is is usefull for instance when closing a dialog on a mouse click, - * to skip the next mouse left button release event - * by the parent window, because the mouse button - * clicked on the dialog is often released in the parent frame, - * and therefore creates a left button released mouse event - * which can be unwanted in some cases - */ - void SkipNextLeftButtonReleaseEvent(); - - virtual void OnHotKey( wxDC* aDC, int aHotKey, const wxPoint& aPosition, - EDA_ITEM* aItem = NULL ); - - /** - * Function AddMenuZoomAndGrid (virtual) - * Add standard zoom commands and submenu zoom and grid selection to a popup menu - * uses zoom hotkeys info base to add hotkeys info to menu commands - * @param aMasterMenu = the menu to populate. - */ - virtual void AddMenuZoomAndGrid( wxMenu* aMasterMenu ); - - void EraseMsgBox(); - void Process_PageSettings( wxCommandEvent& event ); - - /** - * Function SetLanguage - * called on a language menu selection - * when using a derived function, do not forget to call this one - */ - virtual void SetLanguage( wxCommandEvent& event ); - - virtual void ReCreateHToolbar() = 0; - virtual void ReCreateVToolbar() = 0; - virtual void ReCreateMenuBar(); - virtual void ReCreateAuxiliaryToolbar(); - - /** - * Function SetToolID - * sets the tool command ID to \a aId and sets the cursor to \a aCursor. The - * command ID must be greater or equal ::ID_NO_TOOL_SELECTED. If the command - * ID is less than ::ID_NO_TOOL_SELECTED, the tool command ID is set to - * ::ID_NO_TOOL_SELECTED. On debug builds, an assertion will be raised when - * \a aId is invalid. - * @param aId New tool command ID if greater than or equal to ::ID_NO_TOOL_SELECTED. - If less than zero, the current tool command ID is retained. - * @param aCursor Sets the cursor shape if greater than or equal to zero. - * @param aToolMsg The tool message to set in the status bar. - */ - virtual void SetToolID( int aId, int aCursor, const wxString& aToolMsg ); - - int GetToolId() const { return m_toolId; } - - /* These 4 functions provide a basic way to show/hide grid - * and /get/set grid color. - * These parameters are saved in KiCad config for each main frame - */ - /** - * Function IsGridVisible() , virtual - * @return true if the grid must be shown - */ - virtual bool IsGridVisible() const - { - return m_DrawGrid; - } - - /** - * Function SetGridVisibility() , virtual - * It may be overloaded by derived classes - * @param aVisible = true if the grid must be shown - */ - virtual void SetGridVisibility( bool aVisible ) - { - m_DrawGrid = aVisible; - } - - /** - * Function GetGridColor() , virtual - * @return the color of the grid - */ - virtual EDA_COLOR_T GetGridColor() const - { - return m_GridColor; - } - - /** - * Function SetGridColor() , virtual - * @param aColor = the new color of the grid - */ - virtual void SetGridColor( EDA_COLOR_T aColor ) - { - m_GridColor = aColor; - } - - /** - * Function GetGridPosition - * returns the nearest grid position to \a aPosition if a screen is defined and snap to - * grid is enabled. Otherwise, the original positions is returned. - * @see m_snapToGrid and m_BaseScreen members. - * @param aPosition The position to test. - * @return The wxPoint of the appropriate cursor position. - */ - wxPoint GetGridPosition( const wxPoint& aPosition ) const; - - /** - * Function SetNextGrid() - * changes the grid size settings to the next one available. - */ - virtual void SetNextGrid(); - - /** - * Function SetPrevGrid() - * changes the grid size settings to the previous one available. - */ - virtual void SetPrevGrid(); - - /** - * Command event handler for selecting grid sizes. - * - * All commands that set the grid size should eventually end up here. - * This is where the application setting is saved. If you override - * this method, make sure you call down to the base class. - * - * @param event - Command event passed by selecting grid size from the - * grid size combobox on the toolbar. - */ - virtual void OnSelectGrid( wxCommandEvent& event ); - - /** - * Functions OnSelectZoom - * sets the zoom factor when selected by the zoom list box in the main tool bar. - * @note List position 0 is fit to page - * List position >= 1 = zoom (1 to zoom max) - * Last list position is custom zoom not in zoom list. - */ - virtual void OnSelectZoom( wxCommandEvent& event ); - - // Command event handlers shared by all applications derived from EDA_DRAW_FRAME. - void OnToggleGridState( wxCommandEvent& aEvent ); - void OnSelectUnits( wxCommandEvent& aEvent ); - void OnToggleCrossHairStyle( wxCommandEvent& aEvent ); - - // Update user interface event handlers shared by all applications derived from - // EDA_DRAW_FRAME. - void OnUpdateUndo( wxUpdateUIEvent& aEvent ); - void OnUpdateRedo( wxUpdateUIEvent& aEvent ); - void OnUpdateGrid( wxUpdateUIEvent& aEvent ); - void OnUpdateUnits( wxUpdateUIEvent& aEvent ); - void OnUpdateCrossHairStyle( wxUpdateUIEvent& aEvent ); - - /** - * Function GeneralControl - * performs application specific control using \a aDC at \a aPosition in logical units. - *

- * Override this function for application specific control. This function gets - * called on every mouse and key event. - *

- * @param aDC A device context. - * @param aPosition The current cursor position in logical (drawing) units. - * @param aHotKey A key event used for application specific control if not zero. - */ - virtual void GeneralControl( wxDC* aDC, const wxPoint& aPosition, int aHotKey = 0 ) { } - - /** - * Function OnSize - * recalculates the size of toolbars and display panel when the frame size changes. - */ - virtual void OnSize( wxSizeEvent& event ); - - void OnEraseBackground( wxEraseEvent& SizeEvent ); - - virtual void OnZoom( wxCommandEvent& event ); - - /** - * Function SetNextZoom() - * changes the zoom to the next one available. - */ - void SetNextZoom(); - - /** - * Function SetPrevZoom() - * changes the zoom to the previous one available. - */ - void SetPrevZoom(); - - /** - * Function RedrawScreen - * redraws the entire screen area by updating the scroll bars and mouse pointer in - * order to have \a aCenterPoint at the center of the screen. - * @param aCenterPoint The position in logical units to center the scroll bars. - * @param aWarpPointer Moves the mouse cursor to \a aCenterPoint if true. - */ - void RedrawScreen( const wxPoint& aCenterPoint, bool aWarpPointer ); - - /** - * Function RedrawScreen2 - * puts the crosshair back to the screen position it had before zooming - * @param posBefore screen position of the crosshair before zooming - */ - void RedrawScreen2( const wxPoint& posBefore ); - - /** - * Function Zoom_Automatique - * redraws the screen with best zoom level and the best centering - * that shows all the page or the board - */ - void Zoom_Automatique( bool aWarpPointer ); - - /* Set the zoom level to show the area Rect */ - void Window_Zoom( EDA_RECT& Rect ); - - /** Return the zoom level which displays the full page on screen */ - virtual double BestZoom() = 0; - - /** - * Function GetZoom - * @return The current zoom level. - */ - double GetZoom(); - - /** - * Function DrawWorkSheet - * Draws on screen the page layout with the frame and the basic inscriptions. - * @param aDC The device context. - * @param aScreen screen to draw - * @param aLineWidth The pen width to use to draw the layout. - * @param aScale The mils to Iu conversion factor. - * @param aFilename The filename to display in basic inscriptions. - */ - void DrawWorkSheet( wxDC* aDC, BASE_SCREEN* aScreen, int aLineWidth, - double aScale, const wxString &aFilename ); - - void DisplayToolMsg( const wxString& msg ); - virtual void RedrawActiveWindow( wxDC* DC, bool EraseBg ) = 0; - virtual void OnLeftClick( wxDC* DC, const wxPoint& MousePos ) = 0; - virtual void OnLeftDClick( wxDC* DC, const wxPoint& MousePos ); - virtual bool OnRightClick( const wxPoint& MousePos, wxMenu* PopMenu ) = 0; - virtual void ToolOnRightClick( wxCommandEvent& event ); - void AdjustScrollBars( const wxPoint& aCenterPosition ); - - /** - * Function OnActivate (virtual) - * is called when activating the frame. - * In derived classes with a overriding OnActivate function, - * do not forget to call this EDA_DRAW_FRAME::OnActivate( event ) basic function. - */ - virtual void OnActivate( wxActivateEvent& event ); - - /** - * Function UpdateStatusBar - * updates the status bar information. - * - * The base method updates the absolute and relative coordinates and the - * zoom information. If you override this virtual method, make sure to call - * this subclassed method. The status bar can draw itself. This is not - * a drawing function per se, but rather updates lines of text held by - * the components within the status bar which is owned by the wxFrame. - *

- * On a MAC, be careful about calling this function when there is an - * existing wxDC in existence on a sibling window. - */ - virtual void UpdateStatusBar(); - - /** - * Function DisplayUnitsMsg - * displays current unit pane on the status bar. - */ - void DisplayUnitsMsg(); - - /* Handlers for block commands */ - virtual void InitBlockPasteInfos(); - - /** - * Function HandleBlockBegin - * initializes the block command including the command type, initial position, - * and other variables. - */ - virtual bool HandleBlockBegin( wxDC* aDC, int aKey, const wxPoint& aPosition ); - - /** - * Function ReturnBlockCommand - * Returns the block command code (BLOCK_MOVE, BLOCK_COPY...) corresponding to the - * keys pressed (ALT, SHIFT, SHIFT ALT ..) when block command is started by dragging - * the mouse. - * - * @param aKey = the key modifiers (Alt, Shift ...) - * @return the block command id (BLOCK_MOVE, BLOCK_COPY...) - */ - virtual int ReturnBlockCommand( int aKey ); - - /** - * Function HandleBlockPlace( ) - * Called after HandleBlockEnd, when a block command needs to be - * executed after the block is moved to its new place - * (bloc move, drag, copy .. ) - * Parameters must be initialized in GetScreen()->m_BlockLocate - */ - virtual void HandleBlockPlace( wxDC* DC ); - - /** - * Function HandleBlockEnd( ) - * Handle the "end" of a block command, - * i.e. is called at the end of the definition of the area of a block. - * depending on the current block command, this command is executed - * or parameters are initialized to prepare a call to HandleBlockPlace - * in GetScreen()->m_BlockLocate - * @return false if no item selected, or command finished, - * true if some items found and HandleBlockPlace must be called later - */ - virtual bool HandleBlockEnd( wxDC* DC ); - - /** - * Function CopyToClipboard - * copies the current page or the current block to the clipboard. - */ - void CopyToClipboard( wxCommandEvent& event ); - - /* interprocess communication */ - void OnSockRequest( wxSocketEvent& evt ); - void OnSockRequestServer( wxSocketEvent& evt ); - - /** - * Function LoadSettings - * loads the draw frame specific configuration settings. - * - * Don't forget to call this base method from any derived classes or the - * settings common to the draw frame will not get loaded. - */ - virtual void LoadSettings(); - - /** - * Funxtion SaveSettings - * saves the draw frame specific configuration settings. - * - * Don't forget to call this base method from any derived classes or the - * settings common to the draw frame will not get saved. - */ - virtual void SaveSettings(); - - /** - * Append a message to the message panel. - * - * This helper method checks to make sure the message panel exists in - * the frame and appends a message to it using the message panel - * AppendMessage() method. - * - * @param textUpper - The message upper text. - * @param textLower - The message lower text. - * @param color - A color ID from the KiCad color list (see colors.h). - * @param pad - Number of spaces to pad between messages (default = 4). - */ - void AppendMsgPanel( const wxString& textUpper, const wxString& textLower, - EDA_COLOR_T color, int pad = 6 ); - - /** - * Clear all messages from the message panel. - */ - void ClearMsgPanel( void ); - - /** - * Function SetMsgPanel - * clears the message panel and populates it with the contents of \a aList. - * - * @param aList is the list of #MSG_PANEL_ITEM objects to fill the message panel. - */ - void SetMsgPanel( const std::vector< MSG_PANEL_ITEM >& aList ); - - void SetMsgPanel( EDA_ITEM* aItem ); - - /** - * Function PrintPage - * used to print a page - * Print the page pointed by current screen, set by the calling print function - * @param aDC = wxDC given by the calling print function - * @param aPrintMask = not used here - * @param aPrintMirrorMode = not used here (Set when printing in mirror mode) - * @param aData = a pointer on an auxiliary data (not always used, NULL if not used) - */ - virtual void PrintPage( wxDC* aDC, LAYER_MSK aPrintMask, bool aPrintMirrorMode, void* aData = NULL ); - - /** - * Function CoordinateToString - * is a helper to convert the \a integer coordinate \a aValue to a string in inches or mm - * according to the current user units setting. - * @param aValue The coordinate to convert. - * @param aConvertToMils Convert inch values to mils if true. This setting has no effect if - * the current user unit is millimeters. - * @return The converted string for display in user interface elements. - */ - wxString CoordinateToString( int aValue, bool aConvertToMils = false ) const; - - /** - * Function LengthDoubleToString - * is a helper to convert the \a double value \a aValue to a string in inches or mm - * according to the current user units setting. - * @param aValue The coordinate to convert. - * @param aConvertToMils Convert inch values to mils if true. This setting has no effect if - * the current user unit is millimeters. - * @return The converted string for display in user interface elements. - */ - wxString LengthDoubleToString( double aValue, bool aConvertToMils = false ) const; - - /** - * Function UseGalCanvas - * used to switch between standard and GAL-based canvas. - * - * @param aEnable True for GAL-based canvas, false for standard canvas. - */ - virtual void UseGalCanvas( bool aEnable ); - - /** - * Function IsGalCanvasActive - * is used to check which canvas (GAL-based or standard) is currently in use. - * - * @return True for GAL-based canvas, false for standard canvas. - */ - bool IsGalCanvasActive() const { return m_galCanvasActive; } - void SetGalCanvasActive( bool aState ) { m_galCanvasActive = aState; } - - /** - * Function GetGalCanvas - * returns a pointer to GAL-based canvas of given EDA draw frame. - * - * @return Pointer to GAL-based canvas. - */ - EDA_DRAW_PANEL_GAL* GetGalCanvas() const { return m_galCanvas; } - void SetGalCanvas( EDA_DRAW_PANEL_GAL* aPanel ) { m_galCanvas = aPanel; } - - DECLARE_EVENT_TABLE() -}; - - /** * Specialization of the wxAuiPaneInfo class for KiCad panels. * diff --git a/kicad/CMakeLists.txt b/kicad/CMakeLists.txt index b86d4b5035..2647e93792 100644 --- a/kicad/CMakeLists.txt +++ b/kicad/CMakeLists.txt @@ -21,14 +21,10 @@ set(KICAD_SRCS project_template.cpp tree_project_frame.cpp) -if(WIN32) - if(MINGW) - # KICAD_RESOURCES variable is set by the macro. - mingw_resource_compiler(kicad) - else(MINGW) - set(KICAD_RESOURCES kicad.rc) - endif(MINGW) -endif(WIN32) +if(MINGW) + # KICAD_RESOURCES variable is set by the macro. + mingw_resource_compiler(kicad) +endif() if(APPLE) set(KICAD_RESOURCES kicad.icns kicad_doc.icns) diff --git a/kicad/class_treeproject_item.cpp b/kicad/class_treeproject_item.cpp index 01b31af817..b43c93bc18 100644 --- a/kicad/class_treeproject_item.cpp +++ b/kicad/class_treeproject_item.cpp @@ -34,7 +34,8 @@ #include #include -#include +#include +#include #include #include #include @@ -189,7 +190,8 @@ void TREEPROJECT_ITEM::Activate( TREE_PROJECT_FRAME* prjframe ) wxString sep = wxFileName().GetPathSeparator(); wxString FullFileName = GetFileName(); wxTreeItemId id = GetId(); - KICAD_MANAGER_FRAME* mainFrame = (KICAD_MANAGER_FRAME*) wxGetApp().GetTopWindow(); + + KICAD_MANAGER_FRAME* mainFrame = (KICAD_MANAGER_FRAME*) Pgm().App().GetTopWindow(); AddDelimiterString( FullFileName ); @@ -225,7 +227,7 @@ void TREEPROJECT_ITEM::Activate( TREE_PROJECT_FRAME* prjframe ) case TREE_TXT: { - wxString editorname = wxGetApp().GetEditorName(); + wxString editorname = Pgm().GetEditorName(); if( !editorname.IsEmpty() ) mainFrame->Execute( m_parent, editorname, FullFileName ); diff --git a/kicad/files-io.cpp b/kicad/files-io.cpp index 41803864dc..4943e359f3 100644 --- a/kicad/files-io.cpp +++ b/kicad/files-io.cpp @@ -27,7 +27,7 @@ */ #include -#include +#include #include #include #include @@ -47,9 +47,8 @@ static const wxString ZipFileWildcard( wxT( "Zip file (*.zip) | *.zip" ) ); void KICAD_MANAGER_FRAME::OnFileHistory( wxCommandEvent& event ) { - wxString fn; - - fn = GetFileFromHistory( event.GetId(), _( "KiCad project file" ) ); + wxString fn = GetFileFromHistory( event.GetId(), + _( "KiCad project file" ), &Pgm().GetFileHistory() ); if( fn != wxEmptyString ) { diff --git a/kicad/kicad.cpp b/kicad/kicad.cpp index b603c06432..742121c781 100644 --- a/kicad/kicad.cpp +++ b/kicad/kicad.cpp @@ -29,28 +29,131 @@ #include -#include #include +#include +#include #include +#include #include +#include #include -const wxString g_KicadPrjFilenameExtension( wxT( ".pro" ) ); - -/************************************/ -/* Called to initialize the program */ -/************************************/ - -// Create a new application object -IMPLEMENT_APP( EDA_APP ) - -/* MacOSX: Needed for file association - * http://wiki.wxwidgets.org/WxMac-specific_topics - */ -void EDA_APP::MacOpenFile( const wxString& aFileName ) +// a dummy to quiet linking with EDA_BASE_FRAME::config(); +#include +KIFACE_I& Kiface() { + wxASSERT( 0 ); // should never be called, only reference is from EDA_BASE_FRAME::config(); + return (KIFACE_I&) *(KIFACE_I*) 0; +} + +static PGM_KICAD program; + +PGM_KICAD& Pgm() +{ + return program; +} + + +bool PGM_KICAD::OnPgmInit( wxApp* aWxApp ) +{ + m_wx_app = aWxApp; // first thing. + + m_bm.Init(); + +#if 0 // copied from single_top.c, possibly for milestone B) + wxString absoluteArgv0 = wxStandardPaths::Get().GetExecutablePath(); + + if( !wxIsAbsolutePath( absoluteArgv0 ) ) + { + wxLogSysError( wxT( "No meaningful argv[0]" ) ); + return false; + } + + // Set LIB_ENV_VAR *before* loading the DSO, in case the top-level DSO holding the + // KIFACE has hard dependencies on subsidiary DSOs below it. + SetLibEnvVar( absoluteArgv0 ); +#endif + + if( !initPgm() ) + return false; + + // Read current setup and reopen last directory if no filename to open on + // command line. + if( App().argc == 1 ) + { + wxString dir; + + if( PgmSettings()->Read( workingDirKey, &dir ) && wxDirExists( dir ) ) + { + wxSetWorkingDirectory( dir ); + } + } + + KICAD_MANAGER_FRAME* frame = new KICAD_MANAGER_FRAME( NULL, wxT( "KiCad" ), + wxDefaultPosition, wxDefaultSize ); + App().SetTopWindow( frame ); + + bool prjloaded = false; // true when the project is loaded + + if( App().argc > 1 ) + frame->m_ProjectFileName = App().argv[1]; + + else if( GetFileHistory().GetCount() ) + { + // Try to open the last opened project, + // if a project name is not given when starting Kicad + frame->m_ProjectFileName = GetFileHistory().GetHistoryFile( 0 ); + + if( !frame->m_ProjectFileName.FileExists() ) + GetFileHistory().RemoveFileFromHistory( 0 ); + else + { + wxCommandEvent cmd( 0, wxID_FILE1 ); + + frame->OnFileHistory( cmd ); + prjloaded = true; // OnFileHistory() loads the project + } + } + + if( !frame->m_ProjectFileName.FileExists() ) + { + wxFileName namelessProject( wxGetCwd(), NAMELESS_PROJECT, + ProjectFileExtension ); + + frame->m_ProjectFileName = namelessProject; + } + + if( !prjloaded ) + { + wxCommandEvent cmd( 0, wxID_ANY ); + + frame->OnLoadProject( cmd ); + } + + frame->Show( true ); + frame->Raise(); + + return true; +} + + +void PGM_KICAD::OnPgmExit() +{ + saveCommonSettings(); + + // write common settings to disk, and destroy everything in PGM_KICAD, + // especially wxSingleInstanceCheckerImpl earlier than wxApp and earlier + // than static destruction would. + destroy(); +} + + +void PGM_KICAD::MacOpenFile( const wxString& aFileName ) +{ +#if 0 // I'm tired, need a rest. + KICAD_MANAGER_FRAME* frame = (KICAD_MANAGER_FRAME*) GetTopWindow(); wxFileName fn = aFileName; @@ -79,58 +182,113 @@ void EDA_APP::MacOpenFile( const wxString& aFileName ) frame->m_LeftWin->ReCreateTreePrj(); frame->PrintPrjInfo(); +#endif } -bool EDA_APP::OnInit() +void PGM_KICAD::destroy() { - KICAD_MANAGER_FRAME* frame; + // unlike a normal destructor, this is designed to be called more + // than once safely: - InitEDA_Appl( wxT( "KiCad" ), APP_KICAD_T ); + m_bm.End(); - // read current setup and reopen last directory if no filename to open in command line - bool reopenLastUsedDirectory = argc == 1; - GetSettings( reopenLastUsedDirectory ); + PGM_BASE::destroy(); +} - frame = new KICAD_MANAGER_FRAME( NULL, wxT( "KiCad" ), - wxDefaultPosition, wxDefaultSize ); - SetTopWindow( frame ); - bool prjloaded = false; // true when the project is loaded +/** + * Class KIWAY_MGR + * is a container for all KIWAYS [and PROJECTS]. This class needs to work both + * for a C++ project manager and an a wxPython one (after being moved into a + * header later). + */ +class KIWAY_MGR +{ +public: + //KIWAY_MGR(); + // ~KIWAY_MGR(); - if( argc > 1 ) - frame->m_ProjectFileName = argv[1]; - else if( m_fileHistory.GetCount() ) + bool OnStart( wxApp* aProcess ); + + void OnEnd(); + + KIWAY& operator[]( int aIndex ) { - // Try to open the last opened project, - // if a project name is not given when starting Kicad - frame->m_ProjectFileName = m_fileHistory.GetHistoryFile( 0 ); + wxASSERT( m_kiways.size() ); // stuffed in OnStart() + return m_kiways[aIndex]; + } - if( !frame->m_ProjectFileName.FileExists() ) - m_fileHistory.RemoveFileFromHistory( 0 ); - else +private: + + // KIWAYs may not be moved once doled out, since window DNA depends on the + // pointer being good forever. + // boost_ptr::vector however never moves the object pointed to. + typedef boost::ptr_vector KIWAYS; + + KIWAYS m_kiways; +}; + +static KIWAY_MGR kiways; + + +/** + * Struct APP_KICAD + * is not publicly visible because most of the action is in PGM_KICAD these days. + */ +struct APP_KICAD : public wxApp +{ + bool OnInit() // overload wxApp virtual + { + if( kiways.OnStart( this ) ) { - wxCommandEvent cmd( 0, wxID_FILE1 ); - frame->OnFileHistory( cmd ); - prjloaded = true; // OnFileHistory() loads the project + return Pgm().OnPgmInit( this ); } + return false; } - if( !frame->m_ProjectFileName.FileExists() ) + int OnExit() // overload wxApp virtual { - wxFileName namelessProject( wxGetCwd(), NAMELESS_PROJECT, - ProjectFileExtension ); - frame->m_ProjectFileName = namelessProject; + kiways.OnEnd(); + + Pgm().OnPgmExit(); + + return wxApp::OnExit(); } - if( ! prjloaded ) + /** + * Function MacOpenFile + * is specific to MacOSX (not used under Linux or Windows). + * MacOSX requires it for file association. + * @see http://wiki.wxwidgets.org/WxMac-specific_topics + */ + void MacOpenFile( const wxString& aFileName ) // overload wxApp virtual { - wxCommandEvent cmd( 0, wxID_ANY ); - frame->OnLoadProject( cmd ); + Pgm().MacOpenFile( aFileName ); } +}; - frame->Show( true ); - frame->Raise(); +IMPLEMENT_APP( APP_KICAD ); + + +// The C++ project manager supports one open PROJECT, so Prj() calls within +// this link image need this function. +PROJECT& Prj() +{ + return kiways[0].Prj(); +} + + +bool KIWAY_MGR::OnStart( wxApp* aProcess ) +{ + // The C++ project manager supports only one open PROJECT + // We should need no copy constructor for KIWAY to push a pointer. + m_kiways.push_back( new KIWAY() ); return true; } + + +void KIWAY_MGR::OnEnd() +{ +} diff --git a/kicad/kicad.h b/kicad/kicad.h index 73ffbe8ebe..129d29dc82 100644 --- a/kicad/kicad.h +++ b/kicad/kicad.h @@ -39,7 +39,7 @@ #include #include -#include +//#include // With a recent wxWidget, we can use the wxFileSystemWatcherEvent // to monitor files add/remove/rename in tree project @@ -47,8 +47,6 @@ #define KICAD_USE_FILES_WATCHER #endif -extern const wxString g_KicadPrjFilenameExtension; - class LAUNCHER_PANEL; class TREEPROJECTFILES; class TREE_PROJECT_FRAME; @@ -116,11 +114,15 @@ enum id_kicad_frm { }; -/* class KICAD_MANAGER_FRAME - * This is the main KiCad frame +/** + * Class KICAD_MANAGER_FRAME + * is the main KiCad project manager frame. It is not a KIWAY_PLAYER. */ class KICAD_MANAGER_FRAME : public EDA_BASE_FRAME { +protected: + wxConfigBase* config(); // override EDA_BASE_FRAME virtual + public: TREE_PROJECT_FRAME* m_LeftWin; LAUNCHER_PANEL* m_Launcher; @@ -133,7 +135,8 @@ public: private: int m_leftWinWidth; -public: KICAD_MANAGER_FRAME( wxWindow* parent, const wxString& title, +public: + KICAD_MANAGER_FRAME( wxWindow* parent, const wxString& title, const wxPoint& pos, const wxSize& size ); ~KICAD_MANAGER_FRAME(); @@ -204,23 +207,9 @@ public: KICAD_MANAGER_FRAME( wxWindow* parent, const wxString& title, void CreateNewProject( const wxString aPrjFullFileName, bool aTemplateSelector ); - /** - * Function LoadSettings - * loads the KiCad main frame specific configuration settings. - * - * Don't forget to call this base method from any derived classes or the - * settings will not get loaded. - */ - void LoadSettings(); + void LoadSettings( wxConfigBase* aCfg ); - /** - * Function SaveSettings - * saves the KiCad main frame specific configuration settings. - * - * Don't forget to call this base method from any derived classes or the - * settings will not get saved. - */ - void SaveSettings(); + void SaveSettings( wxConfigBase* aCfg ); /** * Function Execute @@ -232,13 +221,13 @@ public: KICAD_MANAGER_FRAME( wxWindow* parent, const wxString& title, void Execute( wxWindow* frame, const wxString& execFile, const wxString& param = wxEmptyString ); - class PROCESS_TERMINATE_EVENT_HANDLER : public wxProcess + class TERMINATE_HANDLER : public wxProcess { private: wxString appName; public: - PROCESS_TERMINATE_EVENT_HANDLER( const wxString& appName ) : + TERMINATE_HANDLER( const wxString& appName ) : appName(appName) { } @@ -287,4 +276,8 @@ private: wxBitmapButton* AddBitmapButton( wxWindowID aId, const wxBitmap& aBitmap ); }; +// The C++ project manager includes a single PROJECT in its link image. +class PROJECT; +extern PROJECT& Prj(); + #endif diff --git a/kicad/mainframe.cpp b/kicad/mainframe.cpp index 1dc1e0cade..55f5f1ba0b 100644 --- a/kicad/mainframe.cpp +++ b/kicad/mainframe.cpp @@ -29,7 +29,7 @@ */ #include -#include +#include #include #include #include @@ -40,12 +40,11 @@ #include -static const wxString TreeFrameWidthEntry( wxT( "LeftWinWidth" ) ); +#define TreeFrameWidthEntry wxT( "LeftWinWidth" ) -KICAD_MANAGER_FRAME::KICAD_MANAGER_FRAME( wxWindow* parent, - const wxString& title, - const wxPoint& pos, - const wxSize& size ) : + +KICAD_MANAGER_FRAME::KICAD_MANAGER_FRAME( wxWindow* parent, + const wxString& title, const wxPoint& pos, const wxSize& size ) : EDA_BASE_FRAME( parent, KICAD_MAIN_FRAME_TYPE, title, pos, size, KICAD_DEFAULT_DRAWFRAME_STYLE, wxT( "KicadFrame" ) ) { @@ -63,7 +62,7 @@ KICAD_MANAGER_FRAME::KICAD_MANAGER_FRAME( wxWindow* parent, SetIcon( icon ); // Give the last sise and pos to main window - LoadSettings(); + LoadSettings( config() ); SetSize( m_FramePos.x, m_FramePos.y, m_FrameSize.x, m_FrameSize.y ); // Left window: is the box which display tree project @@ -71,6 +70,7 @@ KICAD_MANAGER_FRAME::KICAD_MANAGER_FRAME( wxWindow* parent, // Right top Window: buttons to launch applications m_Launcher = new LAUNCHER_PANEL( this ); + // Add the wxTextCtrl showing all messages from KiCad: m_MessagesBox = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, @@ -115,6 +115,14 @@ KICAD_MANAGER_FRAME::~KICAD_MANAGER_FRAME() } +wxConfigBase* KICAD_MANAGER_FRAME::config() +{ + wxConfigBase* ret = Pgm().PgmSettings(); + wxASSERT( ret ); + return ret; +} + + void KICAD_MANAGER_FRAME::PrintMsg( const wxString& aText ) { m_MessagesBox->AppendText( aText ); @@ -134,7 +142,7 @@ void KICAD_MANAGER_FRAME::OnCloseWindow( wxCloseEvent& Event ) { int px, py; - UpdateFileHistory( m_ProjectFileName.GetFullPath() ); + UpdateFileHistory( m_ProjectFileName.GetFullPath(), &Pgm().GetFileHistory() ); if( !IsIconized() ) // save main frame position and size { @@ -150,12 +158,12 @@ void KICAD_MANAGER_FRAME::OnCloseWindow( wxCloseEvent& Event ) Event.SetCanVeto( true ); // Close the help frame - if( wxGetApp().GetHtmlHelpController() ) + if( Pgm().GetHtmlHelpController() ) { - if( wxGetApp().GetHtmlHelpController()->GetFrame() ) // returns NULL if no help frame active - wxGetApp().GetHtmlHelpController()->GetFrame()->Close( true ); + if( Pgm().GetHtmlHelpController()->GetFrame() ) // returns NULL if no help frame active + Pgm().GetHtmlHelpController()->GetFrame()->Close( true ); - wxGetApp().SetHtmlHelpController( NULL ); + Pgm().SetHtmlHelpController( NULL ); } m_LeftWin->Show( false ); @@ -170,14 +178,12 @@ void KICAD_MANAGER_FRAME::OnExit( wxCommandEvent& event ) } -void KICAD_MANAGER_FRAME::PROCESS_TERMINATE_EVENT_HANDLER:: - OnTerminate( int pid, int status ) +void KICAD_MANAGER_FRAME::TERMINATE_HANDLER::OnTerminate( int pid, int status ) { + wxString msg = wxString::Format( _( "%s closed [pid=%d]\n" ), + GetChars( appName ), pid ); - wxString msg; - - msg.Printf( appName + _( " closed [pid=%d]\n" ), pid ); - ( (KICAD_MANAGER_FRAME*) wxGetApp().GetTopWindow() )->PrintMsg( msg ); + ( (KICAD_MANAGER_FRAME*) Pgm().App().GetTopWindow() )->PrintMsg( msg ); delete this; } @@ -186,17 +192,15 @@ void KICAD_MANAGER_FRAME::PROCESS_TERMINATE_EVENT_HANDLER:: void KICAD_MANAGER_FRAME::Execute( wxWindow* frame, const wxString& execFile, const wxString& param ) { + TERMINATE_HANDLER* callback = new TERMINATE_HANDLER( execFile ); - PROCESS_TERMINATE_EVENT_HANDLER* callback; - long pid; - wxString msg; - - callback = new PROCESS_TERMINATE_EVENT_HANDLER( execFile ); - pid = ExecuteFile( frame, execFile, param, callback ); + long pid = ExecuteFile( frame, execFile, param, callback ); if( pid > 0 ) { - msg.Printf( execFile + _( " opened [pid=%ld]\n" ), pid ); + wxString msg = wxString::Format( _( "%s opened [pid=%ld]\n" ), + GetChars( execFile ), pid ); + PrintMsg( msg ); } else @@ -267,7 +271,7 @@ void KICAD_MANAGER_FRAME::OnRunGerbview( wxCommandEvent& event ) void KICAD_MANAGER_FRAME::OnOpenTextEditor( wxCommandEvent& event ) { - wxString editorname = wxGetApp().GetEditorName(); + wxString editorname = Pgm().GetEditorName(); if( !editorname.IsEmpty() ) Execute( this, editorname, wxEmptyString ); @@ -294,8 +298,8 @@ void KICAD_MANAGER_FRAME::OnOpenFileInTextEditor( wxCommandEvent& event ) wxString filename = wxT( "\"" ); filename += dlg.GetPath() + wxT( "\"" ); - if( !dlg.GetPath().IsEmpty() && !wxGetApp().GetEditorName().IsEmpty() ) - Execute( this, wxGetApp().GetEditorName(), filename ); + if( !dlg.GetPath().IsEmpty() && !Pgm().GetEditorName().IsEmpty() ) + Execute( this, Pgm().GetEditorName(), filename ); } @@ -311,29 +315,20 @@ void KICAD_MANAGER_FRAME::ClearMsg() } -void KICAD_MANAGER_FRAME::LoadSettings() +void KICAD_MANAGER_FRAME::LoadSettings( wxConfigBase* aCfg ) { - wxConfig* cfg = wxGetApp().GetSettings(); - - if( cfg ) - { - EDA_BASE_FRAME::LoadSettings(); - cfg->Read( TreeFrameWidthEntry, &m_leftWinWidth ); - } + EDA_BASE_FRAME::LoadSettings( aCfg ); + aCfg->Read( TreeFrameWidthEntry, &m_leftWinWidth ); } -void KICAD_MANAGER_FRAME::SaveSettings() +void KICAD_MANAGER_FRAME::SaveSettings( wxConfigBase* aCfg ) { - wxConfig* cfg = wxGetApp().GetSettings(); - - if( cfg ) - { - EDA_BASE_FRAME::SaveSettings(); - cfg->Write( TreeFrameWidthEntry, m_LeftWin->GetSize().x ); - } + EDA_BASE_FRAME::SaveSettings( aCfg ); + aCfg->Write( TreeFrameWidthEntry, m_LeftWin->GetSize().x ); } + /** * a minor helper function: * Prints the Current Working Dir name and the projet name on the text panel. @@ -346,3 +341,4 @@ void KICAD_MANAGER_FRAME::PrintPrjInfo() GetChars( m_ProjectFileName.GetFullPath() ) ); PrintMsg( msg ); } + diff --git a/kicad/menubar.cpp b/kicad/menubar.cpp index 62cf7a321e..0e1fce998d 100644 --- a/kicad/menubar.cpp +++ b/kicad/menubar.cpp @@ -28,7 +28,7 @@ * @brief (Re)Create the project manager menubar for KiCad */ #include -#include +#include #include #include #include @@ -109,7 +109,7 @@ void KICAD_MANAGER_FRAME::ReCreateMenuBar() // Before deleting, remove the menus managed by m_fileHistory // (the file history will be updated when adding/removing files in history) if( openRecentMenu ) - wxGetApp().GetFileHistory().RemoveMenu( openRecentMenu ); + Pgm().GetFileHistory().RemoveMenu( openRecentMenu ); // Delete all existing menus while( menuBar->GetMenuCount() ) @@ -129,8 +129,8 @@ void KICAD_MANAGER_FRAME::ReCreateMenuBar() // File history openRecentMenu = new wxMenu(); - wxGetApp().GetFileHistory().UseMenu( openRecentMenu ); - wxGetApp().GetFileHistory().AddFilesToMenu( ); + Pgm().GetFileHistory().UseMenu( openRecentMenu ); + Pgm().GetFileHistory().AddFilesToMenu( ); AddMenuItem( fileMenu, openRecentMenu, wxID_ANY, _( "Open &Recent" ), @@ -224,7 +224,7 @@ void KICAD_MANAGER_FRAME::ReCreateMenuBar() KiBitmap( datasheet_xpm ), wxITEM_CHECK ); SubMenuPdfBrowserChoice->Check( ID_SELECT_DEFAULT_PDF_BROWSER, - wxGetApp().UseSystemPdfBrowser() ); + Pgm().UseSystemPdfBrowser() ); // Favourite AddMenuItem( SubMenuPdfBrowserChoice, ID_SELECT_PREFERED_PDF_BROWSER, @@ -233,7 +233,7 @@ void KICAD_MANAGER_FRAME::ReCreateMenuBar() KiBitmap( datasheet_xpm ), wxITEM_CHECK ); SubMenuPdfBrowserChoice->Check( ID_SELECT_PREFERED_PDF_BROWSER, - !wxGetApp().UseSystemPdfBrowser() ); + !Pgm().UseSystemPdfBrowser() ); SubMenuPdfBrowserChoice->AppendSeparator(); // Append PDF Viewer submenu to preferences @@ -251,7 +251,7 @@ void KICAD_MANAGER_FRAME::ReCreateMenuBar() // Language submenu preferencesMenu->AppendSeparator(); - wxGetApp().AddMenuLanguageList( preferencesMenu ); + Pgm().AddMenuLanguageList( preferencesMenu ); // Menu Help: wxMenu* helpMenu = new wxMenu; diff --git a/kicad/pgm_kicad.h b/kicad/pgm_kicad.h new file mode 100644 index 0000000000..5de4cebbb7 --- /dev/null +++ b/kicad/pgm_kicad.h @@ -0,0 +1,74 @@ +#ifndef PGM_KICAD_H_ +#define PGM_KICAD_H_ +/* + * This program source code file is part of KiCad, a free EDA CAD application. + * + * Copyright (C) 2014 SoftPLC Corporation, Dick Hollenbeck + * Copyright (C) 2014 KiCad Developers, see CHANGELOG.TXT for contributors. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, you may find one here: + * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html + * or you may search the http://www.gnu.org website for the version 2 license, + * or you may write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + */ + + +#include +#include + + +/** + * Class PGM_KICAD + * extends PGM_BASE to bring in FileHistory() and PdfBrowser() which were moved + * from EDA_APP into KIFACE_I. KIFACE_I is not applicable in the project manager + * since it is not a KIFACE. This header is in the kicad directory since nobody + * else needs to know about it. + */ +class PGM_KICAD : public PGM_BASE +{ +public: + PGM_KICAD() : + m_bm( "kicad" ) // indicates a "$HOME/.kicad wxConfig like" config file. + {} + + ~PGM_KICAD() + { + destroy(); + } + + bool OnPgmInit( wxApp* aWxApp ); // overload PGM_BASE virtual + void OnPgmExit(); // overload PGM_BASE virtual + void MacOpenFile( const wxString& aFileName ); // overload PGM_BASE virtual + + wxFileHistory& GetFileHistory() { return m_bm.m_history; } + + wxConfigBase* PgmSettings() { return m_bm.m_config; } + + SEARCH_STACK& SysSearch() { return m_bm.m_search; } + +protected: + + // The PGM_* classes can have difficulties at termination if they + // are not destroyed soon enough. Relying on a static destructor can be + // too late for contained objects like wxSingleInstanceChecker. + void destroy(); + + BIN_MOD m_bm; +}; + + +extern PGM_KICAD& Pgm(); + +#endif // PGM_KICAD_H_ diff --git a/kicad/preferences.cpp b/kicad/preferences.cpp index 4ee105735d..19bed9f1d1 100644 --- a/kicad/preferences.cpp +++ b/kicad/preferences.cpp @@ -28,7 +28,7 @@ */ #include -#include +#include #include #include @@ -39,40 +39,33 @@ void KICAD_MANAGER_FRAME::OnUpdateDefaultPdfBrowser( wxUpdateUIEvent& event ) { - event.Check( wxGetApp().UseSystemPdfBrowser() ); + event.Check( Pgm().UseSystemPdfBrowser() ); } void KICAD_MANAGER_FRAME::OnSelectDefaultPdfBrowser( wxCommandEvent& event ) { - wxGetApp().ForceSystemPdfBrowser( true ); - wxGetApp().WritePdfBrowserInfos(); + Pgm().ForceSystemPdfBrowser( true ); + Pgm().WritePdfBrowserInfos(); } void KICAD_MANAGER_FRAME::OnUpdatePreferredPdfBrowser( wxUpdateUIEvent& event ) { - event.Check( !wxGetApp().UseSystemPdfBrowser() ); + event.Check( !Pgm().UseSystemPdfBrowser() ); } void KICAD_MANAGER_FRAME::OnSelectPreferredPdfBrowser( wxCommandEvent& event ) { - wxGetApp().ForceSystemPdfBrowser( false ); + bool select = event.GetId() == ID_SELECT_PREFERED_PDF_BROWSER_NAME; - bool selectName = event.GetId() == ID_SELECT_PREFERED_PDF_BROWSER_NAME; - if( wxGetApp().GetPdfBrowserFileName().IsEmpty() && !selectName ) + if( !Pgm().GetPdfBrowserName() && !select ) { DisplayError( this, _( "You must choose a PDF viewer before using this option." ) ); } - if( !wxGetApp().GetPdfBrowserFileName().IsEmpty() && !selectName ) - { - wxGetApp().WritePdfBrowserInfos(); - return; - } - wxString mask( wxT( "*" ) ); #ifdef __WINDOWS__ @@ -81,8 +74,8 @@ void KICAD_MANAGER_FRAME::OnSelectPreferredPdfBrowser( wxCommandEvent& event ) wxString wildcard = _( "Executable files (" ) + mask + wxT( ")|" ) + mask; - wxGetApp().ReadPdfBrowserInfos(); - wxFileName fn = wxGetApp().GetPdfBrowserFileName(); + Pgm().ReadPdfBrowserInfos(); + wxFileName fn = Pgm().GetPdfBrowserName(); wxFileDialog dlg( this, _( "Select Preferred Pdf Browser" ), fn.GetPath(), fn.GetFullPath(), wildcard, @@ -91,8 +84,8 @@ void KICAD_MANAGER_FRAME::OnSelectPreferredPdfBrowser( wxCommandEvent& event ) if( dlg.ShowModal() == wxID_CANCEL ) return; - wxGetApp().SetPdfBrowserFileName( dlg.GetPath() ); - wxGetApp().WritePdfBrowserInfos(); + Pgm().SetPdfBrowserName( dlg.GetPath() ); + Pgm().WritePdfBrowserInfos(); } diff --git a/kicad/prjconfig.cpp b/kicad/prjconfig.cpp index 93da24b603..978f5eec8b 100644 --- a/kicad/prjconfig.cpp +++ b/kicad/prjconfig.cpp @@ -28,11 +28,12 @@ */ #include -#include +#include +#include #include #include #include -#include +#include #include #include #include @@ -52,9 +53,9 @@ // (Add them in s_KicadManagerParams if any) // Used also to create new .pro files from the kicad.pro template file // for new projects -static const wxString GeneralGroupName( wxT( "/general" ) ); -PARAM_CFG_ARRAY s_KicadManagerParams; +#define GeneralGroupName wxT( "/general" ) +PARAM_CFG_ARRAY s_KicadManagerParams; void KICAD_MANAGER_FRAME::CreateNewProject( const wxString aPrjFullFileName, bool aTemplateSelector = false ) @@ -65,8 +66,8 @@ void KICAD_MANAGER_FRAME::CreateNewProject( const wxString aPrjFullFileName, ClearMsg(); - // Init default config filename - filename = wxGetApp().FindLibraryPath( wxT( "kicad" ) + g_KicadPrjFilenameExtension ); + // default config filename + filename = Pgm().SysSearch().FindValidPath( wxT( "kicad.pro" ) ); // If we are creating a project from a template, make sure the template directory is sane if( aTemplateSelector ) @@ -179,8 +180,8 @@ void KICAD_MANAGER_FRAME::CreateNewProject( const wxString aPrjFullFileName, m_ProjectFileName = newProjectName; // Write settings to project file - wxGetApp().WriteProjectConfig( aPrjFullFileName, - GeneralGroupName, s_KicadManagerParams ); + // was: wxGetApp().WriteProjectConfig( aPrjFullFileName, GeneralGroupName, s_KicadManagerParams ); + Prj().ConfigSave( Pgm().SysSearch(), aPrjFullFileName, GeneralGroupName, s_KicadManagerParams ); } @@ -257,31 +258,33 @@ void KICAD_MANAGER_FRAME::OnLoadProject( wxCommandEvent& event ) /* Check if project file exists and if it is not noname.pro */ wxString filename = m_ProjectFileName.GetFullName(); - wxString nameless_prj = NAMELESS_PROJECT; - nameless_prj += g_KicadPrjFilenameExtension; + wxString nameless_prj = NAMELESS_PROJECT wxT( ".pro" ); if( !m_ProjectFileName.FileExists() && !filename.IsSameAs( nameless_prj ) ) { - wxString msg; - msg.Printf( _( "KiCad project file <%s> not found" ), - GetChars( m_ProjectFileName.GetFullPath() ) ); + wxString msg = wxString::Format( + _( "KiCad project file '%s' not found" ), + GetChars( m_ProjectFileName.GetFullPath() ) ); DisplayError( this, msg ); return; } wxSetWorkingDirectory( m_ProjectFileName.GetPath() ); - wxGetApp().ReadProjectConfig( m_ProjectFileName.GetFullPath(), - GeneralGroupName, s_KicadManagerParams, false ); - title = wxGetApp().GetTitle() + wxT( " " ) + GetBuildVersion() + - wxT( " " ) + m_ProjectFileName.GetFullPath(); + // was wxGetApp().ReadProjectConfig( m_ProjectFileName.GetFullPath(), + // GeneralGroupName, s_KicadManagerParams, false ); + Prj().ConfigLoad( Pgm().SysSearch(), m_ProjectFileName.GetFullPath(), + GeneralGroupName, s_KicadManagerParams, false ); + + title = wxT( "KiCad " ) + GetBuildVersion() + wxT( ' ' ) + m_ProjectFileName.GetFullPath(); if( !m_ProjectFileName.IsDirWritable() ) title += _( " [Read Only]" ); SetTitle( title ); - UpdateFileHistory( m_ProjectFileName.GetFullPath() ); + UpdateFileHistory( m_ProjectFileName.GetFullPath(), &Pgm().GetFileHistory() ); + m_LeftWin->ReCreateTreePrj(); #ifdef KICAD_USE_FILES_WATCHER @@ -301,6 +304,9 @@ void KICAD_MANAGER_FRAME::OnSaveProject( wxCommandEvent& event ) if( !IsWritable( m_ProjectFileName ) ) return; - wxGetApp().WriteProjectConfig( m_ProjectFileName.GetFullPath(), - GeneralGroupName, s_KicadManagerParams ); + // was: wxGetApp().WriteProjectConfig( m_ProjectFileName.GetFullPath(), + // GeneralGroupName, s_KicadManagerParams ); + Prj().ConfigSave( Pgm().SysSearch(), m_ProjectFileName.GetFullPath(), + GeneralGroupName, s_KicadManagerParams ); } + diff --git a/kicad/tree_project_frame.cpp b/kicad/tree_project_frame.cpp index bc7134af42..6e6c706371 100644 --- a/kicad/tree_project_frame.cpp +++ b/kicad/tree_project_frame.cpp @@ -31,7 +31,7 @@ #include #include #include -#include +#include #include #include @@ -713,7 +713,7 @@ void TREE_PROJECT_FRAME::OnOpenSelectedFileWithTextEditor( wxCommandEvent& event wxString FullFileName = tree_data->GetFileName(); AddDelimiterString( FullFileName ); - wxString editorname = wxGetApp().GetEditorName(); + wxString editorname = Pgm().GetEditorName(); if( !editorname.IsEmpty() ) ExecuteFile( this, editorname, FullFileName ); diff --git a/new/toolchain-mingw32.cmake b/new/toolchain-mingw32.cmake index cbfb7af14e..3e902ac2d1 100644 --- a/new/toolchain-mingw32.cmake +++ b/new/toolchain-mingw32.cmake @@ -13,15 +13,26 @@ set( CMAKE_SYSTEM_PROCESSOR i686 ) # configure only the lines within this block, typically set( TC_PATH /usr/bin ) -set( CROSS_COMPILE i686-w64-mingw32- ) +set( CROSS_COMPILE x86_64-w64-mingw32- ) # specify the cross compiler set( CMAKE_C_COMPILER ${TC_PATH}/${CROSS_COMPILE}gcc ) set( CMAKE_CXX_COMPILER ${TC_PATH}/${CROSS_COMPILE}g++ ) set( CMAKE_RC_COMPILER ${TC_PATH}/${CROSS_COMPILE}windres ) +# One compiler generates either 32 bit or 64 bit code, -m32 says generate 32 bit: +set( CMAKE_CXX_FLAGS_INIT "-m32" CACHE STRING "C++ flag which generates 32 bit code." ) +set( CMAKE_C_FLAGS_INIT "-m32" CACHE STRING "C flag which generates 32 bit code." ) +set( CMAKE_SHARED_LINKER_FLAGS "-m32" CACHE STRING "Linker flag which finds 32 bit code." ) +set( CMAKE_MODULE_LINKER_FLAGS "-m32" CACHE STRING "Linker flag which finds 32 bit code." ) +set( CMAKE_EXE_LINKER_FLAGS "-m32" CACHE STRING "Linker flag which finds 32 bit code." ) + +# Tell the 64 bit toolchain to generate a PE32 object file when running windres: +set( CMAKE_RC_FLAGS "-F pe-i386" CACHE STRING "windres flag which generates 32 bit code." ) + + # where is the target environment -set( CMAKE_FIND_ROOT_PATH /usr/i686-w64-mingw32 ) +set( CMAKE_FIND_ROOT_PATH /usr/x86_64-w64-mingw32 ) #---------------------------------------------------- diff --git a/pagelayout_editor/CMakeLists.txt b/pagelayout_editor/CMakeLists.txt index eecc08abd6..95ce1af27f 100644 --- a/pagelayout_editor/CMakeLists.txt +++ b/pagelayout_editor/CMakeLists.txt @@ -1,8 +1,6 @@ -add_definitions(-DPL_EDITOR) +set( MAKE_LINK_MAPS true ) -### -# Includes -### +add_definitions(-DPL_EDITOR) include_directories(BEFORE ${INC_BEFORE}) include_directories( @@ -11,12 +9,7 @@ include_directories( ${INC_AFTER} ) - -### -# Sources -### - -set(PL_EDITOR_SRCS +set( PL_EDITOR_SRCS dialogs/properties_frame_base.cpp dialogs/dialogs_for_printing.cpp dialogs/dialog_new_dataitem_base.cpp @@ -30,7 +23,6 @@ set(PL_EDITOR_SRCS onleftclick.cpp onrightclick.cpp page_layout_writer.cpp - pl_editor.cpp pl_editor_config.cpp pl_editor_frame.cpp pl_editor_undo_redo.cpp @@ -40,10 +32,7 @@ set(PL_EDITOR_SRCS toolbars_pl_editor.cpp ) -### -# We need some extra sources from common -### -set(PL_EDITOR_EXTRA_SRCS +set( PL_EDITOR_EXTRA_SRCS ../common/base_screen.cpp ../common/base_units.cpp ../common/eda_text.cpp @@ -51,58 +40,134 @@ set(PL_EDITOR_EXTRA_SRCS ../common/dialogs/dialog_page_settings.cpp ) -### -# Windows resource file -### -if(WIN32) - if(MINGW) - # PL_EDITOR_RESOURCES variable is set by the macro. - mingw_resource_compiler(pl_editor) - else(MINGW) - set(PL_EDITOR_RESOURCES pl_editor.rc) - endif(MINGW) -endif(WIN32) -### -# Apple resource files -### -if(APPLE) - set(PL_EDITOR_RESOURCES pl_editor.icns pl_editor_doc.icns) - set_source_files_properties("${CMAKE_CURRENT_SOURCE_DIR}/pl_editor.icns" - PROPERTIES MACOSX_PACKAGE_LOCATION Resources) - set_source_files_properties("${CMAKE_CURRENT_SOURCE_DIR}/pl_editor_doc.icns" - PROPERTIES MACOSX_PACKAGE_LOCATION Resources) - set(MACOSX_BUNDLE_ICON_FILE pl_editor.icns) - set(MACOSX_BUNDLE_GUI_IDENTIFIER org.kicad-eda.pl_editor) -endif(APPLE) +if( MINGW ) + # PL_EDITOR_RESOURCES variable is set by the macro. + mingw_resource_compiler(pl_editor) +endif() -### -# Create the pl_editor executable -### -add_executable(pl_editor WIN32 MACOSX_BUNDLE - ${PL_EDITOR_SRCS} - ${DIALOGS_SRCS} - ${PL_EDITOR_EXTRA_SRCS} - ${PL_EDITOR_RESOURCES}) -### -# Set properties for APPLE on pl_editor target -### -if(APPLE) - set_target_properties(pl_editor PROPERTIES MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/Info.plist) -endif(APPLE) +if( USE_KIWAY_DLLS ) -### -# Link executable target pl_editor with correct libraries -### -target_link_libraries(pl_editor common polygon bitmaps - ${OPENGL_LIBRARIES} - ${wxWidgets_LIBRARIES} - ${GDI_PLUS_LIBRARIES}) + # a very small program launcher for pl_editor_kiface + add_executable( pl_editor WIN32 MACOSX_BUNDLE + ../common/single_top.cpp + ../common/pgm_base.cpp + ${PL_EDITOR_RESOURCES} + ) + set_source_files_properties( ../common/single_top.cpp PROPERTIES + COMPILE_DEFINITIONS "TOP_FRAME=PL_EDITOR_FRAME_TYPE;PGM_DATA_FILE_EXT=\"kicad_wks\";BUILD_KIWAY_DLL" + ) + target_link_libraries( pl_editor + #singletop # replaces common, giving us restrictive control and link warnings. + # There's way too much crap coming in from common yet. + common + bitmaps + ${wxWidgets_LIBRARIES} + ) + if( MAKE_LINK_MAPS ) + set_target_properties( pl_editor PROPERTIES + LINK_FLAGS "${TO_LINKER},-cref ${TO_LINKER},-Map=pl_editor.map" ) + endif() -### -# Add pl_editor as install target -### -install(TARGETS pl_editor + # the main pl_editor program, in DSO form. + add_library( pl_editor_kiface MODULE + pl_editor.cpp + ${PL_EDITOR_SRCS} + ${DIALOGS_SRCS} + ${PL_EDITOR_EXTRA_SRCS} +# ${PL_EDITOR_RESOURCES} + ) + target_link_libraries( pl_editor_kiface + common + polygon + bitmaps + ${OPENGL_LIBRARIES} + ${wxWidgets_LIBRARIES} + ${GDI_PLUS_LIBRARIES} + ) + set_target_properties( pl_editor_kiface PROPERTIES + OUTPUT_NAME pl_editor + PREFIX ${KIFACE_PREFIX} + SUFFIX ${KIFACE_SUFFIX} + ) + set_source_files_properties( pl_editor.cpp PROPERTIES + # The KIFACE is in pcbnew.cpp, export it: + COMPILE_DEFINITIONS "BUILD_KIWAY_DLL;COMPILING_DLL" + ) + if( MAKE_LINK_MAPS ) + set_target_properties( pl_editor_kiface PROPERTIES + LINK_FLAGS "${TO_LINKER},-cref ${TO_LINKER},-Map=_pl_editor.kiface.map" ) + endif() + + # if building pl_editor, then also build pl_editor_kiface if out of date. + add_dependencies( pl_editor pl_editor_kiface ) + + # these 2 binaries are a matched set, keep them together: + install( TARGETS pl_editor DESTINATION ${KICAD_BIN} - COMPONENT binary) + COMPONENT binary + ) + install( TARGETS pl_editor_kiface + DESTINATION ${KICAD_BIN} + COMPONENT binary + ) + + if( APPLE ) + # copies kiface into the bundle + add_custom_target( _pleditor_kiface_copy ALL + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/pagelayout_editor/_pl_editor.kiface "${CMAKE_BINARY_DIR}/pagelayout_editor/pl_editor.app/Contents/MacOS/" + DEPENDS pl_editor_kiface + COMMENT "Copying kiface into pleditor" + ) + endif() + +else() + + add_executable( pl_editor WIN32 MACOSX_BUNDLE + pl_editor.cpp + ${PL_EDITOR_SRCS} + ${DIALOGS_SRCS} + ${PL_EDITOR_EXTRA_SRCS} + ${PL_EDITOR_RESOURCES} + ) + + if( APPLE ) + set_target_properties( pl_editor PROPERTIES + MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/Info.plist + ) + endif() + + target_link_libraries( pl_editor + common + polygon + bitmaps + ${OPENGL_LIBRARIES} + ${wxWidgets_LIBRARIES} + ${GDI_PLUS_LIBRARIES} + ) + + install( TARGETS pl_editor + DESTINATION ${KICAD_BIN} + COMPONENT binary + ) + +endif() + + +if( APPLE ) + set( PL_EDITOR_RESOURCES pl_editor.icns pl_editor_doc.icns ) + set_source_files_properties( "${CMAKE_CURRENT_SOURCE_DIR}/pl_editor.icns" PROPERTIES + MACOSX_PACKAGE_LOCATION Resources + ) + set_source_files_properties( "${CMAKE_CURRENT_SOURCE_DIR}/pl_editor_doc.icns" PROPERTIES + MACOSX_PACKAGE_LOCATION Resources + ) + set( MACOSX_BUNDLE_ICON_FILE pl_editor.icns ) + set( MACOSX_BUNDLE_GUI_IDENTIFIER org.kicad-eda.pl_editor ) + + set_target_properties( pl_editor PROPERTIES + MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/Info.plist + ) +endif() + diff --git a/pagelayout_editor/events_functions.cpp b/pagelayout_editor/events_functions.cpp index 0851057923..0473900644 100644 --- a/pagelayout_editor/events_functions.cpp +++ b/pagelayout_editor/events_functions.cpp @@ -28,7 +28,7 @@ #include #include -#include +#include #include #include #include diff --git a/pagelayout_editor/menubar.cpp b/pagelayout_editor/menubar.cpp index 77da7936db..7544f66dd8 100644 --- a/pagelayout_editor/menubar.cpp +++ b/pagelayout_editor/menubar.cpp @@ -29,15 +29,15 @@ #include -#include - +#include +#include #include #include #include #include -void PL_EDITOR_FRAME::ReCreateMenuBar( void ) +void PL_EDITOR_FRAME::ReCreateMenuBar() { // Create and try to get the current menubar wxMenuBar* menuBar = GetMenuBar(); @@ -74,11 +74,13 @@ void PL_EDITOR_FRAME::ReCreateMenuBar( void ) // Add this menu to list menu managed by m_fileHistory // (the file history will be updated when adding/removing files in history if( openRecentMenu ) - wxGetApp().GetFileHistory().RemoveMenu( openRecentMenu ); + Kiface().GetFileHistory().RemoveMenu( openRecentMenu ); openRecentMenu = new wxMenu(); - wxGetApp().GetFileHistory().UseMenu( openRecentMenu ); - wxGetApp().GetFileHistory().AddFilesToMenu(); + + Kiface().GetFileHistory().UseMenu( openRecentMenu ); + Kiface().GetFileHistory().AddFilesToMenu(); + AddMenuItem( fileMenu, openRecentMenu, wxID_ANY, _( "Open &Recent Page Layout File" ), wxEmptyString, KiBitmap( pagelayout_recent_xpm ) ); @@ -132,7 +134,7 @@ void PL_EDITOR_FRAME::ReCreateMenuBar( void ) KiBitmap( editor_xpm ) ); // Language submenu - wxGetApp().AddMenuLanguageList( preferencesMenu ); + Pgm().AddMenuLanguageList( preferencesMenu ); // Hotkey submenu AddHotkeyConfigMenu( preferencesMenu ); diff --git a/pagelayout_editor/pl_editor.cpp b/pagelayout_editor/pl_editor.cpp index f8657090dd..b96b07d4aa 100644 --- a/pagelayout_editor/pl_editor.cpp +++ b/pagelayout_editor/pl_editor.cpp @@ -28,7 +28,8 @@ */ #include -#include +//#include +#include #include #include #include @@ -43,24 +44,113 @@ extern EDA_COLOR_T g_DrawBgColor; -IMPLEMENT_APP( EDA_APP ) +namespace PGE { -/* MacOSX: Needed for file association - * http://wiki.wxwidgets.org/WxMac-specific_topics - */ -void EDA_APP::MacOpenFile( const wxString& aFileName ) +static struct IFACE : public KIFACE_I { - PL_EDITOR_FRAME* frame = ((PL_EDITOR_FRAME*)GetTopWindow()); - wxFileName filename = aFileName; + // Of course all are virtual overloads, implementations of the KIFACE. - if( !filename.FileExists() ) - return; + IFACE( const char* aName, KIWAY::FACE_T aType ) : + KIFACE_I( aName, aType ) + {} - frame->LoadPageLayoutDescrFile( aFileName ); + bool OnKifaceStart( PGM_BASE* aProgram ); + + void OnKifaceEnd(); + + wxWindow* CreateWindow( wxWindow* aParent, int aClassId, KIWAY* aKiway, int aCtlBits = 0 ) + { + switch( aClassId ) + { + case PL_EDITOR_FRAME_TYPE: + { + PL_EDITOR_FRAME* frame = new PL_EDITOR_FRAME( aKiway, aParent ); + + /* Is this really needed since at this point there is no open file? + frame->Zoom_Automatique( true ); // Zoom fit in frame + + if so, why is the constructor not doing it? + */ + + return frame; + } + break; + + default: + ; + } + + return NULL; + } + + /** + * Function IfaceOrAddress + * return a pointer to the requested object. The safest way to use this + * is to retrieve a pointer to a static instance of an interface, similar to + * how the KIFACE interface is exported. But if you know what you are doing + * use it to retrieve anything you want. + * + * @param aDataId identifies which object you want the address of. + * + * @return void* - and must be cast into the know type. + */ + void* IfaceOrAddress( int aDataId ) + { + return NULL; + } + +} kiface( "pl_editor", KIWAY::FACE_PL_EDITOR ); + +} // namespace + +using namespace PGE; + +static PGM_BASE* process; + +KIFACE_I& Kiface() { return kiface; } + + +// KIFACE_GETTER's actual spelling is a substitution macro found in kiway.h. +// KIFACE_GETTER will not have name mangling due to declaration in kiway.h. +MY_API( KIFACE* ) KIFACE_GETTER( int* aKIFACEversion, int aKiwayVersion, PGM_BASE* aProgram ) +{ + process = (PGM_BASE*) aProgram; + return &kiface; } -bool EDA_APP::OnInit() +PGM_BASE& Pgm() +{ + wxASSERT( process ); // KIFACE_GETTER has already been called. + return *process; +} + + +bool IFACE::OnKifaceStart( PGM_BASE* aProgram ) +{ + start_common(); + + // Must be called before creating the main frame in order to + // display the real hotkeys in menus or tool tips + ReadHotkeyConfig( wxT("PlEditorFrame"), s_PlEditor_Hokeys_Descr ); + + g_UserUnit = MILLIMETRES; + g_DrawBgColor = WHITE; + g_ShowPageLimits = true; + + return true; +} + + +void IFACE::OnKifaceEnd() +{ + end_common(); +} + + +#if 0 +bool MYFACE::OnKifaceStart( PGM_BASE* aProgram ) + { wxFileName fn; @@ -127,3 +217,4 @@ bool EDA_APP::OnInit() return true; } +#endif diff --git a/pagelayout_editor/pl_editor_config.cpp b/pagelayout_editor/pl_editor_config.cpp index b5b8f12866..1586a5ca2b 100644 --- a/pagelayout_editor/pl_editor_config.cpp +++ b/pagelayout_editor/pl_editor_config.cpp @@ -31,7 +31,7 @@ #include #include #include -#include +#include #include #include diff --git a/pagelayout_editor/pl_editor_frame.cpp b/pagelayout_editor/pl_editor_frame.cpp index f1f378deee..d5defe8d16 100644 --- a/pagelayout_editor/pl_editor_frame.cpp +++ b/pagelayout_editor/pl_editor_frame.cpp @@ -27,7 +27,8 @@ */ #include -#include +//#include +#include #include #include #include @@ -52,11 +53,9 @@ #define PL_EDITOR_FRAME_NAME wxT( "PlEditorFrame" ) -PL_EDITOR_FRAME::PL_EDITOR_FRAME( wxWindow* aParent, const wxString& aTitle, - const wxPoint& aPosition, const wxSize& aSize, - long aStyle ) : - EDA_DRAW_FRAME( aParent, PL_EDITOR_FRAME_TYPE, aTitle, aPosition, aSize, - aStyle, PL_EDITOR_FRAME_NAME ) +PL_EDITOR_FRAME::PL_EDITOR_FRAME( KIWAY* aKiway, wxWindow* aParent ) : + EDA_DRAW_FRAME( aKiway, aParent, PL_EDITOR_FRAME_TYPE, wxT( "PlEditorFrame" ), + wxDefaultPosition, wxDefaultSize, KICAD_DEFAULT_DRAWFRAME_STYLE, PL_EDITOR_FRAME_NAME ) { m_FrameName = PL_EDITOR_FRAME_NAME; @@ -79,8 +78,7 @@ PL_EDITOR_FRAME::PL_EDITOR_FRAME( wxWindow* aParent, const wxString& aTitle, wxSize pageSizeIU = GetPageLayout().GetPageSettings().GetSizeIU(); SetScreen( new PL_EDITOR_SCREEN( pageSizeIU ) ); - m_config = wxGetApp().GetSettings(); - LoadSettings(); + LoadSettings( config() ); SetSize( m_FramePos.x, m_FramePos.y, m_FrameSize.x, m_FrameSize.y ); if( m_LastGridSizeId < ID_POPUP_GRID_LEVEL_1MM-ID_POPUP_GRID_LEVEL_1000 ) @@ -181,6 +179,28 @@ PL_EDITOR_FRAME::~PL_EDITOR_FRAME() } +bool PL_EDITOR_FRAME::OpenProjectFiles( const std::vector& aFileSet, int aCtl ) +{ + wxString fn = aFileSet[0]; + + if( !LoadPageLayoutDescrFile( fn ) ) + { + wxString msg = wxString::Format( + _( "Error when loading file '%s'" ), + GetChars( fn ) + ); + + wxMessageBox( msg ); + return false; + } + else + { + OnNewPageLayout(); + return true; + } +} + + void PL_EDITOR_FRAME::OnCloseWindow( wxCloseEvent& Event ) { if( GetScreen()->IsModify() ) @@ -232,7 +252,8 @@ void PL_EDITOR_FRAME::OnCloseWindow( wxCloseEvent& Event ) // do not show the window because we do not want any paint event Show( false ); - wxGetApp().SaveCurrentSetupValues( m_configSettings ); + // was: Pgm().SaveCurrentSetupValues( m_configSettings ); + wxConfigSaveSetups( Kiface().KifaceSettings(), m_configSettings ); // On Linux, m_propertiesPagelayout must be destroyed // before deleting the main frame to avoid a crash when closing @@ -268,31 +289,29 @@ double PL_EDITOR_FRAME::BestZoom() #define PROPERTIES_FRAME_WIDTH_KEY wxT("PropertiesFrameWidth") #define CORNER_ORIGIN_CHOICE_KEY wxT("CornerOriginChoice") -void PL_EDITOR_FRAME::LoadSettings() +void PL_EDITOR_FRAME::LoadSettings( wxConfigBase* aCfg ) { - EDA_DRAW_FRAME::LoadSettings(); - m_config->Read( DESIGN_TREE_WIDTH_KEY, &m_designTreeWidth, 100); - m_config->Read( PROPERTIES_FRAME_WIDTH_KEY, &m_propertiesFrameWidth, 150); - m_config->Read( CORNER_ORIGIN_CHOICE_KEY, &m_originSelectChoice ); + EDA_DRAW_FRAME::LoadSettings( aCfg ); + + aCfg->Read( DESIGN_TREE_WIDTH_KEY, &m_designTreeWidth, 100); + aCfg->Read( PROPERTIES_FRAME_WIDTH_KEY, &m_propertiesFrameWidth, 150); + aCfg->Read( CORNER_ORIGIN_CHOICE_KEY, &m_originSelectChoice ); } -void PL_EDITOR_FRAME::SaveSettings() +void PL_EDITOR_FRAME::SaveSettings( wxConfigBase* aCfg ) { - wxConfig* config = wxGetApp().GetSettings(); - - if( config == NULL ) - return; + EDA_DRAW_FRAME::SaveSettings( aCfg ); m_designTreeWidth = m_treePagelayout->GetSize().x; m_propertiesFrameWidth = m_propertiesPagelayout->GetSize().x; - EDA_DRAW_FRAME::SaveSettings(); - m_config->Write( DESIGN_TREE_WIDTH_KEY, m_designTreeWidth); - m_config->Write( PROPERTIES_FRAME_WIDTH_KEY, m_propertiesFrameWidth); - m_config->Write( CORNER_ORIGIN_CHOICE_KEY, m_originSelectChoice ); + aCfg->Write( DESIGN_TREE_WIDTH_KEY, m_designTreeWidth); + aCfg->Write( PROPERTIES_FRAME_WIDTH_KEY, m_propertiesFrameWidth); + aCfg->Write( CORNER_ORIGIN_CHOICE_KEY, m_originSelectChoice ); - wxGetApp().SaveCurrentSetupValues( GetConfigurationSettings() ); + // was: wxGetApp().SaveCurrentSetupValues( GetConfigurationSettings() ); + wxConfigSaveSetups( aCfg, GetConfigurationSettings() ); } diff --git a/pagelayout_editor/pl_editor_frame.h b/pagelayout_editor/pl_editor_frame.h index c88ed638eb..7ba3a8dc15 100644 --- a/pagelayout_editor/pl_editor_frame.h +++ b/pagelayout_editor/pl_editor_frame.h @@ -30,8 +30,8 @@ #define _PL_EDITOR_FRAME_H -#include -#include +#include +#include #include #include #include @@ -40,22 +40,23 @@ class PROPERTIES_FRAME; class DESIGN_TREE_FRAME; class WORKSHEET_DATAITEM; + /** * Class PL_EDITOR_FRAME * is the main window used in the page layout editor. */ - class PL_EDITOR_FRAME : public EDA_DRAW_FRAME { PL_EDITOR_LAYOUT m_pageLayout; - int m_designTreeWidth; // the last width (in pixels) of m_treePagelayout - int m_propertiesFrameWidth; // the last width (in pixels) of m_propertiesPagelayout - wxConfig* m_config; - wxChoice* m_originSelectBox; // Corner origin choice for coordinates - int m_originSelectChoice; // the last choice for m_originSelectBox - wxChoice* m_pageSelectBox; // The page number sel'ector (page 1 or other pages - // usefull when there are some items which are - // only on page 1, not on page 1 + + int m_designTreeWidth; // the last width (in pixels) of m_treePagelayout + int m_propertiesFrameWidth; // the last width (in pixels) of m_propertiesPagelayout + + wxChoice* m_originSelectBox; // Corner origin choice for coordinates + int m_originSelectChoice; // the last choice for m_originSelectBox + wxChoice* m_pageSelectBox; // The page number sel'ector (page 1 or other pages + // usefull when there are some items which are + // only on page 1, not on page 1 wxPoint m_grid_origin; @@ -70,12 +71,33 @@ private: PARAM_CFG_ARRAY m_configSettings; public: - PL_EDITOR_FRAME( wxWindow* aParent, const wxString& aTitle, - const wxPoint& aPosition, const wxSize& aSize, - long aStyle = KICAD_DEFAULT_DRAWFRAME_STYLE ); - + PL_EDITOR_FRAME( KIWAY* aKiway, wxWindow* aParent ); ~PL_EDITOR_FRAME(); + bool OpenProjectFiles( const std::vector& aFileSet, int aCtl ); // overload KIWAY_PLAYER + + /** + * Function LoadPageLayoutDescrFile + * Loads a .kicad_wks page layout descr file + * @param aFullFileName = the filename. + */ + bool LoadPageLayoutDescrFile( const wxString& aFullFileName ); + + /** + * Function SavePageLayoutDescrFile + * Save the current layout in a .kicad_wks page layout descr file + * @param aFullFileName = the filename. + */ + bool SavePageLayoutDescrFile( const wxString& aFullFileName ); + + /** + * Function InsertPageLayoutDescrFile + * Loads a .kicad_wks page layout descr file, and add items + * to the current layout list + * @param aFullFileName = the filename. + */ + bool InsertPageLayoutDescrFile( const wxString& aFullFileName ); + void OnCloseWindow( wxCloseEvent& Event ); // Virtual basic functions: @@ -172,23 +194,9 @@ public: */ PARAM_CFG_ARRAY& GetConfigurationSettings( void ); - /** - * Load applications settings specific to page layout editor. - * - * This overrides the base class EDA_DRAW_FRAME::LoadSettings(). - */ - virtual void LoadSettings(); + void LoadSettings( wxConfigBase* aCfg ); // override virtual - /** - * Save applications settings common to PCB draw frame objects. - * - * This overrides the base class EDA_DRAW_FRAME::SaveSettings() to - * save settings specific to the application main window. It - * calls down to the base class to save settings common to all - * drawing frames. Please put your application settings for pl editor here - * to avoid having application settings saved all over the place. - */ - virtual void SaveSettings(); + void SaveSettings( wxConfigBase* aCfg ); // override virtual /** * Function SetLanguage @@ -266,28 +274,6 @@ public: void OnFileHistory( wxCommandEvent& event ); - /** - * Function LoadPageLayoutDescrFile - * Loads a .kicad_wks page layout descr file - * @param aFullFileName = the filename. - */ - bool LoadPageLayoutDescrFile( const wxString& aFullFileName ); - - /** - * Function SavePageLayoutDescrFile - * Save the current layout in a .kicad_wks page layout descr file - * @param aFullFileName = the filename. - */ - bool SavePageLayoutDescrFile( const wxString& aFullFileName ); - - /** - * Function InsertPageLayoutDescrFile - * Loads a .kicad_wks page layout descr file, and add items - * to the current layout list - * @param aFullFileName = the filename. - */ - bool InsertPageLayoutDescrFile( const wxString& aFullFileName ); - /** * @return the filename of the current layout descr file * If this is the default (no loaded file) returns a emtpy name diff --git a/pcb_calculator/CMakeLists.txt b/pcb_calculator/CMakeLists.txt index 4bbd5be02d..fb8e189859 100644 --- a/pcb_calculator/CMakeLists.txt +++ b/pcb_calculator/CMakeLists.txt @@ -1,5 +1,5 @@ -include_directories(BEFORE ${INC_BEFORE}) +include_directories( BEFORE ${INC_BEFORE} ) include_directories( bitmaps dialogs @@ -10,13 +10,12 @@ include_directories( ${INC_AFTER} ) -set(PCB_CALCULATOR_SRCS +set( PCB_CALCULATOR_SRCS attenuators.cpp board_classes_values.cpp colorcode.cpp electrical_spacing_values.cpp params_read_write.cpp - pcb_calculator.cpp pcb_calculator_frame.cpp datafile_read_write.cpp regulators_funct.cpp @@ -38,24 +37,21 @@ set(PCB_CALCULATOR_SRCS dialogs/dialog_regulator_data_base.cpp ) -if(WIN32) - if(MINGW) - # PCB_CALCULATOR_RESOURCES variable is set by the macro. - mingw_resource_compiler(pcb_calculator) - else(MINGW) - set(PCB_CALCULATOR_RESOURCES pcb_calculator.rc) - endif(MINGW) -endif(WIN32) +if( MINGW ) + # PCB_CALCULATOR_RESOURCES variable is set by the macro. + mingw_resource_compiler(pcb_calculator) +endif() -if(APPLE) - set(PCB_CALCULATOR_RESOURCES pcb_calculator.icns) - set_source_files_properties("${CMAKE_CURRENT_SOURCE_DIR}/pcb_calculator.icns" - PROPERTIES MACOSX_PACKAGE_LOCATION Resources) - set(MACOSX_BUNDLE_ICON_FILE pcb_calculator.icns) - set(MACOSX_BUNDLE_GUI_IDENTIFIER org.kicad-eda.pcb_calculator) - set(MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/Info.plist) -endif(APPLE) +if( APPLE ) + set( PCB_CALCULATOR_RESOURCES pcb_calculator.icns ) + set_source_files_properties("${CMAKE_CURRENT_SOURCE_DIR}/pcb_calculator.icns" PROPERTIES + MACOSX_PACKAGE_LOCATION Resources + ) + set( MACOSX_BUNDLE_ICON_FILE pcb_calculator.icns ) + set( MACOSX_BUNDLE_GUI_IDENTIFIER org.kicad-eda.pcb_calculator ) + set( MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/Info.plist ) +endif() # auto-generate pcb_calculator_datafile.h and pcb_calculator_datafile_keywords.cpp # for the storage data file format. @@ -70,25 +66,113 @@ make_lexer( ) -add_executable(pcb_calculator WIN32 MACOSX_BUNDLE - ${PCB_CALCULATOR_SRCS} - ${PCB_CALCULATOR_RESOURCES} - ) +if( USE_KIWAY_DLLS ) +#if( false ) + add_executable( pcb_calculator WIN32 MACOSX_BUNDLE + ../common/single_top.cpp + ../common/pgm_base.cpp + ${PCB_CALCULATOR_RESOURCES} + ) + set_source_files_properties( ../common/single_top.cpp PROPERTIES + COMPILE_DEFINITIONS "TOP_FRAME=0;BUILD_KIWAY_DLL" + ) + target_link_libraries( pcb_calculator + #singletop # replaces common, giving us restrictive control and link warnings. + # There's way too much crap coming in from common yet. + common + bitmaps + ${wxWidgets_LIBRARIES} + ) + if( MAKE_LINK_MAPS ) + set_target_properties( pcb_calculator PROPERTIES + LINK_FLAGS "${TO_LINKER},-cref ${TO_LINKER},-Map=pcb_calculator.map" ) + endif() -if(APPLE) - set_target_properties(pcb_calculator PROPERTIES MACOSX_BUNDLE_INFO_PLIST - ${CMAKE_CURRENT_SOURCE_DIR}/Info.plist) -endif(APPLE) + # the main pcb_calculator program, in DSO form. + add_library( pcb_calculator_kiface MODULE + pcb_calculator.cpp + ${PCB_CALCULATOR_SRCS} +# ${PCB_CALCULATOR_RESOURCES} + ) + set_target_properties( pcb_calculator_kiface PROPERTIES + OUTPUT_NAME pcb_calculator + PREFIX ${KIFACE_PREFIX} + SUFFIX ${KIFACE_SUFFIX} + ) + target_link_libraries( pcb_calculator_kiface + common + bitmaps + polygon + ${wxWidgets_LIBRARIES} + ) + set_source_files_properties( pcb_calculator.cpp PROPERTIES + # The KIFACE is in pcb_calculator.cpp, export it: + COMPILE_DEFINITIONS "BUILD_KIWAY_DLL;COMPILING_DLL" + ) + if( MAKE_LINK_MAPS ) + set_target_properties( pcb_calculator_kiface PROPERTIES + LINK_FLAGS "${TO_LINKER},-cref ${TO_LINKER},-Map=_pcb_calculator.kiface.map" ) + endif() -target_link_libraries( pcb_calculator - common - bitmaps - polygon - ${wxWidgets_LIBRARIES} - ) + # if building pcb_calculator, then also build pcb_calculator_kiface if out of date. + add_dependencies( pcb_calculator pcb_calculator_kiface ) -install(TARGETS pcb_calculator + # these 2 binaries are a matched set, keep them together + install( TARGETS pcb_calculator DESTINATION ${KICAD_BIN} - COMPONENT binary) + COMPONENT binary + ) + install( TARGETS pcb_calculator_kiface + DESTINATION ${KICAD_BIN} + COMPONENT binary + ) + if( APPLE ) + set_target_properties( pcb_calculator PROPERTIES + MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/Info.plist + ) + endif() + + if( APPLE ) + # copies kiface into the bundle + add_custom_target( _pcb_calculator_kiface_copy ALL + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/pcb_calculator/_pcb_calculator.kiface "${CMAKE_BINARY_DIR}/pcb_calculator/pcb_calculator.app/Contents/MacOS/" + DEPENDS pcb_calculator_kiface + COMMENT "Copying kiface into pcb_calculator" + ) + endif() + +else() + + add_executable( pcb_calculator WIN32 MACOSX_BUNDLE + ../common/single_top.cpp + pcb_calculator.cpp + ${PCB_CALCULATOR_SRCS} + ${PCB_CALCULATOR_RESOURCES} + ) + set_source_files_properties( ../common/single_top.cpp PROPERTIES + COMPILE_DEFINITIONS "TOP_FRAME=0" + ) + set_source_files_properties( pcb_calculator.cpp PROPERTIES + COMPILE_DEFINITIONS "COMPILING_DLL" + ) + + if( APPLE ) + set_target_properties( pcb_calculator PROPERTIES + MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/Info.plist + ) + endif() + + target_link_libraries( pcb_calculator + common + bitmaps + polygon + ${wxWidgets_LIBRARIES} + ) + install( TARGETS pcb_calculator + DESTINATION ${KICAD_BIN} + COMPONENT binary + ) + +endif() diff --git a/pcb_calculator/attenuators.cpp b/pcb_calculator/attenuators.cpp index 18c02cd448..b2f27a2c58 100644 --- a/pcb_calculator/attenuators.cpp +++ b/pcb_calculator/attenuators.cpp @@ -30,7 +30,7 @@ #include #include -extern double ReturnDoubleFromString( const wxString& TextValue ); +extern double DoubleFromString( const wxString& TextValue ); // Called on a attenuator selection void PCB_CALCULATOR_FRAME::OnAttenuatorSelection( wxCommandEvent& event ) @@ -66,11 +66,11 @@ void PCB_CALCULATOR_FRAME::TransfPanelDataToAttenuator() wxString msg; msg = m_AttValueCtrl->GetValue(); - m_currAttenuator->m_Attenuation = ReturnDoubleFromString(msg); + m_currAttenuator->m_Attenuation = DoubleFromString(msg); msg = m_ZinValueCtrl->GetValue(); - m_currAttenuator->m_Zin = ReturnDoubleFromString(msg); + m_currAttenuator->m_Zin = DoubleFromString(msg); msg = m_ZoutValueCtrl->GetValue(); - m_currAttenuator->m_Zout = ReturnDoubleFromString(msg); + m_currAttenuator->m_Zout = DoubleFromString(msg); } diff --git a/pcb_calculator/attenuators/attenuator_classes.cpp b/pcb_calculator/attenuators/attenuator_classes.cpp index 122480ec39..ebec3d887e 100644 --- a/pcb_calculator/attenuators/attenuator_classes.cpp +++ b/pcb_calculator/attenuators/attenuator_classes.cpp @@ -52,7 +52,7 @@ ATTENUATOR::~ATTENUATOR() #define KEYWORD_ATTENUATOR_ZOUT wxT( "Zout" ) #define KEYWORD_ATTENUATORS wxT( "Attenuators/" ) -void ATTENUATOR::ReadConfig( wxConfig* aConfig ) +void ATTENUATOR::ReadConfig( wxConfigBase* aConfig ) { aConfig->SetPath( KEYWORD_ATTENUATORS + m_Name ); if( m_Attenuation_Enable ) @@ -63,7 +63,7 @@ void ATTENUATOR::ReadConfig( wxConfig* aConfig ) } -void ATTENUATOR::WriteConfig( wxConfig* aConfig ) +void ATTENUATOR::WriteConfig( wxConfigBase* aConfig ) { aConfig->SetPath( KEYWORD_ATTENUATORS + m_Name ); aConfig->Write( KEYWORD_ATTENUATOR_ATT, m_Attenuation ); diff --git a/pcb_calculator/attenuators/attenuator_classes.h b/pcb_calculator/attenuators/attenuator_classes.h index 65a3705ee9..a2014fa4a2 100644 --- a/pcb_calculator/attenuators/attenuator_classes.h +++ b/pcb_calculator/attenuators/attenuator_classes.h @@ -64,14 +64,14 @@ public: * Read values stored in config for this attenuator * @param aConfig = the config to use */ - void ReadConfig( wxConfig* aConfig ); + void ReadConfig( wxConfigBase* aConfig ); /** * Function WriteConfig * Read values stored in config for this attenuator * @param aConfig = the config to use */ - void WriteConfig( wxConfig* aConfig ); + void WriteConfig( wxConfigBase* aConfig ); }; class ATTENUATOR_PI : public ATTENUATOR diff --git a/pcb_calculator/datafile_read_write.cpp b/pcb_calculator/datafile_read_write.cpp index 618e426166..aef8427ca9 100644 --- a/pcb_calculator/datafile_read_write.cpp +++ b/pcb_calculator/datafile_read_write.cpp @@ -29,7 +29,7 @@ #include #include #include -#include +#include #include #include #include @@ -127,7 +127,7 @@ int PCB_CALCULATOR_DATAFILE::WriteHeader( OUTPUTFORMATTER* aFormatter ) const th aFormatter->Print( nestlevel++, "(date %s)\n", aFormatter->Quotew( DateAndTime() ).c_str() ); aFormatter->Print( nestlevel++, "(tool %s)\n", - aFormatter->Quotew( wxGetApp().GetAppName() + + aFormatter->Quotew( Pgm().App().GetAppName() + wxChar(' ') + GetBuildVersion() ).c_str() ); return nestlevel; diff --git a/pcb_calculator/dialogs/pcb_calculator_frame_base.cpp b/pcb_calculator/dialogs/pcb_calculator_frame_base.cpp index abb5da9576..c20b6b5080 100644 --- a/pcb_calculator/dialogs/pcb_calculator_frame_base.cpp +++ b/pcb_calculator/dialogs/pcb_calculator_frame_base.cpp @@ -1,5 +1,5 @@ /////////////////////////////////////////////////////////////////////////// -// C++ code generated with wxFormBuilder (version Oct 8 2012) +// C++ code generated with wxFormBuilder (version Nov 5 2013) // http://www.wxformbuilder.org/ // // PLEASE DO "NOT" EDIT THIS FILE! @@ -20,7 +20,7 @@ /////////////////////////////////////////////////////////////////////////// -PCB_CALCULATOR_FRAME_BASE::PCB_CALCULATOR_FRAME_BASE( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxFrame( parent, id, title, pos, size, style ) +PCB_CALCULATOR_FRAME_BASE::PCB_CALCULATOR_FRAME_BASE( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : KIWAY_PLAYER( parent, id, title, pos, size, style ) { this->SetSizeHints( wxDefaultSize, wxDefaultSize ); diff --git a/pcb_calculator/dialogs/pcb_calculator_frame_base.fbp b/pcb_calculator/dialogs/pcb_calculator_frame_base.fbp index 5970dafbc8..da5cd391c3 100644 --- a/pcb_calculator/dialogs/pcb_calculator_frame_base.fbp +++ b/pcb_calculator/dialogs/pcb_calculator_frame_base.fbp @@ -20,8 +20,10 @@ . 1 + 1 1 1 + UI 0 0 @@ -44,7 +46,7 @@ 670,489 wxDEFAULT_FRAME_STYLE|wxRESIZE_BORDER - + KIWAY_PLAYER; kiway_player.h Pcb Calculator @@ -472,7 +474,7 @@ - Load From File; F:\kicad-launchpad\testing\pcb_calculator\bitmaps\regul_3pins.xpm + Load From File; ../bitmaps/regul_3pins.xpm 1 0 @@ -3266,7 +3268,7 @@ Track Width 0 - + 1 1 1 @@ -7332,7 +7334,7 @@ Electrical Spacing 0 - + 1 1 1 @@ -8180,7 +8182,7 @@ TransLine 0 - + 1 1 1 @@ -14621,7 +14623,7 @@ RF Attenuators 0 - + 1 1 1 @@ -16952,11 +16954,11 @@ - + Color Code 0 - + 1 1 1 @@ -18130,11 +18132,11 @@ - + Board Classes 0 - + 1 1 1 diff --git a/pcb_calculator/dialogs/pcb_calculator_frame_base.h b/pcb_calculator/dialogs/pcb_calculator_frame_base.h index 117707e747..4c6c666d59 100644 --- a/pcb_calculator/dialogs/pcb_calculator_frame_base.h +++ b/pcb_calculator/dialogs/pcb_calculator_frame_base.h @@ -1,5 +1,5 @@ /////////////////////////////////////////////////////////////////////////// -// C++ code generated with wxFormBuilder (version Oct 8 2012) +// C++ code generated with wxFormBuilder (version Nov 5 2013) // http://www.wxformbuilder.org/ // // PLEASE DO "NOT" EDIT THIS FILE! @@ -11,11 +11,13 @@ #include #include #include +class KIWAY_PLAYER; class UNIT_SELECTOR_ANGLE; class UNIT_SELECTOR_FREQUENCY; class UNIT_SELECTOR_LEN; class UNIT_SELECTOR_RESISTOR; +#include "kiway_player.h" #include #include #include @@ -48,7 +50,7 @@ class UNIT_SELECTOR_RESISTOR; /////////////////////////////////////////////////////////////////////////////// /// Class PCB_CALCULATOR_FRAME_BASE /////////////////////////////////////////////////////////////////////////////// -class PCB_CALCULATOR_FRAME_BASE : public wxFrame +class PCB_CALCULATOR_FRAME_BASE : public KIWAY_PLAYER { private: diff --git a/pcb_calculator/electrical_spacing_values.cpp b/pcb_calculator/electrical_spacing_values.cpp index 66609d3533..5a9213b61f 100644 --- a/pcb_calculator/electrical_spacing_values.cpp +++ b/pcb_calculator/electrical_spacing_values.cpp @@ -30,7 +30,7 @@ #include #include -extern double ReturnDoubleFromString( const wxString& TextValue ); +extern double DoubleFromString( const wxString& TextValue ); #define VALUE_COUNT 7 @@ -122,7 +122,7 @@ void PCB_CALCULATOR_FRAME::ElectricalSpacingUpdateData( double aUnitScale ) double voltage = 500.0; // to calculate values at V > 500V txt = m_ElectricalSpacingVoltage->GetValue(); if( ! txt.IsEmpty() ) - voltage = ReturnDoubleFromString(txt); + voltage = DoubleFromString(txt); if( voltage < 500.0 ) voltage = 500.0; txt.Printf( wxT( "%g" ), voltage ); diff --git a/pcb_calculator/params_read_write.cpp b/pcb_calculator/params_read_write.cpp index b1f787c8ef..2261943f4b 100644 --- a/pcb_calculator/params_read_write.cpp +++ b/pcb_calculator/params_read_write.cpp @@ -39,7 +39,7 @@ * but units are ignored. * notation like 1e+3 is legal */ -double ReturnDoubleFromString( const wxString& TextValue ) +double DoubleFromString( const wxString& TextValue ) { double value = 0; diff --git a/pcb_calculator/pcb_calculator.cpp b/pcb_calculator/pcb_calculator.cpp index adeae6d2a6..cfec7e2135 100644 --- a/pcb_calculator/pcb_calculator.cpp +++ b/pcb_calculator/pcb_calculator.cpp @@ -22,7 +22,8 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #include -#include +#include +#include #include #include #include @@ -43,24 +44,88 @@ const wxString PcbCalcDataFileExt( wxT("pcbcalc") ); // PCB_CALCULATOR_APP -void EDA_APP::MacOpenFile( const wxString& aFileName ) + +namespace PCBCALC { + +static struct IFACE : public KIFACE_I { + // Of course all are virtual overloads, implementations of the KIFACE. + + IFACE( const char* aName, KIWAY::FACE_T aType ) : + KIFACE_I( aName, aType ) + {} + + bool OnKifaceStart( PGM_BASE* aProgram ); + + void OnKifaceEnd(); + + wxWindow* CreateWindow( wxWindow* aParent, int aClassId, KIWAY* aKiway, int aCtlBits = 0 ) + { + switch( aClassId ) + { + default: + { + PCB_CALCULATOR_FRAME* frame = new PCB_CALCULATOR_FRAME( aKiway, aParent ); + return frame; + } + break; + } + + return NULL; + } + + /** + * Function IfaceOrAddress + * return a pointer to the requested object. The safest way to use this + * is to retrieve a pointer to a static instance of an interface, similar to + * how the KIFACE interface is exported. But if you know what you are doing + * use it to retrieve anything you want. + * + * @param aDataId identifies which object you want the address of. + * + * @return void* - and must be cast into the know type. + */ + void* IfaceOrAddress( int aDataId ) + { + return NULL; + } + +} kiface( "pcb_calculator", KIWAY::FACE_PCB_CALCULATOR ); + +} // namespace + +using namespace PCBCALC; + +static PGM_BASE* process; + +KIFACE_I& Kiface() { return kiface; } + + +// KIFACE_GETTER's actual spelling is a substitution macro found in kiway.h. +// KIFACE_GETTER will not have name mangling due to declaration in kiway.h. +MY_API( KIFACE* ) KIFACE_GETTER( int* aKIFACEversion, int aKiwayVersion, PGM_BASE* aProgram ) +{ + process = (PGM_BASE*) aProgram; + return &kiface; } -IMPLEMENT_APP( EDA_APP ) -///----------------------------------------------------------------------------- -// PCB_CALCULATOR_APP -// main program -//----------------------------------------------------------------------------- - -bool EDA_APP::OnInit() +PGM_BASE& Pgm() { - InitEDA_Appl( wxT( "pcb_calculator" ) ); + wxASSERT( process ); // KIFACE_GETTER has already been called. + return *process; +} - wxFrame* frame = new PCB_CALCULATOR_FRAME( NULL ); - SetTopWindow( frame ); - frame->Show( true ); + +bool IFACE::OnKifaceStart( PGM_BASE* aProgram ) +{ + start_common(); return true; } + + +void IFACE::OnKifaceEnd() +{ + end_common(); +} diff --git a/pcb_calculator/pcb_calculator.h b/pcb_calculator/pcb_calculator.h index 4c09da39d9..0c3633a5ca 100644 --- a/pcb_calculator/pcb_calculator.h +++ b/pcb_calculator/pcb_calculator.h @@ -29,7 +29,7 @@ private: wxSize m_FrameSize; wxPoint m_FramePos; wxConfig * m_Config; - enum transline_type_id m_currTransLineType; + enum TRANSLINE_TYPE_ID m_currTransLineType; TRANSLINE * m_currTransLine; // a pointer to the active transline // List of translines: ordered like in dialog menu list std::vector m_transline_list; @@ -40,13 +40,13 @@ private: public: - PCB_CALCULATOR_FRAME( wxWindow * parent = NULL ); + PCB_CALCULATOR_FRAME( KIWAY* aKiway, wxWindow* aParent ); ~PCB_CALCULATOR_FRAME(); private: // Event handlers - void OnClosePcbCalc( wxCloseEvent& event ); + void OnClosePcbCalc( wxCloseEvent& event ); // These 3 functions are called by the OnPaint event, to draw // icons that show the current item on the specific panels @@ -153,9 +153,9 @@ private: * Update all values, labels and tool tips of parameters needed * by the new transline * Irrelevant parameters texts are blanked. - * @param aType = the transline_type_id of the new selected transline + * @param aType = the TRANSLINE_TYPE_ID of the new selected transline */ - void TranslineTypeSelection( enum transline_type_id aType ); + void TranslineTypeSelection( enum TRANSLINE_TYPE_ID aType ); /** * Function TransfDlgDataToTranslineParams @@ -178,12 +178,12 @@ private: // Regulators Panel void OnRegulatorCalcButtonClick( wxCommandEvent& event ); - void OnRegulTypeSelection( wxCommandEvent& event ); - void OnRegulatorSelection( wxCommandEvent& event ); - void OnDataFileSelection( wxCommandEvent& event ); - void OnAddRegulator( wxCommandEvent& event ); - void OnEditRegulator( wxCommandEvent& event ); - void OnRemoveRegulator( wxCommandEvent& event ); + void OnRegulTypeSelection( wxCommandEvent& event ); + void OnRegulatorSelection( wxCommandEvent& event ); + void OnDataFileSelection( wxCommandEvent& event ); + void OnAddRegulator( wxCommandEvent& event ); + void OnEditRegulator( wxCommandEvent& event ); + void OnRemoveRegulator( wxCommandEvent& event ); /** * Function RegulatorPageUpdate: diff --git a/pcb_calculator/pcb_calculator_frame.cpp b/pcb_calculator/pcb_calculator_frame.cpp index ab32faa8bd..7981201e25 100644 --- a/pcb_calculator/pcb_calculator_frame.cpp +++ b/pcb_calculator/pcb_calculator_frame.cpp @@ -52,21 +52,23 @@ // extention of pcb_calculator data filename: const wxString DataFileNameExt( wxT("pcbcalc") ); -PCB_CALCULATOR_FRAME::PCB_CALCULATOR_FRAME( wxWindow* parent ) : - PCB_CALCULATOR_FRAME_BASE( parent ) +PCB_CALCULATOR_FRAME::PCB_CALCULATOR_FRAME( KIWAY* aKiway, wxWindow* aParent ) : + PCB_CALCULATOR_FRAME_BASE( aParent ) { + SetKiway( this, aKiway ); + m_currTransLine = NULL; - m_currTransLineType = default_type; + m_currTransLineType = DEFAULT_TYPE; m_currAttenuator = NULL; m_RegulatorListChanged = false; m_Config = new wxConfig(); // Populate transline list ordered like in dialog menu list - transline_type_id tltype_list[8] = + const static TRANSLINE_TYPE_ID tltype_list[8] = { - microstrip_type, cpw_type, grounded_cpw_type, - rectwaveguide_type, coax_type, c_microstrip_type, - stripline_type, twistedpair_type + MICROSTRIP_TYPE, CPW_TYPE, GROUNDED_CPW_TYPE, + RECTWAVEGUIDE_TYPE, COAX_TYPE, C_MICROSTRIP_TYPE, + STRIPLINE_TYPE, TWISTEDPAIR_TYPE }; for( int ii = 0; ii < 8; ii++ ) @@ -175,8 +177,8 @@ void PCB_CALCULATOR_FRAME::ReadConfig() m_Config->Read( KEYWORD_FRAME_POSY, &m_FramePos.y, -1 ); m_Config->Read( KEYWORD_FRAME_SIZEX, &m_FrameSize.x, -1 ); m_Config->Read( KEYWORD_FRAME_SIZEY, &m_FrameSize.y, -1 ); - m_Config->Read( KEYWORD_TRANSLINE_SELECTION, <mp, (long) default_type ); - m_currTransLineType = (enum transline_type_id) ltmp; + m_Config->Read( KEYWORD_TRANSLINE_SELECTION, <mp, (long) DEFAULT_TYPE ); + m_currTransLineType = (enum TRANSLINE_TYPE_ID) ltmp; m_Config->Read( KEYWORD_PAGE_SELECTION, <mp, 0 ); m_Notebook->ChangeSelection( ltmp ); m_Config->Read( KEYWORD_COLORCODE_SELECTION, <mp, 1 ); diff --git a/pcb_calculator/regulators_funct.cpp b/pcb_calculator/regulators_funct.cpp index 97dd64ee9c..d8995f48ea 100644 --- a/pcb_calculator/regulators_funct.cpp +++ b/pcb_calculator/regulators_funct.cpp @@ -33,7 +33,7 @@ #include -extern double ReturnDoubleFromString( const wxString& TextValue ); +extern double DoubleFromString( const wxString& TextValue ); class DIALOG_EDITOR_DATA: public DIALOG_EDITOR_DATA_BASE { @@ -49,7 +49,7 @@ public: ~DIALOG_EDITOR_DATA() {}; // Event called functions: - void OnOKClick( wxCommandEvent& event ); + void OnOKClick( wxCommandEvent& event ); /** * Function IsOK() @@ -113,7 +113,7 @@ bool DIALOG_EDITOR_DATA::IsOK() ok = false; else { - double vref = ReturnDoubleFromString( m_textCtrlVref->GetValue() ); + double vref = DoubleFromString( m_textCtrlVref->GetValue() ); if( fabs(vref) < 0.01 ) ok = false; } @@ -140,8 +140,8 @@ void DIALOG_EDITOR_DATA::CopyRegulatorDataToDialog( REGULATOR_DATA * aItem ) REGULATOR_DATA * DIALOG_EDITOR_DATA::BuildRegulatorFromData() { - double vref = ReturnDoubleFromString( m_textCtrlVref->GetValue() ); - double iadj = ReturnDoubleFromString( m_RegulIadjValue->GetValue() ); + double vref = DoubleFromString( m_textCtrlVref->GetValue() ); + double iadj = DoubleFromString( m_RegulIadjValue->GetValue() ); int type = m_choiceRegType->GetSelection(); if( type != 1 ) iadj = 0.0; @@ -382,13 +382,13 @@ void PCB_CALCULATOR_FRAME::RegulatorsSolve() // Read values from panel: txt = m_RegulR1Value->GetValue(); - r1 = ReturnDoubleFromString(txt) * r1scale; + r1 = DoubleFromString(txt) * r1scale; txt = m_RegulR2Value->GetValue(); - r2 = ReturnDoubleFromString(txt) * r2scale; + r2 = DoubleFromString(txt) * r2scale; txt = m_RegulVrefValue->GetValue(); - vref = ReturnDoubleFromString(txt); + vref = DoubleFromString(txt); txt = m_RegulVoutValue->GetValue(); - vout = ReturnDoubleFromString(txt); + vout = DoubleFromString(txt); // Some tests: @@ -415,7 +415,7 @@ void PCB_CALCULATOR_FRAME::RegulatorsSolve() { // 3 terminal regulator txt = m_RegulIadjValue->GetValue(); - double iadj = ReturnDoubleFromString(txt); + double iadj = DoubleFromString(txt); // iadj is given in micro amp, so convert it in amp. iadj /= 1000000; diff --git a/pcb_calculator/tracks_width_versus_current.cpp b/pcb_calculator/tracks_width_versus_current.cpp index 3145f87524..4c759bbd61 100644 --- a/pcb_calculator/tracks_width_versus_current.cpp +++ b/pcb_calculator/tracks_width_versus_current.cpp @@ -38,7 +38,7 @@ #include #include -extern double ReturnDoubleFromString( const wxString& TextValue ); +extern double DoubleFromString( const wxString& TextValue ); // Key words to read/write some parameters in config: #define KEYWORD_TW_CURRENT wxT( "TW_Track_Current" ) @@ -68,10 +68,10 @@ void PCB_CALCULATOR_FRAME::TW_WriteConfig() void PCB_CALCULATOR_FRAME::OnTWCalculateButt( wxCommandEvent& event ) { // Prepare parameters: - double current = std::abs( ReturnDoubleFromString( m_TrackCurrentValue->GetValue() ) ); - double thickness = std::abs( ReturnDoubleFromString( m_TrackThicknessValue->GetValue() ) ); - double deltaT_C = std::abs( ReturnDoubleFromString( m_TrackDeltaTValue->GetValue() ) ); - double track_len = std::abs( ReturnDoubleFromString( m_TrackLengthValue->GetValue() ) ); + double current = std::abs( DoubleFromString( m_TrackCurrentValue->GetValue() ) ); + double thickness = std::abs( DoubleFromString( m_TrackThicknessValue->GetValue() ) ); + double deltaT_C = std::abs( DoubleFromString( m_TrackDeltaTValue->GetValue() ) ); + double track_len = std::abs( DoubleFromString( m_TrackLengthValue->GetValue() ) ); double extTrackWidth; double intTrackWidth; diff --git a/pcb_calculator/transline_dlg_funct.cpp b/pcb_calculator/transline_dlg_funct.cpp index dea6bfde6e..f6ca6a4208 100644 --- a/pcb_calculator/transline_dlg_funct.cpp +++ b/pcb_calculator/transline_dlg_funct.cpp @@ -30,12 +30,10 @@ #include #include -extern double ReturnDoubleFromString( const wxString& TextValue ); +extern double DoubleFromString( const wxString& TextValue ); -/* - * these values come from QucsStudio ( by Michael Margraf ) - */ +// these values come from QucsStudio ( by Michael Margraf ) // Display a selection of usual Er, TanD, Rho values // format is @@ -143,16 +141,16 @@ struct DLG_PRM_DATA * Irrelevant parameters texts are blanked. * @param aType = the transline_type_id of the new selected transline */ -void PCB_CALCULATOR_FRAME::TranslineTypeSelection( enum transline_type_id aType ) +void PCB_CALCULATOR_FRAME::TranslineTypeSelection( enum TRANSLINE_TYPE_ID aType ) { wxString msg; #define DOUBLE_TO_CTLR( dlg_item, value ) { msg.Printf( wxT( "%g" ), value );\ dlg_item->SetValue( msg ); } m_currTransLineType = aType; - if( (m_currTransLineType < start_of_list_type ) - || ( m_currTransLineType >= end_of_list_type ) ) - m_currTransLineType = default_type; + if( (m_currTransLineType < START_OF_LIST_TYPE ) + || ( m_currTransLineType >= END_OF_LIST_TYPE ) ) + m_currTransLineType = DEFAULT_TYPE; TRANSLINE_IDENT* tr_ident = m_transline_list[m_currTransLineType]; m_currTransLine = tr_ident->m_TLine; @@ -348,8 +346,8 @@ void PCB_CALCULATOR_FRAME::TranslineTypeSelection( enum transline_type_id aType /** * Function TransfDlgDataToTranslineParams - * Read values entered in dialog frame, and transfert these - * values in current transline parameters, converted in normalized units + * Read values entered in dialog frame, and copy these values + * in current transline parameters, converted in normalized units */ void PCB_CALCULATOR_FRAME::TransfDlgDataToTranslineParams() { @@ -359,7 +357,7 @@ void PCB_CALCULATOR_FRAME::TransfDlgDataToTranslineParams() TRANSLINE_PRM* prm = tr_ident->GetPrm( ii ); wxTextCtrl * value_ctrl = (wxTextCtrl * ) prm->m_ValueCtrl; wxString value_txt = value_ctrl->GetValue(); - double value = ReturnDoubleFromString(value_txt); + double value = DoubleFromString(value_txt); prm->m_Value = value; UNIT_SELECTOR * unit_ctrl = (UNIT_SELECTOR * ) prm->m_UnitCtrl; if( unit_ctrl ) @@ -378,7 +376,7 @@ void PCB_CALCULATOR_FRAME::TransfDlgDataToTranslineParams() */ void PCB_CALCULATOR_FRAME::OnTranslineSelection( wxCommandEvent& event ) { - enum transline_type_id id = (enum transline_type_id) event.GetSelection(); + enum TRANSLINE_TYPE_ID id = (enum TRANSLINE_TYPE_ID) event.GetSelection(); TranslineTypeSelection( id ); diff --git a/pcb_calculator/transline_ident.cpp b/pcb_calculator/transline_ident.cpp index 44e0a4fcca..fc74e0d27b 100644 --- a/pcb_calculator/transline_ident.cpp +++ b/pcb_calculator/transline_ident.cpp @@ -53,7 +53,7 @@ TRANSLINE_PRM::TRANSLINE_PRM( PRM_TYPE aType, PRMS_ID aId, #define TRANSLINE_PRM_KEY wxT( "translineprm%d" ) -void TRANSLINE_PRM::ReadConfig( wxConfig* aConfig ) +void TRANSLINE_PRM::ReadConfig( wxConfigBase* aConfig ) { if( m_Id == UNKNOWN_ID || m_Id == DUMMY_PRM ) return; @@ -65,7 +65,7 @@ void TRANSLINE_PRM::ReadConfig( wxConfig* aConfig ) } -void TRANSLINE_PRM::WriteConfig( wxConfig* aConfig ) +void TRANSLINE_PRM::WriteConfig( wxConfigBase* aConfig ) { if( m_Id == UNKNOWN_ID || m_Id == DUMMY_PRM ) return; @@ -100,7 +100,7 @@ double TRANSLINE_PRM::FromUserUnit() * A class to handle a list of parameters of a given transline */ -TRANSLINE_IDENT::TRANSLINE_IDENT( enum transline_type_id aType ) +TRANSLINE_IDENT::TRANSLINE_IDENT( enum TRANSLINE_TYPE_ID aType ) { m_Type = aType; // The type of transline handled m_Icon = NULL; // An xpm icon to display in dialogs @@ -129,7 +129,7 @@ TRANSLINE_IDENT::TRANSLINE_IDENT( enum transline_type_id aType ) switch( m_Type ) { - case microstrip_type: // microstrip + case MICROSTRIP_TYPE: // microstrip m_TLine = new MICROSTRIP(); m_Icon = new wxBitmap( microstrip_xpm ); @@ -165,7 +165,7 @@ TRANSLINE_IDENT::TRANSLINE_IDENT( enum transline_type_id aType ) _( "Ang_l" ), _( "Electrical Length" ), 0.0, true ) ); break; - case cpw_type: // coplanar waveguide + case CPW_TYPE: // coplanar waveguide m_TLine = new COPLANAR(); m_Icon = new wxBitmap( cpw_xpm ); m_HasPrmSelection = true; @@ -197,7 +197,7 @@ TRANSLINE_IDENT::TRANSLINE_IDENT( enum transline_type_id aType ) _( "Ang_l" ), _( "Electrical Length" ), 0.0, true ) ); break; - case grounded_cpw_type: // grounded coplanar waveguide + case GROUNDED_CPW_TYPE: // grounded coplanar waveguide m_TLine = new GROUNDEDCOPLANAR(); m_Icon = new wxBitmap( cpw_back_xpm ); m_HasPrmSelection = true; @@ -230,7 +230,7 @@ TRANSLINE_IDENT::TRANSLINE_IDENT( enum transline_type_id aType ) break; - case rectwaveguide_type: // rectangular waveguide + case RECTWAVEGUIDE_TYPE: // rectangular waveguide m_TLine = new RECTWAVEGUIDE(); m_Icon = new wxBitmap( rectwaveguide_xpm ); m_HasPrmSelection = true; @@ -264,7 +264,7 @@ TRANSLINE_IDENT::TRANSLINE_IDENT( enum transline_type_id aType ) _( "Ang_l" ), _( "Electrical Length" ), 0, true ) ); break; - case coax_type: // coaxial cable + case COAX_TYPE: // coaxial cable m_TLine = new COAX(); m_Icon = new wxBitmap( coax_xpm ); m_HasPrmSelection = true; @@ -295,7 +295,7 @@ TRANSLINE_IDENT::TRANSLINE_IDENT( enum transline_type_id aType ) _( "Ang_l" ), _( "Electrical Length" ), 0.0, true ) ); break; - case c_microstrip_type: // coupled microstrip + case C_MICROSTRIP_TYPE: // coupled microstrip m_TLine = new C_MICROSTRIP(); m_Icon = new wxBitmap( c_microstrip_xpm ); m_HasPrmSelection = true; @@ -328,14 +328,14 @@ TRANSLINE_IDENT::TRANSLINE_IDENT( enum transline_type_id aType ) _( "L" ), _( "Line Length" ), 50.0, true ) ); AddPrm( new TRANSLINE_PRM( PRM_TYPE_ELEC, Z0_E_PRM, - _( "Z0e" ), _( "Even-Mode Impedance" ), 50.0, true ) ); + _( "Z0e (Zdiff)" ), _( "Even-Mode impedance (diff impedance)" ), 50.0, true ) ); AddPrm( new TRANSLINE_PRM( PRM_TYPE_ELEC, Z0_O_PRM, - _( "Z0o" ), _( "Odd-Mode Impedance" ), 50.0, true ) ); + _( "Z0o (Z0)" ), _( "Odd-Mode impedance" ), 50.0, true ) ); AddPrm( new TRANSLINE_PRM( PRM_TYPE_ELEC, ANG_L_PRM, - _( "Ang_l" ), _( "Electrical Length" ), 0.0, true ) ); + _( "Ang_l" ), _( "Electrical length" ), 0.0, true ) ); break; - case stripline_type: // stripline + case STRIPLINE_TYPE: // stripline m_TLine = new STRIPLINE(); m_Icon = new wxBitmap( stripline_xpm ); @@ -367,7 +367,7 @@ TRANSLINE_IDENT::TRANSLINE_IDENT( enum transline_type_id aType ) _( "Ang_l" ), _( "Electrical Length" ), 0, true ) ); break; - case twistedpair_type: // twisted pair + case TWISTEDPAIR_TYPE: // twisted pair m_TLine = new TWISTEDPAIR(); m_Icon = new wxBitmap( twistedpair_xpm ); m_HasPrmSelection = true; @@ -399,7 +399,7 @@ TRANSLINE_IDENT::TRANSLINE_IDENT( enum transline_type_id aType ) _( "Ang_l" ), _( "Electrical Length" ), 0.0, true ) ); break; - case end_of_list_type: // Not really used + case END_OF_LIST_TYPE: // Not really used break; } } @@ -415,7 +415,7 @@ TRANSLINE_IDENT::~TRANSLINE_IDENT() } -void TRANSLINE_IDENT::ReadConfig( wxConfig* aConfig ) +void TRANSLINE_IDENT::ReadConfig( wxConfigBase* aConfig ) { wxString text = wxString::FromUTF8( m_TLine->m_name ); aConfig->SetPath( text ); @@ -426,7 +426,7 @@ void TRANSLINE_IDENT::ReadConfig( wxConfig* aConfig ) } -void TRANSLINE_IDENT::WriteConfig( wxConfig* aConfig ) +void TRANSLINE_IDENT::WriteConfig( wxConfigBase* aConfig ) { wxString text = wxString::FromUTF8( m_TLine->m_name ); aConfig->SetPath( text ); diff --git a/pcb_calculator/transline_ident.h b/pcb_calculator/transline_ident.h index 4e607ea78c..d0805b04c7 100644 --- a/pcb_calculator/transline_ident.h +++ b/pcb_calculator/transline_ident.h @@ -12,18 +12,18 @@ #include // An enum to handle muwave shapes: -enum transline_type_id { - start_of_list_type = 0, - default_type = start_of_list_type, - microstrip_type = default_type, - cpw_type, - grounded_cpw_type, - rectwaveguide_type, - coax_type, - c_microstrip_type, - stripline_type, - twistedpair_type, - end_of_list_type +enum TRANSLINE_TYPE_ID { + START_OF_LIST_TYPE = 0, + DEFAULT_TYPE = START_OF_LIST_TYPE, + MICROSTRIP_TYPE = DEFAULT_TYPE, + CPW_TYPE, + GROUNDED_CPW_TYPE, + RECTWAVEGUIDE_TYPE, + COAX_TYPE, + C_MICROSTRIP_TYPE, + STRIPLINE_TYPE, + TWISTEDPAIR_TYPE, + END_OF_LIST_TYPE }; // A Class to handle parameters @@ -54,8 +54,8 @@ public: TRANSLINE_PRM( PRM_TYPE aType, PRMS_ID aId, double aValue = 0.0, bool aConvUnit = false ); - void ReadConfig( wxConfig* aConfig ); - void WriteConfig( wxConfig* aConfig ); + void ReadConfig( wxConfigBase* aConfig ); + void WriteConfig( wxConfigBase* aConfig ); double ToUserUnit(); double FromUserUnit(); }; @@ -66,7 +66,7 @@ public: TRANSLINE_PRM( PRM_TYPE aType, PRMS_ID aId, class TRANSLINE_IDENT { public: - enum transline_type_id m_Type; // The type of transline handled + enum TRANSLINE_TYPE_ID m_Type; // The type of transline handled wxBitmap * m_Icon; // An icon to display in dialogs TRANSLINE* m_TLine; // The TRANSLINE itself wxArrayString m_Messages; // messages for results @@ -75,7 +75,7 @@ public: private: std::vector m_prms_List; -public: TRANSLINE_IDENT( enum transline_type_id aType ); +public: TRANSLINE_IDENT( enum TRANSLINE_TYPE_ID aType ); ~TRANSLINE_IDENT(); // Add a new param in list @@ -100,8 +100,8 @@ public: TRANSLINE_IDENT( enum transline_type_id aType ); } - void ReadConfig( wxConfig* aConfig ); - void WriteConfig( wxConfig* aConfig ); + void ReadConfig( wxConfigBase* aConfig ); + void WriteConfig( wxConfigBase* aConfig ); }; #endif // TRANSLINE_IDENT_H diff --git a/pcbnew/CMakeLists.txt b/pcbnew/CMakeLists.txt index b68f93e05b..58b6edfc25 100644 --- a/pcbnew/CMakeLists.txt +++ b/pcbnew/CMakeLists.txt @@ -1,5 +1,4 @@ - -set( MAKE_LINK_MAPS false ) +set( MAKE_LINK_MAPS true ) add_definitions( -DPCBNEW ) add_subdirectory(router) @@ -20,9 +19,6 @@ if( KICAD_SCRIPTING OR KICAD_SCRIPTING_MODULES ) endif() -### -# Includes -### include_directories( BEFORE ${INC_BEFORE} ) include_directories( ./dialogs @@ -37,9 +33,6 @@ include_directories( ${INC_AFTER} ) -### -# Sources -# set( PCBNEW_DIALOGS dialogs/dialog_block_options_base.cpp dialogs/dialog_cleaning_options_base.cpp @@ -218,7 +211,6 @@ set( PCBNEW_CLASS_SRCS onleftclick.cpp onrightclick.cpp pad_edition_functions.cpp - pcbnew.cpp pcbnew_config.cpp pcbplot.cpp plot_board_layers.cpp @@ -267,23 +259,18 @@ set( PCBNEW_CLASS_SRCS set( PCBNEW_SRCS ${PCBNEW_AUTOROUTER_SRCS} ${PCBNEW_CLASS_SRCS} ${PCBNEW_DIALOGS} ) -### -# We need some extra sources from common -### + +# extra sources from common set( PCBNEW_COMMON_SRCS ../common/dialogs/dialog_page_settings.cpp ../common/base_units.cpp ) -## -# Scripting sources -## set( PCBNEW_SCRIPTING_DIALOGS dialogs/dialog_scripting_base.cpp dialogs/dialog_scripting.cpp ) - set( PCBNEW_SCRIPTING_PYTHON_HELPERS ../scripting/wx_python_helpers.cpp ../scripting/python_scripting.cpp @@ -296,12 +283,9 @@ if( KICAD_SCRIPTING ) ${PCBNEW_SCRIPTING_DIALOGS} pcbnew_wrap.cxx ${PCBNEW_SCRIPTING_PYTHON_HELPERS} - ) + ) endif() -## -# Scripting build -## if( KICAD_SCRIPTING OR KICAD_SCRIPTING_MODULES ) @@ -368,7 +352,7 @@ if( BUILD_GITHUB_PLUGIN ) set( GITHUB_PLUGIN_LIBRARIES github_plugin ) endif() -if( ( KICAD_SCRIPTING OR KICAD_SCRIPTING_MODULES ) AND NOT WIN32 AND NOT APPLE ) +if( UNIX AND NOT APPLE ) list( APPEND PCBNEW_EXTRA_LIBS rt ) endif() @@ -379,7 +363,14 @@ if( KICAD_SCRIPTING_MODULES ) set( CMAKE_SWIG_FLAGS ${SWIG_FLAGS} ) set_source_files_properties( scripting/pcbnew.i PROPERTIES CPLUSPLUS ON ) - swig_add_module( pcbnew python scripting/pcbnew.i ${PCBNEW_SCRIPTING_PYTHON_HELPERS} ${PCBNEW_SRCS} ${PCBNEW_COMMON_SRCS} ) + swig_add_module( pcbnew + python + scripting/pcbnew.i + ${PCBNEW_SCRIPTING_PYTHON_HELPERS} + pcbnew.cpp + ${PCBNEW_SRCS} + ${PCBNEW_COMMON_SRCS} + ) swig_link_libraries( pcbnew 3d-viewer pcbcommon @@ -403,8 +394,8 @@ if( KICAD_SCRIPTING_MODULES ) ) if( MAKE_LINK_MAPS ) - # generate a link map with cross reference - set_target_properties( _pcbnew PROPERTIES LINK_FLAGS "-Wl,-cref -Wl,-Map=_pcbnew.map" ) + set_target_properties( _pcbnew PROPERTIES + LINK_FLAGS "${TO_LINKER},-cref ${TO_LINKER},-Map=pcbnew.so.map" ) endif() endif() @@ -458,28 +449,19 @@ endif() - -### -# Windows resource file -### -if( WIN32 ) - if( MINGW ) - # PCBNEW_RESOURCES variable is set by the macro. - mingw_resource_compiler( pcbnew ) - else() - set( PCBNEW_RESOURCES pcbnew.rc ) - endif() +if( MINGW ) + # PCBNEW_RESOURCES variable is set by the macro. + mingw_resource_compiler( pcbnew ) endif() -### -# Set properties for APPLE on pcbnew target -### if( APPLE ) set( PCBNEW_RESOURCES pcbnew.icns pcbnew_doc.icns ) - set_source_files_properties( "${CMAKE_CURRENT_SOURCE_DIR}/pcbnew.icns" - PROPERTIES MACOSX_PACKAGE_LOCATION Resources ) - set_source_files_properties( "${CMAKE_CURRENT_SOURCE_DIR}/pcbnew_doc.icns" - PROPERTIES MACOSX_PACKAGE_LOCATION Resources ) + set_source_files_properties( "${CMAKE_CURRENT_SOURCE_DIR}/pcbnew.icns" PROPERTIES + MACOSX_PACKAGE_LOCATION Resources + ) + set_source_files_properties( "${CMAKE_CURRENT_SOURCE_DIR}/pcbnew_doc.icns" PROPERTIES + MACOSX_PACKAGE_LOCATION Resources + ) set( MACOSX_BUNDLE_ICON_FILE pcbnew.icns ) set( MACOSX_BUNDLE_GUI_IDENTIFIER org.kicad-eda.pcbnew ) set( MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/Info.plist ) @@ -515,9 +497,6 @@ make_lexer( ) -### -# subcomponents of pcbnew -### add_subdirectory( pcad2kicadpcb_plugin ) if( BUILD_GITHUB_PLUGIN ) add_subdirectory( github ) @@ -525,76 +504,170 @@ if( BUILD_GITHUB_PLUGIN ) endif() -### -# Create the pcbnew executable -### -add_executable( pcbnew WIN32 MACOSX_BUNDLE - ${PCBNEW_SRCS} - ${PCBNEW_COMMON_SRCS} - ${PCBNEW_SCRIPTING_SRCS} - ${PCBNEW_RESOURCES} - ) +if( USE_KIWAY_DLLS ) + + # a very small program launcher for pcbnew_kiface + add_executable( pcbnew WIN32 MACOSX_BUNDLE + ../common/single_top.cpp + ../common/pgm_base.cpp + ${PCBNEW_RESOURCES} + ) + set_source_files_properties( ../common/single_top.cpp PROPERTIES + COMPILE_DEFINITIONS "TOP_FRAME=PCB_FRAME_TYPE;PGM_DATA_FILE_EXT=\"kicad_pcb\";BUILD_KIWAY_DLL" + ) + target_link_libraries( pcbnew + #singletop # replaces common, giving us restrictive control and link warnings. + # There's way too much crap coming in from common yet. + common + bitmaps + ${wxWidgets_LIBRARIES} + ) + if( MAKE_LINK_MAPS ) + set_target_properties( pcbnew PROPERTIES + LINK_FLAGS "${TO_LINKER},-cref ${TO_LINKER},-Map=pcbnew.map" ) + endif() + + # the main pcbnew program, in DSO form. + add_library( pcbnew_kiface MODULE + pcbnew.cpp + ${PCBNEW_SRCS} + ${PCBNEW_COMMON_SRCS} + ${PCBNEW_SCRIPTING_SRCS} +# ${PCBNEW_RESOURCES} + ) + set_target_properties( pcbnew_kiface PROPERTIES + # Decorate OUTPUT_NAME with PREFIX and SUFFIX, creating something like + # _pcbnew.so, _pcbnew.dll, or _pcbnew.kiface + OUTPUT_NAME pcbnew + PREFIX ${KIFACE_PREFIX} + SUFFIX ${KIFACE_SUFFIX} + ) + if( ${OPENMP_FOUND} ) + set_target_properties( pcbnew_kiface PROPERTIES + COMPILE_FLAGS ${OpenMP_CXX_FLAGS} + ) + endif() + target_link_libraries( pcbnew_kiface + 3d-viewer + pcbcommon + pnsrouter + common + pcad2kicadpcb + polygon + bitmaps + gal + lib_dxf + ${GITHUB_PLUGIN_LIBRARIES} + ${wxWidgets_LIBRARIES} + ${OPENGL_LIBRARIES} + ${GDI_PLUS_LIBRARIES} + ${PYTHON_LIBRARIES} + ${GLEW_LIBRARIES} + ${CAIRO_LIBRARIES} + ${PIXMAN_LIBRARY} + ${Boost_LIBRARIES} # must follow GITHUB + ${PCBNEW_EXTRA_LIBS} # -lrt must follow Boost + ${OPENMP_LIBRARIES} + ) + set_source_files_properties( pcbnew.cpp PROPERTIES + # The KIFACE is in pcbnew.cpp, export it: + COMPILE_DEFINITIONS "BUILD_KIWAY_DLL;COMPILING_DLL" + ) + if( MAKE_LINK_MAPS ) + set_target_properties( pcbnew_kiface PROPERTIES + LINK_FLAGS "${TO_LINKER},-cref ${TO_LINKER},-Map=_pcbnew.kiface.map" ) + endif() + + # if building pcbnew, then also build pcbnew_kiface if out of date. + add_dependencies( pcbnew pcbnew_kiface ) + + # these 2 binaries are a matched set, keep them together: + install( TARGETS pcbnew + DESTINATION ${KICAD_BIN} + COMPONENT binary + ) + install( TARGETS pcbnew_kiface + DESTINATION ${KICAD_BIN} + COMPONENT binary + ) + + if( APPLE ) + # copies kiface into the bundle + add_custom_target( _pcbnew_kiface_copy ALL + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/pcbnew/_pcbnew.kiface "${CMAKE_BINARY_DIR}/pcbnew/pcbnew.app/Contents/MacOS/" + DEPENDS pcbnew_kiface + COMMENT "Copying kiface into pcbnew" + ) + endif() + +else() # milestone A) kills this off: + + add_executable( pcbnew WIN32 MACOSX_BUNDLE + pcbnew.cpp + ${PCBNEW_SRCS} + ${PCBNEW_COMMON_SRCS} + ${PCBNEW_SCRIPTING_SRCS} + ${PCBNEW_RESOURCES} + ) + target_link_libraries( pcbnew + 3d-viewer + pcbcommon + pnsrouter + common + pcad2kicadpcb + polygon + bitmaps + gal + lib_dxf + ${GITHUB_PLUGIN_LIBRARIES} + ${wxWidgets_LIBRARIES} + ${OPENGL_LIBRARIES} + ${GDI_PLUS_LIBRARIES} + ${PYTHON_LIBRARIES} + ${GLEW_LIBRARIES} + ${CAIRO_LIBRARIES} + ${PIXMAN_LIBRARY} + ${Boost_LIBRARIES} # must follow GITHUB + ${PCBNEW_EXTRA_LIBS} + ) + + # Only for win32 cross compilation using MXE + if( WIN32 AND MSYS AND CMAKE_CROSSCOMPILING ) + target_link_libraries( pcbnew + opengl32 + glu32 + pixman-1 + fontconfig + freetype + bz2 + ) + endif() + + install( TARGETS pcbnew + DESTINATION ${KICAD_BIN} + COMPONENT binary + ) + +endif() + add_dependencies( pcbnew lib-dependencies ) ### # Set properties for APPLE on pcbnew target ### if( APPLE ) - set_target_properties( pcbnew PROPERTIES MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/Info.plist ) + set_target_properties( pcbnew PROPERTIES + MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/Info.plist ) endif() -### -# Link executable target pcbnew with correct libraries -### - -target_link_libraries( pcbnew - 3d-viewer - pcbcommon - pnsrouter - common - pcad2kicadpcb - polygon - bitmaps - gal - lib_dxf - ${GITHUB_PLUGIN_LIBRARIES} - ${wxWidgets_LIBRARIES} - ${OPENGL_LIBRARIES} - ${GDI_PLUS_LIBRARIES} - ${PYTHON_LIBRARIES} - ${PCBNEW_EXTRA_LIBS} - ${GLEW_LIBRARIES} - ${CAIRO_LIBRARIES} - ${PIXMAN_LIBRARY} - ${Boost_LIBRARIES} # must follow GITHUB - ) - -# Only for win32 cross compilation using MXE -if( WIN32 AND MSYS AND CMAKE_CROSSCOMPILING ) -target_link_libraries( pcbnew - opengl32 - glu32 - pixman-1 - fontconfig - freetype - bz2 - ) -endif() if( MAKE_LINK_MAPS ) # generate a link map with cross reference - set_target_properties( pcbnew PROPERTIES LINK_FLAGS "-Wl,-cref -Wl,-Map=pcbnew.map" ) + set_target_properties( pcbnew PROPERTIES + LINK_FLAGS "${TO_LINKER},-cref ${TO_LINKER},-Map=pcbnew.map" ) endif() -### -# Add pcbnew as install target -### -install( TARGETS pcbnew - DESTINATION ${KICAD_BIN} - COMPONENT binary ) - - if( KICAD_SCRIPTING ) add_custom_target( FixSwigImportsScripting ALL COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_SOURCE_DIR}/scripting/build_tools/fix_swig_imports.py ${CMAKE_CURRENT_BINARY_DIR}/pcbnew.py @@ -604,7 +677,7 @@ if( KICAD_SCRIPTING ) install( FILES ${CMAKE_BINARY_DIR}/pcbnew/pcbnew.py DESTINATION ${PYTHON_DEST} ) - if( APPLE ) + if( APPLE ) # copies all into PYTHON_DEST then all into the bundle ! add_custom_target( _pcbnew_py_copy ALL COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/pcbnew/pcbnew.py "${PYTHON_DEST}/wx-3.0-osx_cocoa/" @@ -620,10 +693,10 @@ if( KICAD_SCRIPTING ) add_custom_target( pcbnew_copy_plugins ALL COMMAND ${CMAKE_COMMAND} -E copy_directory ${PROJECT_SOURCE_DIR}/pcbnew/scripting/plugins ${PROJECT_SOURCE_DIR}/pcbnew/pcbnew.app/Contents/PlugIns/scripting/plugins - DEPENDS pcbnew_copy_wxpython_scripting + DEPENDS pcbnew_copy_wxpython_scripting COMMENT "Copying plugins into bundle" ) - + # fix bundle after copying wxpython, fixing and copying add_dependencies( osx_fix_bundles pcbnew_copy_wxpython_scripting ) @@ -645,13 +718,13 @@ if( KICAD_SCRIPTING_MODULES ) install( FILES ${CMAKE_BINARY_DIR}/pcbnew/pcbnew.py DESTINATION ${PYTHON_DEST} ) - if( WIN32 ) + if( MINGW ) install( FILES ${CMAKE_BINARY_DIR}/pcbnew/_pcbnew.pyd DESTINATION ${PYTHON_DEST} ) else() install( FILES ${CMAKE_BINARY_DIR}/pcbnew/_pcbnew.so DESTINATION ${PYTHON_DEST} ) endif() - if( APPLE ) + if( APPLE ) # copies needed files into PYTHON_DEST then copy all into the bundle ! add_custom_target( _pcbnew_so_copy ALL COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/pcbnew/_pcbnew.so "${PYTHON_DEST}" @@ -665,9 +738,11 @@ if( KICAD_SCRIPTING_MODULES ) COMMENT "Copying wxPython into pcbnew.app Frameworks" ) - # Tell that we have to run osx_fix_bundles fix after building _pcbnew and migrating wxPython - add_dependencies( osx_fix_bundles pcbnew_copy_wxpython_module ) - add_dependencies( osx_fix_bundles _pcbnew ) + if( KICAD_BUILD_DYNAMIC ) + # Tell that we have to run osx_fix_bundles fix after building _pcbnew and migrating wxPython + add_dependencies( osx_fix_bundles pcbnew_copy_wxpython_module ) + add_dependencies( osx_fix_bundles _pcbnew ) + endif() endif() endif() diff --git a/pcbnew/autorouter/graphpcb.cpp b/pcbnew/autorouter/graphpcb.cpp index 294e20e969..28dff7ff32 100644 --- a/pcbnew/autorouter/graphpcb.cpp +++ b/pcbnew/autorouter/graphpcb.cpp @@ -87,7 +87,7 @@ static void TraceCircle( int ux0, int uy0, int ux1, int uy1, int lg, LAYER_NUM l void PlacePad( D_PAD* aPad, int color, int marge, int op_logic ) { int dx, dy; - wxPoint shape_pos = aPad->ReturnShapePos(); + wxPoint shape_pos = aPad->ShapePos(); dx = aPad->GetSize().x / 2; dx += marge; @@ -757,7 +757,7 @@ void TraceCircle( int ux0, int uy0, int ux1, int uy1, int lg, LAYER_NUM layer, int ii; int angle; - radius = KiROUND( Distance( ux0, uy0, ux1, uy1 ) ); + radius = KiROUND( Distance( ux0, uy0, ux1, uy1 ) ); x0 = x1 = radius; y0 = y1 = 0; diff --git a/pcbnew/autorouter/queue.cpp b/pcbnew/autorouter/queue.cpp index cf82a63633..ca251608a2 100644 --- a/pcbnew/autorouter/queue.cpp +++ b/pcbnew/autorouter/queue.cpp @@ -119,7 +119,7 @@ void GetQueue( int* r, int* c, int* s, int* d, int* a ) /* add a search node to the list - * Return: + * : * 1 - OK * 0 - Failed to allocate memory. */ diff --git a/pcbnew/autorouter/solve.cpp b/pcbnew/autorouter/solve.cpp index 063d56c702..86e937073a 100644 --- a/pcbnew/autorouter/solve.cpp +++ b/pcbnew/autorouter/solve.cpp @@ -262,7 +262,7 @@ static long newmask[8] = /* Route all traces - * Return: + * : * 1 if OK * -1 if escape (stop being routed) request * -2 if default memory allocation diff --git a/pcbnew/autorouter/work.cpp b/pcbnew/autorouter/work.cpp index 11d0f1841b..68aa48c1ef 100644 --- a/pcbnew/autorouter/work.cpp +++ b/pcbnew/autorouter/work.cpp @@ -73,7 +73,7 @@ void InitWork() /* add a unit of work to the work list - * Return: + * : * 1 if OK * 0 if memory allocation failed */ diff --git a/pcbnew/basepcbframe.cpp b/pcbnew/basepcbframe.cpp index 1bccc1894a..0e93394930 100644 --- a/pcbnew/basepcbframe.cpp +++ b/pcbnew/basepcbframe.cpp @@ -29,10 +29,12 @@ */ #include +#include #include #include #include -#include +//#include +#include #include #include #include @@ -40,6 +42,7 @@ #include #include +#include #include #include #include @@ -84,7 +87,7 @@ const LAYER_NUM PCB_BASE_FRAME::GAL_LAYER_ORDER[] = ITEM_GAL_LAYER( RATSNEST_VISIBLE ), ITEM_GAL_LAYER( VIAS_HOLES_VISIBLE ), ITEM_GAL_LAYER( PADS_HOLES_VISIBLE ), - ITEM_GAL_LAYER( VIA_THROUGH_VISIBLE ), ITEM_GAL_LAYER( PADS_VISIBLE ), + ITEM_GAL_LAYER( VIAS_VISIBLE ), ITEM_GAL_LAYER( PADS_VISIBLE ), NETNAMES_GAL_LAYER( PAD_FR_NETNAMES_VISIBLE ), ITEM_GAL_LAYER( PAD_FR_VISIBLE ), SOLDERMASK_N_FRONT, NETNAMES_GAL_LAYER( LAYER_16_NETNAMES_VISIBLE ), LAYER_N_FRONT, @@ -127,11 +130,10 @@ BEGIN_EVENT_TABLE( PCB_BASE_FRAME, EDA_DRAW_FRAME ) END_EVENT_TABLE() -PCB_BASE_FRAME::PCB_BASE_FRAME( wxWindow* aParent, ID_DRAWFRAME_TYPE aFrameType, - const wxString& aTitle, - const wxPoint& aPos, const wxSize& aSize, - long aStyle, const wxString & aFrameName) : - EDA_DRAW_FRAME( aParent, aFrameType, aTitle, aPos, aSize, aStyle, aFrameName ), +PCB_BASE_FRAME::PCB_BASE_FRAME( KIWAY* aKiway, wxWindow* aParent, ID_DRAWFRAME_TYPE aFrameType, + const wxString& aTitle, const wxPoint& aPos, const wxSize& aSize, + long aStyle, const wxString & aFrameName ) : + EDA_DRAW_FRAME( aKiway, aParent, aFrameType, aTitle, aPos, aSize, aStyle, aFrameName ), m_toolManager( TOOL_MANAGER::Instance() ) { m_Pcb = NULL; @@ -173,6 +175,25 @@ PCB_BASE_FRAME::~PCB_BASE_FRAME() } +FP_LIB_TABLE* PCB_BASE_FRAME::FootprintLibs() const +{ + PROJECT& prj = Prj(); + FP_LIB_TABLE* tbl = dynamic_cast( prj.Elem( PROJECT::FPTBL ) ); + + if( !tbl ) + { + // Stack the project specific FP_LIB_TABLE overlay on top of the global table. + // ~FP_LIB_TABLE() will not touch the fallback table, so multiple projects may + // stack this way, all using the same global fallback table. + tbl = new FP_LIB_TABLE( &GFootprintTable ); + + prj.Elem( PROJECT::FPTBL, tbl ); + } + + return tbl; +} + + void PCB_BASE_FRAME::SetBoard( BOARD* aBoard ) { delete m_Pcb; @@ -736,39 +757,35 @@ void PCB_BASE_FRAME::unitsChangeRefresh() } -void PCB_BASE_FRAME::LoadSettings() +void PCB_BASE_FRAME::LoadSettings( wxConfigBase* aCfg ) { - wxASSERT( wxGetApp().GetSettings() != NULL ); - - wxConfig* cfg = wxGetApp().GetSettings(); - - EDA_DRAW_FRAME::LoadSettings(); + EDA_DRAW_FRAME::LoadSettings( aCfg ); // Ensure grid id is an existent grid id: if( (m_LastGridSizeId <= 0) || (m_LastGridSizeId > (ID_POPUP_GRID_USER - ID_POPUP_GRID_LEVEL_1000)) ) m_LastGridSizeId = ID_POPUP_GRID_LEVEL_500 - ID_POPUP_GRID_LEVEL_1000; - cfg->Read( m_FrameName + UserGridSizeXEntry, &m_UserGridSize.x, 0.01 ); - cfg->Read( m_FrameName + UserGridSizeYEntry, &m_UserGridSize.y, 0.01 ); + aCfg->Read( m_FrameName + UserGridSizeXEntry, &m_UserGridSize.x, 0.01 ); + aCfg->Read( m_FrameName + UserGridSizeYEntry, &m_UserGridSize.y, 0.01 ); long itmp; - cfg->Read( m_FrameName + UserGridUnitsEntry, &itmp, ( long )INCHES ); + aCfg->Read( m_FrameName + UserGridUnitsEntry, &itmp, ( long )INCHES ); m_UserGridUnit = (EDA_UNITS_T) itmp; - cfg->Read( m_FrameName + DisplayPadFillEntry, &m_DisplayPadFill, true ); - cfg->Read( m_FrameName + DisplayViaFillEntry, &m_DisplayViaFill, true ); - cfg->Read( m_FrameName + DisplayPadNumberEntry, &m_DisplayPadNum, true ); - cfg->Read( m_FrameName + DisplayModuleEdgeEntry, &m_DisplayModEdge, ( long )FILLED ); + aCfg->Read( m_FrameName + DisplayPadFillEntry, &m_DisplayPadFill, true ); + aCfg->Read( m_FrameName + DisplayViaFillEntry, &m_DisplayViaFill, true ); + aCfg->Read( m_FrameName + DisplayPadNumberEntry, &m_DisplayPadNum, true ); + aCfg->Read( m_FrameName + DisplayModuleEdgeEntry, &m_DisplayModEdge, ( long )FILLED ); - cfg->Read( m_FrameName + FastGrid1Entry, &itmp, ( long )0); + aCfg->Read( m_FrameName + FastGrid1Entry, &itmp, ( long )0); m_FastGrid1 = itmp; - cfg->Read( m_FrameName + FastGrid2Entry, &itmp, ( long )0); + aCfg->Read( m_FrameName + FastGrid2Entry, &itmp, ( long )0); m_FastGrid2 = itmp; if( m_DisplayModEdge < LINE || m_DisplayModEdge > SKETCH ) m_DisplayModEdge = FILLED; - cfg->Read( m_FrameName + DisplayModuleTextEntry, &m_DisplayModText, ( long )FILLED ); + aCfg->Read( m_FrameName + DisplayModuleTextEntry, &m_DisplayModText, ( long )FILLED ); if( m_DisplayModText < LINE || m_DisplayModText > SKETCH ) m_DisplayModText = FILLED; @@ -799,7 +816,7 @@ void PCB_BASE_FRAME::LoadSettings() } // Some more required layers settings - view->SetRequired( ITEM_GAL_LAYER( VIAS_HOLES_VISIBLE ), ITEM_GAL_LAYER( VIA_THROUGH_VISIBLE ) ); + view->SetRequired( ITEM_GAL_LAYER( VIAS_HOLES_VISIBLE ), ITEM_GAL_LAYER( VIAS_VISIBLE ) ); view->SetRequired( ITEM_GAL_LAYER( PADS_HOLES_VISIBLE ), ITEM_GAL_LAYER( PADS_VISIBLE ) ); view->SetRequired( NETNAMES_GAL_LAYER( PADS_NETNAMES_VISIBLE ), ITEM_GAL_LAYER( PADS_VISIBLE ) ); @@ -839,23 +856,20 @@ void PCB_BASE_FRAME::LoadSettings() } -void PCB_BASE_FRAME::SaveSettings() +void PCB_BASE_FRAME::SaveSettings( wxConfigBase* aCfg ) { - wxASSERT( wxGetApp().GetSettings() != NULL ); + EDA_DRAW_FRAME::SaveSettings( aCfg ); - wxConfig* cfg = wxGetApp().GetSettings(); - - EDA_DRAW_FRAME::SaveSettings(); - cfg->Write( m_FrameName + UserGridSizeXEntry, m_UserGridSize.x ); - cfg->Write( m_FrameName + UserGridSizeYEntry, m_UserGridSize.y ); - cfg->Write( m_FrameName + UserGridUnitsEntry, ( long )m_UserGridUnit ); - cfg->Write( m_FrameName + DisplayPadFillEntry, m_DisplayPadFill ); - cfg->Write( m_FrameName + DisplayViaFillEntry, m_DisplayViaFill ); - cfg->Write( m_FrameName + DisplayPadNumberEntry, m_DisplayPadNum ); - cfg->Write( m_FrameName + DisplayModuleEdgeEntry, ( long )m_DisplayModEdge ); - cfg->Write( m_FrameName + DisplayModuleTextEntry, ( long )m_DisplayModText ); - cfg->Write( m_FrameName + FastGrid1Entry, ( long )m_FastGrid1 ); - cfg->Write( m_FrameName + FastGrid2Entry, ( long )m_FastGrid2 ); + aCfg->Write( m_FrameName + UserGridSizeXEntry, m_UserGridSize.x ); + aCfg->Write( m_FrameName + UserGridSizeYEntry, m_UserGridSize.y ); + aCfg->Write( m_FrameName + UserGridUnitsEntry, ( long )m_UserGridUnit ); + aCfg->Write( m_FrameName + DisplayPadFillEntry, m_DisplayPadFill ); + aCfg->Write( m_FrameName + DisplayViaFillEntry, m_DisplayViaFill ); + aCfg->Write( m_FrameName + DisplayPadNumberEntry, m_DisplayPadNum ); + aCfg->Write( m_FrameName + DisplayModuleEdgeEntry, ( long )m_DisplayModEdge ); + aCfg->Write( m_FrameName + DisplayModuleTextEntry, ( long )m_DisplayModText ); + aCfg->Write( m_FrameName + FastGrid1Entry, ( long )m_FastGrid1 ); + aCfg->Write( m_FrameName + FastGrid2Entry, ( long )m_FastGrid2 ); } @@ -914,7 +928,6 @@ void PCB_BASE_FRAME::updateGridSelectBox() } } - void PCB_BASE_FRAME::updateZoomSelectBox() { if( m_zoomSelectBox == NULL ) diff --git a/pcbnew/block.cpp b/pcbnew/block.cpp index bb86e61cfa..b2924676b9 100644 --- a/pcbnew/block.cpp +++ b/pcbnew/block.cpp @@ -179,7 +179,7 @@ void DIALOG_BLOCK_OPTIONS::ExecuteCommand( wxCommandEvent& event ) } -int PCB_EDIT_FRAME::ReturnBlockCommand( int aKey ) +int PCB_EDIT_FRAME::BlockCommand( int aKey ) { int cmd = 0; @@ -656,8 +656,8 @@ void PCB_EDIT_FRAME::Block_Delete() void PCB_EDIT_FRAME::Block_Rotate() { wxPoint oldpos; - wxPoint centre; // rotation cent-re for the rotation transform - int rotAngle = 900; // rotation angle in 0.1 deg. + wxPoint centre; // rotation cent-re for the rotation transform + int rotAngle = m_rotationAngle; // rotation angle in 0.1 deg. oldpos = GetCrossHairPosition(); centre = GetScreen()->m_BlockLocate.Centre(); @@ -665,14 +665,13 @@ void PCB_EDIT_FRAME::Block_Rotate() OnModify(); PICKED_ITEMS_LIST* itemsList = &GetScreen()->m_BlockLocate.GetItems(); - itemsList->m_Status = UR_ROTATED; + itemsList->m_Status = UR_CHANGED; for( unsigned ii = 0; ii < itemsList->GetCount(); ii++ ) { BOARD_ITEM* item = (BOARD_ITEM*) itemsList->GetPickedItem( ii ); wxASSERT( item ); - itemsList->SetPickedItemStatus( UR_ROTATED, ii ); - item->Rotate( centre, rotAngle ); + itemsList->SetPickedItemStatus( UR_CHANGED, ii ); switch( item->Type() ) { @@ -706,7 +705,16 @@ void PCB_EDIT_FRAME::Block_Rotate() } } - SaveCopyInUndoList( *itemsList, UR_ROTATED, centre ); + // Save all the block items in there current state before applying the rotation. + SaveCopyInUndoList( *itemsList, UR_CHANGED, centre ); + + // Now perform the rotation. + for( unsigned ii = 0; ii < itemsList->GetCount(); ii++ ) + { + BOARD_ITEM* item = (BOARD_ITEM*) itemsList->GetPickedItem( ii ); + wxASSERT( item ); + item->Rotate( centre, rotAngle ); + } Compile_Ratsnest( NULL, true ); m_canvas->Refresh( true ); diff --git a/pcbnew/block_module_editor.cpp b/pcbnew/block_module_editor.cpp index d83c1378e7..9fc22bd1e1 100644 --- a/pcbnew/block_module_editor.cpp +++ b/pcbnew/block_module_editor.cpp @@ -30,7 +30,7 @@ */ #include -#include +#include #include #include #include @@ -73,7 +73,7 @@ static void MoveMarkedItems( MODULE* module, wxPoint offset ); static void DeleteMarkedItems( MODULE* module ); -int FOOTPRINT_EDIT_FRAME::ReturnBlockCommand( int key ) +int FOOTPRINT_EDIT_FRAME::BlockCommand( int key ) { int cmd; @@ -306,7 +306,7 @@ static void DrawMovingBlockOutlines( EDA_DRAW_PANEL* aPanel, wxDC* aDC, const wx bool aErase ) { BASE_SCREEN* screen = aPanel->GetScreen(); - FOOTPRINT_EDIT_FRAME* moduleEditFrame = FOOTPRINT_EDIT_FRAME::GetActiveFootprintEditor(); + FOOTPRINT_EDIT_FRAME* moduleEditFrame = FOOTPRINT_EDIT_FRAME::GetActiveFootprintEditor( aPanel->GetParent() ); wxASSERT( moduleEditFrame ); MODULE* currentModule = moduleEditFrame->GetBoard()->m_Modules; diff --git a/pcbnew/board_items_to_polygon_shape_transform.cpp b/pcbnew/board_items_to_polygon_shape_transform.cpp index 4cf371eedb..e08cceec96 100644 --- a/pcbnew/board_items_to_polygon_shape_transform.cpp +++ b/pcbnew/board_items_to_polygon_shape_transform.cpp @@ -450,7 +450,7 @@ void D_PAD:: TransformShapeWithClearanceToPolygon( CPOLYGONS_LIST& aCornerBuffer int dy = (m_Size.y / 2) + aClearanceValue; double delta = 3600.0 / aCircleToSegmentsCount; // rot angle in 0.1 degree - wxPoint PadShapePos = ReturnShapePos(); /* Note: for pad having a shape offset, + wxPoint PadShapePos = ShapePos(); /* Note: for pad having a shape offset, * the pad position is NOT the shape position */ wxSize psize = m_Size; /* pad size unsed in RECT and TRAPEZOIDAL pads * trapezoidal pads are considered as rect @@ -579,7 +579,7 @@ void D_PAD::BuildPadShapePolygon( CPOLYGONS_LIST& aCornerBuffer, double aCorrectionFactor ) const { wxPoint corners[4]; - wxPoint PadShapePos = ReturnShapePos(); /* Note: for pad having a shape offset, + wxPoint PadShapePos = ShapePos(); /* Note: for pad having a shape offset, * the pad position is NOT the shape position */ switch( GetShape() ) { @@ -694,8 +694,8 @@ void CreateThermalReliefPadPolygon( CPOLYGONS_LIST& aCornerBuffer, double aThermalRot ) { wxPoint corner, corner_end; - wxPoint PadShapePos = aPad.ReturnShapePos(); /* Note: for pad having a shape offset, - * the pad position is NOT the shape position */ + wxPoint PadShapePos = aPad.ShapePos(); // Note: for pad having a shape offset, + // the pad position is NOT the shape position wxSize copper_thickness; int dx = aPad.GetSize().x / 2; diff --git a/pcbnew/class_board.cpp b/pcbnew/class_board.cpp index ff2a89a0d5..20860474eb 100644 --- a/pcbnew/class_board.cpp +++ b/pcbnew/class_board.cpp @@ -1435,7 +1435,7 @@ static bool s_SortByNodes( const NETINFO_ITEM* a, const NETINFO_ITEM* b ) } -int BOARD::ReturnSortedNetnamesList( wxArrayString& aNames, bool aSortbyPadsCount ) +int BOARD::SortedNetnamesList( wxArrayString& aNames, bool aSortbyPadsCount ) { if( m_NetInfo.GetNetCount() == 0 ) return 0; diff --git a/pcbnew/class_board.h b/pcbnew/class_board.h index 0d394297b2..6131859bb3 100644 --- a/pcbnew/class_board.h +++ b/pcbnew/class_board.h @@ -1013,13 +1013,13 @@ public: REPORTER* aReporter = NULL ); /** - * Function ReturnSortedNetnamesList + * Function SortedNetnamesList * @param aNames An array string to fill with net names. * @param aSortbyPadsCount true = sort by active pads count, false = no sort (i.e. * leave the sort by net names) * @return int - net names count. */ - int ReturnSortedNetnamesList( wxArrayString& aNames, bool aSortbyPadsCount ); + int SortedNetnamesList( wxArrayString& aNames, bool aSortbyPadsCount ); /**************************************/ /** diff --git a/pcbnew/class_module.cpp b/pcbnew/class_module.cpp index 29f5c0fe06..237a24499d 100644 --- a/pcbnew/class_module.cpp +++ b/pcbnew/class_module.cpp @@ -573,7 +573,7 @@ D_PAD* MODULE::FindPadByName( const wxString& aPadName ) const for( D_PAD* pad = m_Pads; pad; pad = pad->Next() ) { - pad->ReturnStringPadName( buf ); + pad->StringPadName( buf ); #if 1 if( buf.CmpNoCase( aPadName ) == 0 ) // why case insensitive? #else @@ -588,7 +588,7 @@ D_PAD* MODULE::FindPadByName( const wxString& aPadName ) const D_PAD* MODULE::GetPad( const wxPoint& aPosition, LAYER_MSK aLayerMask ) { - for( D_PAD* pad = m_Pads; pad; pad = pad->Next() ) + for( D_PAD* pad = m_Pads; pad; pad = pad->Next() ) { // ... and on the correct layer. if( ( pad->GetLayerMask() & aLayerMask ) == 0 ) @@ -770,7 +770,7 @@ void MODULE::ViewUpdate( int aUpdateFlags ) */ bool MODULE::IsLibNameValid( const wxString & aName ) { - const wxChar * invalids = ReturnStringLibNameInvalidChars( false ); + const wxChar * invalids = StringLibNameInvalidChars( false ); if( aName.find_first_of( invalids ) != std::string::npos ) return false; @@ -786,7 +786,7 @@ bool MODULE::IsLibNameValid( const wxString & aName ) * return a constant string giving the list of invalid chars in lib name * static function */ -const wxChar* MODULE::ReturnStringLibNameInvalidChars( bool aUserReadable ) +const wxChar* MODULE::StringLibNameInvalidChars( bool aUserReadable ) { static const wxChar invalidChars[] = wxT("%$\t \"\\/"); static const wxChar invalidCharsReadable[] = wxT("% $ 'tab' 'space' \\ \" /"); @@ -892,7 +892,7 @@ void MODULE::Flip( const wxPoint& aCentre ) case PCB_MODULE_TEXT_T: text = (TEXTE_MODULE*) item; text->m_Pos.y -= m_Pos.y; - NEGATE( text->m_Pos0.y ); + NEGATE( text->m_Pos.y ); text->m_Pos.y += m_Pos.y; NEGATE( text->m_Pos0.y ); NEGATE_AND_NORMALIZE_ANGLE_POS( text->m_Orient ); diff --git a/pcbnew/class_module.h b/pcbnew/class_module.h index dbea0179d9..3127d73fb1 100644 --- a/pcbnew/class_module.h +++ b/pcbnew/class_module.h @@ -251,8 +251,14 @@ public: * function ReadandInsert3DComponentShape * read the 3D component shape(s) of the footprint (physical shape) * and insert mesh in gl list + * @param glcanvas = the openGL canvas + * @param aAllowNonTransparentObjects = true to load non transparent objects + * @param aAllowTransparentObjects = true to load non transparent objects + * in openGL, transparent objects should be drawn *after* non transparent objects */ - void ReadAndInsert3DComponentShape( EDA_3D_CANVAS* glcanvas ); + void ReadAndInsert3DComponentShape( EDA_3D_CANVAS* glcanvas, + bool aAllowNonTransparentObjects, + bool aAllowTransparentObjects ); /** * function TransformPadsShapesWithClearanceToPolygon @@ -482,14 +488,14 @@ public: static bool IsLibNameValid( const wxString & aName ); /** - * static function ReturnStringLibNameInvalidChars + * static function StringLibNameInvalidChars * Test for validity of the name in a library of the footprint * ( no spaces, dir separators ... ) * @param aUserReadable = false to get the list of invalid chars * true to get a readable form (i.e ' ' = 'space' '\\t'= 'tab') * @return a constant std::string giving the list of invalid chars in lib name */ - static const wxChar* ReturnStringLibNameInvalidChars( bool aUserReadable ); + static const wxChar* StringLibNameInvalidChars( bool aUserReadable ); /** * Function SetInitialComments diff --git a/pcbnew/class_pad.cpp b/pcbnew/class_pad.cpp index c4a83d2441..43b2b17f04 100644 --- a/pcbnew/class_pad.cpp +++ b/pcbnew/class_pad.cpp @@ -269,7 +269,7 @@ void D_PAD::AppendConfigs( PARAM_CFG_ARRAY* aResult ) // Returns the position of the pad. -const wxPoint D_PAD::ReturnShapePos() const +const wxPoint D_PAD::ShapePos() const { if( m_Offset.x == 0 && m_Offset.y == 0 ) return m_Pos; @@ -308,13 +308,13 @@ const wxString D_PAD::GetPadName() const wxString name; - ReturnStringPadName( name ); + StringPadName( name ); return name; #endif } -void D_PAD::ReturnStringPadName( wxString& text ) const +void D_PAD::StringPadName( wxString& text ) const { #if 0 // m_Padname is not ASCII and not UTF8, it is LATIN1 basically, whatever // 8 bit font is supported in KiCad plotting and drawing. @@ -564,7 +564,7 @@ void D_PAD::GetMsgPanelInfo( std::vector< MSG_PANEL_ITEM>& aList ) { wxString msg = module->GetReference(); aList.push_back( MSG_PANEL_ITEM( _( "Module" ), msg, DARKCYAN ) ); - ReturnStringPadName( Line ); + StringPadName( Line ); aList.push_back( MSG_PANEL_ITEM( _( "Pad" ), Line, BROWN ) ); } @@ -641,7 +641,7 @@ bool D_PAD::HitTest( const wxPoint& aPosition ) { int dx, dy; - wxPoint shape_pos = ReturnShapePos(); + wxPoint shape_pos = ShapePos(); wxPoint delta = aPosition - shape_pos; @@ -833,29 +833,40 @@ void D_PAD::ViewGetLayers( int aLayers[], int& aCount ) const // Multi layer pad aLayers[aCount++] = ITEM_GAL_LAYER( PADS_VISIBLE ); aLayers[aCount++] = NETNAMES_GAL_LAYER( PADS_NETNAMES_VISIBLE ); - aLayers[aCount++] = SOLDERMASK_N_FRONT; - aLayers[aCount++] = SOLDERMASK_N_BACK; - aLayers[aCount++] = SOLDERPASTE_N_FRONT; - aLayers[aCount++] = SOLDERPASTE_N_BACK; } else if( IsOnLayer( LAYER_N_FRONT ) ) { aLayers[aCount++] = ITEM_GAL_LAYER( PAD_FR_VISIBLE ); aLayers[aCount++] = NETNAMES_GAL_LAYER( PAD_FR_NETNAMES_VISIBLE ); - aLayers[aCount++] = SOLDERMASK_N_FRONT; - aLayers[aCount++] = SOLDERPASTE_N_FRONT; } else if( IsOnLayer( LAYER_N_BACK ) ) { aLayers[aCount++] = ITEM_GAL_LAYER( PAD_BK_VISIBLE ); aLayers[aCount++] = NETNAMES_GAL_LAYER( PAD_BK_NETNAMES_VISIBLE ); - aLayers[aCount++] = SOLDERMASK_N_BACK; - aLayers[aCount++] = SOLDERPASTE_N_BACK; } + + if( IsOnLayer( SOLDERMASK_N_FRONT ) ) + aLayers[aCount++] = SOLDERMASK_N_FRONT; + + if( IsOnLayer( SOLDERMASK_N_BACK ) ) + aLayers[aCount++] = SOLDERMASK_N_BACK; + + if( IsOnLayer( SOLDERPASTE_N_FRONT ) ) + aLayers[aCount++] = SOLDERPASTE_N_FRONT; + + if( IsOnLayer( SOLDERPASTE_N_BACK ) ) + aLayers[aCount++] = SOLDERPASTE_N_BACK; + + if( IsOnLayer( ADHESIVE_N_BACK ) ) + aLayers[aCount++] = ADHESIVE_N_BACK; + + if( IsOnLayer( ADHESIVE_N_FRONT ) ) + aLayers[aCount++] = ADHESIVE_N_FRONT; + #ifdef __WXDEBUG__ - else // Should not occur + if( aCount == 0 ) // Should not occur { - wxLogWarning( wxT("D_PAD::ViewGetLayers():PAD on layer different than FRONT/BACK") ); + wxLogWarning( wxT("D_PAD::ViewGetLayers():PAD has no layer") ); } #endif } diff --git a/pcbnew/class_pad.h b/pcbnew/class_pad.h index 7ceb06016d..11b49568c1 100644 --- a/pcbnew/class_pad.h +++ b/pcbnew/class_pad.h @@ -35,7 +35,7 @@ #include #include #include -#include // PARAM_CFG_ARRAY +#include // PARAM_CFG_ARRAY #include "zones.h" @@ -335,7 +335,7 @@ public: int BuildSegmentFromOvalShape( wxPoint& aSegStart, wxPoint& aSegEnd, double aRotation, const wxSize& aMargin ) const; - void ReturnStringPadName( wxString& text ) const; // Return pad name as string in a buffer + void StringPadName( wxString& text ) const; // Return pad name as string in a buffer /** * Function GetBoundingRadius @@ -354,7 +354,7 @@ public: return m_boundingRadius; } - const wxPoint ReturnShapePos() const; + const wxPoint ShapePos() const; /** * Function GetSubRatsnest @@ -489,7 +489,7 @@ private: * In all cases the pad position is the pad hole. * The physical shape position (used to draw it for instance) is pad * position (m_Pos) + m_Offset. - * D_PAD::ReturnShapePos() returns the physical shape position according to + * D_PAD::ShapePos() returns the physical shape position according to * the offset and the pad rotation. */ wxPoint m_Offset; diff --git a/pcbnew/class_pad_draw_functions.cpp b/pcbnew/class_pad_draw_functions.cpp index 7c21d9c4b2..dfa489041a 100644 --- a/pcbnew/class_pad_draw_functions.cpp +++ b/pcbnew/class_pad_draw_functions.cpp @@ -317,7 +317,7 @@ void D_PAD::DrawShape( EDA_RECT* aClipBox, wxDC* aDC, PAD_DRAWINFO& aDrawInfo ) GRSetDrawMode( aDC, aDrawInfo.m_DrawMode ); // calculate pad shape position : - wxPoint shape_pos = ReturnShapePos() - aDrawInfo.m_Offset; + wxPoint shape_pos = ShapePos() - aDrawInfo.m_Offset; wxSize halfsize = m_Size; halfsize.x >>= 1; @@ -544,7 +544,7 @@ void D_PAD::DrawShape( EDA_RECT* aClipBox, wxDC* aDC, PAD_DRAWINFO& aDrawInfo ) if( aDrawInfo.m_Display_padnum ) { - ReturnStringPadName( buffer ); + StringPadName( buffer ); int numpad_len = buffer.Len(); numpad_len = std::max( numpad_len, MIN_CHAR_COUNT ); diff --git a/pcbnew/class_pcb_layer_widget.cpp b/pcbnew/class_pcb_layer_widget.cpp index cd80e35b75..e9a8042775 100644 --- a/pcbnew/class_pcb_layer_widget.cpp +++ b/pcbnew/class_pcb_layer_widget.cpp @@ -29,7 +29,7 @@ /******************************************************/ #include -#include +#include #include #include #include @@ -49,6 +49,8 @@ #include #include +#include + /// This is a read only template that is copied and modified before adding to LAYER_WIDGET const LAYER_WIDGET::ROW PCB_LAYER_WIDGET::s_render_rows[] = { @@ -420,8 +422,13 @@ void PCB_LAYER_WIDGET::OnRenderEnable( int aId, bool isEnabled ) EDA_DRAW_PANEL_GAL* galCanvas = myframe->GetGalCanvas(); if( galCanvas ) { - KIGFX::VIEW* view = galCanvas->GetView(); - view->SetLayerVisible( ITEM_GAL_LAYER( aId ), isEnabled ); + if( aId == GRID_VISIBLE ) + { + galCanvas->GetGAL()->SetGridVisibility( myframe->IsGridVisible() ); + galCanvas->GetView()->MarkTargetDirty( KIGFX::TARGET_NONCACHED ); + } + else + galCanvas->GetView()->SetLayerVisible( ITEM_GAL_LAYER( aId ), isEnabled ); } if( galCanvas && myframe->IsGalCanvasActive() ) diff --git a/pcbnew/class_track.cpp b/pcbnew/class_track.cpp index 93288465c2..8346dabeb5 100644 --- a/pcbnew/class_track.cpp +++ b/pcbnew/class_track.cpp @@ -215,7 +215,7 @@ wxString SEGVIA::GetSelectMenuText() const // say which layers, only two for now LAYER_NUM topLayer; LAYER_NUM botLayer; - ReturnLayerPair( &topLayer, &botLayer ); + LayerPair( &topLayer, &botLayer ); text.Printf( format.GetData(), GetChars( ShowWidth() ), GetChars( netname ), GetNetCode(), GetChars( board->GetLayerName( topLayer ) ), @@ -395,7 +395,7 @@ bool SEGVIA::IsOnLayer( LAYER_NUM layer_number ) const { LAYER_NUM bottom_layer, top_layer; - ReturnLayerPair( &top_layer, &bottom_layer ); + LayerPair( &top_layer, &bottom_layer ); if( bottom_layer <= layer_number && layer_number <= top_layer ) return true; @@ -417,8 +417,8 @@ LAYER_MSK TRACK::GetLayerMask() const LAYER_NUM bottom_layer, top_layer; - // ReturnLayerPair() knows how layers are stored - ( (SEGVIA*) this )->ReturnLayerPair( &top_layer, &bottom_layer ); + // LayerPair() knows how layers are stored + ( (SEGVIA*) this )->LayerPair( &top_layer, &bottom_layer ); LAYER_MSK layermask = NO_LAYERS; @@ -453,7 +453,7 @@ void SEGVIA::SetLayerPair( LAYER_NUM top_layer, LAYER_NUM bottom_layer ) } -void SEGVIA::ReturnLayerPair( LAYER_NUM* top_layer, LAYER_NUM* bottom_layer ) const +void SEGVIA::LayerPair( LAYER_NUM* top_layer, LAYER_NUM* bottom_layer ) const { LAYER_NUM b_layer = LAYER_N_BACK; LAYER_NUM t_layer = LAYER_N_FRONT; @@ -922,7 +922,7 @@ void SEGVIA::Draw( EDA_DRAW_PANEL* panel, wxDC* aDC, GR_DRAWMODE aDrawMode, int ax = 0, ay = radius, bx = 0, by = drill_radius; LAYER_NUM layer_top, layer_bottom; - ( (SEGVIA*) this )->ReturnLayerPair( &layer_top, &layer_bottom ); + ( (SEGVIA*) this )->LayerPair( &layer_top, &layer_bottom ); // lines for the top layer RotatePoint( &ax, &ay, layer_top * 3600.0 / brd->GetCopperLayerCount( ) ); @@ -1144,7 +1144,7 @@ void TRACK::GetMsgPanelInfoBase( std::vector< MSG_PANEL_ITEM >& aList ) SEGVIA* Via = (SEGVIA*) this; LAYER_NUM top_layer, bottom_layer; - Via->ReturnLayerPair( &top_layer, &bottom_layer ); + Via->LayerPair( &top_layer, &bottom_layer ); if( board ) msg = board->GetLayerName( top_layer ) + wxT( "/" ) + board->GetLayerName( bottom_layer ); diff --git a/pcbnew/class_track.h b/pcbnew/class_track.h index 594678bf40..56ac970102 100644 --- a/pcbnew/class_track.h +++ b/pcbnew/class_track.h @@ -400,13 +400,13 @@ public: void SetLayerPair( LAYER_NUM top_layer, LAYER_NUM bottom_layer ); /** - * Function ReturnLayerPair + * Function LayerPair * Return the 2 layers used by the via (the via actually uses * all layers between these 2 layers) * @param top_layer = pointer to the first layer (can be null) * @param bottom_layer = pointer to the last layer (can be null) */ - void ReturnLayerPair( LAYER_NUM* top_layer, LAYER_NUM* bottom_layer ) const; + void LayerPair( LAYER_NUM* top_layer, LAYER_NUM* bottom_layer ) const; const wxPoint& GetPosition() const { return m_Start; } // was overload void SetPosition( const wxPoint& aPoint ) { m_Start = aPoint; m_End = aPoint; } // was overload diff --git a/pcbnew/clean.cpp b/pcbnew/clean.cpp index 8e2f77d506..e90a496bf0 100644 --- a/pcbnew/clean.cpp +++ b/pcbnew/clean.cpp @@ -327,7 +327,7 @@ bool TRACKS_CLEANER::deleteUnconnectedTracks() } else { - ((SEGVIA*)track)->ReturnLayerPair( &top_layer, &bottom_layer ); + ((SEGVIA*)track)->LayerPair( &top_layer, &bottom_layer ); zone = m_Brd->HitTestForAnyFilledArea( track->GetStart(), top_layer, bottom_layer, track->GetNetCode() ); @@ -355,7 +355,7 @@ bool TRACKS_CLEANER::deleteUnconnectedTracks() if( other == NULL ) { - via->ReturnLayerPair( &top_layer, &bottom_layer ); + via->LayerPair( &top_layer, &bottom_layer ); zone = m_Brd->HitTestForAnyFilledArea( via->GetStart(), bottom_layer, top_layer, @@ -387,7 +387,7 @@ bool TRACKS_CLEANER::deleteUnconnectedTracks() } else { - ((SEGVIA*)track)->ReturnLayerPair( &top_layer, &bottom_layer ); + ((SEGVIA*)track)->LayerPair( &top_layer, &bottom_layer ); zone = m_Brd->HitTestForAnyFilledArea( track->GetEnd(), top_layer, bottom_layer, track->GetNetCode() ); @@ -416,7 +416,7 @@ bool TRACKS_CLEANER::deleteUnconnectedTracks() if( other == NULL ) { - via->ReturnLayerPair( &top_layer, &bottom_layer ); + via->LayerPair( &top_layer, &bottom_layer ); zone = m_Brd->HitTestForAnyFilledArea( via->GetEnd(), bottom_layer, top_layer, via->GetNetCode() ); diff --git a/pcbnew/connect.cpp b/pcbnew/connect.cpp index 9fd2c7ad47..4623c5e932 100644 --- a/pcbnew/connect.cpp +++ b/pcbnew/connect.cpp @@ -79,7 +79,7 @@ void CONNECTIONS::SearchConnectionsPadsToIntersectingPads() pad->m_PadsConnected.clear(); candidates.clear(); - CollectItemsNearTo( candidates, pad->ReturnShapePos(), pad->GetBoundingRadius() ); + CollectItemsNearTo( candidates, pad->ShapePos(), pad->GetBoundingRadius() ); // add pads to pad.m_PadsConnected, if they are connected for( unsigned jj = 0; jj < candidates.size(); jj++ ) diff --git a/pcbnew/cross-probing.cpp b/pcbnew/cross-probing.cpp index 8042a892a0..6aba44cb2b 100644 --- a/pcbnew/cross-probing.cpp +++ b/pcbnew/cross-probing.cpp @@ -11,7 +11,7 @@ */ #include -#include +#include #include #include #include diff --git a/pcbnew/dialogs/dialog_SVG_print.cpp b/pcbnew/dialogs/dialog_SVG_print.cpp index cfd0f4fa3b..5fb3757479 100644 --- a/pcbnew/dialogs/dialog_SVG_print.cpp +++ b/pcbnew/dialogs/dialog_SVG_print.cpp @@ -28,7 +28,8 @@ #include -#include +//#include +#include #include #include #include @@ -66,7 +67,7 @@ DIALOG_SVG_PRINT::DIALOG_SVG_PRINT( EDA_DRAW_FRAME* parent ) : DIALOG_SVG_PRINT_base( parent ) { m_parent = (PCB_BASE_FRAME*) parent; - m_config = wxGetApp().GetSettings(); + m_config = Kiface().KifaceSettings(); initDialog(); GetSizer()->SetSizeHints( this ); Centre(); @@ -103,7 +104,7 @@ void DIALOG_SVG_PRINT::initDialog() AddUnitSymbol( *m_TextPenWidth, g_UserUnit ); m_DialogDefaultPenSize->SetValue( - ReturnStringFromValue( g_UserUnit, g_DrawDefaultLineThickness ) ); + StringFromValue( g_UserUnit, g_DrawDefaultLineThickness ) ); // Create layers list LAYER_NUM layer; @@ -206,7 +207,7 @@ void DIALOG_SVG_PRINT::OnOutputDirectoryBrowseClicked( wxCommandEvent& event ) void DIALOG_SVG_PRINT::SetPenWidth() { - int pensize = ReturnValueFromTextCtrl( *m_DialogDefaultPenSize ); + int pensize = ValueFromTextCtrl( *m_DialogDefaultPenSize ); if( pensize > WIDTH_MAX_VALUE ) { @@ -219,7 +220,7 @@ void DIALOG_SVG_PRINT::SetPenWidth() } g_DrawDefaultLineThickness = pensize; - m_DialogDefaultPenSize->SetValue( ReturnStringFromValue( g_UserUnit, pensize ) ); + m_DialogDefaultPenSize->SetValue( StringFromValue( g_UserUnit, pensize ) ); } diff --git a/pcbnew/dialogs/dialog_SVG_print.h b/pcbnew/dialogs/dialog_SVG_print.h index 8fc110286c..bf7309c409 100644 --- a/pcbnew/dialogs/dialog_SVG_print.h +++ b/pcbnew/dialogs/dialog_SVG_print.h @@ -16,7 +16,7 @@ class DIALOG_SVG_PRINT : public DIALOG_SVG_PRINT_base private: PCB_BASE_FRAME* m_parent; BOARD* m_board; - wxConfig* m_config; + wxConfigBase* m_config; LAYER_MSK m_printMaskLayer; wxCheckBox* m_boxSelectLayer[32]; bool m_printBW; diff --git a/pcbnew/dialogs/dialog_copper_zones.cpp b/pcbnew/dialogs/dialog_copper_zones.cpp index 0b07db304f..a343c60198 100644 --- a/pcbnew/dialogs/dialog_copper_zones.cpp +++ b/pcbnew/dialogs/dialog_copper_zones.cpp @@ -29,7 +29,8 @@ #include #include -#include +//#include +#include #include #include #include @@ -57,7 +58,7 @@ public: private: PCB_BASE_FRAME* m_Parent; - wxConfig* m_Config; ///< Current config + wxConfigBase* m_Config; ///< Current config ZONE_EDIT_T m_OnExitCode; ///< exit code: ZONE_ABORT if no change, ///< ZONE_OK if new values accepted @@ -139,7 +140,7 @@ DIALOG_COPPER_ZONE::DIALOG_COPPER_ZONE( PCB_BASE_FRAME* aParent, ZONE_SETTINGS* DIALOG_COPPER_ZONE_BASE( aParent ) { m_Parent = aParent; - m_Config = wxGetApp().GetSettings(); + m_Config = Kiface().KifaceSettings(); m_ptr = aSettings; m_settings = *aSettings; @@ -173,11 +174,11 @@ void DIALOG_COPPER_ZONE::initDialog() m_FillModeCtrl->SetSelection( m_settings.m_FillMode ? 1 : 0 ); AddUnitSymbol( *m_ClearanceValueTitle, g_UserUnit ); - msg = ReturnStringFromValue( g_UserUnit, m_settings.m_ZoneClearance ); + msg = StringFromValue( g_UserUnit, m_settings.m_ZoneClearance ); m_ZoneClearanceCtrl->SetValue( msg ); AddUnitSymbol( *m_MinThicknessValueTitle, g_UserUnit ); - msg = ReturnStringFromValue( g_UserUnit, m_settings.m_ZoneMinThickness ); + msg = StringFromValue( g_UserUnit, m_settings.m_ZoneMinThickness ); m_ZoneMinThicknessCtrl->SetValue( msg ); switch( m_settings.GetPadConnection() ) @@ -388,7 +389,7 @@ bool DIALOG_COPPER_ZONE::AcceptOptions( bool aPromptForErrors, bool aUseExportab m_settings.m_FillMode = (m_FillModeCtrl->GetSelection() == 0) ? 0 : 1; wxString txtvalue = m_ZoneClearanceCtrl->GetValue(); - m_settings.m_ZoneClearance = ReturnValueFromString( g_UserUnit, txtvalue ); + m_settings.m_ZoneClearance = ValueFromString( g_UserUnit, txtvalue ); // Test if this is a reasonable value for this parameter // A too large value can hang Pcbnew @@ -403,7 +404,7 @@ bool DIALOG_COPPER_ZONE::AcceptOptions( bool aPromptForErrors, bool aUseExportab } txtvalue = m_ZoneMinThicknessCtrl->GetValue(); - m_settings.m_ZoneMinThickness = ReturnValueFromString( g_UserUnit, txtvalue ); + m_settings.m_ZoneMinThickness = ValueFromString( g_UserUnit, txtvalue ); if( m_settings.m_ZoneMinThickness < (ZONE_THICKNESS_MIN_VALUE_MIL*IU_PER_MILS) ) { @@ -416,7 +417,7 @@ bool DIALOG_COPPER_ZONE::AcceptOptions( bool aPromptForErrors, bool aUseExportab m_settings.SetCornerSmoothingType( m_cornerSmoothingChoice->GetSelection() ); txtvalue = m_cornerSmoothingCtrl->GetValue(); - m_settings.SetCornerRadius( ReturnValueFromString( g_UserUnit, txtvalue ) ); + m_settings.SetCornerRadius( ValueFromString( g_UserUnit, txtvalue ) ); m_settings.m_ZonePriority = m_PriorityLevelCtrl->GetValue(); @@ -425,8 +426,8 @@ bool DIALOG_COPPER_ZONE::AcceptOptions( bool aPromptForErrors, bool aUseExportab else m_settings.m_Zone_45_Only = true; - m_settings.m_ThermalReliefGap = ReturnValueFromTextCtrl( *m_AntipadSizeValue ); - m_settings.m_ThermalReliefCopperBridge = ReturnValueFromTextCtrl( *m_CopperWidthValue ); + m_settings.m_ThermalReliefGap = ValueFromTextCtrl( *m_AntipadSizeValue ); + m_settings.m_ThermalReliefCopperBridge = ValueFromTextCtrl( *m_CopperWidthValue ); if( m_Config ) { @@ -624,7 +625,7 @@ void DIALOG_COPPER_ZONE::buildAvailableListOfNets() { wxArrayString listNetName; - m_Parent->GetBoard()->ReturnSortedNetnamesList( listNetName, m_NetSortingByPadCount ); + m_Parent->GetBoard()->SortedNetnamesList( listNetName, m_NetSortingByPadCount ); if( m_NetFiltering ) { diff --git a/pcbnew/dialogs/dialog_design_rules.cpp b/pcbnew/dialogs/dialog_design_rules.cpp index e5325943fe..f83be84b9e 100644 --- a/pcbnew/dialogs/dialog_design_rules.cpp +++ b/pcbnew/dialogs/dialog_design_rules.cpp @@ -190,15 +190,15 @@ void DIALOG_DESIGN_RULES::PrintCurrentSettings() m_MessagesList->AppendToPage( _( "Current general settings:
" ) ); // Display min values: - value = ReturnStringFromValue( g_UserUnit, m_BrdSettings.m_TrackMinWidth, true ); + value = StringFromValue( g_UserUnit, m_BrdSettings.m_TrackMinWidth, true ); msg.Printf( _( "Minimum value for tracks width: %s
\n" ), GetChars( value ) ); m_MessagesList->AppendToPage( msg ); - value = ReturnStringFromValue( g_UserUnit, m_BrdSettings.m_ViasMinSize, true ); + value = StringFromValue( g_UserUnit, m_BrdSettings.m_ViasMinSize, true ); msg.Printf( _( "Minimum value for vias diameter: %s
\n" ), GetChars( value ) ); m_MessagesList->AppendToPage( msg ); - value = ReturnStringFromValue( g_UserUnit, m_BrdSettings.m_MicroViasMinSize, true ); + value = StringFromValue( g_UserUnit, m_BrdSettings.m_MicroViasMinSize, true ); msg.Printf( _( "Minimum value for microvias diameter: %s
\n" ), GetChars( value ) ); m_MessagesList->AppendToPage( msg ); } @@ -312,17 +312,17 @@ void DIALOG_DESIGN_RULES::InitDimensionsLists() for( unsigned ii = 0; ii < m_TracksWidthList.size(); ii++ ) { - msg = ReturnStringFromValue( g_UserUnit, m_TracksWidthList[ii], false ); + msg = StringFromValue( g_UserUnit, m_TracksWidthList[ii], false ); m_gridTrackWidthList->SetCellValue( ii, 0, msg ); } for( unsigned ii = 0; ii < m_ViasDimensionsList.size(); ii++ ) { - msg = ReturnStringFromValue( g_UserUnit, m_ViasDimensionsList[ii].m_Diameter, false ); + msg = StringFromValue( g_UserUnit, m_ViasDimensionsList[ii].m_Diameter, false ); m_gridViaSizeList->SetCellValue( ii, 0, msg ); if( m_ViasDimensionsList[ii].m_Drill > 0 ) { - msg = ReturnStringFromValue( g_UserUnit, m_ViasDimensionsList[ii].m_Drill, false ); + msg = StringFromValue( g_UserUnit, m_ViasDimensionsList[ii].m_Drill, false ); m_gridViaSizeList->SetCellValue( ii, 1, msg ); } } @@ -458,22 +458,22 @@ static void class2gridRow( wxGrid* grid, int row, NETCLASS* nc ) // label is netclass name grid->SetRowLabelValue( row, nc->GetName() ); - msg = ReturnStringFromValue( g_UserUnit, nc->GetClearance() ); + msg = StringFromValue( g_UserUnit, nc->GetClearance() ); grid->SetCellValue( row, GRID_CLEARANCE, msg ); - msg = ReturnStringFromValue( g_UserUnit, nc->GetTrackWidth() ); + msg = StringFromValue( g_UserUnit, nc->GetTrackWidth() ); grid->SetCellValue( row, GRID_TRACKSIZE, msg ); - msg = ReturnStringFromValue( g_UserUnit, nc->GetViaDiameter() ); + msg = StringFromValue( g_UserUnit, nc->GetViaDiameter() ); grid->SetCellValue( row, GRID_VIASIZE, msg ); - msg = ReturnStringFromValue( g_UserUnit, nc->GetViaDrill() ); + msg = StringFromValue( g_UserUnit, nc->GetViaDrill() ); grid->SetCellValue( row, GRID_VIADRILL, msg ); - msg = ReturnStringFromValue( g_UserUnit, nc->GetuViaDiameter() ); + msg = StringFromValue( g_UserUnit, nc->GetuViaDiameter() ); grid->SetCellValue( row, GRID_uVIASIZE, msg ); - msg = ReturnStringFromValue( g_UserUnit, nc->GetuViaDrill() ); + msg = StringFromValue( g_UserUnit, nc->GetuViaDrill() ); grid->SetCellValue( row, GRID_uVIADRILL, msg ); } @@ -509,7 +509,7 @@ void DIALOG_DESIGN_RULES::InitRulesList() static void gridRow2class( wxGrid* grid, int row, NETCLASS* nc ) { #define MYCELL( col ) \ - ReturnValueFromString( g_UserUnit, grid->GetCellValue( row, col ) ) + ValueFromString( g_UserUnit, grid->GetCellValue( row, col ) ) nc->SetClearance( MYCELL( GRID_CLEARANCE ) ); nc->SetTrackWidth( MYCELL( GRID_TRACKSIZE ) ); @@ -571,17 +571,17 @@ void DIALOG_DESIGN_RULES::CopyGlobalRulesToBoard() m_BrdSettings.m_BlindBuriedViaAllowed = m_OptViaType->GetSelection() > 0; // Update vias minimum values for DRC - m_BrdSettings.m_ViasMinSize = ReturnValueFromTextCtrl( *m_SetViasMinSizeCtrl ); - m_BrdSettings.m_ViasMinDrill = ReturnValueFromTextCtrl( *m_SetViasMinDrillCtrl ); + m_BrdSettings.m_ViasMinSize = ValueFromTextCtrl( *m_SetViasMinSizeCtrl ); + m_BrdSettings.m_ViasMinDrill = ValueFromTextCtrl( *m_SetViasMinDrillCtrl ); m_BrdSettings.m_MicroViasAllowed = m_AllowMicroViaCtrl->GetSelection() == 1; // Update microvias minimum values for DRC - m_BrdSettings.m_MicroViasMinSize = ReturnValueFromTextCtrl( *m_SetMicroViasMinSizeCtrl ); - m_BrdSettings.m_MicroViasMinDrill = ReturnValueFromTextCtrl( *m_SetMicroViasMinDrillCtrl ); + m_BrdSettings.m_MicroViasMinSize = ValueFromTextCtrl( *m_SetMicroViasMinSizeCtrl ); + m_BrdSettings.m_MicroViasMinDrill = ValueFromTextCtrl( *m_SetMicroViasMinDrillCtrl ); // Update tracks minimum values for DRC - m_BrdSettings.m_TrackMinWidth = ReturnValueFromTextCtrl( *m_SetTrackMinWidthCtrl ); + m_BrdSettings.m_TrackMinWidth = ValueFromTextCtrl( *m_SetTrackMinWidthCtrl ); } @@ -600,7 +600,7 @@ void DIALOG_DESIGN_RULES::CopyDimensionsListsToBoard() if( msg.IsEmpty() ) continue; - int value = ReturnValueFromString( g_UserUnit, msg ); + int value = ValueFromString( g_UserUnit, msg ); m_TracksWidthList.push_back( value ); } @@ -617,14 +617,14 @@ void DIALOG_DESIGN_RULES::CopyDimensionsListsToBoard() if( msg.IsEmpty() ) continue; - int value = ReturnValueFromString( g_UserUnit, msg ); + int value = ValueFromString( g_UserUnit, msg ); VIA_DIMENSION via_dim; via_dim.m_Diameter = value; msg = m_gridViaSizeList->GetCellValue( row, 1 ); if( !msg.IsEmpty() ) { - value = ReturnValueFromString( g_UserUnit, msg ); + value = ValueFromString( g_UserUnit, msg ); via_dim.m_Drill = value; } @@ -949,18 +949,18 @@ bool DIALOG_DESIGN_RULES::TestDataValidity() wxString msg; - int minViaDia = ReturnValueFromTextCtrl( *m_SetViasMinSizeCtrl ); - int minViaDrill = ReturnValueFromTextCtrl( *m_SetViasMinDrillCtrl ); - int minUViaDia = ReturnValueFromTextCtrl( *m_SetMicroViasMinSizeCtrl ); - int minUViaDrill = ReturnValueFromTextCtrl( *m_SetMicroViasMinDrillCtrl ); - int minTrackWidth = ReturnValueFromTextCtrl( *m_SetTrackMinWidthCtrl ); + int minViaDia = ValueFromTextCtrl( *m_SetViasMinSizeCtrl ); + int minViaDrill = ValueFromTextCtrl( *m_SetViasMinDrillCtrl ); + int minUViaDia = ValueFromTextCtrl( *m_SetMicroViasMinSizeCtrl ); + int minUViaDrill = ValueFromTextCtrl( *m_SetMicroViasMinDrillCtrl ); + int minTrackWidth = ValueFromTextCtrl( *m_SetTrackMinWidthCtrl ); int maxval = 1000 * IU_PER_MILS; // a max value for tracks and vias sizes (1 inch) for( int row = 0; row < m_grid->GetNumberRows(); row++ ) { - int tracksize = ReturnValueFromString( g_UserUnit, + int tracksize = ValueFromString( g_UserUnit, m_grid->GetCellValue( row, GRID_TRACKSIZE ) ); if( tracksize < minTrackWidth ) { @@ -972,7 +972,7 @@ bool DIALOG_DESIGN_RULES::TestDataValidity() } // Test vias - int viadia = ReturnValueFromString( g_UserUnit, + int viadia = ValueFromString( g_UserUnit, m_grid->GetCellValue( row, GRID_VIASIZE ) ); if( viadia < minViaDia ) @@ -984,7 +984,7 @@ bool DIALOG_DESIGN_RULES::TestDataValidity() m_MessagesList->AppendToPage( msg ); } - int viadrill = ReturnValueFromString( g_UserUnit, + int viadrill = ValueFromString( g_UserUnit, m_grid->GetCellValue( row, GRID_VIADRILL ) ); if( viadrill >= viadia ) { @@ -1005,7 +1005,7 @@ bool DIALOG_DESIGN_RULES::TestDataValidity() } // Test Micro vias - int muviadia = ReturnValueFromString( g_UserUnit, + int muviadia = ValueFromString( g_UserUnit, m_grid->GetCellValue( row, GRID_uVIASIZE ) ); if( muviadia < minUViaDia ) @@ -1017,7 +1017,7 @@ bool DIALOG_DESIGN_RULES::TestDataValidity() m_MessagesList->AppendToPage( msg ); } - int muviadrill = ReturnValueFromString( g_UserUnit, + int muviadrill = ValueFromString( g_UserUnit, m_grid->GetCellValue( row, GRID_uVIADRILL ) ); if( muviadrill >= muviadia ) { @@ -1046,7 +1046,7 @@ bool DIALOG_DESIGN_RULES::TestDataValidity() if( tvalue.IsEmpty() ) continue; - int tracksize = ReturnValueFromString( g_UserUnit, tvalue ); + int tracksize = ValueFromString( g_UserUnit, tvalue ); if( tracksize < minTrackWidth ) { @@ -1073,12 +1073,12 @@ bool DIALOG_DESIGN_RULES::TestDataValidity() if( tvalue.IsEmpty() ) continue; - int viadia = ReturnValueFromString( g_UserUnit, tvalue ); + int viadia = ValueFromString( g_UserUnit, tvalue ); int viadrill = 0; wxString drlvalue = m_gridViaSizeList->GetCellValue( row, 1 ); if( !drlvalue.IsEmpty() ) - viadrill = ReturnValueFromString( g_UserUnit, drlvalue ); + viadrill = ValueFromString( g_UserUnit, drlvalue ); if( viadia < minViaDia ) { diff --git a/pcbnew/dialogs/dialog_drc.cpp b/pcbnew/dialogs/dialog_drc.cpp index d65d497784..4eafff3832 100644 --- a/pcbnew/dialogs/dialog_drc.cpp +++ b/pcbnew/dialogs/dialog_drc.cpp @@ -99,9 +99,9 @@ void DIALOG_DRC_CONTROL::InitValues() */ void DIALOG_DRC_CONTROL::SetDrcParmeters( ) { - m_BrdSettings.m_TrackMinWidth = ReturnValueFromTextCtrl( *m_SetTrackMinWidthCtrl ); - m_BrdSettings.m_ViasMinSize = ReturnValueFromTextCtrl( *m_SetViaMinSizeCtrl ); - m_BrdSettings.m_MicroViasMinSize = ReturnValueFromTextCtrl( *m_SetMicroViakMinSizeCtrl ); + m_BrdSettings.m_TrackMinWidth = ValueFromTextCtrl( *m_SetTrackMinWidthCtrl ); + m_BrdSettings.m_ViasMinSize = ValueFromTextCtrl( *m_SetViaMinSizeCtrl ); + m_BrdSettings.m_MicroViasMinSize = ValueFromTextCtrl( *m_SetMicroViakMinSizeCtrl ); m_Parent->GetBoard()->SetDesignSettings( m_BrdSettings ); } diff --git a/pcbnew/dialogs/dialog_edit_module_for_BoardEditor.cpp b/pcbnew/dialogs/dialog_edit_module_for_BoardEditor.cpp index 00c860a3fd..d8b6648b7a 100644 --- a/pcbnew/dialogs/dialog_edit_module_for_BoardEditor.cpp +++ b/pcbnew/dialogs/dialog_edit_module_for_BoardEditor.cpp @@ -29,11 +29,12 @@ #include +#include #include #include #include #include -#include +#include #include #include <3d_struct.h> #include <3d_viewer.h> @@ -427,17 +428,30 @@ void DIALOG_MODULE_BOARD_EDITOR::Remove3DShape( wxCommandEvent& event ) void DIALOG_MODULE_BOARD_EDITOR::Browse3DLib( wxCommandEvent& event ) { - wxString fullfilename, shortfilename; - wxString fullpath; + PROJECT& prj = Prj(); + SEARCH_STACK& search = Kiface().KifaceSearch(); + + wxString fullpath; + wxString kisys3dmod = wxGetenv( wxT( KISYS3DMOD ) ); + + if( !kisys3dmod || !wxFileName::IsDirReadable( kisys3dmod ) ) + { + fullpath = search.FindValidPath( LIB3D_PATH ); + } + + if( !fullpath ) + fullpath = prj.RPath(PROJECT::VIEWER_3D).LastVisitedPath( search, LIB3D_PATH ); - fullpath = wxGetApp().ReturnLastVisitedLibraryPath( LIB3D_PATH ); #ifdef __WINDOWS__ fullpath.Replace( wxT( "/" ), wxT( "\\" ) ); #endif - wxString fileFilters; - fileFilters = wxGetTranslation( Shapes3DFileWildcard ); - fileFilters += wxChar( '|' ); + wxString fullfilename; + wxString shortfilename; + + wxString fileFilters = wxGetTranslation( Shapes3DFileWildcard ); + + fileFilters += wxChar( '|' ); fileFilters += wxGetTranslation( IDF3DFileWildcard ); fullfilename = EDA_FileSelector( _( "3D Shape:" ), @@ -454,45 +468,42 @@ void DIALOG_MODULE_BOARD_EDITOR::Browse3DLib( wxCommandEvent& event ) return; wxFileName fn = fullfilename; - wxGetApp().SaveLastVisitedLibraryPath( fn.GetPath() ); - /* If the file path is already in the default search path - * list, just add the name to the list. Otherwise, add - * the name with the full or relative path. + prj.RPath(PROJECT::VIEWER_3D).SaveLastVisitedPath( fn.GetPath() ); + + /* If the file 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 search path, when the path is a - * sub path + * because it preserve use of default libraries paths, when the path is a + * sub path of these default paths */ + shortfilename = search.FilenameWithRelativePathInSearchList( fullfilename ); - wxString default_path; - wxGetEnv( wxT( KISYS3DMOD ), &default_path ); - fn.MakeRelativeTo( default_path ); - - // Here, we want a path relative only to the default_path - if( fn.GetPathWithSep().StartsWith( wxT("..") ) ) - fn = fullfilename; // keep the full file name - - shortfilename = fn.GetFullPath(); - - if( fn.IsAbsolute() ) - { // Absolute path, ask if the user wants a relative one + wxFileName aux = shortfilename; + if( aux.IsAbsolute() ) + { + // Absolute path, ask if the user wants a relative one int diag = wxMessageBox( _( "Use a relative path?" ), _( "Path type" ), wxYES_NO | wxICON_QUESTION, this ); if( diag == wxYES ) - { // Make it relative - fn.MakeRelativeTo( wxT(".") ); - shortfilename = fn.GetFullPath(); + { + // Make it relative + aux.MakeRelativeTo( wxT(".") ); + shortfilename = aux.GetPathWithSep() + aux.GetFullName(); } } S3D_MASTER* new3DShape = new S3D_MASTER( NULL ); + #ifdef __WINDOWS__ // Store filename in Unix notation shortfilename.Replace( wxT( "\\" ), wxT( "/" ) ); #endif + new3DShape->SetShape3DName( shortfilename ); m_Shapes3D_list.push_back( new3DShape ); m_3D_ShapeNameListBox->Append( shortfilename ); @@ -526,9 +537,9 @@ void DIALOG_MODULE_BOARD_EDITOR::OnOkClick( wxCommandEvent& event ) m_CurrentModule->Value().Copy( m_ValueCopy ); // Initialize masks clearances - m_CurrentModule->SetLocalClearance( ReturnValueFromTextCtrl( *m_NetClearanceValueCtrl ) ); - m_CurrentModule->SetLocalSolderMaskMargin( ReturnValueFromTextCtrl( *m_SolderMaskMarginCtrl ) ); - m_CurrentModule->SetLocalSolderPasteMargin( ReturnValueFromTextCtrl( *m_SolderPasteMarginCtrl ) ); + m_CurrentModule->SetLocalClearance( ValueFromTextCtrl( *m_NetClearanceValueCtrl ) ); + m_CurrentModule->SetLocalSolderMaskMargin( ValueFromTextCtrl( *m_SolderMaskMarginCtrl ) ); + m_CurrentModule->SetLocalSolderPasteMargin( ValueFromTextCtrl( *m_SolderPasteMarginCtrl ) ); double dtmp = 0.0; msg = m_SolderPasteMarginRatioCtrl->GetValue(); @@ -565,8 +576,8 @@ void DIALOG_MODULE_BOARD_EDITOR::OnOkClick( wxCommandEvent& event ) } // Set Module Position - modpos.x = ReturnValueFromTextCtrl( *m_ModPositionX ); - modpos.y = ReturnValueFromTextCtrl( *m_ModPositionY ); + modpos.x = ValueFromTextCtrl( *m_ModPositionX ); + modpos.y = ValueFromTextCtrl( *m_ModPositionY ); m_CurrentModule->SetPosition( modpos ); m_CurrentModule->SetLocked( m_AutoPlaceCtrl->GetSelection() == 1 ); @@ -614,7 +625,7 @@ void DIALOG_MODULE_BOARD_EDITOR::OnOkClick( wxCommandEvent& event ) m_CurrentModule->Flip( m_CurrentModule->GetPosition() ); // Update 3D shape list - int ii = m_3D_ShapeNameListBox->GetSelection(); + int ii = m_3D_ShapeNameListBox->GetSelection(); if( ii >= 0 ) TransfertDisplayTo3DValues( ii ); @@ -692,3 +703,4 @@ void DIALOG_MODULE_BOARD_EDITOR::OnEditValue( wxCommandEvent& event ) m_Parent->SetCrossHairPosition( tmp ); m_ValueCtrl->SetValue( m_ValueCopy->GetText() ); } + diff --git a/pcbnew/dialogs/dialog_edit_module_for_Modedit.cpp b/pcbnew/dialogs/dialog_edit_module_for_Modedit.cpp index 169e4e6c9a..6e0ee4bd19 100644 --- a/pcbnew/dialogs/dialog_edit_module_for_Modedit.cpp +++ b/pcbnew/dialogs/dialog_edit_module_for_Modedit.cpp @@ -35,7 +35,7 @@ #include #include #include -#include +#include #include #include <3d_struct.h> #include <3d_viewer.h> @@ -291,17 +291,27 @@ void DIALOG_MODULE_MODULE_EDITOR::Remove3DShape(wxCommandEvent& event) void DIALOG_MODULE_MODULE_EDITOR::BrowseAndAdd3DLib( wxCommandEvent& event ) { - wxString fullfilename, shortfilename; - wxString fullpath; + PROJECT& prj = Prj(); + SEARCH_STACK& search = Kiface().KifaceSearch(); - fullpath = wxGetApp().ReturnLastVisitedLibraryPath( LIB3D_PATH ); + wxString fullpath; + wxString kisys3dmod = wxGetenv( wxT( KISYS3DMOD ) ); + + if( !kisys3dmod || !wxFileName::IsDirReadable( kisys3dmod ) ) + { + fullpath = search.FindValidPath( LIB3D_PATH ); + } + + if( !fullpath ) + fullpath = prj.RPath(PROJECT::VIEWER_3D).LastVisitedPath( search, LIB3D_PATH ); #ifdef __WINDOWS__ fullpath.Replace( wxT( "/" ), wxT( "\\" ) ); #endif - wxString fileFilters; - fileFilters = wxGetTranslation( Shapes3DFileWildcard ); + wxString fullfilename, shortfilename; + wxString fileFilters = wxGetTranslation( Shapes3DFileWildcard ); + fileFilters += wxChar( '|' ); fileFilters += wxGetTranslation( IDF3DFileWildcard ); @@ -319,27 +329,20 @@ void DIALOG_MODULE_MODULE_EDITOR::BrowseAndAdd3DLib( wxCommandEvent& event ) return; wxFileName fn = fullfilename; - wxGetApp().SaveLastVisitedLibraryPath( fn.GetPath() ); - /* If the file path is already in the default search path - * list, just add the name to the list. Otherwise, add - * the name with the full or relative path. + prj.RPath(PROJECT::VIEWER_3D).SaveLastVisitedPath( fn.GetPath() ); + + /* If the file 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 search path, when the path is a - * sub path + * because it preserve use of default libraries paths, when the path is a sub path of these default paths */ + shortfilename = search.FilenameWithRelativePathInSearchList( fullfilename ); - wxString default_path; - wxGetEnv( wxT( KISYS3DMOD ), &default_path ); - fn.MakeRelativeTo( default_path ); + wxFileName aux = shortfilename; - // Here, we want a path relative only to the default_path - if( fn.GetPathWithSep().StartsWith( wxT("..") ) ) - fn = fullfilename; // keep the full file name - - shortfilename = fn.GetFullPath(); - - if( fn.IsAbsolute() ) + if( aux.IsAbsolute() ) { // Absolute path, ask if the user wants a relative one int diag = wxMessageBox( _( "Use a relative path?" ), @@ -348,8 +351,8 @@ void DIALOG_MODULE_MODULE_EDITOR::BrowseAndAdd3DLib( wxCommandEvent& event ) if( diag == wxYES ) { // Make it relative - fn.MakeRelativeTo( wxT( "." ) ); - shortfilename = fn.GetFullPath(); + aux.MakeRelativeTo( wxT( "." ) ); + shortfilename = aux.GetPathWithSep() + aux.GetFullName(); } } @@ -370,7 +373,6 @@ void DIALOG_MODULE_MODULE_EDITOR::BrowseAndAdd3DLib( wxCommandEvent& event ) m_lastSelected3DShapeIndex = m_3D_ShapeNameListBox->GetCount() - 1; m_3D_ShapeNameListBox->SetSelection( m_lastSelected3DShapeIndex ); Transfert3DValuesToDisplay( m_shapes3D_list[m_lastSelected3DShapeIndex] ); - } @@ -391,7 +393,7 @@ void DIALOG_MODULE_MODULE_EDITOR::OnOkClick( wxCommandEvent& event ) { wxString msg; msg.Printf( _( "Error:\none of invalid chars <%s> found\nin <%s>" ), - MODULE::ReturnStringLibNameInvalidChars( true ), + MODULE::StringLibNameInvalidChars( true ), GetChars( footprintName ) ); DisplayError( NULL, msg ); @@ -431,9 +433,9 @@ void DIALOG_MODULE_MODULE_EDITOR::OnOkClick( wxCommandEvent& event ) m_currentModule->Value().Copy( m_valueCopy ); // Initialize masks clearances - m_currentModule->SetLocalClearance( ReturnValueFromTextCtrl( *m_NetClearanceValueCtrl ) ); - m_currentModule->SetLocalSolderMaskMargin( ReturnValueFromTextCtrl( *m_SolderMaskMarginCtrl ) ); - m_currentModule->SetLocalSolderPasteMargin( ReturnValueFromTextCtrl( *m_SolderPasteMarginCtrl ) ); + m_currentModule->SetLocalClearance( ValueFromTextCtrl( *m_NetClearanceValueCtrl ) ); + m_currentModule->SetLocalSolderMaskMargin( ValueFromTextCtrl( *m_SolderMaskMarginCtrl ) ); + m_currentModule->SetLocalSolderPasteMargin( ValueFromTextCtrl( *m_SolderPasteMarginCtrl ) ); double dtmp; wxString msg = m_SolderPasteMarginRatioCtrl->GetValue(); msg.ToDouble( &dtmp ); diff --git a/pcbnew/dialogs/dialog_edit_module_text.cpp b/pcbnew/dialogs/dialog_edit_module_text.cpp index 267bc05cd6..928ca8541c 100644 --- a/pcbnew/dialogs/dialog_edit_module_text.cpp +++ b/pcbnew/dialogs/dialog_edit_module_text.cpp @@ -197,15 +197,15 @@ void DialogEditModuleText::OnOkClick( wxCommandEvent& event ) wxPoint tmp; msg = m_TxtPosCtrlX->GetValue(); - tmp.x = ReturnValueFromString( g_UserUnit, msg ); + tmp.x = ValueFromString( g_UserUnit, msg ); msg = m_TxtPosCtrlY->GetValue(); - tmp.y = ReturnValueFromString( g_UserUnit, msg ); + tmp.y = ValueFromString( g_UserUnit, msg ); m_currentText->SetPos0( tmp ); - wxSize textSize( wxSize( ReturnValueFromString( g_UserUnit, m_TxtSizeCtrlX->GetValue() ), - ReturnValueFromString( g_UserUnit, m_TxtSizeCtrlY->GetValue() ) ) ); + wxSize textSize( wxSize( ValueFromString( g_UserUnit, m_TxtSizeCtrlX->GetValue() ), + ValueFromString( g_UserUnit, m_TxtSizeCtrlY->GetValue() ) ) ); // Test for a reasonnable size: if( textSize.x < TEXTS_MIN_SIZE ) @@ -216,7 +216,7 @@ void DialogEditModuleText::OnOkClick( wxCommandEvent& event ) m_currentText->SetSize( textSize ), msg = m_TxtWidthCtlr->GetValue(); - int width = ReturnValueFromString( g_UserUnit, msg ); + int width = ValueFromString( g_UserUnit, msg ); // Test for a reasonnable width: if( width <= 1 ) diff --git a/pcbnew/dialogs/dialog_export_idf.cpp b/pcbnew/dialogs/dialog_export_idf.cpp index 6f7b762d27..955c5e932a 100644 --- a/pcbnew/dialogs/dialog_export_idf.cpp +++ b/pcbnew/dialogs/dialog_export_idf.cpp @@ -26,7 +26,7 @@ */ #include -#include +#include #include #include @@ -43,7 +43,7 @@ class DIALOG_EXPORT_IDF3: public DIALOG_EXPORT_IDF3_BASE { private: PCB_EDIT_FRAME* m_parent; - wxConfig* m_config; + wxConfigBase* m_config; bool m_idfThouOpt; // remember last preference for units in THOU void OnCancelClick( wxCommandEvent& event ) @@ -60,7 +60,7 @@ public: DIALOG_EXPORT_IDF3_BASE( parent ) { m_parent = parent; - m_config = wxGetApp().GetSettings(); + m_config = Kiface().KifaceSettings(); SetFocus(); m_idfThouOpt = false; m_config->Read( OPTKEY_IDF_THOU, &m_idfThouOpt ); diff --git a/pcbnew/dialogs/dialog_export_vrml.cpp b/pcbnew/dialogs/dialog_export_vrml.cpp index bc8e5994e7..b47b9011d6 100644 --- a/pcbnew/dialogs/dialog_export_vrml.cpp +++ b/pcbnew/dialogs/dialog_export_vrml.cpp @@ -28,10 +28,11 @@ */ #include #include -#include +#include #include #include + /* the dialog to create VRML files, derived from DIALOG_EXPORT_3DFILE_BASE, * created by wxFormBuilder */ @@ -44,7 +45,7 @@ class DIALOG_EXPORT_3DFILE : public DIALOG_EXPORT_3DFILE_BASE { private: PCB_EDIT_FRAME* m_parent; - wxConfig* m_config; + wxConfigBase* m_config; int m_unitsOpt; // to remember last option int m_3DFilesOpt; // to remember last option @@ -56,7 +57,7 @@ public: DIALOG_EXPORT_3DFILE_BASE( parent ) { m_parent = parent; - m_config = wxGetApp().GetSettings(); + m_config = Kiface().KifaceSettings(); SetFocus(); m_config->Read( OPTKEY_OUTPUT_UNIT, &m_unitsOpt ); m_config->Read( OPTKEY_3DFILES_OPT, &m_3DFilesOpt ); diff --git a/pcbnew/dialogs/dialog_fp_lib_table.cpp b/pcbnew/dialogs/dialog_fp_lib_table.cpp index 0a4d383ea2..a2ed8f5d38 100644 --- a/pcbnew/dialogs/dialog_fp_lib_table.cpp +++ b/pcbnew/dialogs/dialog_fp_lib_table.cpp @@ -35,6 +35,7 @@ #include #include +#include #include #include #include @@ -705,7 +706,7 @@ private: // Make sure this special environment variable shows up even if it was // not used yet. It is automatically set by KiCad to the directory holding // the current project. - unique.insert( FP_LIB_TABLE::ProjectPathEnvVariableName() ); + unique.insert( PROJECT_VAR_NAME ); unique.insert( FP_LIB_TABLE::GlobalPathEnvVariableName() ); m_path_subs_grid->AppendRows( unique.size() ); diff --git a/pcbnew/dialogs/dialog_freeroute_exchange.cpp b/pcbnew/dialogs/dialog_freeroute_exchange.cpp index ca3bef0cde..43755778d3 100644 --- a/pcbnew/dialogs/dialog_freeroute_exchange.cpp +++ b/pcbnew/dialogs/dialog_freeroute_exchange.cpp @@ -27,12 +27,14 @@ */ #include -#include +//#include +#include #include #include #include #include #include +#include #include <../common/dialogs/dialog_display_info_HTML_base.h> @@ -75,14 +77,26 @@ void DIALOG_FREEROUTE::MyInit() { SetFocus(); m_FreeRouteSetupChanged = false; + m_freeRouterIsLocal = false; wxString msg; - wxGetApp().GetSettings()->Read( FREEROUTE_URL_KEY, &msg ); + + wxConfigBase* cfg = Kiface().KifaceSettings(); + + cfg->Read( FREEROUTE_URL_KEY, &msg ); if( msg.IsEmpty() ) m_FreerouteURLName->SetValue( wxT( "http://www.freerouting.net/" ) ); else m_FreerouteURLName->SetValue( msg ); + + wxFileName fileName( FindKicadFile( wxT( "freeroute.jar" ) ), wxPATH_UNIX ); + + if( fileName.FileExists() ) + { + m_freeRouterIsLocal = true; + m_buttonLaunchFreeroute->SetLabel( _("Create .dsn File and Launch FreeRouter") ); + } } const char * s_FreeRouteHelpInfo = @@ -112,7 +126,7 @@ void DIALOG_FREEROUTE::OnImportButtonClick( wxCommandEvent& event ) { m_Parent->ImportSpecctraSession( event ); - /* Connectivity inf must be rebuild. + /* Connectivity must be rebuild. * because for large board it can take some time, this is made only on demand */ if( IsOK( this, _("Do you want to rebuild connectivity data ?" ) ) ) @@ -124,13 +138,24 @@ void DIALOG_FREEROUTE::OnImportButtonClick( wxCommandEvent& event ) */ void DIALOG_FREEROUTE::OnLaunchButtonClick( wxCommandEvent& event ) { - wxString url; + wxString javaCommand; wxString command; + + if( m_freeRouterIsLocal ) + { + javaCommand = CmdRunFreeRouterLocal(); + + if( javaCommand.IsEmpty() ) // Something is wrong + return; + } + else + javaCommand = wxT( "javaws" ); + + wxString url; wxFileName fileName( FindKicadFile( wxT( "freeroute.jnlp" ) ), wxPATH_UNIX ); - if( fileName.FileExists() ) + if( m_freeRouterIsLocal || fileName.FileExists() ) { - wxString javaWebStartCommand = wxT( "javaws" ); // Find the Java web start application on Windows. #ifdef __WINDOWS__ @@ -141,13 +166,20 @@ void DIALOG_FREEROUTE::OnLaunchButtonClick( wxCommandEvent& event ) // Windows and the build version of KiCad. // This key works for 32 bit Java on 32 bit Windows and 64 bit Java on 64 bit Windows. - wxRegKey key( wxRegKey::HKLM, wxT( "SOFTWARE\\JavaSoft\\Java Web Start" ), + wxString keyName = m_freeRouterIsLocal ? wxT( "SOFTWARE\\JavaSoft\\Java Runtime Environment" ) + : wxT( "SOFTWARE\\JavaSoft\\Java Web Start" ); + wxRegKey key( wxRegKey::HKLM, keyName, wxIsPlatform64Bit() ? wxRegKey::WOW64ViewMode_64 : wxRegKey::WOW64ViewMode_Default ); // It's possible that 32 bit Java is installed on 64 bit Windows. if( !key.Exists() && wxIsPlatform64Bit() ) - key.SetName( wxRegKey::HKLM, wxT( "SOFTWARE\\Wow6432Node\\JavaSoft\\Java Web Start" ) ); + { + keyName = m_freeRouterIsLocal ? + wxT( "SOFTWARE\\Wow6432Node\\JavaSoft\\Java Runtime Environment" ) + : wxT( "SOFTWARE\\Wow6432Node\\JavaSoft\\Java Web Start" ); + key.SetName( wxRegKey::HKLM, keyName ); + } if( !key.Exists() ) { @@ -164,17 +196,27 @@ void DIALOG_FREEROUTE::OnLaunchButtonClick( wxCommandEvent& event ) wxString value; key.QueryValue( wxT( "CurrentVersion" ), value ); key.SetName( key.GetName() + wxT( "\\" ) + value ); - key.QueryValue( wxT( "Home" ), value ); - javaWebStartCommand = value + wxFileName::GetPathSeparator() + javaWebStartCommand; + + key.QueryValue( m_freeRouterIsLocal ? wxT( "JavaHome" ) : wxT( "Home" ), value ); + wxString javaCommandPath = value + wxFileName::GetPathSeparator(); + command = javaCommandPath; #else #warning Kicad needs wxWidgets >= 2.9.4. version 2.8 is only supported for testing purposes #endif // wxCHECK_VERSION( 2, 9, 0 ) -#endif // __WINDOWS__ - // Wrap FullFileName in double quotes in case it has C:\Program Files in it. - // The space is interpreted as an argument separator. - command << javaWebStartCommand << wxChar( ' ' ) << wxChar( '"' ) - << fileName.GetFullPath() << wxChar( '"' ); + if( m_freeRouterIsLocal ) + command << wxT("bin\\") << javaCommand; +#else // __WINDOWS__ + + if( m_freeRouterIsLocal ) + command << javaCommand; +#endif + else + // Wrap FullFileName in double quotes in case it has C:\Program Files in it. + // The space is interpreted as an argument separator. + command << javaCommand << wxChar( ' ' ) << wxChar( '"' ) + << fileName.GetFullPath() << wxChar( '"' ); + ProcessExecute( command ); return; } @@ -184,6 +226,47 @@ void DIALOG_FREEROUTE::OnLaunchButtonClick( wxCommandEvent& event ) wxLaunchDefaultBrowser( url ); } +wxString DIALOG_FREEROUTE::CmdRunFreeRouterLocal() +{ + wxString fullFileName = m_Parent->GetBoard()->GetFileName(); + wxString path; + wxString name; + wxString ext; + wxString dsn_ext = wxT( ".dsn" ); + wxString mask = wxT( "*" ) + dsn_ext; + + wxFileName::SplitPath( fullFileName, &path, &name, &ext ); + + name += dsn_ext; + + fullFileName = EDA_FileSelector( _( "Specctra DSN file:" ), + path, + name, // name.ext without path! + dsn_ext, + mask, + this, + wxFD_SAVE, + false + ); + + if( fullFileName == wxEmptyString ) + return fullFileName; + + if( ! m_Parent->ExportSpecctraFile( fullFileName ) ) // the file was not created + return fullFileName; + + wxFileName jarfileName( FindKicadFile( wxT( "freeroute.jar" ) ), wxPATH_UNIX ); + + wxString command = wxT("java -jar "); + // add "freeroute.jar" to command line: + command << wxChar( '"' ) << jarfileName.GetFullPath() << wxChar( '"' ); + // add option to load the .dsn file + command << wxT( " -de " ); + // add *.dsn full filename (quoted): + command << wxChar( '"' ) << fullFileName << wxChar( '"' ); + + return command; +} /* wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_BUTTON */ @@ -207,8 +290,8 @@ void DIALOG_FREEROUTE::OnOKButtonClick( wxCommandEvent& event ) { if( m_FreeRouteSetupChanged ) // Save new config { - wxGetApp().GetSettings()->Write( FREEROUTE_URL_KEY, - m_FreerouteURLName->GetValue() ); + Kiface().KifaceSettings()->Write( + FREEROUTE_URL_KEY, m_FreerouteURLName->GetValue() ); } EndModal(wxID_OK); diff --git a/pcbnew/dialogs/dialog_freeroute_exchange.h b/pcbnew/dialogs/dialog_freeroute_exchange.h index 0f1e6f97ff..e9646060f0 100644 --- a/pcbnew/dialogs/dialog_freeroute_exchange.h +++ b/pcbnew/dialogs/dialog_freeroute_exchange.h @@ -16,6 +16,7 @@ class DIALOG_FREEROUTE : public DIALOG_FREEROUTE_BASE private: PCB_EDIT_FRAME* m_Parent; bool m_FreeRouteSetupChanged; + bool m_freeRouterIsLocal; private: // Virtual event handlers @@ -28,7 +29,7 @@ private: void OnCancelButtonClick( wxCommandEvent& event ); void OnTextEditFrUrlUpdated( wxCommandEvent& event ); void MyInit ( ); - + wxString CmdRunFreeRouterLocal(); public: DIALOG_FREEROUTE( PCB_EDIT_FRAME* parent ); diff --git a/pcbnew/dialogs/dialog_gendrill.cpp b/pcbnew/dialogs/dialog_gendrill.cpp index ee54fd6e82..dc03481fca 100644 --- a/pcbnew/dialogs/dialog_gendrill.cpp +++ b/pcbnew/dialogs/dialog_gendrill.cpp @@ -27,7 +27,8 @@ */ #include -#include +//#include +#include #include #include #include @@ -74,7 +75,7 @@ DIALOG_GENDRILL::DIALOG_GENDRILL( PCB_EDIT_FRAME* parent ) : { m_parent = parent; m_board = parent->GetBoard(); - m_config = wxGetApp().GetSettings(); + m_config = Kiface().KifaceSettings(); m_plotOpts = m_parent->GetPlotSettings(); SetReturnCode( 1 ); diff --git a/pcbnew/dialogs/dialog_gendrill.h b/pcbnew/dialogs/dialog_gendrill.h index c9b32cfed0..048f2f99cc 100644 --- a/pcbnew/dialogs/dialog_gendrill.h +++ b/pcbnew/dialogs/dialog_gendrill.h @@ -51,7 +51,7 @@ public: private: PCB_EDIT_FRAME* m_parent; - wxConfig* m_config; + wxConfigBase* m_config; BOARD* m_board; PCB_PLOT_PARAMS m_plotOpts; diff --git a/pcbnew/dialogs/dialog_global_edit_tracks_and_vias.cpp b/pcbnew/dialogs/dialog_global_edit_tracks_and_vias.cpp index b5114a0ce8..02577075cd 100644 --- a/pcbnew/dialogs/dialog_global_edit_tracks_and_vias.cpp +++ b/pcbnew/dialogs/dialog_global_edit_tracks_and_vias.cpp @@ -74,13 +74,13 @@ void DIALOG_GLOBAL_EDIT_TRACKS_AND_VIAS::MyInit() // Display current values, and current netclass values: int value = netclass->GetTrackWidth(); // Display track width - msg = ReturnStringFromValue( g_UserUnit, value, true ); + msg = StringFromValue( g_UserUnit, value, true ); m_gridDisplayCurrentSettings->SetCellValue( 0, 0, msg ); if( board->GetTrackWidthIndex() ) { value = board->GetCurrentTrackWidth(); - msg = ReturnStringFromValue( g_UserUnit, value, true ); + msg = StringFromValue( g_UserUnit, value, true ); } else msg = _( "Default" ); @@ -88,45 +88,45 @@ void DIALOG_GLOBAL_EDIT_TRACKS_AND_VIAS::MyInit() m_gridDisplayCurrentSettings->SetCellValue( 1, 0, msg ); value = netclass->GetViaDiameter(); // Display via diameter - msg = ReturnStringFromValue( g_UserUnit, value, true ); + msg = StringFromValue( g_UserUnit, value, true ); m_gridDisplayCurrentSettings->SetCellValue( 0, 1, msg ); if( board->GetViaSizeIndex() ) { value = board->GetCurrentViaSize(); - msg = ReturnStringFromValue( g_UserUnit, value, true ); + msg = StringFromValue( g_UserUnit, value, true ); } else msg = _( "Default" ); m_gridDisplayCurrentSettings->SetCellValue( 1, 1, msg ); value = netclass->GetViaDrill(); // Display via drill - msg = ReturnStringFromValue( g_UserUnit, value, true ); + msg = StringFromValue( g_UserUnit, value, true ); m_gridDisplayCurrentSettings->SetCellValue( 0, 2, msg ); value = board->GetCurrentViaDrill(); if( value >= 0 ) - msg = ReturnStringFromValue( g_UserUnit, value, true ); + msg = StringFromValue( g_UserUnit, value, true ); else msg = _( "Default" ); m_gridDisplayCurrentSettings->SetCellValue( 1, 2, msg ); value = netclass->GetuViaDiameter(); // Display micro via diameter - msg = ReturnStringFromValue( g_UserUnit, value, true ); + msg = StringFromValue( g_UserUnit, value, true ); m_gridDisplayCurrentSettings->SetCellValue( 0, 3, msg ); #if 0 // Currently we use always the default netclass value value = board->GetCurrentMicroViaSize(); - msg = ReturnStringFromValue( g_UserUnit, value, true ); + msg = StringFromValue( g_UserUnit, value, true ); #endif msg = _( "Default" ); m_gridDisplayCurrentSettings->SetCellValue( 1, 3, msg ); value = netclass->GetuViaDrill(); // Display micro via drill - msg = ReturnStringFromValue( g_UserUnit, value, true ); + msg = StringFromValue( g_UserUnit, value, true ); m_gridDisplayCurrentSettings->SetCellValue( 0, 4, msg ); #if 0 // Currently we use always the default netclass value value = board->GetCurrentMicroViaDrill(); if( value >= 0 ) - msg = ReturnStringFromValue( g_UserUnit, value, true ); + msg = StringFromValue( g_UserUnit, value, true ); else #endif msg = _( "Default" ); diff --git a/pcbnew/dialogs/dialog_global_modules_fields_edition.cpp b/pcbnew/dialogs/dialog_global_modules_fields_edition.cpp index 63b4df2308..9f391c2e24 100644 --- a/pcbnew/dialogs/dialog_global_modules_fields_edition.cpp +++ b/pcbnew/dialogs/dialog_global_modules_fields_edition.cpp @@ -97,11 +97,11 @@ void DIALOG_GLOBAL_MODULES_FIELDS_EDITION::initDialog() m_SizeYunit->SetLabel( GetAbbreviatedUnitsLabel() ); m_Ticknessunit->SetLabel( GetAbbreviatedUnitsLabel() ); m_SizeX_Value->SetValue( - ReturnStringFromValue( g_UserUnit, m_brdSettings->m_ModuleTextSize.x ) ); + StringFromValue( g_UserUnit, m_brdSettings->m_ModuleTextSize.x ) ); m_SizeY_Value->SetValue( - ReturnStringFromValue( g_UserUnit, m_brdSettings->m_ModuleTextSize.y ) ); + StringFromValue( g_UserUnit, m_brdSettings->m_ModuleTextSize.y ) ); m_TicknessValue->SetValue( - ReturnStringFromValue( g_UserUnit, m_brdSettings->m_ModuleTextWidth) ); + StringFromValue( g_UserUnit, m_brdSettings->m_ModuleTextWidth) ); Layout(); GetSizer()->SetSizeHints( this ); @@ -116,9 +116,9 @@ void DIALOG_GLOBAL_MODULES_FIELDS_EDITION::OnOKClick( wxCommandEvent& event ) m_othersSelection = m_OtherFields->GetValue(); m_filterString = m_ModuleFilter->GetValue(); - m_brdSettings->m_ModuleTextSize.x = ReturnValueFromTextCtrl( *m_SizeX_Value ); - m_brdSettings->m_ModuleTextSize.y = ReturnValueFromTextCtrl( *m_SizeY_Value ); - m_brdSettings->m_ModuleTextWidth = ReturnValueFromTextCtrl( *m_TicknessValue ); + m_brdSettings->m_ModuleTextSize.x = ValueFromTextCtrl( *m_SizeX_Value ); + m_brdSettings->m_ModuleTextSize.y = ValueFromTextCtrl( *m_SizeY_Value ); + m_brdSettings->m_ModuleTextWidth = ValueFromTextCtrl( *m_TicknessValue ); // clip m_ModuleTextWidth to the 1/4 of min size, to keep it always readable int minsize = std::min( m_brdSettings->m_ModuleTextSize.x, diff --git a/pcbnew/dialogs/dialog_graphic_item_properties.cpp b/pcbnew/dialogs/dialog_graphic_item_properties.cpp index ddff38dbd8..ea133794b8 100644 --- a/pcbnew/dialogs/dialog_graphic_item_properties.cpp +++ b/pcbnew/dialogs/dialog_graphic_item_properties.cpp @@ -215,22 +215,22 @@ void DIALOG_GRAPHIC_ITEM_PROPERTIES::OnOkClick( wxCommandEvent& event ) m_Item->Draw( m_parent->GetCanvas(), m_DC, GR_XOR ); msg = m_Center_StartXCtrl->GetValue(); - m_Item->SetStartX( ReturnValueFromString( g_UserUnit, msg ) ); + m_Item->SetStartX( ValueFromString( g_UserUnit, msg ) ); msg = m_Center_StartYCtrl->GetValue(); - m_Item->SetStartY( ReturnValueFromString( g_UserUnit, msg ) ); + m_Item->SetStartY( ValueFromString( g_UserUnit, msg ) ); msg = m_EndX_Radius_Ctrl->GetValue(); - m_Item->SetEndX( ReturnValueFromString( g_UserUnit, msg ) ); + m_Item->SetEndX( ValueFromString( g_UserUnit, msg ) ); msg = m_EndY_Ctrl->GetValue(); - m_Item->SetEndY( ReturnValueFromString( g_UserUnit, msg ) ); + m_Item->SetEndY( ValueFromString( g_UserUnit, msg ) ); msg = m_ThicknessCtrl->GetValue(); - m_Item->SetWidth( ReturnValueFromString( g_UserUnit, msg ) ); + m_Item->SetWidth( ValueFromString( g_UserUnit, msg ) ); msg = m_DefaultThicknessCtrl->GetValue(); - int thickness = ReturnValueFromString( g_UserUnit, msg ); + int thickness = ValueFromString( g_UserUnit, msg ); m_Item->SetLayer( m_LayerSelectionCtrl->GetLayerSelection() ); diff --git a/pcbnew/dialogs/dialog_graphic_item_properties_for_Modedit.cpp b/pcbnew/dialogs/dialog_graphic_item_properties_for_Modedit.cpp index 9c4fdd2dfe..c04fb03acd 100644 --- a/pcbnew/dialogs/dialog_graphic_item_properties_for_Modedit.cpp +++ b/pcbnew/dialogs/dialog_graphic_item_properties_for_Modedit.cpp @@ -199,24 +199,24 @@ void DIALOG_MODEDIT_FP_BODY_ITEM_PROPERTIES::OnOkClick( wxCommandEvent& event ) wxPoint coord; msg = m_Center_StartXCtrl->GetValue(); - coord.x = ReturnValueFromString( g_UserUnit, msg ); + coord.x = ValueFromString( g_UserUnit, msg ); msg = m_Center_StartYCtrl->GetValue(); - coord.y = ReturnValueFromString( g_UserUnit, msg ); + coord.y = ValueFromString( g_UserUnit, msg ); m_item->SetStart( coord ); m_item->SetStart0( coord ); msg = m_EndX_Radius_Ctrl->GetValue(); - coord.x = ReturnValueFromString( g_UserUnit, msg ); + coord.x = ValueFromString( g_UserUnit, msg ); msg = m_EndY_Ctrl->GetValue(); - coord.y = ReturnValueFromString( g_UserUnit, msg ); + coord.y = ValueFromString( g_UserUnit, msg ); m_item->SetEnd( coord ); m_item->SetEnd0( coord ); msg = m_ThicknessCtrl->GetValue(); - m_item->SetWidth( ReturnValueFromString( g_UserUnit, msg ) ); + m_item->SetWidth( ValueFromString( g_UserUnit, msg ) ); msg = m_DefaultThicknessCtrl->GetValue(); - int thickness = ReturnValueFromString( g_UserUnit, msg ); + int thickness = ValueFromString( g_UserUnit, msg ); m_brdSettings.m_ModuleSegmentWidth = thickness; m_parent->SetDesignSettings( m_brdSettings ); diff --git a/pcbnew/dialogs/dialog_graphic_items_options.cpp b/pcbnew/dialogs/dialog_graphic_items_options.cpp index 7b39406aa8..b68819810f 100644 --- a/pcbnew/dialogs/dialog_graphic_items_options.cpp +++ b/pcbnew/dialogs/dialog_graphic_items_options.cpp @@ -97,20 +97,20 @@ void DIALOG_GRAPHIC_ITEMS_OPTIONS::initValues() void DIALOG_GRAPHIC_ITEMS_OPTIONS::OnOkClick( wxCommandEvent& event ) { - m_brdSettings.m_DrawSegmentWidth = ReturnValueFromTextCtrl( *m_OptPcbSegmWidth ); - m_brdSettings.m_EdgeSegmentWidth = ReturnValueFromTextCtrl( *m_OptPcbEdgesWidth ); - m_brdSettings.m_PcbTextWidth = ReturnValueFromTextCtrl( *m_OptPcbTextWidth ); - m_brdSettings.m_PcbTextSize.y = ReturnValueFromTextCtrl( *m_OptPcbTextVSize ); - m_brdSettings.m_PcbTextSize.x = ReturnValueFromTextCtrl( *m_OptPcbTextHSize ); + m_brdSettings.m_DrawSegmentWidth = ValueFromTextCtrl( *m_OptPcbSegmWidth ); + m_brdSettings.m_EdgeSegmentWidth = ValueFromTextCtrl( *m_OptPcbEdgesWidth ); + m_brdSettings.m_PcbTextWidth = ValueFromTextCtrl( *m_OptPcbTextWidth ); + m_brdSettings.m_PcbTextSize.y = ValueFromTextCtrl( *m_OptPcbTextVSize ); + m_brdSettings.m_PcbTextSize.x = ValueFromTextCtrl( *m_OptPcbTextHSize ); m_parent->GetBoard()->SetDesignSettings( m_brdSettings ); - m_brdSettings.m_ModuleSegmentWidth = ReturnValueFromTextCtrl( *m_OptModuleEdgesWidth ); - m_brdSettings.m_ModuleTextWidth = ReturnValueFromTextCtrl( *m_OptModuleTextWidth ); - m_brdSettings.m_ModuleTextSize.y = ReturnValueFromTextCtrl( *m_OptModuleTextVSize ); - m_brdSettings.m_ModuleTextSize.x = ReturnValueFromTextCtrl( *m_OptModuleTextHSize ); + m_brdSettings.m_ModuleSegmentWidth = ValueFromTextCtrl( *m_OptModuleEdgesWidth ); + m_brdSettings.m_ModuleTextWidth = ValueFromTextCtrl( *m_OptModuleTextWidth ); + m_brdSettings.m_ModuleTextSize.y = ValueFromTextCtrl( *m_OptModuleTextVSize ); + m_brdSettings.m_ModuleTextSize.x = ValueFromTextCtrl( *m_OptModuleTextHSize ); - g_DrawDefaultLineThickness = ReturnValueFromTextCtrl( *m_DefaultPenSizeCtrl ); + g_DrawDefaultLineThickness = ValueFromTextCtrl( *m_DefaultPenSizeCtrl ); if( g_DrawDefaultLineThickness < 0 ) g_DrawDefaultLineThickness = 0; diff --git a/pcbnew/dialogs/dialog_keepout_area_properties.cpp b/pcbnew/dialogs/dialog_keepout_area_properties.cpp index 17e7843054..af5ba6ff24 100644 --- a/pcbnew/dialogs/dialog_keepout_area_properties.cpp +++ b/pcbnew/dialogs/dialog_keepout_area_properties.cpp @@ -29,7 +29,8 @@ #include #include -#include +//#include +#include #include #include #include @@ -56,7 +57,7 @@ public: private: PCB_BASE_FRAME* m_parent; - wxConfig* m_config; ///< Current config + wxConfigBase* m_config; ///< Current config ZONE_SETTINGS m_zonesettings; ZONE_SETTINGS* m_ptr; @@ -105,7 +106,7 @@ DIALOG_KEEPOUT_AREA_PROPERTIES::DIALOG_KEEPOUT_AREA_PROPERTIES( PCB_BASE_FRAME* DIALOG_KEEPOUT_AREA_PROPERTIES_BASE( aParent ) { m_parent = aParent; - m_config = wxGetApp().GetSettings(); + m_config = Kiface().KifaceSettings(); m_ptr = aSettings; m_zonesettings = *aSettings; diff --git a/pcbnew/dialogs/dialog_layers_setup.cpp b/pcbnew/dialogs/dialog_layers_setup.cpp index 2c3756af5a..636cea9687 100644 --- a/pcbnew/dialogs/dialog_layers_setup.cpp +++ b/pcbnew/dialogs/dialog_layers_setup.cpp @@ -176,19 +176,19 @@ static const LAYER_MSK presets[] = NO_LAYERS, // shift the array index up by one, matches with "Custom". // "Two layers, parts on Front only" - EDGE_LAYER | LAYER_FRONT | LAYER_BACK | FRONT_AUX_LAYERS, + EDGE_LAYER | LAYER_FRONT | LAYER_BACK | FRONT_TECH_LAYERS, // "Two layers, parts on Back only", - EDGE_LAYER | LAYER_FRONT | LAYER_BACK | BACK_AUX_LAYERS, + EDGE_LAYER | LAYER_FRONT | LAYER_BACK | BACK_TECH_LAYERS, // "Two layers, parts on Front and Back", - EDGE_LAYER | LAYER_FRONT | LAYER_BACK | ALL_AUX_LAYERS, + EDGE_LAYER | LAYER_FRONT | LAYER_BACK | ALL_TECH_LAYERS, // "Four layers, parts on Front only" - EDGE_LAYER | LAYER_FRONT | LAYER_BACK | LAYER_2 | LAYER_3 | FRONT_AUX_LAYERS, + EDGE_LAYER | LAYER_FRONT | LAYER_BACK | LAYER_2 | LAYER_3 | FRONT_TECH_LAYERS, // "Four layers, parts on Front and Back" - EDGE_LAYER | LAYER_FRONT | LAYER_BACK | LAYER_2 | LAYER_3 | ALL_AUX_LAYERS, + EDGE_LAYER | LAYER_FRONT | LAYER_BACK | LAYER_2 | LAYER_3 | ALL_TECH_LAYERS, // "All layers on", ALL_LAYERS, diff --git a/pcbnew/dialogs/dialog_mask_clearance.cpp b/pcbnew/dialogs/dialog_mask_clearance.cpp index 07f8948a16..913ba2e8ff 100644 --- a/pcbnew/dialogs/dialog_mask_clearance.cpp +++ b/pcbnew/dialogs/dialog_mask_clearance.cpp @@ -85,10 +85,10 @@ void DIALOG_PADS_MASK_CLEARANCE::myInit() void DIALOG_PADS_MASK_CLEARANCE::OnButtonOkClick( wxCommandEvent& event ) { - m_brdSettings.m_SolderMaskMargin = ReturnValueFromTextCtrl( *m_SolderMaskMarginCtrl ); - m_brdSettings.m_SolderMaskMinWidth = ReturnValueFromTextCtrl( *m_SolderMaskMinWidthCtrl ); + m_brdSettings.m_SolderMaskMargin = ValueFromTextCtrl( *m_SolderMaskMarginCtrl ); + m_brdSettings.m_SolderMaskMinWidth = ValueFromTextCtrl( *m_SolderMaskMinWidthCtrl ); - m_brdSettings.m_SolderPasteMargin = ReturnValueFromTextCtrl( *m_SolderPasteMarginCtrl ); + m_brdSettings.m_SolderPasteMargin = ValueFromTextCtrl( *m_SolderPasteMarginCtrl ); double dtmp = 0; wxString msg = m_SolderPasteMarginRatioCtrl->GetValue(); diff --git a/pcbnew/dialogs/dialog_netlist.cpp b/pcbnew/dialogs/dialog_netlist.cpp index 50ad5f0063..e7cb66c29e 100644 --- a/pcbnew/dialogs/dialog_netlist.cpp +++ b/pcbnew/dialogs/dialog_netlist.cpp @@ -27,7 +27,9 @@ */ #include -#include +//#include +#include +#include #include #include #include @@ -86,7 +88,10 @@ void PCB_EDIT_FRAME::InstallNetlistFrame( wxDC* DC ) { wxFileName fn = GetBoard()->GetFileName(); fn.SetExt( ProjectFileExtension ); - wxGetApp().WriteProjectConfig( fn.GetFullPath(), GROUP, GetProjectFileParameters() ); + + // was: wxGetApp().WriteProjectConfig( fn.GetFullPath(), GROUP, GetProjectFileParameters() ); + Prj().ConfigSave( Kiface().KifaceSearch(), fn.GetFullPath(), + GROUP, GetProjectFileParameters() ); } } @@ -97,7 +102,7 @@ DIALOG_NETLIST::DIALOG_NETLIST( PCB_EDIT_FRAME* aParent, wxDC * aDC, { m_parent = aParent; m_dc = aDC; - m_config = wxGetApp().GetSettings(); + m_config = Kiface().KifaceSettings(); m_silentMode = m_config->Read( NETLIST_SILENTMODE_KEY, 0l ); m_reportAll = m_config->Read( NETLIST_FULLMESSAGES_KEY, 1l ); bool tmp = m_config->Read( NETLIST_DELETESINGLEPADNETS_KEY, 0l ); diff --git a/pcbnew/dialogs/dialog_netlist.h b/pcbnew/dialogs/dialog_netlist.h index 475588bce0..33910fbbe5 100644 --- a/pcbnew/dialogs/dialog_netlist.h +++ b/pcbnew/dialogs/dialog_netlist.h @@ -43,7 +43,7 @@ private: bool m_silentMode; // if true, do not display warning message about undo bool m_reportAll; // If true report all messages, // false, report only warnings or errors - wxConfig* m_config; + wxConfigBase* m_config; public: DIALOG_NETLIST( PCB_EDIT_FRAME* aParent, wxDC* aDC, const wxString & aNetlistFullFilename ); diff --git a/pcbnew/dialogs/dialog_pad_properties.cpp b/pcbnew/dialogs/dialog_pad_properties.cpp index 42f75d220c..21c306b66f 100644 --- a/pcbnew/dialogs/dialog_pad_properties.cpp +++ b/pcbnew/dialogs/dialog_pad_properties.cpp @@ -95,8 +95,8 @@ public: private: PCB_BASE_FRAME* m_parent; - D_PAD* m_currentPad; // pad currently being edited - D_PAD* m_dummyPad; // a working copy used to show changes + D_PAD* m_currentPad; // pad currently being edited + D_PAD* m_dummyPad; // a working copy used to show changes BOARD* m_board; D_PAD& m_padMaster; bool m_isFlipped; // true if the parent footprint (therefore pads) is flipped (mirrored) @@ -149,10 +149,10 @@ DIALOG_PAD_PROPERTIES::DIALOG_PAD_PROPERTIES( PCB_BASE_FRAME* aParent, D_PAD* aP { m_canUpdate = false; m_parent = aParent; - m_currentPad = aPad; + m_currentPad = aPad; // aPad can be NULL, if the dialog is called + // from the module editor to set default pad characteristics m_board = m_parent->GetBoard(); - m_dummyPad = new D_PAD( aPad->GetParent() ); - m_padMaster.SetParent( aPad->GetParent() ); + m_dummyPad = new D_PAD( (MODULE*) NULL ); if( aPad ) m_dummyPad->Copy( aPad ); @@ -673,11 +673,11 @@ bool DIALOG_PAD_PROPERTIES::padValuesOK() } LAYER_MSK padlayers_mask = m_dummyPad->GetLayerMask(); - if( ( padlayers_mask == 0 ) && ( m_dummyPad->GetAttribute() != PAD_HOLE_NOT_PLATED ) ) - error_msgs.Add( _( "Error: pad has no layer and is not a mechanical pad" ) ); - padlayers_mask &= (LAYER_BACK | LAYER_FRONT); if( padlayers_mask == 0 ) + error_msgs.Add( _( "Error: pad has no layer" ) ); + + if( ( padlayers_mask & (LAYER_BACK | LAYER_FRONT) ) == 0 ) { if( m_dummyPad->GetDrillSize().x || m_dummyPad->GetDrillSize().y ) { @@ -715,20 +715,21 @@ bool DIALOG_PAD_PROPERTIES::padValuesOK() switch( m_dummyPad->GetAttribute() ) { - case PAD_STANDARD : // Pad through hole, a hole is expected + case PAD_HOLE_NOT_PLATED: // Not plated, but through hole, a hole is expected + case PAD_STANDARD : // Pad through hole, a hole is also expected if( m_dummyPad->GetDrillSize().x <= 0 ) - error_msgs.Add( _( "Incorrect value for pad drill (too small value)" ) ); + error_msgs.Add( _( "Error: Through hole pad: drill diameter set to 0" ) ); break; - case PAD_SMD: // SMD and Connector pads (One external copper layer only) + case PAD_CONN: // Connector pads are smd pads, just they do not have solder paste. + if( (padlayers_mask & SOLDERPASTE_LAYER_BACK) || + (padlayers_mask & SOLDERPASTE_LAYER_FRONT) ) + error_msgs.Add( _( "Error: Connector pads are not on the solder paste layer\n" + "Use SMD pads instead" ) ); + // Fall trough + case PAD_SMD: // SMD and Connector pads (One external copper layer only) if( (padlayers_mask & LAYER_BACK) && (padlayers_mask & LAYER_FRONT) ) - error_msgs.Add( _( "Error: only one copper layer allowed for this pad" ) ); - break; - - case PAD_CONN: // connectors can have pads on "All" Cu layers. - break; - - case PAD_HOLE_NOT_PLATED: // Not plated + error_msgs.Add( _( "Error: only one copper layer allowed for SMD or Connector pads" ) ); break; } @@ -738,6 +739,7 @@ bool DIALOG_PAD_PROPERTIES::padValuesOK() dlg.ListSet( error_msgs ); dlg.ShowModal(); } + return error_msgs.GetCount() == 0; } @@ -856,11 +858,11 @@ bool DIALOG_PAD_PROPERTIES::transferDataToPad( D_PAD* aPad ) aPad->SetShape( CodeShape[m_PadShape->GetSelection()] ); // Read pad clearances values: - aPad->SetLocalClearance( ReturnValueFromTextCtrl( *m_NetClearanceValueCtrl ) ); - aPad->SetLocalSolderMaskMargin( ReturnValueFromTextCtrl( *m_SolderMaskMarginCtrl ) ); - aPad->SetLocalSolderPasteMargin( ReturnValueFromTextCtrl( *m_SolderPasteMarginCtrl ) ); - aPad->SetThermalWidth( ReturnValueFromTextCtrl( *m_ThermalWidthCtrl ) ); - aPad->SetThermalGap( ReturnValueFromTextCtrl( *m_ThermalGapCtrl ) ); + aPad->SetLocalClearance( ValueFromTextCtrl( *m_NetClearanceValueCtrl ) ); + aPad->SetLocalSolderMaskMargin( ValueFromTextCtrl( *m_SolderMaskMarginCtrl ) ); + aPad->SetLocalSolderPasteMargin( ValueFromTextCtrl( *m_SolderPasteMarginCtrl ) ); + aPad->SetThermalWidth( ValueFromTextCtrl( *m_ThermalWidthCtrl ) ); + aPad->SetThermalGap( ValueFromTextCtrl( *m_ThermalGapCtrl ) ); double dtmp = 0.0; msg = m_SolderPasteMarginRatioCtrl->GetValue(); msg.ToDouble( &dtmp ); @@ -896,15 +898,15 @@ bool DIALOG_PAD_PROPERTIES::transferDataToPad( D_PAD* aPad ) } // Read pad position: - x = ReturnValueFromTextCtrl( *m_PadPosition_X_Ctrl ); - y = ReturnValueFromTextCtrl( *m_PadPosition_Y_Ctrl ); + x = ValueFromTextCtrl( *m_PadPosition_X_Ctrl ); + y = ValueFromTextCtrl( *m_PadPosition_Y_Ctrl ); aPad->SetPosition( wxPoint( x, y ) ); aPad->SetPos0( wxPoint( x, y ) ); // Read pad drill: - x = ReturnValueFromTextCtrl( *m_PadDrill_X_Ctrl ); - y = ReturnValueFromTextCtrl( *m_PadDrill_Y_Ctrl ); + x = ValueFromTextCtrl( *m_PadDrill_X_Ctrl ); + y = ValueFromTextCtrl( *m_PadDrill_Y_Ctrl ); if( m_DrillShapeCtrl->GetSelection() == 0 ) { @@ -917,24 +919,24 @@ bool DIALOG_PAD_PROPERTIES::transferDataToPad( D_PAD* aPad ) aPad->SetDrillSize( wxSize( x, y ) ); // Read pad shape size: - x = ReturnValueFromTextCtrl( *m_ShapeSize_X_Ctrl ); - y = ReturnValueFromTextCtrl( *m_ShapeSize_Y_Ctrl ); + x = ValueFromTextCtrl( *m_ShapeSize_X_Ctrl ); + y = ValueFromTextCtrl( *m_ShapeSize_Y_Ctrl ); if( aPad->GetShape() == PAD_CIRCLE ) y = x; aPad->SetSize( wxSize( x, y ) ); // Read pad length die - aPad->SetPadToDieLength( ReturnValueFromTextCtrl( *m_LengthPadToDieCtrl ) ); + aPad->SetPadToDieLength( ValueFromTextCtrl( *m_LengthPadToDieCtrl ) ); // Read pad shape delta size: // m_DeltaSize.x or m_DeltaSize.y must be NULL. for a trapezoid. wxSize delta; if( m_trapDeltaDirChoice->GetSelection() == 0 ) - delta.x = ReturnValueFromTextCtrl( *m_ShapeDelta_Ctrl ); + delta.x = ValueFromTextCtrl( *m_ShapeDelta_Ctrl ); else - delta.y = ReturnValueFromTextCtrl( *m_ShapeDelta_Ctrl ); + delta.y = ValueFromTextCtrl( *m_ShapeDelta_Ctrl ); // Test bad values (be sure delta values are not too large) // remember DeltaSize.x is the Y size variation @@ -967,8 +969,8 @@ bool DIALOG_PAD_PROPERTIES::transferDataToPad( D_PAD* aPad ) aPad->SetDelta( delta ); // Read pad shape offset: - x = ReturnValueFromTextCtrl( *m_ShapeOffset_X_Ctrl ); - y = ReturnValueFromTextCtrl( *m_ShapeOffset_Y_Ctrl ); + x = ValueFromTextCtrl( *m_ShapeOffset_X_Ctrl ); + y = ValueFromTextCtrl( *m_ShapeOffset_Y_Ctrl ); aPad->SetOffset( wxPoint( x, y ) ); double orient_value = 0; diff --git a/pcbnew/dialogs/dialog_pcb_text_properties.cpp b/pcbnew/dialogs/dialog_pcb_text_properties.cpp index 4a0f91440e..9f58be5e1d 100644 --- a/pcbnew/dialogs/dialog_pcb_text_properties.cpp +++ b/pcbnew/dialogs/dialog_pcb_text_properties.cpp @@ -211,13 +211,13 @@ void DIALOG_PCB_TEXT_PROPERTIES::OnOkClick( wxCommandEvent& event ) } // Set PCB Text position - newPosition.x = ReturnValueFromString( g_UserUnit, m_PositionXCtrl->GetValue() ); - newPosition.y = ReturnValueFromString( g_UserUnit, m_PositionYCtrl->GetValue() ); + newPosition.x = ValueFromString( g_UserUnit, m_PositionXCtrl->GetValue() ); + newPosition.y = ValueFromString( g_UserUnit, m_PositionYCtrl->GetValue() ); m_SelectedPCBText->SetTextPosition( newPosition ); // Check constraints and set PCB Text size - newSize.x = ReturnValueFromString( g_UserUnit, m_SizeXCtrl->GetValue() ); - newSize.y = ReturnValueFromString( g_UserUnit, m_SizeYCtrl->GetValue() ); + newSize.x = ValueFromString( g_UserUnit, m_SizeXCtrl->GetValue() ); + newSize.y = ValueFromString( g_UserUnit, m_SizeYCtrl->GetValue() ); if( newSize.x < TEXTS_MIN_SIZE ) newSize.x = TEXTS_MIN_SIZE; @@ -234,7 +234,7 @@ void DIALOG_PCB_TEXT_PROPERTIES::OnOkClick( wxCommandEvent& event ) m_SelectedPCBText->SetSize( newSize ); // Set the new thickness - m_SelectedPCBText->SetThickness( ReturnValueFromString( g_UserUnit, + m_SelectedPCBText->SetThickness( ValueFromString( g_UserUnit, m_ThicknessCtrl->GetValue() ) ); // Test for acceptable values for thickness and size and clamp if fails diff --git a/pcbnew/dialogs/dialog_plot.cpp b/pcbnew/dialogs/dialog_plot.cpp index bc13af8558..3b2550e931 100644 --- a/pcbnew/dialogs/dialog_plot.cpp +++ b/pcbnew/dialogs/dialog_plot.cpp @@ -25,7 +25,8 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ -#include + +#include #include #include #include @@ -44,7 +45,7 @@ DIALOG_PLOT::DIALOG_PLOT( PCB_EDIT_FRAME* aParent ) : m_board( aParent->GetBoard() ), m_plotOpts( aParent->GetPlotSettings() ) { - m_config = wxGetApp().GetSettings(); + m_config = Kiface().KifaceSettings(); m_brdSettings = m_board->GetDesignSettings(); Init_Dialog(); @@ -100,25 +101,25 @@ void DIALOG_PLOT::Init_Dialog() break; } - msg = ReturnStringFromValue( g_UserUnit, m_brdSettings.m_SolderMaskMargin, true ); + msg = StringFromValue( g_UserUnit, m_brdSettings.m_SolderMaskMargin, true ); m_SolderMaskMarginCurrValue->SetLabel( msg ); - msg = ReturnStringFromValue( g_UserUnit, m_brdSettings.m_SolderMaskMinWidth, true ); + msg = StringFromValue( g_UserUnit, m_brdSettings.m_SolderMaskMinWidth, true ); m_SolderMaskMinWidthCurrValue->SetLabel( msg ); // Set units and value for HPGL pen size (this param in in mils). AddUnitSymbol( *m_textPenSize, g_UserUnit ); - msg = ReturnStringFromValue( g_UserUnit, + msg = StringFromValue( g_UserUnit, m_plotOpts.GetHPGLPenDiameter() * IU_PER_MILS ); m_HPGLPenSizeOpt->AppendText( msg ); // Set units and value for HPGL pen overlay (this param in in mils). AddUnitSymbol( *m_textPenOvr, g_UserUnit ); - msg = ReturnStringFromValue( g_UserUnit, + msg = StringFromValue( g_UserUnit, m_plotOpts.GetHPGLPenOverlay() * IU_PER_MILS ); m_HPGLPenOverlayOpt->AppendText( msg ); AddUnitSymbol( *m_textDefaultPenSize, g_UserUnit ); - msg = ReturnStringFromValue( g_UserUnit, m_plotOpts.GetLineWidth() ); + msg = StringFromValue( g_UserUnit, m_plotOpts.GetLineWidth() ); m_linesWidth->AppendText( msg ); // Set units for PS global width correction. @@ -246,7 +247,7 @@ void DIALOG_PLOT::OnPopUpLayers( wxCommandEvent& event ) for( i = 0; i < m_layerList.size(); i++ ) { LAYER_MSK layermask = GetLayerMask( m_layerList[ i ] ); - if( layermask & ( ALL_CU_LAYERS | ALL_AUX_LAYERS ) ) + if( layermask & ( ALL_CU_LAYERS | ALL_TECH_LAYERS ) ) m_layerCheckListBox->Check( i, true ); else m_layerCheckListBox->Check( i, false ); @@ -583,11 +584,11 @@ void DIALOG_PLOT::applyPlotSettings() // read HPLG pen size (this param is stored in mils) wxString msg = m_HPGLPenSizeOpt->GetValue(); - int tmp = ReturnValueFromString( g_UserUnit, msg ) / IU_PER_MILS; + int tmp = ValueFromString( g_UserUnit, msg ) / IU_PER_MILS; if( !tempOptions.SetHPGLPenDiameter( tmp ) ) { - msg = ReturnStringFromValue( g_UserUnit, tempOptions.GetHPGLPenDiameter() * IU_PER_MILS ); + msg = StringFromValue( g_UserUnit, tempOptions.GetHPGLPenDiameter() * IU_PER_MILS ); m_HPGLPenSizeOpt->SetValue( msg ); msg.Printf( _( "HPGL pen size constrained!\n" ) ); m_messagesBox->AppendText( msg ); @@ -595,11 +596,11 @@ void DIALOG_PLOT::applyPlotSettings() // Read HPGL pen overlay (this param is stored in mils) msg = m_HPGLPenOverlayOpt->GetValue(); - tmp = ReturnValueFromString( g_UserUnit, msg ) / IU_PER_MILS; + tmp = ValueFromString( g_UserUnit, msg ) / IU_PER_MILS; if( !tempOptions.SetHPGLPenOverlay( tmp ) ) { - msg = ReturnStringFromValue( g_UserUnit, + msg = StringFromValue( g_UserUnit, tempOptions.GetHPGLPenOverlay() * IU_PER_MILS ); m_HPGLPenOverlayOpt->SetValue( msg ); msg.Printf( _( "HPGL pen overlay constrained!\n" ) ); @@ -608,11 +609,11 @@ void DIALOG_PLOT::applyPlotSettings() // Default linewidth msg = m_linesWidth->GetValue(); - tmp = ReturnValueFromString( g_UserUnit, msg ); + tmp = ValueFromString( g_UserUnit, msg ); if( !tempOptions.SetLineWidth( tmp ) ) { - msg = ReturnStringFromValue( g_UserUnit, tempOptions.GetLineWidth() ); + msg = StringFromValue( g_UserUnit, tempOptions.GetLineWidth() ); m_linesWidth->SetValue( msg ); msg.Printf( _( "Default line width constrained!\n" ) ); m_messagesBox->AppendText( msg ); @@ -649,11 +650,11 @@ void DIALOG_PLOT::applyPlotSettings() // PS Width correction msg = m_PSFineAdjustWidthOpt->GetValue(); - int itmp = ReturnValueFromString( g_UserUnit, msg ); + int itmp = ValueFromString( g_UserUnit, msg ); if( !setInt( &m_PSWidthAdjust, itmp, m_widthAdjustMinValue, m_widthAdjustMaxValue ) ) { - msg = ReturnStringFromValue( g_UserUnit, m_PSWidthAdjust ); + msg = StringFromValue( g_UserUnit, m_PSWidthAdjust ); m_PSFineAdjustWidthOpt->SetValue( msg ); msg.Printf( _( "Width correction constrained!\n" "The reasonable width correction value must be in a range of\n" diff --git a/pcbnew/dialogs/dialog_plot.h b/pcbnew/dialogs/dialog_plot.h index 14bb893fcc..4be5e712d5 100644 --- a/pcbnew/dialogs/dialog_plot.h +++ b/pcbnew/dialogs/dialog_plot.h @@ -42,7 +42,7 @@ private: PCB_EDIT_FRAME* m_parent; BOARD* m_board; BOARD_DESIGN_SETTINGS m_brdSettings; - wxConfig* m_config; + wxConfigBase* m_config; std::vector m_layerList; // List to hold CheckListBox layer numbers double m_XScaleAdjust; // X scale factor adjust to compensate // plotter X scaling error diff --git a/pcbnew/dialogs/dialog_print_for_modedit.cpp b/pcbnew/dialogs/dialog_print_for_modedit.cpp index 9a2b0beda7..12073f5df3 100644 --- a/pcbnew/dialogs/dialog_print_for_modedit.cpp +++ b/pcbnew/dialogs/dialog_print_for_modedit.cpp @@ -2,7 +2,8 @@ /* File: dialog_print_for_modedit.cpp */ #include -#include +//#include +#include #include #include #include @@ -34,7 +35,7 @@ public: private: PCB_BASE_FRAME* m_parent; - wxConfig* m_config; + wxConfigBase* m_config; void OnCloseWindow( wxCloseEvent& event ); @@ -87,7 +88,7 @@ DIALOG_PRINT_FOR_MODEDIT::DIALOG_PRINT_FOR_MODEDIT( PCB_BASE_FRAME* parent ) : { m_parent = parent; s_Parameters.m_ForceCentered = true; - m_config = wxGetApp().GetSettings(); + m_config = Kiface().KifaceSettings(); InitValues(); m_buttonPrint->SetDefault(); diff --git a/pcbnew/dialogs/dialog_print_using_printer.cpp b/pcbnew/dialogs/dialog_print_using_printer.cpp index 33f9a5662a..fae82d0625 100644 --- a/pcbnew/dialogs/dialog_print_using_printer.cpp +++ b/pcbnew/dialogs/dialog_print_using_printer.cpp @@ -6,7 +6,8 @@ //#define wxTEST_POSTSCRIPT_IN_MSW 1 #include -#include +//#include +#include #include #include #include @@ -61,7 +62,7 @@ public: private: PCB_EDIT_FRAME* m_parent; - wxConfig* m_config; + wxConfigBase* m_config; wxCheckBox* m_BoxSelectLayer[32]; static bool m_ExcludeEdgeLayer; @@ -124,7 +125,7 @@ DIALOG_PRINT_USING_PRINTER::DIALOG_PRINT_USING_PRINTER( PCB_EDIT_FRAME* parent ) DIALOG_PRINT_USING_PRINTER_base( parent ) { m_parent = parent; - m_config = wxGetApp().GetSettings(); + m_config = Kiface().KifaceSettings(); InitValues( ); @@ -259,7 +260,7 @@ void DIALOG_PRINT_USING_PRINTER::InitValues( ) s_Parameters.m_PenDefaultSize = g_DrawDefaultLineThickness; AddUnitSymbol( *m_TextPenWidth, g_UserUnit ); m_DialogPenWidth->SetValue( - ReturnStringFromValue( g_UserUnit, s_Parameters.m_PenDefaultSize ) ); + StringFromValue( g_UserUnit, s_Parameters.m_PenDefaultSize ) ); // Create scale adjust option msg.Printf( wxT( "%f" ), s_Parameters.m_XScaleAdjust ); @@ -385,7 +386,7 @@ void DIALOG_PRINT_USING_PRINTER::SetPenWidth() // Get the new pen width value, and verify min et max value // NOTE: s_Parameters.m_PenDefaultSize is in internal units - s_Parameters.m_PenDefaultSize = ReturnValueFromTextCtrl( *m_DialogPenWidth ); + s_Parameters.m_PenDefaultSize = ValueFromTextCtrl( *m_DialogPenWidth ); if( s_Parameters.m_PenDefaultSize > PEN_WIDTH_MAX_VALUE ) { @@ -400,7 +401,7 @@ void DIALOG_PRINT_USING_PRINTER::SetPenWidth() g_DrawDefaultLineThickness = s_Parameters.m_PenDefaultSize; m_DialogPenWidth->SetValue( - ReturnStringFromValue( g_UserUnit, s_Parameters.m_PenDefaultSize ) ); + StringFromValue( g_UserUnit, s_Parameters.m_PenDefaultSize ) ); } void DIALOG_PRINT_USING_PRINTER::OnScaleSelectionClick( wxCommandEvent& event ) diff --git a/pcbnew/dialogs/dialog_set_grid.cpp b/pcbnew/dialogs/dialog_set_grid.cpp index d22890b572..d60e152805 100644 --- a/pcbnew/dialogs/dialog_set_grid.cpp +++ b/pcbnew/dialogs/dialog_set_grid.cpp @@ -141,8 +141,8 @@ wxPoint DIALOG_SET_GRID::getGridOrigin() wxPoint grid; // @todo Some error checking here would be a good thing. - grid.x = ReturnValueFromTextCtrl( *m_GridOriginXCtrl ); - grid.y = ReturnValueFromTextCtrl( *m_GridOriginYCtrl ); + grid.x = ValueFromTextCtrl( *m_GridOriginXCtrl ); + grid.y = ValueFromTextCtrl( *m_GridOriginYCtrl ); return grid; } diff --git a/pcbnew/dimension.cpp b/pcbnew/dimension.cpp index db02e08ae4..fc1f828a89 100644 --- a/pcbnew/dimension.cpp +++ b/pcbnew/dimension.cpp @@ -160,10 +160,12 @@ void DIALOG_DIMENSION_EDITOR::OnCancelClick( wxCommandEvent& event ) void DIALOG_DIMENSION_EDITOR::OnOKClick( wxCommandEvent& event ) { +#ifndef USE_WX_OVERLAY if( m_DC ) // Delete old text. { CurrentDimension->Draw( m_Parent->GetCanvas(), m_DC, GR_XOR ); } +#endif m_Parent->SaveCopyInUndoList(CurrentDimension, UR_CHANGED); @@ -176,22 +178,22 @@ void DIALOG_DIMENSION_EDITOR::OnOKClick( wxCommandEvent& event ) // Get new size value: msg = m_TxtSizeXCtrl->GetValue(); - CurrentDimension->Text().SetWidth( ReturnValueFromString( g_UserUnit, msg ) ); + CurrentDimension->Text().SetWidth( ValueFromString( g_UserUnit, msg ) ); msg = m_TxtSizeYCtrl->GetValue(); - CurrentDimension->Text().SetHeight( ReturnValueFromString( g_UserUnit, msg ) ); + CurrentDimension->Text().SetHeight( ValueFromString( g_UserUnit, msg ) ); // Get new position value: // It will be copied later in dimension, because msg = m_textCtrlPosX->GetValue(); wxPoint pos; - pos.x = ReturnValueFromString( g_UserUnit, msg ); + pos.x = ValueFromString( g_UserUnit, msg ); msg = m_textCtrlPosY->GetValue(); - pos.y = ReturnValueFromString( g_UserUnit, msg ); + pos.y = ValueFromString( g_UserUnit, msg ); CurrentDimension->Text().SetTextPosition( pos ); // Get new line thickness value: msg = m_TxtWidthCtrl->GetValue(); - int width = ReturnValueFromString( g_UserUnit, msg ); + int width = ValueFromString( g_UserUnit, msg ); int maxthickness = Clamp_Text_PenSize( width, CurrentDimension->Text().GetSize() ); if( width > maxthickness ) @@ -207,12 +209,14 @@ void DIALOG_DIMENSION_EDITOR::OnOKClick( wxCommandEvent& event ) CurrentDimension->Text().SetMirrored( ( m_rbMirror->GetSelection() == 1 ) ? true : false ); CurrentDimension->SetLayer( m_SelLayerBox->GetLayerSelection() ); - +#ifndef USE_WX_OVERLAY if( m_DC ) // Display new text { CurrentDimension->Draw( m_Parent->GetCanvas(), m_DC, GR_OR ); } - +#else + m_Parent->Refresh(); +#endif m_Parent->OnModify(); EndModal( 1 ); } diff --git a/pcbnew/drc.cpp b/pcbnew/drc.cpp index 1039fc3492..630475ac23 100644 --- a/pcbnew/drc.cpp +++ b/pcbnew/drc.cpp @@ -301,7 +301,7 @@ bool DRC::doNetClass( NETCLASS* nc, wxString& msg ) const BOARD_DESIGN_SETTINGS& g = m_pcb->GetDesignSettings(); -#define FmtVal( x ) GetChars( ReturnStringFromValue( g_UserUnit, x ) ) +#define FmtVal( x ) GetChars( StringFromValue( g_UserUnit, x ) ) #if 0 // set to 1 when (if...) BOARD_DESIGN_SETTINGS has a m_MinClearance value if( nc->GetClearance() < g.m_MinClearance ) diff --git a/pcbnew/drc_clearance_test_functions.cpp b/pcbnew/drc_clearance_test_functions.cpp index 06bc935cd1..0550f6cfa2 100644 --- a/pcbnew/drc_clearance_test_functions.cpp +++ b/pcbnew/drc_clearance_test_functions.cpp @@ -207,7 +207,7 @@ bool DRC::doTrackDrc( TRACK* aRefSeg, TRACK* aStart, bool testPads ) LAYER_NUM layer1, layer2; bool err = true; - ( (SEGVIA*) aRefSeg )->ReturnLayerPair( &layer1, &layer2 ); + ( (SEGVIA*) aRefSeg )->LayerPair( &layer1, &layer2 ); if( layer1 > layer2 ) EXCHG( layer1, layer2 ); @@ -315,7 +315,7 @@ bool DRC::doTrackDrc( TRACK* aRefSeg, TRACK* aStart, bool testPads ) continue; // DRC for the pad - shape_pos = pad->ReturnShapePos(); + shape_pos = pad->ShapePos(); m_padToTestPos = shape_pos - origin; if( !checkClearanceSegmToPad( pad, aRefSeg->GetWidth(), aRefSeg->GetClearance( pad ) ) ) @@ -588,7 +588,7 @@ bool DRC::checkClearancePadToPad( D_PAD* aRefPad, D_PAD* aPad ) int dist_min = aRefPad->GetClearance( aPad ); // relativePadPos is the aPad shape position relative to the aRefPad shape position - wxPoint relativePadPos = aPad->ReturnShapePos() - aRefPad->ReturnShapePos(); + wxPoint relativePadPos = aPad->ShapePos() - aRefPad->ShapePos(); dist = KiROUND( EuclideanNorm( relativePadPos ) ); diff --git a/pcbnew/edgemod.cpp b/pcbnew/edgemod.cpp index 14843623a1..7239dc37a8 100644 --- a/pcbnew/edgemod.cpp +++ b/pcbnew/edgemod.cpp @@ -251,14 +251,14 @@ void FOOTPRINT_EDIT_FRAME::Enter_Edge_Width( EDGE_MODULE* aEdge ) { wxString buffer; - buffer = ReturnStringFromValue( g_UserUnit, GetDesignSettings().m_ModuleSegmentWidth ); + buffer = StringFromValue( g_UserUnit, GetDesignSettings().m_ModuleSegmentWidth ); wxTextEntryDialog dlg( this, _( "New Width:" ), _( "Edge Width" ), buffer ); if( dlg.ShowModal() != wxID_OK ) return; // canceled by user buffer = dlg.GetValue( ); - GetDesignSettings().m_ModuleSegmentWidth = ReturnValueFromString( g_UserUnit, buffer ); + GetDesignSettings().m_ModuleSegmentWidth = ValueFromString( g_UserUnit, buffer ); if( aEdge ) { diff --git a/pcbnew/edit.cpp b/pcbnew/edit.cpp index cf1c9242e2..eff1aa15b5 100644 --- a/pcbnew/edit.cpp +++ b/pcbnew/edit.cpp @@ -30,7 +30,8 @@ */ #include -#include +#include +#include #include #include #include @@ -192,36 +193,38 @@ void PCB_EDIT_FRAME::Process_Special_Functions( wxCommandEvent& event ) case ID_OPEN_MODULE_EDITOR: { - FOOTPRINT_EDIT_FRAME* editorFrame = FOOTPRINT_EDIT_FRAME::GetActiveFootprintEditor(); + FOOTPRINT_EDIT_FRAME* editor = FOOTPRINT_EDIT_FRAME::GetActiveFootprintEditor( this ); - if( editorFrame == NULL ) + if( !editor ) { - editorFrame = new FOOTPRINT_EDIT_FRAME( this, m_footprintLibTable ); - editorFrame->Show( true ); - editorFrame->Zoom_Automatique( false ); + editor = (FOOTPRINT_EDIT_FRAME*) Kiface().CreateWindow( this, MODULE_EDITOR_FRAME_TYPE, &Kiway() ); + + editor->Show( true ); + editor->Zoom_Automatique( false ); } else { - if( editorFrame->IsIconized() ) - editorFrame->Iconize( false ); + if( editor->IsIconized() ) + editor->Iconize( false ); - editorFrame->Raise(); + editor->Raise(); // Raising the window does not set the focus on Linux. This should work on // any platform. - if( wxWindow::FindFocus() != editorFrame ) - editorFrame->SetFocus(); + if( wxWindow::FindFocus() != editor ) + editor->SetFocus(); } } break; case ID_OPEN_MODULE_VIEWER: { - FOOTPRINT_VIEWER_FRAME * viewer = - FOOTPRINT_VIEWER_FRAME::GetActiveFootprintViewer(); - if( viewer == NULL ) + FOOTPRINT_VIEWER_FRAME* viewer = FOOTPRINT_VIEWER_FRAME::GetActiveFootprintViewer( this ); + + if( !viewer ) { - viewer = new FOOTPRINT_VIEWER_FRAME( this, m_footprintLibTable, NULL ); + viewer = (FOOTPRINT_VIEWER_FRAME*) Kiface().CreateWindow( this, MODULE_VIEWER_FRAME_TYPE, &Kiway() ); + viewer->Show( true ); viewer->Zoom_Automatique( false ); } @@ -835,16 +838,18 @@ void PCB_EDIT_FRAME::Process_Special_Functions( wxCommandEvent& event ) } { - FOOTPRINT_EDIT_FRAME* editorFrame = FOOTPRINT_EDIT_FRAME::GetActiveFootprintEditor(); + FOOTPRINT_EDIT_FRAME* editor = FOOTPRINT_EDIT_FRAME::GetActiveFootprintEditor( this ); - if( editorFrame == NULL ) - editorFrame = new FOOTPRINT_EDIT_FRAME( this, m_footprintLibTable ); + if( !editor ) + { + editor = (FOOTPRINT_EDIT_FRAME*) Kiface().CreateWindow( this, MODULE_EDITOR_FRAME_TYPE, &Kiway() ); + } - editorFrame->Load_Module_From_BOARD( (MODULE*)GetCurItem() ); + editor->Load_Module_From_BOARD( (MODULE*)GetCurItem() ); SetCurItem( NULL ); // the current module could be deleted by - editorFrame->Show( true ); - editorFrame->Iconize( false ); + editor->Show( true ); + editor->Iconize( false ); } m_canvas->MoveCursorToCrossHair(); break; @@ -1177,9 +1182,9 @@ void PCB_EDIT_FRAME::Process_Special_Functions( wxCommandEvent& event ) case ID_POPUP_PCB_DISPLAY_FOOTPRINT_DOC: { - wxConfig* cfg = wxGetApp().GetCommonSettings(); + wxConfigBase* cfg = Pgm().CommonSettings(); cfg->Read( wxT( "module_doc_file" ), g_DocModulesFileName ); - GetAssociatedDocument( this, g_DocModulesFileName, &wxGetApp().GetLibraryPathList() ); + GetAssociatedDocument( this, g_DocModulesFileName, &Kiface().KifaceSearch() ); } break; diff --git a/pcbnew/editmod.cpp b/pcbnew/editmod.cpp index 1f217d6194..7eed255d4c 100644 --- a/pcbnew/editmod.cpp +++ b/pcbnew/editmod.cpp @@ -27,6 +27,7 @@ */ #include +#include #include #include #include @@ -67,22 +68,24 @@ void PCB_EDIT_FRAME::InstallModuleOptionsFrame( MODULE* Module, wxDC* DC ) #ifdef __WXMAC__ // If something edited, push a refresh request - if (retvalue == 0 || retvalue == 1) + if( retvalue == 0 || retvalue == 1 ) m_canvas->Refresh(); #endif if( retvalue == 2 ) { - FOOTPRINT_EDIT_FRAME* editorFrame = FOOTPRINT_EDIT_FRAME::GetActiveFootprintEditor(); + FOOTPRINT_EDIT_FRAME* editor = FOOTPRINT_EDIT_FRAME::GetActiveFootprintEditor( this ); - if( editorFrame == NULL ) - editorFrame = new FOOTPRINT_EDIT_FRAME( this, m_footprintLibTable ); + if( !editor ) + { + editor = (FOOTPRINT_EDIT_FRAME*) Kiface().CreateWindow( this, MODULE_EDITOR_FRAME_TYPE, &Kiway() ); + } - editorFrame->Load_Module_From_BOARD( Module ); + editor->Load_Module_From_BOARD( Module ); SetCurItem( NULL ); - editorFrame->Show( true ); - editorFrame->Iconize( false ); + editor->Show( true ); + editor->Iconize( false ); } } diff --git a/pcbnew/exporters/export_d356.cpp b/pcbnew/exporters/export_d356.cpp index 1c64ff64bd..865986acc9 100644 --- a/pcbnew/exporters/export_d356.cpp +++ b/pcbnew/exporters/export_d356.cpp @@ -27,22 +27,22 @@ * @brief Export IPC-D-356 test format */ -#include "fctsys.h" -#include "class_drawpanel.h" -#include "confirm.h" -#include "gestfich.h" -#include "appl_wxstruct.h" -#include "wxPcbStruct.h" -#include "trigo.h" -#include "build_version.h" -#include "macros.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include -#include "pcbnew.h" +#include -#include "class_board.h" -#include "class_module.h" -#include "class_track.h" -#include "class_edge_mod.h" +#include +#include +#include +#include #include #include @@ -50,14 +50,14 @@ * Useful because 356A (when implemented) must be sorted before outputting it */ struct D356_RECORD { - bool smd; - bool hole; - wxString netname; - wxString refdes; - wxString pin; - bool midpoint; + bool smd; + bool hole; + wxString netname; + wxString refdes; + wxString pin; + bool midpoint; int drill; - bool mechanical; + bool mechanical; int access; // Access 0 is 'both sides' int soldermask; // All these in PCB units, will be output in decimils @@ -74,19 +74,19 @@ static int compute_pad_access_code( BOARD *aPcb, LAYER_MSK aLayerMask ) // Non-copper is not interesting here aLayerMask &= ALL_CU_LAYERS; if( aLayerMask == 0 ) - return -1; + return -1; // Traditional TH pad if( (aLayerMask & LAYER_FRONT) && (aLayerMask & LAYER_BACK) ) - return 0; + return 0; // Front SMD pad if( (aLayerMask & LAYER_FRONT) ) - return 1; + return 1; // Back SMD pad if( (aLayerMask & LAYER_BACK) ) - return aPcb->GetCopperLayerCount(); + return aPcb->GetCopperLayerCount(); // OK, we have an inner-layer only pad (and I have no idea about // what could be used for); anyway, find the first copper layer @@ -129,36 +129,36 @@ static void build_pad_testpoints( BOARD *aPcb, // It could be a mask only pad, we only handle pads with copper here if( rk.access != -1 ) { - rk.netname = pad->GetNetname(); - rk.refdes = module->GetReference(); - pad->ReturnStringPadName( rk.pin ); - rk.midpoint = false; // XXX MAYBE need to be computed (how?) - const wxSize& drill = pad->GetDrillSize(); - rk.drill = std::min( drill.x, drill.y ); - rk.hole = (rk.drill != 0); - rk.smd = pad->GetAttribute() == PAD_SMD; - rk.mechanical = (pad->GetAttribute() == PAD_HOLE_NOT_PLATED); - rk.x_location = pad->GetPosition().x - origin.x; - rk.y_location = origin.y - pad->GetPosition().y; - rk.x_size = pad->GetSize().x; + rk.netname = pad->GetNetname(); + rk.refdes = module->GetReference(); + pad->StringPadName( rk.pin ); + rk.midpoint = false; // XXX MAYBE need to be computed (how?) + const wxSize& drill = pad->GetDrillSize(); + rk.drill = std::min( drill.x, drill.y ); + rk.hole = (rk.drill != 0); + rk.smd = pad->GetAttribute() == PAD_SMD; + rk.mechanical = (pad->GetAttribute() == PAD_HOLE_NOT_PLATED); + rk.x_location = pad->GetPosition().x - origin.x; + rk.y_location = origin.y - pad->GetPosition().y; + rk.x_size = pad->GetSize().x; - // Rule: round pads have y = 0 - if( pad->GetShape() == PAD_CIRCLE ) - rk.y_size = 0; - else - rk.y_size = pad->GetSize().y; + // Rule: round pads have y = 0 + if( pad->GetShape() == PAD_CIRCLE ) + rk.y_size = 0; + else + rk.y_size = pad->GetSize().y; - rk.rotation = -KiROUND( pad->GetOrientation() ) / 10; - if( rk.rotation < 0 ) rk.rotation += 360; + rk.rotation = -KiROUND( pad->GetOrientation() ) / 10; + if( rk.rotation < 0 ) rk.rotation += 360; - // the value indicates which sides are *not* accessible - rk.soldermask = 3; - if( pad->GetLayerMask() & SOLDERMASK_LAYER_FRONT) - rk.soldermask &= ~1; - if( pad->GetLayerMask() & SOLDERMASK_LAYER_BACK) - rk.soldermask &= ~2; + // the value indicates which sides are *not* accessible + rk.soldermask = 3; + if( pad->GetLayerMask() & SOLDERMASK_LAYER_FRONT) + rk.soldermask &= ~1; + if( pad->GetLayerMask() & SOLDERMASK_LAYER_BACK) + rk.soldermask &= ~2; - aRecords.push_back( rk ); + aRecords.push_back( rk ); } } } @@ -172,15 +172,15 @@ static int via_access_code( BOARD *aPcb, int top_layer, int bottom_layer ) // Easy case for through vias: top_layer is component, bottom_layer is // solder, access code is 0 if( (top_layer == LAYER_N_FRONT) && (bottom_layer == LAYER_N_BACK) ) - return 0; + return 0; // Blind via, reachable from front if( top_layer == LAYER_N_FRONT ) - return 1; + return 1; // Blind via, reachable from bottom if( bottom_layer == LAYER_N_BACK ) - return aPcb->GetCopperLayerCount(); + return aPcb->GetCopperLayerCount(); // It's a buried via, accessible from some inner layer // (maybe could be used for testing before laminating? no idea) @@ -214,7 +214,7 @@ static void build_via_testpoints( BOARD *aPcb, rk.drill = via->GetDrillValue(); rk.mechanical = false; LAYER_NUM top_layer, bottom_layer; - via->ReturnLayerPair( &top_layer, &bottom_layer ); + via->LayerPair( &top_layer, &bottom_layer ); rk.access = via_access_code( aPcb, top_layer, bottom_layer ); rk.x_location = via->GetPosition().x - origin.x; rk.y_location = origin.y - via->GetPosition().y; diff --git a/pcbnew/exporters/export_gencad.cpp b/pcbnew/exporters/export_gencad.cpp index 638d22f55d..8ef7e19214 100644 --- a/pcbnew/exporters/export_gencad.cpp +++ b/pcbnew/exporters/export_gencad.cpp @@ -33,7 +33,7 @@ #include #include #include -#include +#include #include #include #include @@ -525,7 +525,7 @@ static void CreateShapesSection( FILE* aFile, BOARD* aPcb ) layer = ( module->GetFlag() ) ? "BOTTOM" : "TOP"; } - pad->ReturnStringPadName( pinname ); + pad->StringPadName( pinname ); if( pinname.IsEmpty() ) pinname = wxT( "none" ); @@ -666,7 +666,7 @@ static void CreateSignalsSection( FILE* aFile, BOARD* aPcb ) if( pad->GetNetCode() != net->GetNet() ) continue; - pad->ReturnStringPadName( padname ); + pad->StringPadName( padname ); msg.Printf( wxT( "NODE %s %s" ), GetChars( module->GetReference() ), GetChars( padname ) ); @@ -692,7 +692,7 @@ static bool CreateHeaderInfoData( FILE* aFile, PCB_EDIT_FRAME* aFrame ) // Please note: GenCAD syntax requires quoted strings if they can contain spaces msg.Printf( wxT( "USER \"%s %s\"\n" ), - GetChars( wxGetApp().GetAppName() ), + GetChars( Pgm().App().GetAppName() ), GetChars( GetBuildVersion() ) ); fputs( TO_UTF8( msg ), aFile ); diff --git a/pcbnew/exporters/export_vrml.cpp b/pcbnew/exporters/export_vrml.cpp index 53845f1db4..ae1b37c194 100644 --- a/pcbnew/exporters/export_vrml.cpp +++ b/pcbnew/exporters/export_vrml.cpp @@ -67,7 +67,7 @@ #include #include #include -#include +#include #include <3d_struct.h> #include @@ -812,7 +812,7 @@ static void export_vrml_via( MODEL_VRML& aModel, BOARD* pcb, SEGVIA* via ) r = via->GetWidth() * aModel.scale / 2.0; x = via->GetStart().x * aModel.scale + aModel.tx; y = via->GetStart().y * aModel.scale + aModel.ty; - via->ReturnLayerPair( &top_layer, &bottom_layer ); + via->LayerPair( &top_layer, &bottom_layer ); // do not render a buried via if( top_layer != LAST_COPPER_LAYER && bottom_layer != FIRST_COPPER_LAYER ) @@ -994,7 +994,7 @@ static void export_vrml_padshape( MODEL_VRML& aModel, VRML_LAYER* aLayer, VRML_LAYER* aTinLayer, D_PAD* aPad ) { // The (maybe offset) pad position - wxPoint pad_pos = aPad->ReturnShapePos(); + wxPoint pad_pos = aPad->ShapePos(); double pad_x = pad_pos.x * aModel.scale + aModel.tx; double pad_y = pad_pos.y * aModel.scale + aModel.ty; wxSize pad_delta = aPad->GetDelta(); diff --git a/pcbnew/exporters/gen_drill_report_files.cpp b/pcbnew/exporters/gen_drill_report_files.cpp index 2c4f9b8c7c..c378353e11 100644 --- a/pcbnew/exporters/gen_drill_report_files.cpp +++ b/pcbnew/exporters/gen_drill_report_files.cpp @@ -55,12 +55,6 @@ inline double diameter_in_mm( double ius ) } -/* Creates a hole map of the board in HPGL, POSTSCRIPT or other supported formats - * Each hole size has a the drill mark symbol (circle, cross X, cross + ...) up to - * PLOTTER::MARKER_COUNT different values. - * If more than PLOTTER::MARKER_COUNT different values, - * these other vaules share the same mark - */ bool EXCELLON_WRITER::GenDrillMapFile( const wxString& aFullFileName, const PAGE_INFO& aSheet, PlotFormat aFormat ) @@ -87,15 +81,15 @@ bool EXCELLON_WRITER::GenDrillMapFile( const wxString& aFullFileName, break; case PLOT_FORMAT_HPGL: // Scale for HPGL format. - { - HPGL_PLOTTER* hpgl_plotter = new HPGL_PLOTTER; - plotter = hpgl_plotter; - hpgl_plotter->SetPenNumber( plot_opts.GetHPGLPenNum() ); - hpgl_plotter->SetPenSpeed( plot_opts.GetHPGLPenSpeed() ); - hpgl_plotter->SetPenOverlap( 0 ); - plotter->SetPageSettings( aSheet ); - plotter->SetViewport( offset, IU_PER_DECIMILS, scale, false ); - } + { + HPGL_PLOTTER* hpgl_plotter = new HPGL_PLOTTER; + plotter = hpgl_plotter; + hpgl_plotter->SetPenNumber( plot_opts.GetHPGLPenNum() ); + hpgl_plotter->SetPenSpeed( plot_opts.GetHPGLPenSpeed() ); + hpgl_plotter->SetPenOverlap( 0 ); + plotter->SetPageSettings( aSheet ); + plotter->SetViewport( offset, IU_PER_DECIMILS, scale, false ); + } break; @@ -104,59 +98,59 @@ bool EXCELLON_WRITER::GenDrillMapFile( const wxString& aFullFileName, // fall through case PLOT_FORMAT_PDF: case PLOT_FORMAT_POST: - { - PAGE_INFO pageA4( wxT( "A4" ) ); - wxSize pageSizeIU = pageA4.GetSizeIU(); + { + PAGE_INFO pageA4( wxT( "A4" ) ); + wxSize pageSizeIU = pageA4.GetSizeIU(); - // Reserve a margin around the page. - int margin = KiROUND( 20 * IU_PER_MM ); + // Reserve a margin around the page. + int margin = KiROUND( 20 * IU_PER_MM ); - // Calculate a scaling factor to print the board on the sheet - double Xscale = double( pageSizeIU.x - ( 2 * margin ) ) / bbbox.GetWidth(); + // Calculate a scaling factor to print the board on the sheet + double Xscale = double( pageSizeIU.x - ( 2 * margin ) ) / bbbox.GetWidth(); - // We should print the list of drill sizes, so reserve room for it - // 60% height for board 40% height for list - int ypagesize_for_board = KiROUND( pageSizeIU.y * 0.6 ); - double Yscale = double( ypagesize_for_board - margin ) / bbbox.GetHeight(); + // We should print the list of drill sizes, so reserve room for it + // 60% height for board 40% height for list + int ypagesize_for_board = KiROUND( pageSizeIU.y * 0.6 ); + double Yscale = double( ypagesize_for_board - margin ) / bbbox.GetHeight(); - scale = std::min( Xscale, Yscale ); + scale = std::min( Xscale, Yscale ); - // Experience shows the scale should not to large, because texts - // create problem (can be to big or too small). - // So the scale is clipped at 3.0; - scale = std::min( scale, 3.0 ); + // Experience shows the scale should not to large, because texts + // create problem (can be to big or too small). + // So the scale is clipped at 3.0; + scale = std::min( scale, 3.0 ); - offset.x = KiROUND( double( bbbox.Centre().x ) - - ( pageSizeIU.x / 2.0 ) / scale ); - offset.y = KiROUND( double( bbbox.Centre().y ) - - ( ypagesize_for_board / 2.0 ) / scale ); + offset.x = KiROUND( double( bbbox.Centre().x ) - + ( pageSizeIU.x / 2.0 ) / scale ); + offset.y = KiROUND( double( bbbox.Centre().y ) - + ( ypagesize_for_board / 2.0 ) / scale ); - if( aFormat == PLOT_FORMAT_PDF ) - plotter = new PDF_PLOTTER; - else - plotter = new PS_PLOTTER; + if( aFormat == PLOT_FORMAT_PDF ) + plotter = new PDF_PLOTTER; + else + plotter = new PS_PLOTTER; - plotter->SetPageSettings( pageA4 ); - plotter->SetViewport( offset, IU_PER_DECIMILS, scale, false ); - } + plotter->SetPageSettings( pageA4 ); + plotter->SetViewport( offset, IU_PER_DECIMILS, scale, false ); + } break; case PLOT_FORMAT_DXF: - { - DXF_PLOTTER* dxf_plotter = new DXF_PLOTTER; - plotter = dxf_plotter; - plotter->SetPageSettings( aSheet ); - plotter->SetViewport( offset, IU_PER_DECIMILS, scale, false ); - } + { + DXF_PLOTTER* dxf_plotter = new DXF_PLOTTER; + plotter = dxf_plotter; + plotter->SetPageSettings( aSheet ); + plotter->SetViewport( offset, IU_PER_DECIMILS, scale, false ); + } break; case PLOT_FORMAT_SVG: - { - SVG_PLOTTER* svg_plotter = new SVG_PLOTTER; - plotter = svg_plotter; - plotter->SetPageSettings( aSheet ); - plotter->SetViewport( offset, IU_PER_DECIMILS, scale, false ); - } + { + SVG_PLOTTER* svg_plotter = new SVG_PLOTTER; + plotter = svg_plotter; + plotter->SetPageSettings( aSheet ); + plotter->SetViewport( offset, IU_PER_DECIMILS, scale, false ); + } break; } @@ -239,8 +233,7 @@ bool EXCELLON_WRITER::GenDrillMapFile( const wxString& aFullFileName, plotY += intervalle; plot_diam = KiROUND( m_toolListBuffer[ii].m_Diameter ); - x = KiROUND( plotX - textmarginaftersymbol * charScale - - plot_diam / 2.0 ); + x = KiROUND( plotX - textmarginaftersymbol * charScale - plot_diam / 2.0 ); y = KiROUND( plotY + charSize * charScale ); plotter->Marker( wxPoint( x, y ), plot_diam, ii ); @@ -267,10 +260,9 @@ bool EXCELLON_WRITER::GenDrillMapFile( const wxString& aFullFileName, m_toolListBuffer[ii].m_OvalCount ); msg += FROM_UTF8( line ); - plotter->Text( wxPoint( plotX, y ), UNSPECIFIED_COLOR, - msg, - 0, wxSize( KiROUND( charSize * charScale ), - KiROUND( charSize * charScale ) ), + plotter->Text( wxPoint( plotX, y ), UNSPECIFIED_COLOR, msg, 0, + wxSize( KiROUND( charSize * charScale ), + KiROUND( charSize * charScale ) ), GR_TEXT_HJUSTIFY_LEFT, GR_TEXT_VJUSTIFY_CENTER, TextWidth, false, false ); @@ -287,52 +279,6 @@ bool EXCELLON_WRITER::GenDrillMapFile( const wxString& aFullFileName, } -/* - * Create a plain text report file giving a list of drill values and drill count - * for through holes, oblong holes, and for buried vias, - * drill values and drill count per layer pair - */ -/* Here is a sample created by this function: - * Drill report for F:/tmp/interf_u/interf_u.brd - * Created on 04/10/2012 20:48:38 - * Selected Drill Unit: Imperial (inches) - * - * Drill report for plated through holes : - * T1 0,025" 0,64mm (88 holes) - * T2 0,031" 0,79mm (120 holes) - * T3 0,032" 0,81mm (151 holes) (with 1 slot) - * T4 0,040" 1,02mm (43 holes) - * T5 0,079" 2,00mm (1 hole) (with 1 slot) - * T6 0,120" 3,05mm (1 hole) (with 1 slot) - * - * Total plated holes count 404 - * - * - * Drill report for buried and blind vias : - * - * Drill report for holes from layer Soudure to layer Interne1 : - * - * Total plated holes count 0 - * - * - * Drill report for holes from layer Interne1 to layer Interne2 : - * T1 0,025" 0,64mm (3 holes) - * - * Total plated holes count 3 - * - * - * Drill report for holes from layer Interne2 to layer Composant : - * T1 0,025" 0,64mm (1 hole) - * - * Total plated holes count 1 - * - * - * Drill report for unplated through holes : - * T1 0,120" 3,05mm (1 hole) (with 1 slot) - * - * Total unplated holes count 1 - * - */ bool EXCELLON_WRITER::GenDrillReportFile( const wxString& aFullFileName ) { unsigned totalHoleCount; @@ -360,7 +306,7 @@ bool EXCELLON_WRITER::GenDrillReportFile( const wxString& aFullFileName ) for( ; ; ) { BuildHolesList( layer1, layer2, - gen_through_holes ? false : true, gen_NPTH_holes, false); + gen_through_holes ? false : true, gen_NPTH_holes, false); totalHoleCount = 0; @@ -461,17 +407,17 @@ bool EXCELLON_WRITER::GenDrillReportFile( const wxString& aFullFileName ) return true; } -// Helper function to plot drill marks: + bool EXCELLON_WRITER::PlotDrillMarks( PLOTTER* aPlotter ) { // Plot the drill map: wxPoint pos; + for( unsigned ii = 0; ii < m_holeListBuffer.size(); ii++ ) { pos = m_holeListBuffer[ii].m_Hole_Pos; - /* Always plot the drill symbol (for slots identifies the needed - * cutter!) */ + // Always plot the drill symbol (for slots identifies the needed cutter! aPlotter->Marker( pos, m_holeListBuffer[ii].m_Hole_Diameter, m_holeListBuffer[ii].m_Tool_Reference - 1 ); diff --git a/pcbnew/exporters/gen_modules_placefile.cpp b/pcbnew/exporters/gen_modules_placefile.cpp index 609b6adebf..b572338064 100644 --- a/pcbnew/exporters/gen_modules_placefile.cpp +++ b/pcbnew/exporters/gen_modules_placefile.cpp @@ -35,7 +35,7 @@ #include #include #include -#include +#include #include #include @@ -462,7 +462,7 @@ int PCB_EDIT_FRAME::DoGenFootprintsPositionFile( const wxString& aFullFileName, sprintf( line, "### Module positions - created on %s ###\n", TO_UTF8( DateAndTime() ) ); fputs( line, file ); - wxString Title = wxGetApp().GetAppName() + wxT( " " ) + GetBuildVersion(); + wxString Title = Pgm().App().GetAppName() + wxT( " " ) + GetBuildVersion(); sprintf( line, "### Printed by Pcbnew version %s\n", TO_UTF8( Title ) ); fputs( line, file ); @@ -582,7 +582,7 @@ bool PCB_EDIT_FRAME::DoGenFootprintsReport( const wxString& aFullFilename, bool sprintf( line, "## Module report - date %s\n", TO_UTF8( DateAndTime() ) ); fputs( line, rptfile ); - wxString Title = wxGetApp().GetAppName() + wxT( " " ) + GetBuildVersion(); + wxString Title = Pgm().App().GetAppName() + wxT( " " ) + GetBuildVersion(); sprintf( line, "## Created by Pcbnew version %s\n", TO_UTF8( Title ) ); fputs( line, rptfile ); fputs( unit_text, rptfile ); diff --git a/pcbnew/exporters/gendrill_Excellon_writer.cpp b/pcbnew/exporters/gendrill_Excellon_writer.cpp index 91b486c4ad..8a3413db1f 100644 --- a/pcbnew/exporters/gendrill_Excellon_writer.cpp +++ b/pcbnew/exporters/gendrill_Excellon_writer.cpp @@ -42,7 +42,7 @@ #include #include #include -#include +#include #include #include @@ -69,11 +69,7 @@ */ -/* - * Create the drill file in EXCELLON format - * return hole count - */ -int EXCELLON_WRITER::CreateDrillFile( FILE * aFile ) +int EXCELLON_WRITER::CreateDrillFile( FILE* aFile ) { m_file = aFile; @@ -100,7 +96,8 @@ int EXCELLON_WRITER::CreateDrillFile( FILE * aFile ) fputs( "G90\n", m_file ); // Absolute mode fputs( "G05\n", m_file ); // Drill mode - /* Units : */ + + // Units : if( !m_minimalHeader ) { if( m_unitsDecimal ) @@ -112,12 +109,14 @@ int EXCELLON_WRITER::CreateDrillFile( FILE * aFile ) /* Read the hole file and generate lines for normal holes (oblong * holes will be created later) */ int tool_reference = -2; + for( unsigned ii = 0; ii < m_holeListBuffer.size(); ii++ ) { HOLE_INFO& hole_descr = m_holeListBuffer[ii]; if( hole_descr.m_Hole_Shape ) continue; // oblong holes will be created later + if( tool_reference != hole_descr.m_Tool_Reference ) { tool_reference = hole_descr.m_Tool_Reference; @@ -145,16 +144,18 @@ int EXCELLON_WRITER::CreateDrillFile( FILE * aFile ) for( unsigned ii = 0; ii < m_holeListBuffer.size(); ii++ ) { HOLE_INFO& hole_descr = m_holeListBuffer[ii]; + if( hole_descr.m_Hole_Shape == 0 ) continue; // wait for oblong holes + if( tool_reference != hole_descr.m_Tool_Reference ) { tool_reference = hole_descr.m_Tool_Reference; fprintf( m_file, "T%d\n", tool_reference ); } - diam = std::min( hole_descr.m_Hole_Size.x, - hole_descr.m_Hole_Size.y ); + diam = std::min( hole_descr.m_Hole_Size.x, hole_descr.m_Hole_Size.y ); + if( diam == 0 ) continue; @@ -166,20 +167,23 @@ int EXCELLON_WRITER::CreateDrillFile( FILE * aFile ) if( hole_descr.m_Hole_Size.x < hole_descr.m_Hole_Size.y ) { int delta = ( hole_descr.m_Hole_Size.y - hole_descr.m_Hole_Size.x ) / 2; - y0 -= delta; yf += delta; + y0 -= delta; + yf += delta; } else { int delta = ( hole_descr.m_Hole_Size.x - hole_descr.m_Hole_Size.y ) / 2; - x0 -= delta; xf += delta; + x0 -= delta; + xf += delta; } + RotatePoint( &x0, &y0, xc, yc, hole_descr.m_Hole_Orient ); RotatePoint( &xf, &yf, xc, yc, hole_descr.m_Hole_Orient ); - if( !m_mirror ) { - y0 *= -1; yf *= -1; + y0 *= -1; + yf *= -1; } xt = x0 * m_conversionUnits; @@ -189,11 +193,12 @@ int EXCELLON_WRITER::CreateDrillFile( FILE * aFile ) /* remove the '\n' from end of line, because we must add the "G85" * command to the line: */ for( int kk = 0; line[kk] != 0; kk++ ) + { if( line[kk] == '\n' || line[kk] =='\r' ) line[kk] = 0; + } fputs( line, m_file ); - fputs( "G85", m_file ); // add the "G85" command xt = xf * m_conversionUnits; @@ -213,14 +218,6 @@ int EXCELLON_WRITER::CreateDrillFile( FILE * aFile ) } -/** - * SetFormat - * Initialize internal parameters to match the given format - * @param aMetric = true for metric coordinates, false for imperial units - * @param aZerosFmt = DECIMAL_FORMAT, SUPPRESS_LEADING, SUPPRESS_TRAILING, KEEP_ZEROS - * @param aLeftDigits = number of digits for integer part of coordinates - * @param aRightDigits = number of digits for mantissa part of coordinates - */ void EXCELLON_WRITER::SetFormat( bool aMetric, zeros_fmt aZerosFmt, int aLeftDigits, @@ -240,10 +237,6 @@ void EXCELLON_WRITER::SetFormat( bool aMetric, } -/* Created a line like: - * X48000Y19500 - * According to the selected format - */ void EXCELLON_WRITER::WriteCoordinates( char* aLine, double aCoordX, double aCoordY ) { wxString xs, ys; @@ -277,8 +270,10 @@ void EXCELLON_WRITER::WriteCoordinates( char* aLine, double aCoordX, double aCoo //Remove useless trailing 0 while( xs.Last() == '0' ) xs.RemoveLast(); + while( ys.Last() == '0' ) ys.RemoveLast(); + sprintf( aLine, "X%sY%s\n", TO_UTF8( xs ), TO_UTF8( ys ) ); break; @@ -301,6 +296,7 @@ void EXCELLON_WRITER::WriteCoordinates( char* aLine, double aCoordX, double aCoo if( aCoordX < 0 ) xpad++; + if( aCoordY < 0 ) ypad++; @@ -308,10 +304,12 @@ void EXCELLON_WRITER::WriteCoordinates( char* aLine, double aCoordX, double aCoo ys.Printf( wxT( "%0*d" ), ypad, KiROUND( aCoordY ) ); size_t j = xs.Len() - 1; + while( xs[j] == '0' && j ) xs.Truncate( j-- ); j = ys.Len() - 1; + while( ys[j] == '0' && j ) ys.Truncate( j-- ); @@ -327,8 +325,10 @@ void EXCELLON_WRITER::WriteCoordinates( char* aLine, double aCoordX, double aCoo if( aCoordX < 0 ) xpad++; + if( aCoordY < 0 ) ypad++; + xs.Printf( wxT( "%0*d" ), xpad, KiROUND( aCoordX ) ); ys.Printf( wxT( "%0*d" ), ypad, KiROUND( aCoordY ) ); sprintf( aLine, "X%sY%s\n", TO_UTF8( xs ), TO_UTF8( ys ) ); @@ -337,13 +337,6 @@ void EXCELLON_WRITER::WriteCoordinates( char* aLine, double aCoordX, double aCoo } -/* Print the DRILL file header. The full header is: - * M48 - * ;DRILL file {PCBNEW (2007-11-29-b)} date 17/1/2008-21:02:35 - * ;FORMAT={ / absolute / / } - * FMAT,2 - * INCH,TZ - */ void EXCELLON_WRITER::WriteEXCELLONHeader() { fputs( "M48\n", m_file ); // The beginning of a header @@ -351,7 +344,8 @@ void EXCELLON_WRITER::WriteEXCELLONHeader() if( !m_minimalHeader ) { // The next 2 lines in EXCELLON files are comments: - wxString msg = wxGetApp().GetTitle() + wxT( " " ) + GetBuildVersion(); + wxString msg = Pgm().App().GetAppName() + wxT( " " ) + GetBuildVersion(); + fprintf( m_file, ";DRILL file {%s} date %s\n", TO_UTF8( msg ), TO_UTF8( DateAndTime() ) ); msg = wxT( ";FORMAT={" ); @@ -361,13 +355,14 @@ void EXCELLON_WRITER::WriteEXCELLONHeader() msg << m_precision.GetPrecisionString(); else msg << wxT( "-:-" ); // in decimal format the precision is irrelevant + msg << wxT( "/ absolute / " ); msg << ( m_unitsDecimal ? wxT( "metric" ) : wxT( "inch" ) ); /* Adding numbers notation format. * this is same as m_Choice_Zeros_Format strings, but NOT translated - * because some EXCELLON parsers do not like non ascii values - * so we use ONLY english (ascii) strings. + * because some EXCELLON parsers do not like non ASCII values + * so we use ONLY English (ASCII) strings. * if new options are added in m_Choice_Zeros_Format, they must also * be added here */ @@ -432,18 +427,6 @@ static bool CmpHoleDiameterValue( const HOLE_INFO& a, const HOLE_INFO& b ) } -/* - * Create the list of holes and tools for a given board - * The list is sorted by increasing drill values - * Only holes from aFirstLayer to aLastLayer copper layers are listed (for vias, because pad holes are always through holes) - * param aFirstLayer = first layer to consider. if < 0 aFirstLayer is ignored (used to creates report file) - * param aLastLayer = last layer to consider. if < 0 aLastLayer is ignored - * param aExcludeThroughHoles : if true, exclude through holes ( pads and vias through ) - * param aGenerateNPTH_list : - * true to create NPTH only list (with no plated holes) - * false to created plated holes list (with no NPTH ) - * param aMergePTHNPTH : if true, merge PTH and NPTH holes into one file by treating all holes as PTH - */ void EXCELLON_WRITER::BuildHolesList( int aFirstLayer, int aLastLayer, bool aExcludeThroughHoles, @@ -467,8 +450,7 @@ void EXCELLON_WRITER::BuildHolesList( int aFirstLayer, return; } - /* build hole list for vias - */ + // build hole list for vias if( ! aGenerateNPTH_list ) // vias are always plated ! { for( TRACK* track = m_pcb->m_Track; track; track = track->Next() ) @@ -489,9 +471,9 @@ void EXCELLON_WRITER::BuildHolesList( int aFirstLayer, new_hole.m_Hole_Shape = 0; // hole shape: round new_hole.m_Hole_Pos = via->GetStart(); - via->ReturnLayerPair( &new_hole.m_Hole_Top_Layer, &new_hole.m_Hole_Bottom_Layer ); + via->LayerPair( &new_hole.m_Hole_Top_Layer, &new_hole.m_Hole_Bottom_Layer ); - // ReturnLayerPair return params with m_Hole_Bottom_Layer < m_Hole_Top_Layer + // LayerPair return params with m_Hole_Bottom_Layer < m_Hole_Top_Layer if( (new_hole.m_Hole_Bottom_Layer > aFirstLayer) && (aFirstLayer >= 0) ) continue; @@ -526,15 +508,15 @@ void EXCELLON_WRITER::BuildHolesList( int aFirstLayer, new_hole.m_Hole_NotPlated = (pad->GetAttribute() == PAD_HOLE_NOT_PLATED); new_hole.m_Tool_Reference = -1; // Flag is: Not initialized new_hole.m_Hole_Orient = pad->GetOrientation(); - new_hole.m_Hole_Shape = 0; // hole shape: round - new_hole.m_Hole_Diameter = std::min( pad->GetDrillSize().x, pad->GetDrillSize().y ); + new_hole.m_Hole_Shape = 0; // hole shape: round + new_hole.m_Hole_Diameter = std::min( pad->GetDrillSize().x, pad->GetDrillSize().y ); new_hole.m_Hole_Size.x = new_hole.m_Hole_Size.y = new_hole.m_Hole_Diameter; if( pad->GetDrillShape() != PAD_DRILL_CIRCLE ) new_hole.m_Hole_Shape = 1; // oval flag set - new_hole.m_Hole_Size = pad->GetDrillSize(); - new_hole.m_Hole_Pos = pad->GetPosition(); // hole position + new_hole.m_Hole_Size = pad->GetDrillSize(); + new_hole.m_Hole_Pos = pad->GetPosition(); // hole position new_hole.m_Hole_Bottom_Layer = LAYER_N_BACK; new_hole.m_Hole_Top_Layer = LAYER_N_FRONT;// pad holes are through holes m_holeListBuffer.push_back( new_hole ); @@ -546,7 +528,7 @@ void EXCELLON_WRITER::BuildHolesList( int aFirstLayer, sort( m_holeListBuffer.begin(), m_holeListBuffer.end(), CmpHoleDiameterValue ); // build the tool list - int LastHole = -1; /* Set to not initialised (this is a value not used + int LastHole = -1; /* Set to not initialized (this is a value not used * for m_holeListBuffer[ii].m_Hole_Diameter) */ DRILL_TOOL new_tool( 0 ); unsigned jj; @@ -563,7 +545,7 @@ void EXCELLON_WRITER::BuildHolesList( int aFirstLayer, jj = m_toolListBuffer.size(); if( jj == 0 ) - continue; // Should not occurs + continue; // Should not occurs m_holeListBuffer[ii].m_Tool_Reference = jj; // Tool value Initialized (value >= 1) diff --git a/pcbnew/exporters/gendrill_Excellon_writer.h b/pcbnew/exporters/gendrill_Excellon_writer.h index e62501e80a..d198187711 100644 --- a/pcbnew/exporters/gendrill_Excellon_writer.h +++ b/pcbnew/exporters/gendrill_Excellon_writer.h @@ -60,7 +60,7 @@ public: * So we must generate a drill file for each layer pair (adjacent layers) * Not plated holes are always through holes, and must be output on a specific drill file * because they are drilled after the Pcb process is finished. -*/ + */ class HOLE_INFO { public: @@ -74,6 +74,7 @@ public: LAYER_NUM m_Hole_Top_Layer; // hole ending layer (usually front layer): // m_Hole_First_Layer < m_Hole_Last_Layer bool m_Hole_NotPlated; // hole not plated. Must be in a specific drill file + public: HOLE_INFO() { @@ -88,7 +89,7 @@ class DRILL_PRECISION { public: int m_lhs; // Left digit number (integer value of coordinates) - int m_rhs; // Right digit number (deciam value of coordinates) + int m_rhs; // Right digit number (decimal value of coordinates) public: DRILL_PRECISION( int l = 2, int r = 4 ) { @@ -120,26 +121,28 @@ public: SUPPRESS_TRAILING, KEEP_ZEROS }; - wxPoint m_Offset; // offset coordinates - bool m_ShortHeader; // true to generate the smallest header (strip comments) + + wxPoint m_Offset; // offset coordinates + bool m_ShortHeader; // true to generate the smallest header (strip comments) private: FILE* m_file; // The output file BOARD* m_pcb; - bool m_minimalHeader; // True to use minimal haeder + bool m_minimalHeader; // True to use minimal header // in excellon file (strip comments) bool m_unitsDecimal; // true = decimal, false = inches zeros_fmt m_zeroFormat; // the zero format option for output file - DRILL_PRECISION m_precision; // The current coordinate precision (not used in decimat format) + DRILL_PRECISION m_precision; // The current coordinate precision (not used in decimal format) double m_conversionUnits; // scaling factor to convert the board unites to Excellon units // (i.e inches or mm) bool m_mirror; - wxPoint m_offset; // Drill offset ooordinates + wxPoint m_offset; // Drill offset coordinates bool m_mergePTHNPTH; std::vector m_holeListBuffer; // Buffer containing holes std::vector m_toolListBuffer; // Buffer containing tools -public: EXCELLON_WRITER( BOARD* aPcb, wxPoint aOffset ) +public: + EXCELLON_WRITER( BOARD* aPcb, wxPoint aOffset ) { m_file = NULL; m_pcb = aPcb; @@ -158,7 +161,7 @@ public: EXCELLON_WRITER( BOARD* aPcb, wxPoint aOffset ) /** * Return the plot offset (usually the position - * of the auxiliaty axis + * of the auxiliary axis */ const wxPoint GetOffset() { return m_offset; } @@ -201,17 +204,16 @@ public: EXCELLON_WRITER( BOARD* aPcb, wxPoint aOffset ) * false to created plated holes list (with no NPTH ) */ void BuildHolesList( int aFirstLayer, int aLastLayer, - bool aExcludeThroughHoles, - bool aGenerateNPTH_list, - bool aMergePTHNPTH ); + bool aExcludeThroughHoles, + bool aGenerateNPTH_list, + bool aMergePTHNPTH ); int GetHolesCount() const { return m_holeListBuffer.size(); } /** * Function CreateDrillFile * Creates an Excellon drill file - * @param aFile = an opened file to write to - * will be closed by CreateDrillFile + * @param aFile = an opened file to write to will be closed by CreateDrillFile * @return hole count */ int CreateDrillFile( FILE * aFile ); @@ -222,6 +224,47 @@ public: EXCELLON_WRITER( BOARD* aPcb, wxPoint aOffset ) * for through holes, oblong holes, and for buried vias, * drill values and drill count per layer pair * there is only one report for all drill files even when buried or blinds vias exist + * + * Here is a sample created by this function: + * Drill report for F:/tmp/interf_u/interf_u.brd + * Created on 04/10/2012 20:48:38 + * Selected Drill Unit: Imperial (inches) + * + * Drill report for plated through holes : + * T1 0,025" 0,64mm (88 holes) + * T2 0,031" 0,79mm (120 holes) + * T3 0,032" 0,81mm (151 holes) (with 1 slot) + * T4 0,040" 1,02mm (43 holes) + * T5 0,079" 2,00mm (1 hole) (with 1 slot) + * T6 0,120" 3,05mm (1 hole) (with 1 slot) + * + * Total plated holes count 404 + * + * + * Drill report for buried and blind vias : + * + * Drill report for holes from layer Soudure to layer Interne1 : + * + * Total plated holes count 0 + * + * + * Drill report for holes from layer Interne1 to layer Interne2 : + * T1 0,025" 0,64mm (3 holes) + * + * Total plated holes count 3 + * + * + * Drill report for holes from layer Interne2 to layer Composant : + * T1 0,025" 0,64mm (1 hole) + * + * Total plated holes count 1 + * + * + * Drill report for unplated through holes : + * T1 0,120" 3,05mm (1 hole) (with 1 slot) + * + * Total unplated holes count 1 + * * @param aFullFileName : the name of the file to create * m_unitsDecimal = false tu use inches, true to use mm in report file * @@ -233,16 +276,29 @@ public: EXCELLON_WRITER( BOARD* aPcb, wxPoint aOffset ) * Function GenDrillMapFile * Plot a map of drill marks for holes. * @param aFullFileNameWithoutExt : the full filename of the file to create, - * without extension (will be added accordint ti the format) - * @param aSheet : the paper sheet touse for plot + * without extension (will be added according to the format) + * @param aSheet : the paper sheet to use for plot * @param aFormat : one of the supported plot formats (see enum PlotFormat ) */ bool GenDrillMapFile( const wxString& aFullFileNameWithoutExt, const PAGE_INFO& aSheet, PlotFormat aFormat ); private: + /* Print the DRILL file header. The full header is: + * M48 + * ;DRILL file {PCBNEW (2007-11-29-b)} date 17/1/2008-21:02:35 + * ;FORMAT={ / absolute / / } + * FMAT,2 + * INCH,TZ + */ void WriteEXCELLONHeader(); + void WriteEXCELLONEndOfFile(); + + /* Created a line like: + * X48000Y19500 + * According to the selected format + */ void WriteCoordinates( char* aLine, double aCoordX, double aCoordY ); /** Helper function. @@ -257,6 +313,4 @@ private: }; - - #endif // #ifndef _GENDRILL_EXCELLON_WRITER_ diff --git a/pcbnew/exporters/idf.cpp b/pcbnew/exporters/idf.cpp index 21e4af1c9d..69d2487c65 100644 --- a/pcbnew/exporters/idf.cpp +++ b/pcbnew/exporters/idf.cpp @@ -39,7 +39,8 @@ #include #include #include -#include +#include +#include #include #include #include @@ -568,8 +569,8 @@ bool IDF_BOARD::WriteDrills( void ) fprintf( layoutFile, ".DRILLED_HOLES\n" ); - std::list::iterator ds = drills.begin(); - std::list::iterator de = drills.end(); + std::list::iterator ds = drills.begin(); + std::list::iterator de = drills.end(); while( ds != de ) { diff --git a/pcbnew/exporters/vrml_board.cpp b/pcbnew/exporters/vrml_board.cpp index 4ef750278b..e8b13de36b 100644 --- a/pcbnew/exporters/vrml_board.cpp +++ b/pcbnew/exporters/vrml_board.cpp @@ -712,7 +712,7 @@ bool VRML_LAYER::Tesselate( VRML_LAYER* holes ) std::ostringstream ostr; ostr << "Tesselate():FAILED: " << holes->GetError(); error = ostr.str(); - return NULL; + return false; } if( Fault ) diff --git a/pcbnew/exporters/vrml_board.h b/pcbnew/exporters/vrml_board.h index aa7e935abe..9cb4a26f4f 100644 --- a/pcbnew/exporters/vrml_board.h +++ b/pcbnew/exporters/vrml_board.h @@ -58,7 +58,7 @@ #define M_PI4 ( M_PI / 4.0 ) #endif -struct GLUtesselator; +class GLUtesselator; struct VERTEX_3D { diff --git a/pcbnew/files.cpp b/pcbnew/files.cpp index 77dfeea698..d95a13df2c 100644 --- a/pcbnew/files.cpp +++ b/pcbnew/files.cpp @@ -39,7 +39,7 @@ #include <3d_viewer.h> #include #include -#include +#include #include #include @@ -58,20 +58,29 @@ #define USE_INSTRUMENTATION false -static const wxString backupFileExtensionSuffix( wxT( "-bak" ) ); -static const wxString autosaveFilePrefix( wxT( "_autosave-" ) ); +static const wxChar backupSuffix[] = wxT( "-bak" ); +static const wxChar autosavePrefix[]= wxT( "_autosave-" ); + void PCB_EDIT_FRAME::OnFileHistory( wxCommandEvent& event ) { - wxString fn; + wxString fn = GetFileFromHistory( event.GetId(), _( "Printed circuit board" ) ); - fn = GetFileFromHistory( event.GetId(), _( "Printed circuit board" ) ); - - if( fn != wxEmptyString ) + if( !!fn ) { + int open_ctl = 0; + m_canvas->EndMouseCapture( ID_NO_TOOL_SELECTED, m_canvas->GetDefaultCursor() ); ::wxSetWorkingDirectory( ::wxPathOnly( fn ) ); - LoadOnePcbFile( fn ); + + // LoadOnePcbFile( fn, bool aAppend = false, bool aForceFileDialog = false ); + if( !wxFileName::IsFileReadable( fn ) ) + { + if( !AskBoardFileName( this, &open_ctl, &fn ) ) + return; + } + + OpenProjectFiles( std::vector( 1, fn ), open_ctl ); } } @@ -91,7 +100,17 @@ void PCB_EDIT_FRAME::Files_io( wxCommandEvent& event ) switch( id ) { case ID_LOAD_FILE: - LoadOnePcbFile( GetBoard()->GetFileName(), false, true ); + { + // LoadOnePcbFile( GetBoard()->GetFileName(), append=false, aForceFileDialog=true ); + + int open_ctl; + wxString fileName = GetBoard()->GetFileName(); + + if( !AskBoardFileName( this, &open_ctl, &fileName ) ) + return; + + OpenProjectFiles( std::vector( 1, fileName ), open_ctl ); + } break; case ID_MENU_READ_BOARD_BACKUP_FILE: @@ -99,33 +118,36 @@ void PCB_EDIT_FRAME::Files_io( wxCommandEvent& event ) { wxFileName currfn = GetBoard()->GetFileName(); wxFileName fn = currfn; + if( id == ID_MENU_RECOVER_BOARD_AUTOSAVE ) { - wxString rec_name = autosaveFilePrefix + fn.GetName(); + wxString rec_name = wxString( autosavePrefix ) + fn.GetName(); fn.SetName( rec_name ); } else { - wxString backup_ext = fn.GetExt()+ backupFileExtensionSuffix; + wxString backup_ext = fn.GetExt()+ backupSuffix; fn.SetExt( backup_ext ); } if( !fn.FileExists() ) { - msg.Printf( _( "Recovery file <%s> not found." ), + msg.Printf( _( "Recovery file '%s' not found." ), GetChars( fn.GetFullPath() ) ); DisplayInfoMessage( this, msg ); break; } - msg.Printf( _( "OK to load recovery or backup file <%s>" ), + 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(), false ); + + // LoadOnePcbFile( fn.GetFullPath(), aAppend=false, aForceFileDialog=false ); + OpenProjectFiles( std::vector( 1, fn.GetFullPath() ) ); // Re-set the name since name or extension was changed GetBoard()->SetFileName( currfn.GetFullPath() ); @@ -134,34 +156,34 @@ void PCB_EDIT_FRAME::Files_io( wxCommandEvent& event ) break; case ID_APPEND_FILE: - LoadOnePcbFile( wxEmptyString, true ); + { + // LoadOnePcbFile( wxEmptyString, aAppend = true, aForceFileDialog=false ); + int open_ctl; + wxString fileName; + + if( !AskBoardFileName( this, &open_ctl, &fileName ) ) + break; + + OpenProjectFiles( std::vector( 1, fileName ), open_ctl | KICTL_OPEN_APPEND ); + } break; case ID_NEW_BOARD: { Clear_Pcb( true ); - // Create a new empty footprint library table for the new board. - delete m_footprintLibTable; - m_footprintLibTable = new FP_LIB_TABLE( m_globalFootprintTable ); - - FOOTPRINT_EDIT_FRAME* editFrame = FOOTPRINT_EDIT_FRAME::GetActiveFootprintEditor(); - - if( editFrame ) - editFrame->SetFootprintLibTable( m_footprintLibTable ); - - FOOTPRINT_VIEWER_FRAME* viewFrame = FOOTPRINT_VIEWER_FRAME::GetActiveFootprintViewer(); - - if( viewFrame ) - viewFrame->SetFootprintLibTable( m_footprintLibTable ); - - wxFileName emptyFileName; - FP_LIB_TABLE::SetProjectPathEnvVariable( emptyFileName ); + // Clear footprint library table for the new board. + FootprintLibs()->Clear(); wxFileName fn; + fn.AssignCwd(); fn.SetName( wxT( "noname" ) ); + + Prj().SetProjectFullName( fn.GetFullPath() ); + fn.SetExt( PcbFileExtension ); + GetBoard()->SetFileName( fn.GetFullPath() ); UpdateTitle(); ReCreateLayerBox(); @@ -182,33 +204,8 @@ void PCB_EDIT_FRAME::Files_io( wxCommandEvent& event ) } -bool PCB_EDIT_FRAME::LoadOnePcbFile( const wxString& aFileName, bool aAppend, - bool aForceFileDialog ) +bool AskBoardFileName( wxWindow* aParent, int* aCtl, wxString* aFileName ) { - if( GetScreen()->IsModify() && !aAppend ) - { - 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(), true ); - } - - if( aAppend ) - { - GetBoard()->SetFileName( wxEmptyString ); - OnModify(); - GetBoard()->m_Status_Pcb = 0; - } - - wxFileName fileName = aFileName; - - IO_MGR::PCB_FILE_T pluginType = IO_MGR::LEGACY; - // This is a subset of all PLUGINs which are trusted to be able to // load a BOARD. Order is subject to change as KICAD plugin matures. // User may occasionally use the wrong plugin to load a *.brd file, @@ -226,56 +223,114 @@ bool PCB_EDIT_FRAME::LoadOnePcbFile( const wxString& aFileName, bool aAppend, { PCadPcbFileWildcard, IO_MGR::PCAD }, }; - if( !fileName.IsOk() || !fileName.FileExists() || aForceFileDialog ) + wxFileName fileName( *aFileName ); + wxString fileFilters; + + for( unsigned i=0; i 0 ) + fileFilters += wxChar( '|' ); - for( unsigned i=0; i 0 ) - fileFilters += wxChar( '|' ); + fileFilters += wxGetTranslation( loaders[i].filter ); + } - fileFilters += wxGetTranslation( loaders[i].filter ); - } + wxString path; + wxString name; - if( aForceFileDialog && fileName.FileExists() ) - { - path = fileName.GetPath(); - name = fileName.GetFullName(); - } + if( fileName.FileExists() ) + { + path = fileName.GetPath(); + name = fileName.GetFullName(); + } + else + { + path = wxGetCwd(); + // leave name empty + } - wxFileDialog dlg( this, _( "Open Board File" ), path, name, fileFilters, - wxFD_OPEN | wxFD_FILE_MUST_EXIST ); - - if( dlg.ShowModal() == wxID_CANCEL ) - return false; - - fileName = dlg.GetPath(); + wxFileDialog dlg( aParent, _( "Open Board File" ), path, name, fileFilters, + wxFD_OPEN | wxFD_FILE_MUST_EXIST ); + if( dlg.ShowModal() != wxID_CANCEL ) + { int chosenFilter = dlg.GetFilterIndex(); - pluginType = loaders[chosenFilter].pluginType; + + // if Eagle, tell OpenProjectFiles() to use Eagle plugin. It's the only special + // case because of the duplicate use of the *.brd file extension. Other cases + // are clear because of unique file extensions. + *aCtl = chosenFilter == 2 ? KICTL_EAGLE_BRD : 0; + *aFileName = dlg.GetPath(); + + return true; } - else // if a filename is given, force IO_MGR::KICAD if the file ext is kicad_pcb - // for instance if the filename comes from file history - // or it is a backup file with ext = kicad_pcb-bak + else + return false; +} + + +bool PCB_EDIT_FRAME::OpenProjectFiles( const std::vector& aFileSet, int aCtl ) +{ + wxASSERT( aFileSet.size() == 1 ); + + bool doAppend = aCtl & KICTL_OPEN_APPEND; + wxFileName fileName( aFileSet[0] ); + + // Make filename absolute, to avoid issues when the filename is relative, + // for instance when stored in history list without path, and when building + // the config filename ( which should have a path ) + if( fileName.IsRelative() ) + fileName.MakeAbsolute(); + + if( GetScreen()->IsModify() && !doAppend ) { - wxString backup_ext = IO_MGR::GetFileExtension( IO_MGR::KICAD ) + - backupFileExtensionSuffix; - if( fileName.GetExt() == IO_MGR::GetFileExtension( IO_MGR::KICAD ) || - fileName.GetExt() == backup_ext ) - pluginType = IO_MGR::KICAD; + 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(), true ); } + if( doAppend ) + { + GetBoard()->SetFileName( wxEmptyString ); + OnModify(); + GetBoard()->m_Status_Pcb = 0; + } + + // The KIWAY_PLAYER::OpenProjectFiles() API knows nothing about plugins, so + // determine how to load the BOARD here, with minor assistance from KICTL_EAGLE_BRD + // bit flag. + + IO_MGR::PCB_FILE_T pluginType; + + if( fileName.GetExt() == IO_MGR::GetFileExtension( IO_MGR::LEGACY ) ) + { + // both legacy and eagle share a common file extension. + pluginType = ( aCtl & KICTL_EAGLE_BRD ) ? IO_MGR::EAGLE : IO_MGR::LEGACY; + } + else if( fileName.GetExt() == IO_MGR::GetFileExtension( IO_MGR::LEGACY ) + backupSuffix ) + { + pluginType = IO_MGR::LEGACY; + } + else if( fileName.GetExt() == IO_MGR::GetFileExtension( IO_MGR::IO_MGR::PCAD ) ) + { + pluginType = IO_MGR::PCAD; + } + else + pluginType = IO_MGR::KICAD; + PLUGIN::RELEASER pi( IO_MGR::PluginFind( pluginType ) ); - if( !fileName.HasExt() ) - fileName.SetExt( pi->GetFileExtension() ); - - if( !aAppend ) + if( !doAppend ) { - if( !wxGetApp().LockFile( fileName.GetFullPath() ) ) + if( !Pgm().LockFile( fileName.GetFullPath() ) ) { DisplayError( this, _( "This file is already open." ) ); return false; @@ -287,7 +342,7 @@ bool PCB_EDIT_FRAME::LoadOnePcbFile( const wxString& aFileName, bool aAppend, GetBoard()->SetFileName( fileName.GetFullPath() ); - if( !aAppend ) + if( !doAppend ) { // Update the option toolbar m_DisplayPcbTrackFill = DisplayOpt.DisplayPcbTrackFill; @@ -325,7 +380,7 @@ bool PCB_EDIT_FRAME::LoadOnePcbFile( const wxString& aFileName, bool aAppend, #endif // load or append either: - loadedBoard = pi->Load( GetBoard()->GetFileName(), aAppend ? GetBoard() : NULL, &props ); + loadedBoard = pi->Load( GetBoard()->GetFileName(), doAppend ? GetBoard() : NULL, &props ); #if USE_INSTRUMENTATION unsigned stopTime = GetRunningMicroSecs(); @@ -336,7 +391,7 @@ bool PCB_EDIT_FRAME::LoadOnePcbFile( const wxString& aFileName, bool aAppend, // set its own name GetBoard()->SetFileName( fileName.GetFullPath() ); - if( !aAppend ) + if( !doAppend ) { if( pluginType == IO_MGR::LEGACY && loadedBoard->GetFileFormatVersionAtLoad() < LEGACY_BOARD_FILE_VERSION ) @@ -364,16 +419,19 @@ bool PCB_EDIT_FRAME::LoadOnePcbFile( const wxString& aFileName, bool aAppend, SetStatusText( wxEmptyString ); BestZoom(); + + // update the layer names in the listbox + ReCreateLayerBox( false ); } GetScreen()->ClrModify(); - // If append option: change the initial board name to -append.brd - if( aAppend ) + if( doAppend ) { + // change the initial board name to -append.brd wxString new_filename = GetBoard()->GetFileName().BeforeLast( '.' ); - if ( ! new_filename.EndsWith( wxT( "-append" ) ) ) + if( !new_filename.EndsWith( wxT( "-append" ) ) ) new_filename += wxT( "-append" ); new_filename += wxT( "." ) + PcbFileExtension; @@ -448,8 +506,11 @@ bool PCB_EDIT_FRAME::LoadOnePcbFile( const wxString& aFileName, bool aAppend, Zoom_Automatique( false ); // Compile ratsnest and displays net info - wxBusyCursor dummy; // Displays an Hourglass while building connectivity - Compile_Ratsnest( NULL, true ); + { + wxBusyCursor dummy; // Displays an Hourglass while building connectivity + Compile_Ratsnest( NULL, true ); + } + SetMsgPanel( GetBoard() ); // Refresh the 3D view, if any @@ -457,16 +518,24 @@ bool PCB_EDIT_FRAME::LoadOnePcbFile( const wxString& aFileName, bool aAppend, m_Draw3DFrame->NewDisplay(); #if 0 && defined(DEBUG) - // note this freezes up Pcbnew when run under the KiCad project - // manager. runs fine from command prompt. This is because the KiCad - // project manager redirects stdout of the child Pcbnew process to itself, - // but never reads from that pipe, and that in turn eventually blocks - // the Pcbnew program when the pipe it is writing to gets full. - // 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; } @@ -528,33 +597,33 @@ bool PCB_EDIT_FRAME::SavePcbFile( const wxString& aFileName, bool aCreateBackupF // when multiple wildcards are defined, we have to check it ourselves to prevent an // existing board file from silently being over written. if( pcbFileName.FileExists() - && !IsOK( this, wxString::Format( _( "The file <%s> already exists.\n\nDo you want " + && !IsOK( this, wxString::Format( _( "The file '%s' already exists.\n\nDo you want " "to overwrite it?" ), GetChars( pcbFileName.GetFullPath() ) )) ) return false; // Save the project specific footprint library table. - if( !m_footprintLibTable->IsEmpty( false ) ) + if( !FootprintLibs()->IsEmpty( false ) ) { - wxFileName fn = pcbFileName; - fn.ClearExt(); - fn.SetName( FP_LIB_TABLE::GetFileName() ); + wxString fp_lib_tbl = Prj().FootprintLibTblName(); - if( fn.FileExists() + if( wxFileName::FileExists( fp_lib_tbl ) && IsOK( this, _( "A footprint library table already exists in this path.\n\nDo " "you want to overwrite it?" ) ) ) { try { - m_footprintLibTable->Save( fn ); + FootprintLibs()->Save( fp_lib_tbl ); } - catch( IO_ERROR& ioe ) + catch( const IO_ERROR& ioe ) { - DisplayError( this, - wxString::Format( _( "An error occurred attempting to save the " - "footprint library table <%s>\n\n%s" ), - GetChars( fn.GetFullPath() ), - GetChars( ioe.errorText ) ) ); + wxString msg = wxString::Format( _( + "An error occurred attempting to save the " + "footprint library table '%s'\n\n%s" ), + GetChars( fp_lib_tbl ), + GetChars( ioe.errorText ) + ); + DisplayError( this, msg ); } } } @@ -579,7 +648,7 @@ bool PCB_EDIT_FRAME::SavePcbFile( const wxString& aFileName, bool aCreateBackupF { // Get the backup file name backupFileName = pcbFileName; - backupFileName.SetExt( pcbFileName.GetExt() + backupFileExtensionSuffix ); + backupFileName.SetExt( pcbFileName.GetExt() + backupSuffix ); // If an old backup file exists, delete it. If an old board file exists, rename // it to the backup file name. @@ -656,7 +725,8 @@ bool PCB_EDIT_FRAME::SavePcbFile( const wxString& aFileName, bool aCreateBackupF { // Delete auto save file on successful save. wxFileName autoSaveFileName = pcbFileName; - autoSaveFileName.SetName( autosaveFilePrefix + pcbFileName.GetName() ); + + autoSaveFileName.SetName( wxString( autosavePrefix ) + pcbFileName.GetName() ); if( autoSaveFileName.FileExists() ) wxRemoveFile( autoSaveFileName.GetFullPath() ); @@ -687,7 +757,7 @@ bool PCB_EDIT_FRAME::doAutoSave() // Auto save file name is the normal file name prepended with // autosaveFilePrefix string. - fn.SetName( autosaveFilePrefix + fn.GetName() ); + fn.SetName( wxString( autosavePrefix ) + fn.GetName() ); wxLogTrace( traceAutoSave, wxT( "Creating auto save file <" + fn.GetFullPath() ) + wxT( ">" ) ); diff --git a/pcbnew/footprint_wizard_frame.cpp b/pcbnew/footprint_wizard_frame.cpp index 23ee998473..a5d5a5a325 100644 --- a/pcbnew/footprint_wizard_frame.cpp +++ b/pcbnew/footprint_wizard_frame.cpp @@ -29,7 +29,7 @@ */ #include -#include +#include #include #include #include <3d_viewer.h> @@ -119,9 +119,9 @@ static wxAcceleratorEntry accels[] = #define FOOTPRINT_WIZARD_FRAME_NAME wxT( "FootprintWizard" ) -FOOTPRINT_WIZARD_FRAME::FOOTPRINT_WIZARD_FRAME( FOOTPRINT_EDIT_FRAME* parent, - wxSemaphore* semaphore, long style ) : - PCB_BASE_FRAME( parent, FOOTPRINT_WIZARD_FRAME_TYPE, +FOOTPRINT_WIZARD_FRAME::FOOTPRINT_WIZARD_FRAME( KIWAY* aKiway, FOOTPRINT_EDIT_FRAME* aParent, + wxSemaphore* semaphore, long style ) : + PCB_BASE_FRAME( aKiway, aParent, FOOTPRINT_WIZARD_FRAME_TYPE, _( "Footprint Wizard" ), wxDefaultPosition, wxDefaultSize, style, FOOTPRINT_WIZARD_FRAME_NAME ) { @@ -150,7 +150,7 @@ FOOTPRINT_WIZARD_FRAME::FOOTPRINT_WIZARD_FRAME( FOOTPRINT_EDIT_FRAME* parent, SetScreen( new PCB_SCREEN( GetPageSizeIU() ) ); GetScreen()->m_Center = true; // Center coordinate origins on screen. - LoadSettings(); + LoadSettings( config() ); SetSize( m_FramePos.x, m_FramePos.y, m_FrameSize.x, m_FrameSize.y ); GetScreen()->SetGrid( ID_POPUP_GRID_LEVEL_1000 + m_LastGridSizeId ); @@ -429,18 +429,14 @@ void FOOTPRINT_WIZARD_FRAME::ClickOnPageList( wxCommandEvent& event ) #define PARAMLIST_WIDTH_KEY wxT( "Paramlist_width" ) -void FOOTPRINT_WIZARD_FRAME::LoadSettings() +void FOOTPRINT_WIZARD_FRAME::LoadSettings( wxConfigBase* aCfg ) { - wxConfig* cfg; + EDA_DRAW_FRAME::LoadSettings( aCfg ); - EDA_DRAW_FRAME::LoadSettings(); + wxConfigPathChanger cpc( aCfg, m_configPath ); - wxConfigPathChanger cpc( wxGetApp().GetSettings(), m_configPath ); - - cfg = wxGetApp().GetSettings(); - - cfg->Read( PARTLIST_WIDTH_KEY, &m_pageListWidth, 100 ); - cfg->Read( PARAMLIST_WIDTH_KEY, &m_parameterGridWidth, 200 ); + aCfg->Read( PARTLIST_WIDTH_KEY, &m_pageListWidth, 100 ); + aCfg->Read( PARAMLIST_WIDTH_KEY, &m_parameterGridWidth, 200 ); // Set parameters to a reasonable value. if( m_pageListWidth > m_FrameSize.x / 3 ) @@ -451,15 +447,13 @@ void FOOTPRINT_WIZARD_FRAME::LoadSettings() } -void FOOTPRINT_WIZARD_FRAME::SaveSettings() +void FOOTPRINT_WIZARD_FRAME::SaveSettings( wxConfigBase* aCfg ) { - wxConfig* cfg = wxGetApp().GetSettings();; + EDA_DRAW_FRAME::SaveSettings( aCfg ); - EDA_DRAW_FRAME::SaveSettings(); - - wxConfigPathChanger cpc( cfg, m_configPath ); - cfg->Write( PARTLIST_WIDTH_KEY, m_pageList->GetSize().x ); - cfg->Write( PARAMLIST_WIDTH_KEY, m_parameterGrid->GetSize().x ); + wxConfigPathChanger cpc( aCfg, m_configPath ); + aCfg->Write( PARTLIST_WIDTH_KEY, m_pageList->GetSize().x ); + aCfg->Write( PARAMLIST_WIDTH_KEY, m_parameterGrid->GetSize().x ); } @@ -591,7 +585,7 @@ void FOOTPRINT_WIZARD_FRAME::Show3D_Frame( wxCommandEvent& event ) return; } - m_Draw3DFrame = new EDA_3D_FRAME( this, wxEmptyString ); + m_Draw3DFrame = new EDA_3D_FRAME( &Kiway(), this, wxEmptyString ); Update3D_Frame( false ); m_Draw3DFrame->Show( true ); } diff --git a/pcbnew/footprint_wizard_frame.h b/pcbnew/footprint_wizard_frame.h index da1b6c86b0..c36ecc70c3 100644 --- a/pcbnew/footprint_wizard_frame.h +++ b/pcbnew/footprint_wizard_frame.h @@ -63,9 +63,9 @@ protected: wxString m_wizardStatus; // < current wizard status public: - FOOTPRINT_WIZARD_FRAME( FOOTPRINT_EDIT_FRAME* parent, - wxSemaphore* semaphore = NULL, - long style = KICAD_DEFAULT_DRAWFRAME_STYLE ); + FOOTPRINT_WIZARD_FRAME( KIWAY* aKiway, + FOOTPRINT_EDIT_FRAME* parent, wxSemaphore* semaphore = NULL, + long style = KICAD_DEFAULT_DRAWFRAME_STYLE ); ~FOOTPRINT_WIZARD_FRAME(); @@ -140,23 +140,8 @@ private: void GeneralControl( wxDC* aDC, const wxPoint& aPosition, int aHotKey = 0 ); - /** - * Function LoadSettings - * loads the library viewer frame specific configuration settings. - * - * Don't forget to call this base method from any derived classes or the - * settings will not get loaded. - */ - void LoadSettings(); - - /** - * Function SaveSettings - * save library viewer frame specific configuration settings. - * - * Don't forget to call this base method from any derived classes or the - * settings will not get saved. - */ - void SaveSettings(); + void LoadSettings( wxConfigBase* aCfg ); // override virtual + void SaveSettings( wxConfigBase* aCfg ); // override virtual /** diff --git a/pcbnew/import_dxf/dialog_dxf_import.cpp b/pcbnew/import_dxf/dialog_dxf_import.cpp index d3fe5e4d97..aaeeba403a 100644 --- a/pcbnew/import_dxf/dialog_dxf_import.cpp +++ b/pcbnew/import_dxf/dialog_dxf_import.cpp @@ -27,7 +27,8 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ -#include +//#include +#include #include #include #include @@ -44,7 +45,7 @@ class DIALOG_DXF_IMPORT : public DIALOG_DXF_IMPORT_BASE { private: PCB_EDIT_FRAME * m_parent; - wxConfig* m_config; // Current config + wxConfigBase* m_config; // Current config static wxString m_dxfFilename; static int m_offsetSelection; @@ -59,7 +60,7 @@ private: // Virtual event handlers void OnCancelClick( wxCommandEvent& event ) { event.Skip(); } void OnOKClick( wxCommandEvent& event ); - void OnBrowseDxfFiles( wxCommandEvent& event ); + void OnBrowseDxfFiles( wxCommandEvent& event ); }; // Static members of DIALOG_DXF_IMPORT, to remember @@ -73,7 +74,7 @@ DIALOG_DXF_IMPORT::DIALOG_DXF_IMPORT( PCB_EDIT_FRAME* aParent ) : DIALOG_DXF_IMPORT_BASE( aParent ) { m_parent = aParent; - m_config = wxGetApp().GetSettings(); + m_config = Kiface().KifaceSettings(); if( m_config ) { diff --git a/pcbnew/initpcb.cpp b/pcbnew/initpcb.cpp index 0cb84ac8fb..ee146c2177 100644 --- a/pcbnew/initpcb.cpp +++ b/pcbnew/initpcb.cpp @@ -16,11 +16,6 @@ #include -/** - * Function Clear_Pcb - * delete all and reinitialize the current board - * @param aQuery = true to prompt user for confirmation, false to initialize silently - */ bool PCB_EDIT_FRAME::Clear_Pcb( bool aQuery ) { if( GetBoard() == NULL ) @@ -40,11 +35,11 @@ bool PCB_EDIT_FRAME::Clear_Pcb( bool aQuery ) // Clear undo and redo lists because we want a full deletion GetScreen()->ClearUndoRedoList(); - /* Items visibility flags will be set becuse a new board will be created. - * Grid and ratsnest can be left to their previous state - */ + // Items visibility flags will be set becuse a new board will be created. + // Grid and ratsnest can be left to their previous state bool showGrid = IsElementVisible( GRID_VISIBLE ); bool showRats = IsElementVisible( RATSNEST_VISIBLE ); + // delete the old BOARD and create a new BOARD so that the default // layer names are put into the BOARD. SetBoard( new BOARD() ); @@ -84,7 +79,6 @@ bool PCB_EDIT_FRAME::Clear_Pcb( bool aQuery ) } - bool FOOTPRINT_EDIT_FRAME::Clear_Pcb( bool aQuery ) { if( GetBoard() == NULL ) diff --git a/pcbnew/kicad_plugin.cpp b/pcbnew/kicad_plugin.cpp index 90bd3d8772..07b80aef42 100644 --- a/pcbnew/kicad_plugin.cpp +++ b/pcbnew/kicad_plugin.cpp @@ -1343,14 +1343,14 @@ void PCB_IO::format( TRACK* aTrack, int aNestLevel ) const LAYER_NUM layer1, layer2; SEGVIA* via = (SEGVIA*) aTrack; - BOARD* board = (BOARD*) via->GetParent(); + BOARD* board = (BOARD*) via->GetParent(); wxCHECK_RET( board != 0, wxT( "Via " ) + via->GetSelectMenuText() + wxT( " has no parent." ) ); m_out->Print( aNestLevel, "(via" ); - via->ReturnLayerPair( &layer1, &layer2 ); + via->LayerPair( &layer1, &layer2 ); switch( aTrack->GetShape() ) { diff --git a/pcbnew/librairi.cpp b/pcbnew/librairi.cpp index 7fd65174f3..1b65c89b97 100644 --- a/pcbnew/librairi.cpp +++ b/pcbnew/librairi.cpp @@ -29,7 +29,8 @@ #include #include -#include +#include +#include #include #include #include @@ -96,8 +97,9 @@ MODULE* FOOTPRINT_EDIT_FRAME::Import_Module() // Some day it might be useful save the last library type selected along with the path. static int lastFilterIndex = 0; - wxString lastOpenedPathForLoading; - wxConfig* config = wxGetApp().GetSettings(); + + wxString lastOpenedPathForLoading; + wxConfigBase* config = Kiface().KifaceSettings(); if( config ) config->Read( EXPORT_IMPORT_LASTPATH_KEY, &lastOpenedPathForLoading ); @@ -279,10 +281,10 @@ MODULE* FOOTPRINT_EDIT_FRAME::Import_Module() void FOOTPRINT_EDIT_FRAME::Export_Module( MODULE* aModule ) { - wxFileName fn; - wxConfig* config = wxGetApp().GetSettings(); + wxFileName fn; + wxConfigBase* config = Kiface().KifaceSettings(); - if( aModule == NULL ) + if( !aModule ) return; fn.SetName( aModule->GetFPID().GetFootprintName() ); @@ -366,8 +368,8 @@ bool FOOTPRINT_EDIT_FRAME::SaveCurrentModule( const wxString* aLibPath ) wxString FOOTPRINT_EDIT_FRAME::CreateNewLibrary() { - wxFileName fn; - wxConfig* config = wxGetApp().GetSettings(); + wxFileName fn; + wxConfigBase* config = Kiface().KifaceSettings(); if( config ) { @@ -467,7 +469,7 @@ bool FOOTPRINT_EDIT_FRAME::DeleteModuleFromCurrentLibrary() { wxString nickname = getLibNickName(); - if( !m_footprintLibTable->IsFootprintLibWritable( nickname ) ) + if( !FootprintLibs()->IsFootprintLibWritable( nickname ) ) { wxString msg = wxString::Format( _( "Library '%s' is read only" ), @@ -479,7 +481,7 @@ bool FOOTPRINT_EDIT_FRAME::DeleteModuleFromCurrentLibrary() } wxString fpid_txt = PCB_BASE_FRAME::SelectFootprint( this, nickname, - wxEmptyString, wxEmptyString, m_footprintLibTable ); + wxEmptyString, wxEmptyString, FootprintLibs() ); if( !fpid_txt ) return false; @@ -495,7 +497,7 @@ bool FOOTPRINT_EDIT_FRAME::DeleteModuleFromCurrentLibrary() try { - m_footprintLibTable->FootprintDelete( nickname, fpname ); + FootprintLibs()->FootprintDelete( nickname, fpname ); } catch( IO_ERROR ioe ) { @@ -519,14 +521,17 @@ void PCB_EDIT_FRAME::ArchiveModulesOnBoard( bool aNewModulesOnly ) return; } - wxString last_nickname = wxGetApp().ReturnLastVisitedLibraryPath(); + PROJECT& prj = Prj(); + SEARCH_STACK& search = Kiface().KifaceSearch(); + + wxString last_nickname = prj.RPath(PROJECT::PCB_LIB).LastVisitedPath( search ); wxString nickname = SelectLibrary( last_nickname ); if( !nickname ) return; - wxGetApp().SaveLastVisitedLibraryPath( nickname ); + prj.RPath(PROJECT::PCB_LIB).SaveLastVisitedPath( nickname ); if( !aNewModulesOnly ) { @@ -543,19 +548,19 @@ void PCB_EDIT_FRAME::ArchiveModulesOnBoard( bool aNewModulesOnly ) // Delete old library if we're replacing it entirely. if( !aNewModulesOnly ) { - m_footprintLibTable->FootprintLibDelete( nickname ); - m_footprintLibTable->FootprintLibCreate( nickname ); + FootprintLibs()->FootprintLibDelete( nickname ); + FootprintLibs()->FootprintLibCreate( nickname ); for( MODULE* m = GetBoard()->m_Modules; m; m = m->Next() ) { - m_footprintLibTable->FootprintSave( nickname, m, true ); + FootprintLibs()->FootprintSave( nickname, m, true ); } } else { for( MODULE* m = GetBoard()->m_Modules; m; m = m->Next() ) { - m_footprintLibTable->FootprintSave( nickname, m, false ); + FootprintLibs()->FootprintSave( nickname, m, false ); // Check for request to stop backup (ESCAPE key actuated) if( m_canvas->GetAbortRequest() ) @@ -601,7 +606,7 @@ bool PCB_BASE_FRAME::Save_Module_In_Library( const wxString& aLibrary, { wxString msg = wxString::Format( _("Error:\none of invalid chars '%s' found\nin '%s'" ), - MODULE::ReturnStringLibNameInvalidChars( true ), + MODULE::StringLibNameInvalidChars( true ), GetChars( footprintName ) ); DisplayError( NULL, msg ); @@ -622,7 +627,7 @@ bool PCB_BASE_FRAME::Save_Module_In_Library( const wxString& aLibrary, try { - MODULE* m = m_footprintLibTable->FootprintLoad( aLibrary, footprintName ); + MODULE* m = FootprintLibs()->FootprintLoad( aLibrary, footprintName ); if( m ) { @@ -648,7 +653,7 @@ bool PCB_BASE_FRAME::Save_Module_In_Library( const wxString& aLibrary, // this always overwrites any existing footprint, but should yell on its // own if the library or footprint is not writable. - m_footprintLibTable->FootprintSave( aLibrary, aModule ); + FootprintLibs()->FootprintSave( aLibrary, aModule ); } catch( IO_ERROR ioe ) { @@ -733,15 +738,17 @@ wxString PCB_BASE_FRAME::SelectLibrary( const wxString& aNicknameExisting ) headers.Add( _( "Nickname" ) ); headers.Add( _( "Description" ) ); + FP_LIB_TABLE* fptbl = FootprintLibs(); + std::vector< wxArrayString > itemsToDisplay; - std::vector< wxString > nicknames = m_footprintLibTable->GetLogicalLibs(); + std::vector< wxString > nicknames = fptbl->GetLogicalLibs(); for( unsigned i = 0; i < nicknames.size(); i++ ) { wxArrayString item; item.Add( nicknames[i] ); - item.Add( m_footprintLibTable->GetDescription( nicknames[i] ) ); + item.Add( fptbl->GetDescription( nicknames[i] ) ); itemsToDisplay.push_back( item ); } diff --git a/pcbnew/loadcmp.cpp b/pcbnew/loadcmp.cpp index 059d1f66a4..990198953a 100644 --- a/pcbnew/loadcmp.cpp +++ b/pcbnew/loadcmp.cpp @@ -33,7 +33,7 @@ #include #include #include -#include +#include #include #include #include @@ -119,13 +119,12 @@ wxString PCB_BASE_FRAME::SelectFootprintFromLibBrowser() wxSemaphore semaphore( 0, 1 ); // Close the current Lib browser, if opened, and open a new one, in "modal" mode: - FOOTPRINT_VIEWER_FRAME * viewer = FOOTPRINT_VIEWER_FRAME::GetActiveFootprintViewer(); + FOOTPRINT_VIEWER_FRAME* viewer = FOOTPRINT_VIEWER_FRAME::GetActiveFootprintViewer( this ); if( viewer ) viewer->Destroy(); - viewer = new FOOTPRINT_VIEWER_FRAME( this, m_footprintLibTable, &semaphore, - KICAD_DEFAULT_DRAWFRAME_STYLE | wxFRAME_FLOAT_ON_PARENT ); + viewer = new FOOTPRINT_VIEWER_FRAME( &Kiway(), this, &semaphore ); // Show the library viewer frame until it is closed while( semaphore.TryWait() == wxSEMA_BUSY ) // Wait for viewer closing event @@ -318,28 +317,29 @@ MODULE* PCB_BASE_FRAME::LoadFootprint( const FPID& aFootprintId ) MODULE* PCB_BASE_FRAME::loadFootprint( const FPID& aFootprintId ) throw( IO_ERROR, PARSE_ERROR ) { - wxCHECK_MSG( m_footprintLibTable != NULL, NULL, - wxT( "Cannot look up FPID in NULL FP_LIB_TABLE." ) ); + FP_LIB_TABLE* fptbl = FootprintLibs(); + + wxCHECK_MSG( fptbl, NULL, wxT( "Cannot look up FPID in NULL FP_LIB_TABLE." ) ); wxString nickname = aFootprintId.GetLibNickname(); wxString fpname = aFootprintId.GetFootprintName(); if( nickname.size() ) { - return m_footprintLibTable->FootprintLoad( nickname, fpname ); + return fptbl->FootprintLoad( nickname, fpname ); } // user did not enter a nickname, just a footprint name, help him out a little: else { - std::vector nicks = m_footprintLibTable->GetLogicalLibs(); + std::vector nicks = fptbl->GetLogicalLibs(); // Search each library going through libraries alphabetically. for( unsigned i = 0; iFootprintLoad( nicks[i], fpname ); + MODULE* ret = fptbl->FootprintLoad( nicks[i], fpname ); if( ret ) return ret; } diff --git a/pcbnew/menubar_pcbframe.cpp b/pcbnew/menubar_pcbframe.cpp index 780d876ee6..fd61c9cba4 100644 --- a/pcbnew/menubar_pcbframe.cpp +++ b/pcbnew/menubar_pcbframe.cpp @@ -29,7 +29,8 @@ * Pcbnew editor menu bar */ #include -#include +#include +#include #include #include #include @@ -46,6 +47,8 @@ void PCB_EDIT_FRAME::ReCreateMenuBar() wxString text; wxMenuBar* menuBar = GetMenuBar(); + wxFileHistory& fhist = Kiface().GetFileHistory(); + if( ! menuBar ) menuBar = new wxMenuBar(); @@ -79,17 +82,18 @@ void PCB_EDIT_FRAME::ReCreateMenuBar() // Add this menu to list menu managed by m_fileHistory // (the file history will be updated when adding/removing files in history if( openRecentMenu ) - wxGetApp().GetFileHistory().RemoveMenu( openRecentMenu ); + fhist.RemoveMenu( openRecentMenu ); openRecentMenu = new wxMenu(); - wxGetApp().GetFileHistory().UseMenu( openRecentMenu ); - wxGetApp().GetFileHistory().AddFilesToMenu(); + + fhist.UseMenu( openRecentMenu ); + fhist.AddFilesToMenu(); + AddMenuItem( filesMenu, openRecentMenu, -1, _( "Open &Recent" ), _( "Open a recent opened board" ), KiBitmap( open_project_xpm ) ); - // Pcbnew Board AddMenuItem( filesMenu, ID_APPEND_FILE, _( "&Append Board" ), @@ -525,7 +529,7 @@ void PCB_EDIT_FRAME::ReCreateMenuBar() // Language submenu - wxGetApp().AddMenuLanguageList( configmenu ); + Pgm().AddMenuLanguageList( configmenu ); // Hotkey submenu AddHotkeyConfigMenu( configmenu ); diff --git a/pcbnew/modedit.cpp b/pcbnew/modedit.cpp index e4d13c9952..2729504ab1 100644 --- a/pcbnew/modedit.cpp +++ b/pcbnew/modedit.cpp @@ -26,11 +26,11 @@ */ #include -#include +#include #include #include #include -#include +#include #include #include <3d_viewer.h> #include @@ -262,11 +262,16 @@ void FOOTPRINT_EDIT_FRAME::Process_Special_Functions( wxCommandEvent& event ) case ID_OPEN_MODULE_VIEWER: { - FOOTPRINT_VIEWER_FRAME * viewer = FOOTPRINT_VIEWER_FRAME::GetActiveFootprintViewer(); + // Make a _project specific_ PCB_EDIT_FRAME be the start of the search in + // FOOTPRINT_VIEWER_FRAME::GetActiveFootprintViewer(); - if( viewer == NULL ) + PCB_EDIT_FRAME* top_project = dynamic_cast( GetParent() ); + wxASSERT( top_project ); // dynamic_cast returns NULL if class mismatch. + + FOOTPRINT_VIEWER_FRAME* viewer = FOOTPRINT_VIEWER_FRAME::GetActiveFootprintViewer( top_project ); + if( !viewer ) { - viewer = new FOOTPRINT_VIEWER_FRAME( this, m_footprintLibTable, NULL ); + viewer = (FOOTPRINT_VIEWER_FRAME*) Kiface().CreateWindow( this, MODULE_VIEWER_FRAME_TYPE, &Kiway() ); viewer->Show( true ); viewer->Zoom_Automatique( false ); } @@ -290,36 +295,38 @@ void FOOTPRINT_EDIT_FRAME::Process_Special_Functions( wxCommandEvent& event ) break; case ID_MODEDIT_NEW_MODULE: - { - Clear_Pcb( true ); - GetScreen()->ClearUndoRedoList(); - SetCurItem( NULL ); - SetCrossHairPosition( wxPoint( 0, 0 ) ); - - MODULE* module = Create_1_Module( wxEmptyString ); - - if( module ) // i.e. if create module command not aborted { - // Initialize data relative to nets and netclasses (for a new - // module the defaults are used) - // This is mandatory to handle and draw pads - GetBoard()->BuildListOfNets(); - redraw = true; - module->SetPosition( wxPoint( 0, 0 ) ); + Clear_Pcb( true ); + GetScreen()->ClearUndoRedoList(); + SetCurItem( NULL ); + SetCrossHairPosition( wxPoint( 0, 0 ) ); - if( GetBoard()->m_Modules ) - GetBoard()->m_Modules->ClearFlags(); + MODULE* module = Create_1_Module( wxEmptyString ); - Zoom_Automatique( false ); + if( module ) // i.e. if create module command not aborted + { + // Initialize data relative to nets and netclasses (for a new + // module the defaults are used) + // This is mandatory to handle and draw pads + GetBoard()->BuildListOfNets(); + redraw = true; + module->SetPosition( wxPoint( 0, 0 ) ); + + if( GetBoard()->m_Modules ) + GetBoard()->m_Modules->ClearFlags(); + + Zoom_Automatique( false ); + } } - } break; case ID_MODEDIT_NEW_MODULE_FROM_WIZARD: { wxSemaphore semaphore( 0, 1 ); - FOOTPRINT_WIZARD_FRAME *wizard = new FOOTPRINT_WIZARD_FRAME( this, &semaphore, - KICAD_DEFAULT_DRAWFRAME_STYLE | wxFRAME_FLOAT_ON_PARENT ); + + FOOTPRINT_WIZARD_FRAME* wizard = new FOOTPRINT_WIZARD_FRAME( &Kiway(), this, &semaphore, + KICAD_DEFAULT_DRAWFRAME_STYLE | wxFRAME_FLOAT_ON_PARENT ); + wizard->Show( true ); wizard->Zoom_Automatique( false ); @@ -492,7 +499,7 @@ void FOOTPRINT_EDIT_FRAME::Process_Special_Functions( wxCommandEvent& event ) Clear_Pcb( true ); SetCrossHairPosition( wxPoint( 0, 0 ) ); - LoadModuleFromLibrary( getLibNickName(), m_footprintLibTable, true ); + LoadModuleFromLibrary( getLibNickName(), FootprintLibs(), true ); redraw = true; if( GetBoard()->m_Modules ) diff --git a/pcbnew/module_editor_frame.h b/pcbnew/module_editor_frame.h index 1c2a6128ed..4378beac06 100644 --- a/pcbnew/module_editor_frame.h +++ b/pcbnew/module_editor_frame.h @@ -35,11 +35,14 @@ class FP_LIB_TABLE; +namespace PCB { struct IFACE; } // A KIFACE_I coded in pcbnew.c + class FOOTPRINT_EDIT_FRAME : public PCB_BASE_FRAME { + friend struct PCB::IFACE; + public: - FOOTPRINT_EDIT_FRAME( PCB_EDIT_FRAME* aParent, FP_LIB_TABLE* aTable ); ~FOOTPRINT_EDIT_FRAME(); @@ -52,10 +55,14 @@ public: /** * Function GetActiveFootprintEditor (static) + * + * @param aTopOfProject is a PCB_EDIT_FRAME* window which anchors the search in + * a project specific way. + * * @return a reference to the current opened Footprint editor * or NULL if no Footprint editor currently opened */ - static FOOTPRINT_EDIT_FRAME* GetActiveFootprintEditor(); + static FOOTPRINT_EDIT_FRAME* GetActiveFootprintEditor( const wxWindow* aTopOfProject ); BOARD_DESIGN_SETTINGS& GetDesignSettings() const; // overload PCB_BASE_FRAME, get parent's void SetDesignSettings( const BOARD_DESIGN_SETTINGS& aSettings ); // overload @@ -195,7 +202,7 @@ public: bool Clear_Pcb( bool aQuery ); /* handlers for block commands */ - virtual int ReturnBlockCommand( int key ); + virtual int BlockCommand( int key ); /** * Function HandleBlockPlace @@ -406,6 +413,10 @@ public: DECLARE_EVENT_TABLE() protected: + + /// protected so only friend PCB::IFACE::CreateWindow() can act as sole factory. + FOOTPRINT_EDIT_FRAME( KIWAY* aKiway, PCB_EDIT_FRAME* aParent ); + static BOARD* s_Pcb; ///< retain board across invocations of module editor /** @@ -433,7 +444,7 @@ protected: /// The library nickName is a short string, for now the same as the library path /// but without path and without extension. After library table support it becomes /// a lookup key. - const wxString& getLibNickName() const; + const wxString getLibNickName() const; void setLibNickName( const wxString& aNickname ); diff --git a/pcbnew/moduleframe.cpp b/pcbnew/moduleframe.cpp index 02b2f52958..bdbaf7d971 100644 --- a/pcbnew/moduleframe.cpp +++ b/pcbnew/moduleframe.cpp @@ -30,7 +30,9 @@ */ #include -#include +#include +//#include +#include #include #include #include @@ -150,8 +152,8 @@ END_EVENT_TABLE() #define FOOTPRINT_EDIT_FRAME_NAME wxT( "ModEditFrame" ) -FOOTPRINT_EDIT_FRAME::FOOTPRINT_EDIT_FRAME( PCB_EDIT_FRAME* aParent, FP_LIB_TABLE* aTable ) : - PCB_BASE_FRAME( aParent, MODULE_EDITOR_FRAME_TYPE, wxEmptyString, +FOOTPRINT_EDIT_FRAME::FOOTPRINT_EDIT_FRAME( KIWAY* aKiway, PCB_EDIT_FRAME* aParent ) : + PCB_BASE_FRAME( aKiway, aParent, MODULE_EDITOR_FRAME_TYPE, wxEmptyString, wxDefaultPosition, wxDefaultSize, KICAD_DEFAULT_DRAWFRAME_STYLE, GetFootprintEditorFrameName() ) { @@ -160,7 +162,6 @@ FOOTPRINT_EDIT_FRAME::FOOTPRINT_EDIT_FRAME( PCB_EDIT_FRAME* aParent, FP_LIB_TABL m_showAxis = true; // true to show X and Y axis on screen m_showGridAxis = true; // show the grid origin axis m_HotkeysZoomAndGridList = g_Module_Editor_Hokeys_Descr; - m_footprintLibTable = aTable; // Give an icon wxIcon icon; @@ -186,7 +187,7 @@ FOOTPRINT_EDIT_FRAME::FOOTPRINT_EDIT_FRAME( PCB_EDIT_FRAME* aParent, FP_LIB_TABL SetScreen( s_screenModule ); GetScreen()->SetCurItem( NULL ); - LoadSettings(); + LoadSettings( config() ); GetBoard()->SetVisibleAlls(); @@ -256,15 +257,15 @@ FOOTPRINT_EDIT_FRAME::~FOOTPRINT_EDIT_FRAME() } -const wxString& FOOTPRINT_EDIT_FRAME::getLibNickName() const +const wxString FOOTPRINT_EDIT_FRAME::getLibNickName() const { - return wxGetApp().GetModuleLibraryNickname(); + return Prj().GetModuleLibraryNickname(); } void FOOTPRINT_EDIT_FRAME::setLibNickName( const wxString& aNickname ) { - wxGetApp().SetModuleLibraryNickname( aNickname ); + Prj().SetModuleLibraryNickname( aNickname ); } @@ -274,7 +275,7 @@ wxString FOOTPRINT_EDIT_FRAME::getLibPath() { const wxString& nickname = getLibNickName(); - const FP_LIB_TABLE::ROW* row = GetFootprintLibraryTable()->FindRow( nickname ); + const FP_LIB_TABLE::ROW* row = FootprintLibs()->FindRow( nickname ); return row->GetFullURI( true ); } @@ -294,9 +295,13 @@ const wxChar* FOOTPRINT_EDIT_FRAME::GetFootprintEditorFrameName() /* return a reference to the current opened Footprint editor * or NULL if no Footprint editor currently opened */ -FOOTPRINT_EDIT_FRAME* FOOTPRINT_EDIT_FRAME::GetActiveFootprintEditor() +FOOTPRINT_EDIT_FRAME* FOOTPRINT_EDIT_FRAME::GetActiveFootprintEditor( const wxWindow* aParent ) { - return (FOOTPRINT_EDIT_FRAME*) wxWindow::FindWindowByName( GetFootprintEditorFrameName() ); + // top_of_project! + wxASSERT( dynamic_cast( aParent ) ); + + wxWindow* ret = wxWindow::FindWindowByName( GetFootprintEditorFrameName(), aParent ); + return (FOOTPRINT_EDIT_FRAME*) ret; } @@ -484,7 +489,9 @@ void FOOTPRINT_EDIT_FRAME::OnUpdateReplaceModuleInBoard( wxUpdateUIEvent& aEvent void FOOTPRINT_EDIT_FRAME::OnUpdateSelectCurrentLib( wxUpdateUIEvent& aEvent ) { - aEvent.Enable( m_footprintLibTable && !m_footprintLibTable->IsEmpty() ); + FP_LIB_TABLE* fptbl = FootprintLibs(); + + aEvent.Enable( fptbl && !fptbl->IsEmpty() ); } @@ -506,7 +513,7 @@ void FOOTPRINT_EDIT_FRAME::Show3D_Frame( wxCommandEvent& event ) return; } - m_Draw3DFrame = new EDA_3D_FRAME( this, _( "3D Viewer" ) ); + m_Draw3DFrame = new EDA_3D_FRAME( &Kiway(), this, _( "3D Viewer" ) ); m_Draw3DFrame->Show( true ); } @@ -622,7 +629,7 @@ void FOOTPRINT_EDIT_FRAME::updateTitle() { try { - bool writable = m_footprintLibTable->IsFootprintLibWritable( nickname ); + bool writable = FootprintLibs()->IsFootprintLibWritable( nickname ); // no exception was thrown, this means libPath is valid, but it may be read only. title = _( "Module Editor (active library: " ) + nickname + wxT( ")" ); diff --git a/pcbnew/modview_frame.cpp b/pcbnew/modview_frame.cpp index 99677a34ed..8375336b75 100644 --- a/pcbnew/modview_frame.cpp +++ b/pcbnew/modview_frame.cpp @@ -28,7 +28,7 @@ */ #include -#include +#include #include #include #include @@ -118,17 +118,16 @@ static wxAcceleratorEntry accels[] = #define FOOTPRINT_VIEWER_FRAME_NAME wxT( "ModViewFrame" ) -FOOTPRINT_VIEWER_FRAME::FOOTPRINT_VIEWER_FRAME( PCB_BASE_FRAME* aParent, - FP_LIB_TABLE* aTable, - wxSemaphore* aSemaphore, - long aStyle ) : - PCB_BASE_FRAME( aParent, MODULE_VIEWER_FRAME_TYPE, _( "Footprint Library Browser" ), - wxDefaultPosition, wxDefaultSize, aStyle, GetFootprintViewerFrameName() ) +FOOTPRINT_VIEWER_FRAME::FOOTPRINT_VIEWER_FRAME( KIWAY* aKiway, PCB_BASE_FRAME* aParent, wxSemaphore* aSemaphore ) : + PCB_BASE_FRAME( aKiway, aParent, MODULE_VIEWER_FRAME_TYPE, _( "Footprint Library Browser" ), + wxDefaultPosition, wxDefaultSize, + !aSemaphore ? + KICAD_DEFAULT_DRAWFRAME_STYLE : + KICAD_DEFAULT_DRAWFRAME_STYLE | wxFRAME_FLOAT_ON_PARENT, + GetFootprintViewerFrameName() ) { wxAcceleratorTable table( DIM( accels ), accels ); - m_footprintLibTable = aTable; - m_FrameName = GetFootprintViewerFrameName(); m_configPath = wxT( "FootprintViewer" ); m_showAxis = true; // true to draw axis. @@ -159,8 +158,7 @@ FOOTPRINT_VIEWER_FRAME::FOOTPRINT_VIEWER_FRAME( PCB_BASE_FRAME* aParent, SetScreen( new PCB_SCREEN( GetPageSizeIU() ) ); GetScreen()->m_Center = true; // Center coordinate origins on screen. - LoadSettings(); - + LoadSettings( config() ); SetSize( m_FramePos.x, m_FramePos.y, m_FrameSize.x, m_FrameSize.y ); @@ -273,10 +271,13 @@ const wxChar* FOOTPRINT_VIEWER_FRAME::GetFootprintViewerFrameName() } -FOOTPRINT_VIEWER_FRAME* FOOTPRINT_VIEWER_FRAME::GetActiveFootprintViewer() +FOOTPRINT_VIEWER_FRAME* FOOTPRINT_VIEWER_FRAME::GetActiveFootprintViewer( const wxWindow* aParent ) { - return (FOOTPRINT_VIEWER_FRAME*) - wxWindow::FindWindowByName( GetFootprintViewerFrameName() ); + // top_of_project! + wxASSERT( dynamic_cast( aParent ) ); + + return (FOOTPRINT_VIEWER_FRAME*) wxWindow::FindWindowByName( + GetFootprintViewerFrameName(), aParent ); } @@ -314,7 +315,7 @@ void FOOTPRINT_VIEWER_FRAME::ReCreateLibraryList() { m_libList->Clear(); - std::vector< wxString > nicknames = m_footprintLibTable->GetLogicalLibs(); + std::vector< wxString > nicknames = FootprintLibs()->GetLogicalLibs(); for( unsigned ii = 0; ii < nicknames.size(); ii++ ) m_libList->Append( nicknames[ii] ); @@ -353,7 +354,7 @@ void FOOTPRINT_VIEWER_FRAME::ReCreateFootprintList() FOOTPRINT_LIST fp_info_list; - fp_info_list.ReadFootprintFiles( m_footprintLibTable, &m_libraryName ); + fp_info_list.ReadFootprintFiles( FootprintLibs(), &m_libraryName ); if( fp_info_list.GetErrorCount() ) { @@ -468,29 +469,15 @@ void FOOTPRINT_VIEWER_FRAME::ExportSelectedFootprint( wxCommandEvent& event ) } -void FOOTPRINT_VIEWER_FRAME::LoadSettings( ) +void FOOTPRINT_VIEWER_FRAME::LoadSettings( wxConfigBase* aCfg ) { - EDA_DRAW_FRAME::LoadSettings(); - -/* - wxConfigPathChanger cpc( wxGetApp().GetSettings(), m_configPath ); - - // wxConfig* cfg = - wxGetApp().GetSettings(); -*/ + EDA_DRAW_FRAME::LoadSettings( aCfg ); } -void FOOTPRINT_VIEWER_FRAME::SaveSettings() +void FOOTPRINT_VIEWER_FRAME::SaveSettings( wxConfigBase* aCfg ) { - EDA_DRAW_FRAME::SaveSettings(); - -/* - wxConfigPathChanger cpc( wxGetApp().GetSettings(), m_configPath ); - - // wxConfig* cfg = - wxGetApp().GetSettings(); -*/ + EDA_DRAW_FRAME::SaveSettings( aCfg ); } @@ -505,7 +492,7 @@ void FOOTPRINT_VIEWER_FRAME::OnActivate( wxActivateEvent& event ) m_selectedFootprintName.Empty(); // Ensure we have the right library list: - std::vector< wxString > libNicknames = m_footprintLibTable->GetLogicalLibs(); + std::vector< wxString > libNicknames = FootprintLibs()->GetLogicalLibs(); if( libNicknames.size() == m_libList->GetCount() ) { @@ -635,7 +622,7 @@ void FOOTPRINT_VIEWER_FRAME::Show3D_Frame( wxCommandEvent& event ) return; } - m_Draw3DFrame = new EDA_3D_FRAME( this, wxEmptyString ); + m_Draw3DFrame = new EDA_3D_FRAME( &Kiway(), this, wxEmptyString ); Update3D_Frame( false ); m_Draw3DFrame->Show( true ); } @@ -741,7 +728,7 @@ void FOOTPRINT_VIEWER_FRAME::SelectCurrentFootprint( wxCommandEvent& event ) PCB_EDIT_FRAME* parent = (PCB_EDIT_FRAME*) GetParent(); wxString libname = m_libraryName + wxT( "." ) + LegacyFootprintLibPathExtension; MODULE* oldmodule = GetBoard()->m_Modules; - MODULE* module = LoadModuleFromLibrary( libname, parent->GetFootprintLibraryTable(), + MODULE* module = LoadModuleFromLibrary( libname, parent->FootprintLibs(), false ); if( module ) @@ -802,7 +789,7 @@ void FOOTPRINT_VIEWER_FRAME::SelectAndViewFootprint( int aMode ) // Delete the current footprint GetBoard()->m_Modules.DeleteAll(); - MODULE* footprint = m_footprintLibTable->FootprintLoad( m_libraryName, m_footprintName ); + MODULE* footprint = FootprintLibs()->FootprintLoad( m_libraryName, m_footprintName ); if( footprint ) GetBoard()->Add( footprint, ADD_APPEND ); diff --git a/pcbnew/modview_frame.h b/pcbnew/modview_frame.h index 212f687dd8..b28242a811 100644 --- a/pcbnew/modview_frame.h +++ b/pcbnew/modview_frame.h @@ -37,12 +37,15 @@ class wxListBox; class wxSemaphore; class FP_LIB_TABLE; +namespace PCB { struct IFACE; } /** * Component library viewer main window. */ class FOOTPRINT_VIEWER_FRAME : public PCB_BASE_FRAME { + friend struct PCB::IFACE; + private: wxListBox* m_libList; // The list of libs names wxListBox* m_footprintList; // The list of footprint names @@ -58,9 +61,7 @@ protected: // the selected footprint is here public: - FOOTPRINT_VIEWER_FRAME( PCB_BASE_FRAME* aParent, FP_LIB_TABLE* aTable, - wxSemaphore* aSemaphore = NULL, - long aStyle = KICAD_DEFAULT_DRAWFRAME_STYLE ); + FOOTPRINT_VIEWER_FRAME( KIWAY* aKiway, PCB_BASE_FRAME* aParent, wxSemaphore* aSemaphore = NULL ); ~FOOTPRINT_VIEWER_FRAME(); @@ -76,10 +77,10 @@ public: * @return a reference to the current opened Footprint viewer * or NULL if no Footprint viewer currently opened */ - static FOOTPRINT_VIEWER_FRAME* GetActiveFootprintViewer(); + static FOOTPRINT_VIEWER_FRAME* GetActiveFootprintViewer( const wxWindow* aParent ); wxString& GetSelectedFootprint( void ) const { return m_selectedFootprintName; } - const wxString GetSelectedLibraryFullName( void ); + const wxString GetSelectedLibraryFullName(); /** * Function GetSelectedLibrary @@ -87,7 +88,7 @@ public: */ const wxString& GetSelectedLibrary() { return m_libraryName; } - virtual EDA_COLOR_T GetGridColor( void ) const; + virtual EDA_COLOR_T GetGridColor() const; /** * Function ReCreateLibraryList @@ -128,23 +129,8 @@ private: void GeneralControl( wxDC* aDC, const wxPoint& aPosition, int aHotKey = 0 ); - /** - * Function LoadSettings - * loads the library viewer frame specific configuration settings. - * - * Don't forget to call this base method from any derived classes or the - * settings will not get loaded. - */ - void LoadSettings(); - - /** - * Function SaveSettings - * save library viewer frame specific configuration settings. - * - * Don't forget to call this base method from any derived classes or the - * settings will not get saved. - */ - void SaveSettings(); + void LoadSettings( wxConfigBase* aCfg ); // override virtual + void SaveSettings( wxConfigBase* aCfg ); // override virtual wxString& GetFootprintName( void ) const { return m_footprintName; } diff --git a/pcbnew/muonde.cpp b/pcbnew/muonde.cpp index bd0d6c191a..f943b13c42 100644 --- a/pcbnew/muonde.cpp +++ b/pcbnew/muonde.cpp @@ -198,14 +198,14 @@ MODULE* PCB_EDIT_FRAME::Genere_Self( wxDC* DC ) Mself.lng = min_len; // Enter the desired length. - msg = ReturnStringFromValue( g_UserUnit, Mself.lng ); + msg = StringFromValue( g_UserUnit, Mself.lng ); wxTextEntryDialog dlg( this, _( "Length:" ), _( "Length" ), msg ); if( dlg.ShowModal() != wxID_OK ) return NULL; // canceled by user msg = dlg.GetValue(); - Mself.lng = ReturnValueFromString( g_UserUnit, msg ); + Mself.lng = ValueFromString( g_UserUnit, msg ); // Control values (ii = minimum length) if( Mself.lng < min_len ) @@ -614,7 +614,7 @@ MODULE* PCB_EDIT_FRAME::Create_MuWaveComponent( int shape_type ) break; } - wxString value = ReturnStringFromValue( g_UserUnit, gap_size ); + wxString value = StringFromValue( g_UserUnit, gap_size ); wxTextEntryDialog dlg( this, msg, _( "Create microwave module" ), value ); if( dlg.ShowModal() != wxID_OK ) @@ -624,7 +624,7 @@ MODULE* PCB_EDIT_FRAME::Create_MuWaveComponent( int shape_type ) } value = dlg.GetValue(); - gap_size = ReturnValueFromString( g_UserUnit, value ); + gap_size = ValueFromString( g_UserUnit, value ); bool abort = false; @@ -1094,14 +1094,14 @@ void PCB_EDIT_FRAME::Edit_Gap( wxDC* DC, MODULE* aModule ) gap_size = next_pad->GetPos0().x - pad->GetPos0().x - pad->GetSize().x; // Entrer the desired length of the gap. - msg = ReturnStringFromValue( g_UserUnit, gap_size ); + msg = StringFromValue( g_UserUnit, gap_size ); wxTextEntryDialog dlg( this, _( "Gap:" ), _( "Create Microwave Gap" ), msg ); if( dlg.ShowModal() != wxID_OK ) return; // cancelled by user msg = dlg.GetValue(); - gap_size = ReturnValueFromString( g_UserUnit, msg ); + gap_size = ValueFromString( g_UserUnit, msg ); // Updating sizes of pads forming the gap. int tw = GetBoard()->GetCurrentTrackWidth(); diff --git a/pcbnew/netlist.cpp b/pcbnew/netlist.cpp index 18d60f8cfd..258bea0c8f 100644 --- a/pcbnew/netlist.cpp +++ b/pcbnew/netlist.cpp @@ -28,7 +28,7 @@ */ #include -#include +#include #include #include #include @@ -172,7 +172,7 @@ void PCB_EDIT_FRAME::loadFootprints( NETLIST& aNetlist, REPORTER* aReporter ) MODULE* module = 0; MODULE* fpOnBoard; - if( aNetlist.IsEmpty() || m_footprintLibTable->IsEmpty() ) + if( aNetlist.IsEmpty() || FootprintLibs()->IsEmpty() ) return; aNetlist.SortByFPID(); diff --git a/pcbnew/onleftclick.cpp b/pcbnew/onleftclick.cpp index 43f0486fe1..f4a6024c90 100644 --- a/pcbnew/onleftclick.cpp +++ b/pcbnew/onleftclick.cpp @@ -354,8 +354,9 @@ void PCB_EDIT_FRAME::OnLeftClick( wxDC* aDC, const wxPoint& aPosition ) if( (DrawStruct == NULL) || (DrawStruct->GetFlags() == 0) ) { m_canvas->MoveCursorToCrossHair(); - DrawStruct = (BOARD_ITEM*) LoadModuleFromLibrary( wxEmptyString, m_footprintLibTable, - true, aDC ); + DrawStruct = (BOARD_ITEM*) LoadModuleFromLibrary( + wxEmptyString, FootprintLibs(), true, aDC ); + SetCurItem( DrawStruct ); if( DrawStruct ) diff --git a/pcbnew/onrightclick.cpp b/pcbnew/onrightclick.cpp index e0a156f66f..75d704a889 100644 --- a/pcbnew/onrightclick.cpp +++ b/pcbnew/onrightclick.cpp @@ -137,11 +137,7 @@ bool PCB_EDIT_FRAME::OnRightClick( const wxPoint& aMousePos, wxMenu* aPopMenu ) } item = GetCurItem(); - - if( item ) - flags = item->GetFlags(); - else - flags = 0; + flags = item ? item->GetFlags() : 0; // Add the context menu, which depends on the picked item: if( item ) @@ -971,7 +967,7 @@ static wxMenu* Append_Track_Width_List( BOARD* aBoard ) for( unsigned ii = 0; ii < aBoard->m_TrackWidthList.size(); ii++ ) { - value = ReturnStringFromValue( g_UserUnit, aBoard->m_TrackWidthList[ii], true ); + value = StringFromValue( g_UserUnit, aBoard->m_TrackWidthList[ii], true ); msg.Printf( _( "Track %s" ), GetChars( value ) ); if( ii == 0 ) @@ -984,9 +980,9 @@ static wxMenu* Append_Track_Width_List( BOARD* aBoard ) for( unsigned ii = 0; ii < aBoard->m_ViasDimensionsList.size(); ii++ ) { - value = ReturnStringFromValue( g_UserUnit, aBoard->m_ViasDimensionsList[ii].m_Diameter, + value = StringFromValue( g_UserUnit, aBoard->m_ViasDimensionsList[ii].m_Diameter, true ); - wxString drill = ReturnStringFromValue( g_UserUnit, + wxString drill = StringFromValue( g_UserUnit, aBoard->m_ViasDimensionsList[ii].m_Drill, true ); diff --git a/pcbnew/pcb_painter.cpp b/pcbnew/pcb_painter.cpp index 33f44f2dd9..4475494d7e 100644 --- a/pcbnew/pcb_painter.cpp +++ b/pcbnew/pcb_painter.cpp @@ -447,7 +447,7 @@ void PCB_PAINTER::draw( const D_PAD* aPad, int aLayer ) if( m_pcbSettings->m_padNumbers ) { textpos.y = -textpos.y; - aPad->ReturnStringPadName( buffer ); + aPad->StringPadName( buffer ); int len = buffer.Length(); double tsize = padsize.x / std::max( len, MIN_CHAR_COUNT ); tsize = std::min( tsize, size ); diff --git a/pcbnew/pcb_parser.cpp b/pcbnew/pcb_parser.cpp index 70e3295f17..db66648d21 100644 --- a/pcbnew/pcb_parser.cpp +++ b/pcbnew/pcb_parser.cpp @@ -2429,8 +2429,9 @@ ZONE_CONTAINER* PCB_PARSER::parseZONE_CONTAINER() throw( IO_ERROR, PARSE_ERROR ) NeedSYMBOLorNUMBER(); if( zone->GetNet()->GetNetname() != FromUTF8() ) { - wxString msg = _( "There is a zone that belongs to a not " - "existing net (" ) + FromUTF8() + _("), you should verify it." ); + wxString msg; + msg.Printf( _( "There is a zone that belongs to a not existing net" + "(%s), you should verify it." ), GetChars( FromUTF8() ) ); DisplayError( NULL, msg ); zone->SetNetCode( NETINFO_LIST::UNCONNECTED ); } diff --git a/pcbnew/pcbframe.cpp b/pcbnew/pcbframe.cpp index b168e54300..6fc807c083 100644 --- a/pcbnew/pcbframe.cpp +++ b/pcbnew/pcbframe.cpp @@ -30,7 +30,8 @@ */ #include -#include +#include +#include #include #include #include @@ -295,11 +296,9 @@ END_EVENT_TABLE() #define PCB_EDIT_FRAME_NAME wxT( "PcbFrame" ) -PCB_EDIT_FRAME::PCB_EDIT_FRAME( wxWindow* parent, const wxString& title, - const wxPoint& pos, const wxSize& size, - long style ) : - PCB_BASE_FRAME( parent, PCB_FRAME_TYPE, title, pos, size, - style, PCB_EDIT_FRAME_NAME ) +PCB_EDIT_FRAME::PCB_EDIT_FRAME( KIWAY* aKiway, wxWindow* aParent ) : + PCB_BASE_FRAME( aKiway, aParent, PCB_FRAME_TYPE, wxT( "Pcbnew" ), wxDefaultPosition, + wxDefaultSize, KICAD_DEFAULT_DRAWFRAME_STYLE, PCB_EDIT_FRAME_NAME ) { m_FrameName = PCB_EDIT_FRAME_NAME; m_showBorderAndTitleBlock = true; // true to display sheet references @@ -317,8 +316,6 @@ PCB_EDIT_FRAME::PCB_EDIT_FRAME( wxWindow* parent, const wxString& title, m_microWaveToolBar = NULL; m_useCmpFileForFpNames = true; - m_footprintLibTable = NULL; - m_globalFootprintTable = NULL; m_rotationAngle = 900; #ifdef KICAD_SCRIPTING_WXPYTHON @@ -356,7 +353,7 @@ PCB_EDIT_FRAME::PCB_EDIT_FRAME( wxWindow* parent, const wxString& title, // LoadSettings() *after* creating m_LayersManager, because LoadSettings() // initialize parameters in m_LayersManager - LoadSettings(); + LoadSettings( config() ); // Be sure options are updated m_DisplayPcbTrackFill = DisplayOpt.DisplayPcbTrackFill; @@ -472,34 +469,6 @@ PCB_EDIT_FRAME::PCB_EDIT_FRAME( wxWindow* parent, const wxString& title, m_auimgr.Update(); - if( m_globalFootprintTable == NULL ) - { - try - { - m_globalFootprintTable = new FP_LIB_TABLE(); - - if( !FP_LIB_TABLE::LoadGlobalTable( *m_globalFootprintTable ) ) - { - DisplayInfoMessage( this, wxT( "You have run Pcbnew for the first time using the " - "new footprint library table method for finding " - "footprints. Pcbnew has either copied the default " - "table or created an empty table in your home " - "folder. You must first configure the library " - "table to include all footprint libraries not " - "included with KiCad. See the \"Footprint Library " - "Table\" section of the CvPcb documentation for " - "more information." ) ); - } - } - catch( IO_ERROR ioe ) - { - wxString msg; - msg.Printf( _( "An error occurred attempting to load the global footprint library " - "table:\n\n%s" ), GetChars( ioe.errorText ) ); - DisplayError( this, msg ); - } - } - setupTools(); } @@ -513,9 +482,6 @@ PCB_EDIT_FRAME::~PCB_EDIT_FRAME() m_Macros[i].m_Record.clear(); delete m_drc; - - delete m_footprintLibTable; - delete m_globalFootprintTable; } @@ -661,7 +627,7 @@ void PCB_EDIT_FRAME::OnCloseWindow( wxCloseEvent& Event ) msg.Printf( _( "The auto save file <%s> could not be removed!" ), GetChars( fn.GetFullPath() ) ); - wxMessageBox( msg, wxGetApp().GetAppName(), wxOK | wxICON_ERROR, this ); + wxMessageBox( msg, Pgm().App().GetAppName(), wxOK | wxICON_ERROR, this ); } // Delete board structs and undo/redo lists, to avoid crash on exit @@ -694,7 +660,7 @@ void PCB_EDIT_FRAME::Show3D_Frame( wxCommandEvent& event ) return; } - m_Draw3DFrame = new EDA_3D_FRAME( this, _( "3D Viewer" ) ); + m_Draw3DFrame = new EDA_3D_FRAME( &Kiway(), this, _( "3D Viewer" ) ); m_Draw3DFrame->SetDefaultFileName( GetBoard()->GetFileName() ); m_Draw3DFrame->Show( true ); } @@ -756,62 +722,55 @@ void PCB_EDIT_FRAME::ShowDesignRulesEditor( wxCommandEvent& event ) } -void PCB_EDIT_FRAME::LoadSettings() +void PCB_EDIT_FRAME::LoadSettings( wxConfigBase* aCfg ) { - wxConfig* config = wxGetApp().GetSettings(); + PCB_BASE_FRAME::LoadSettings( aCfg ); - if( config == NULL ) - return; - - // The configuration setting that used to be mixed in with the project file settings. - wxGetApp().ReadCurrentSetupValues( GetConfigurationSettings() ); - - PCB_BASE_FRAME::LoadSettings(); + wxConfigLoadSetups( aCfg, GetConfigurationSettings() ); double dtmp; - config->Read( OPTKEY_DEFAULT_LINEWIDTH_VALUE, &dtmp, 0.1 ); // stored in mm + aCfg->Read( OPTKEY_DEFAULT_LINEWIDTH_VALUE, &dtmp, 0.1 ); // stored in mm + if( dtmp < 0.01 ) dtmp = 0.01; + if( dtmp > 5.0 ) dtmp = 5.0; + g_DrawDefaultLineThickness = Millimeter2iu( dtmp ); + long tmp; - config->Read( PCB_SHOW_FULL_RATSNET_OPT, &tmp ); + + aCfg->Read( PCB_SHOW_FULL_RATSNET_OPT, &tmp ); GetBoard()->SetElementVisibility(RATSNEST_VISIBLE, tmp); - config->Read( PCB_MAGNETIC_PADS_OPT, &g_MagneticPadOption ); - config->Read( PCB_MAGNETIC_TRACKS_OPT, &g_MagneticTrackOption ); - config->Read( SHOW_MICROWAVE_TOOLS, &m_show_microwave_tools ); - config->Read( SHOW_LAYER_MANAGER_TOOLS, &m_show_layer_manager_tools ); + aCfg->Read( PCB_MAGNETIC_PADS_OPT, &g_MagneticPadOption ); + aCfg->Read( PCB_MAGNETIC_TRACKS_OPT, &g_MagneticTrackOption ); + aCfg->Read( SHOW_MICROWAVE_TOOLS, &m_show_microwave_tools ); + aCfg->Read( SHOW_LAYER_MANAGER_TOOLS, &m_show_layer_manager_tools ); // WxWidgets 2.9.1 seems call setlocale( LC_NUMERIC, "" ) - // when reading doubles in config, + // when reading doubles in cfg, // but forget to back to current locale. So we call SetLocaleTo_Default SetLocaleTo_Default( ); } -void PCB_EDIT_FRAME::SaveSettings() +void PCB_EDIT_FRAME::SaveSettings( wxConfigBase* aCfg ) { - wxConfig* config = wxGetApp().GetSettings(); + PCB_BASE_FRAME::SaveSettings( aCfg ); - if( config == NULL ) - return; - - // The configuration setting that used to be mixed in with the project file settings. - wxGetApp().SaveCurrentSetupValues( GetConfigurationSettings() ); - - PCB_BASE_FRAME::SaveSettings(); + wxConfigSaveSetups( aCfg, GetConfigurationSettings() ); // This value is stored in mm ) - config->Write( OPTKEY_DEFAULT_LINEWIDTH_VALUE, + aCfg->Write( OPTKEY_DEFAULT_LINEWIDTH_VALUE, MM_PER_IU * g_DrawDefaultLineThickness ); long tmp = GetBoard()->IsElementVisible(RATSNEST_VISIBLE); - config->Write( PCB_SHOW_FULL_RATSNET_OPT, tmp ); - config->Write( PCB_MAGNETIC_PADS_OPT, (long) g_MagneticPadOption ); - config->Write( PCB_MAGNETIC_TRACKS_OPT, (long) g_MagneticTrackOption ); - config->Write( SHOW_MICROWAVE_TOOLS, (long) m_show_microwave_tools ); - config->Write( SHOW_LAYER_MANAGER_TOOLS, (long)m_show_layer_manager_tools ); + aCfg->Write( PCB_SHOW_FULL_RATSNET_OPT, tmp ); + aCfg->Write( PCB_MAGNETIC_PADS_OPT, (long) g_MagneticPadOption ); + aCfg->Write( PCB_MAGNETIC_TRACKS_OPT, (long) g_MagneticTrackOption ); + aCfg->Write( SHOW_MICROWAVE_TOOLS, (long) m_show_microwave_tools ); + aCfg->Write( SHOW_LAYER_MANAGER_TOOLS, (long)m_show_layer_manager_tools ); } @@ -1037,12 +996,14 @@ void PCB_EDIT_FRAME::SetLanguage( wxCommandEvent& event ) { EDA_DRAW_FRAME::SetLanguage( event ); m_Layers->SetLayersManagerTabsText(); + wxAuiPaneInfo& pane_info = m_auimgr.GetPane( m_Layers ); + pane_info.Caption( _( "Visibles" ) ); m_auimgr.Update(); ReFillLayerWidget(); - FOOTPRINT_EDIT_FRAME * moduleEditFrame = FOOTPRINT_EDIT_FRAME::GetActiveFootprintEditor(); + FOOTPRINT_EDIT_FRAME* moduleEditFrame = FOOTPRINT_EDIT_FRAME::GetActiveFootprintEditor( this ); if( moduleEditFrame ) moduleEditFrame->EDA_DRAW_FRAME::SetLanguage( event ); } @@ -1095,10 +1056,8 @@ void PCB_EDIT_FRAME::SVG_Print( wxCommandEvent& event ) void PCB_EDIT_FRAME::UpdateTitle() { - wxString title; - wxFileName fileName = GetBoard()->GetFileName(); - - title.Printf( wxT( "Pcbnew %s " ), GetChars( GetBuildVersion() ) ); + wxFileName fileName = GetBoard()->GetFileName(); + wxString title = wxString::Format( wxT( "Pcbnew %s " ), GetChars( GetBuildVersion() ) ); if( fileName.IsOk() && fileName.FileExists() ) { @@ -1146,24 +1105,29 @@ void PCB_EDIT_FRAME::OnSelectAutoPlaceMode( wxCommandEvent& aEvent ) switch( aEvent.GetId() ) { - case ID_TOOLBARH_PCB_MODE_MODULE: - if( aEvent.IsChecked() && - m_mainToolBar->GetToolToggled( ID_TOOLBARH_PCB_MODE_TRACKS ) ) - m_mainToolBar->ToggleTool( ID_TOOLBARH_PCB_MODE_TRACKS, false ); - break; - - case ID_TOOLBARH_PCB_MODE_TRACKS: - if( aEvent.IsChecked() && - m_mainToolBar->GetToolToggled( ID_TOOLBARH_PCB_MODE_MODULE ) ) - m_mainToolBar->ToggleTool( ID_TOOLBARH_PCB_MODE_MODULE, false ); - break; + case ID_TOOLBARH_PCB_MODE_MODULE: + if( aEvent.IsChecked() && + m_mainToolBar->GetToolToggled( ID_TOOLBARH_PCB_MODE_TRACKS ) ) + { + m_mainToolBar->ToggleTool( ID_TOOLBARH_PCB_MODE_TRACKS, false ); } + break; + + case ID_TOOLBARH_PCB_MODE_TRACKS: + if( aEvent.IsChecked() && + m_mainToolBar->GetToolToggled( ID_TOOLBARH_PCB_MODE_MODULE ) ) + { + m_mainToolBar->ToggleTool( ID_TOOLBARH_PCB_MODE_MODULE, false ); + } + break; + } } void PCB_EDIT_FRAME::ToPlotter( wxCommandEvent& event ) { DIALOG_PLOT dlg( this ); + dlg.ShowModal(); } @@ -1175,3 +1139,4 @@ void PCB_EDIT_FRAME::SetRotationAngle( int aRotationAngle ) m_rotationAngle = aRotationAngle; } + diff --git a/pcbnew/pcbnew.cpp b/pcbnew/pcbnew.cpp index a7b4db9f4c..a8eac6b21a 100644 --- a/pcbnew/pcbnew.cpp +++ b/pcbnew/pcbnew.cpp @@ -29,11 +29,12 @@ */ #ifdef KICAD_SCRIPTING -#include -#include + #include + #include #endif #include -#include +#include +#include #include #include #include @@ -48,82 +49,294 @@ #include #include #include +#include #include #include #include #include #include +#include <3d_viewer.h> +#include +#include +#include // Colors for layers and items COLORS_DESIGN_SETTINGS g_ColorsSettings; -bool g_Drc_On = true; -bool g_AutoDeleteOldTrack = true; -bool g_Show_Module_Ratsnest; -bool g_Raccord_45_Auto = true; -bool g_Alternate_Track_Posture = false; -bool g_Track_45_Only_Allowed = true; // True to allow horiz, vert. and 45deg only tracks -bool g_Segments_45_Only; // True to allow horiz, vert. and 45deg only graphic segments -bool g_TwoSegmentTrackBuild = true; +bool g_Drc_On = true; +bool g_AutoDeleteOldTrack = true; +bool g_Show_Module_Ratsnest; +bool g_Raccord_45_Auto = true; +bool g_Alternate_Track_Posture = false; +bool g_Track_45_Only_Allowed = true; // True to allow horiz, vert. and 45deg only tracks +bool g_Segments_45_Only; // True to allow horiz, vert. and 45deg only graphic segments +bool g_TwoSegmentTrackBuild = true; -LAYER_NUM g_Route_Layer_TOP; -LAYER_NUM g_Route_Layer_BOTTOM; -int g_MaxLinksShowed; -int g_MagneticPadOption = capture_cursor_in_track_tool; -int g_MagneticTrackOption = capture_cursor_in_track_tool; +LAYER_NUM g_Route_Layer_TOP; +LAYER_NUM g_Route_Layer_BOTTOM; +int g_MaxLinksShowed; +int g_MagneticPadOption = capture_cursor_in_track_tool; +int g_MagneticTrackOption = capture_cursor_in_track_tool; -wxPoint g_Offset_Module; /* Distance to offset module trace when moving. */ +wxPoint g_Offset_Module; /* Distance to offset module trace when moving. */ /* Name of the document footprint list * usually located in share/modules/footprints_doc * this is of the responsibility to users to create this file * if they want to have a list of footprints */ -wxString g_DocModulesFileName = wxT( "footprints_doc/footprints.pdf" ); +wxString g_DocModulesFileName = wxT( "footprints_doc/footprints.pdf" ); // wxWindow* DoPythonStuff(wxWindow* parent); // declaration -IMPLEMENT_APP( EDA_APP ) +namespace PCB { - -/* MacOSX: Needed for file association - * http://wiki.wxwidgets.org/WxMac-specific_topics - */ -void EDA_APP::MacOpenFile( const wxString& aFileName ) +static struct IFACE : public KIFACE_I { - PCB_EDIT_FRAME* frame = ( (PCB_EDIT_FRAME*) GetTopWindow() ); - wxFileName filename = aFileName; + // Of course all are virtual overloads, implementations of the KIFACE. - if( !filename.FileExists() ) - return; + IFACE( const char* aName, KIWAY::FACE_T aType ) : + KIFACE_I( aName, aType ) + {} - frame->LoadOnePcbFile( aFileName, false ); + bool OnKifaceStart( PGM_BASE* aProgram ); + + void OnKifaceEnd(); + + wxWindow* CreateWindow( wxWindow* aParent, int aClassId, KIWAY* aKiway, int aCtlBits = 0 ) + { + switch( aClassId ) + { + + case PCB_FRAME_TYPE: + { + PCB_EDIT_FRAME* frame = new PCB_EDIT_FRAME( aKiway, aParent ); + + frame->Zoom_Automatique( true ); + +#ifdef KICAD_SCRIPTING + // give the scripting helpers access to our frame + ScriptingSetPcbEditFrame( frame ); +#endif + + // @todo temporarily here + CreateServer( frame, KICAD_PCB_PORT_SERVICE_NUMBER ); + + return frame; + } + break; + + case MODULE_EDITOR_FRAME_TYPE: + { + // yuck: + PCB_EDIT_FRAME* editor = dynamic_cast( aParent ); + wxASSERT( editor ); + + FOOTPRINT_EDIT_FRAME* frame = new FOOTPRINT_EDIT_FRAME( aKiway, editor ); + + frame->Zoom_Automatique( true ); + + /* Read a default config file in case no project given on command line. + frame->LoadProjectFile( wxEmptyString, true ); + */ + + return frame; + } + break; + + case MODULE_VIEWER_FRAME_TYPE: + { + // yuck: + PCB_BASE_FRAME* editor = dynamic_cast( aParent ); + wxASSERT( editor ); + + FOOTPRINT_VIEWER_FRAME* frame = new FOOTPRINT_VIEWER_FRAME( aKiway, editor ); + + frame->Zoom_Automatique( true ); + + /* Read a default config file in case no project given on command line. + frame->LoadProjectFile( wxEmptyString, true ); + */ + + return frame; + } + break; + + default: + ; + } + + return NULL; + } + + /** + * Function IfaceOrAddress + * return a pointer to the requested object. The safest way to use this + * is to retrieve a pointer to a static instance of an interface, similar to + * how the KIFACE interface is exported. But if you know what you are doing + * use it to retrieve anything you want. + * + * @param aDataId identifies which object you want the address of. + * + * @return void* - and must be cast into the know type. + */ + void* IfaceOrAddress( int aDataId ) + { + return NULL; + } + +} kiface( "pcbnew", KIWAY::FACE_PCB ); + +} // namespace + +using namespace PCB; + + +static PGM_BASE* process; + + +KIFACE_I& Kiface() { return kiface; } + + +// KIFACE_GETTER's actual spelling is a substitution macro found in kiway.h. +// KIFACE_GETTER will not have name mangling due to declaration in kiway.h. +MY_API( KIFACE* ) KIFACE_GETTER( int* aKIFACEversion, int aKiwayVersion, PGM_BASE* aProgram ) +{ + process = (PGM_BASE*) aProgram; + return &kiface; } -bool EDA_APP::OnInit() +PGM_BASE& Pgm() { - wxFileName fn; - PCB_EDIT_FRAME* frame = NULL; - wxString msg; + wxASSERT( process ); // KIFACE_GETTER has already been called. + return *process; +} + + +/** + * Function set3DShapesPath + * attempts to set the environment variable given by aKiSys3Dmod to a valid path. + * (typically "KISYS3DMOD" ) + * If the environment variable is already set, + * then it left as is to respect the wishes of the user. + * + * The path is determined by attempting to find the path modules/packages3d + * files in kicad tree. + * This may or may not be the best path but it provides the best solution for + * backwards compatibility with the previous 3D shapes search path implementation. + * + * @note This must be called after #SetBinDir() is called at least on Windows. + * Otherwise, the kicad path is not known (Windows specific) + * + * @param aKiSys3Dmod = the value of environment variable, typically "KISYS3DMOD" + * @return false if the aKiSys3Dmod path is not valid. + */ +static bool set3DShapesPath( const wxString& aKiSys3Dmod ) +{ + wxString path; + + // Set the KISYS3DMOD environment variable for the current process, + // if it is not already defined in the user's environment and valid. + if( wxGetEnv( aKiSys3Dmod, &path ) && wxFileName::DirExists( path ) ) + return true; + + // Attempt to determine where the 3D shape libraries were installed using the + // legacy path: + // on Unix: /usr/local/kicad/share/modules/packages3d + // or /usr/share/kicad/modules/packages3d + // On Windows: bin../share/modules/packages3d + wxString relpath( wxT( "modules/packages3d" ) ); + +// Apple MacOSx +#ifdef __WXMAC__ + path = wxT("/Library/Application Support/kicad/modules/packages3d/"); + + if( wxFileName::DirExists( path ) ) + { + wxSetEnv( aKiSys3Dmod, path ); + return true; + } + + path = wxString( wxGetenv( wxT( "HOME" ) ) ) + wxT("/Library/Application Support/kicad/modules/packages3d/"); + + if( wxFileName::DirExists( path ) ) + { + wxSetEnv( aKiSys3Dmod, path ); + return true; + } + +#elif defined(__UNIX__) // Linux and non-Apple Unix + // Try the home directory: + path.Empty(); + wxGetEnv( wxT("HOME"), &path ); + path += wxT("/kicad/share/") + relpath; + + if( wxFileName::DirExists( path ) ) + { + wxSetEnv( aKiSys3Dmod, path ); + return true; + } + + // Try the standard install path: + path = wxT("/usr/local/kicad/share/") + relpath; + + if( wxFileName::DirExists( path ) ) + { + wxSetEnv( aKiSys3Dmod, path ); + return true; + } + + // Try the official distrib standard install path: + path = wxT("/usr/share/kicad/") + relpath; + + if( wxFileName::DirExists( path ) ) + { + wxSetEnv( aKiSys3Dmod, path ); + return true; + } + +#else // Windows + // On Windows, the install path is given by the path of executables + wxFileName fn; + fn.AssignDir( Pgm().GetExecutablePath() ); + fn.RemoveLastDir(); + path = fn.GetPathWithSep() + wxT("share/") + relpath; + + if( wxFileName::DirExists( path ) ) + { + wxSetEnv( aKiSys3Dmod, path ); + return true; + } +#endif + + return false; +} - InitEDA_Appl( wxT( "Pcbnew" ), APP_PCBNEW_T ); #ifdef KICAD_SCRIPTING - msg.Empty(); -#ifdef __WINDOWS__ +static bool scriptingSetup() +{ + wxString path_frag; + + #ifdef __MINGW32__ // force python environment under Windows: - const wxString python_us("python27_us"); + const wxString python_us( "python27_us" ); // Build our python path inside kicad - wxString kipython = m_BinDir + python_us; + wxString kipython = FindKicadFile( python_us + wxT("/python.exe") ); + + //we need only the path: + wxFileName fn( kipython ); + kipython = fn.GetPath(); // If our python install is existing inside kicad, use it if( wxDirExists( kipython ) ) { wxString ppath; + if( !wxGetEnv( wxT( "PYTHONPATH" ), &ppath ) || !ppath.Contains( python_us ) ) { ppath << kipython << wxT("/pylib;"); @@ -151,218 +364,126 @@ bool EDA_APP::OnInit() // which are ( [KICAD_PATH] is an environment variable to define) // [KICAD_PATH]/scripting/plugins // Add this default search path: - msg = wxGetApp().GetExecutablePath() + wxT("scripting/plugins"); -#else + path_frag = Pgm().GetExecutablePath() + wxT( "scripting/plugins" ); + #else // Add this default search path: - msg = wxT("/usr/local/kicad/bin/scripting/plugins"); + path_frag = wxT( "/usr/local/kicad/bin/scripting/plugins" ); -#ifdef __WXMAC__ + #ifdef __WXMAC__ // OSX // System Library first // User Library then // (TODO) Bundle package ? where to place ? Shared Support ? - msg = wxT("/Library/Application Support/kicad/scripting"); - msg = wxString( wxGetenv("HOME") ) + wxT("/Library/Application Support/kicad/scripting"); + path_frag = wxT( "/Library/Application Support/kicad/scripting" ); + path_frag = wxString( wxGetenv("HOME") ) + wxT( "/Library/Application Support/kicad/scripting" ); // Get pcbnew.app/Contents directory wxFileName bundledir( wxStandardPaths::Get().GetExecutablePath() ) ; bundledir.RemoveLastDir(); // Prepend in PYTHONPATH the content of the bundle libraries ! - wxSetEnv("PYTHONPATH",((wxGetenv("PYTHONPATH") != NULL ) ? (wxString(wxGetenv("PYTHONPATH")) + ":") : wxString("")) + - bundledir.GetPath() + - "/Frameworks/wxPython/lib/python2.6/site-packages/wx-3.0-osx_cocoa" + ":" + - "/Library/Application Support/kicad/" + ":" + - bundledir.GetPath() + "/PlugIns" + ":" + - wxString( wxGetenv("HOME") ) + "/Library/Application Support/kicad/" - ); -#endif -#endif + wxSetEnv( "PYTHONPATH", ((wxGetenv("PYTHONPATH") != NULL ) ? (wxString(wxGetenv("PYTHONPATH")) + ":") : wxString("")) + + bundledir.GetPath() + + "/Frameworks/wxPython/lib/python2.6/site-packages/wx-3.0-osx_cocoa" + ":" + + "/Library/Application Support/kicad/" + ":" + + bundledir.GetPath() + "/PlugIns" + ":" + + wxString( wxGetenv("HOME") ) + "/Library/Application Support/kicad/" + ); + #endif + #endif + // On linux and osx, 2 others paths are // [HOME]/.kicad_plugins/ // [HOME]/.kicad/scripting/plugins/ - if ( !pcbnewInitPythonScripting( TO_UTF8(msg) ) ) + if( !pcbnewInitPythonScripting( TO_UTF8( path_frag ) ) ) { - wxMessageBox( wxT( "pcbnewInitPythonScripting() fails" ) ); + wxLogSysError( wxT( "pcbnewInitPythonScripting() failed." ) ); return false; } -#endif + return true; +} +#endif // KICAD_SCRIPTING - if( argc > 1 ) - { - fn = argv[1]; - // Be sure the filename is absolute, to avoid issues - // when the filename is relative, - // for instance when stored in history list without path, - // and when building the config filename ( which should have a path ) - if( fn.IsRelative() ) - fn.MakeAbsolute(); +/// The global footprint library table. This is not dynamically allocated because +/// in a multiple project environment we must keep its address constant (since it is +/// the fallback table for multiple projects). +FP_LIB_TABLE GFootprintTable; - if( fn.GetExt() != PcbFileExtension && fn.GetExt() != LegacyPcbFileExtension ) - { - msg.Printf( _( "Pcbnew file <%s> has a wrong extension.\n" - "Changing extension to .%s." ), - GetChars( fn.GetFullPath() ), - GetChars( PcbFileExtension ) ); - fn.SetExt( PcbFileExtension ); - wxMessageBox( msg ); - } - if( !wxGetApp().LockFile( fn.GetFullPath() ) ) - { - DisplayError( NULL, _( "This file is already open." ) ); - return false; - } - } +bool IFACE::OnKifaceStart( PGM_BASE* aProgram ) +{ + // This is process level, not project level, initialization of the DSO. - if( m_Checker && m_Checker->IsAnotherRunning() ) - { - if( !IsOK( NULL, _( "Pcbnew is already running, Continue?" ) ) ) - return false; - } + // Do nothing in here pertinent to a project! - // read current setup and reopen last directory if no filename to open in command line - bool reopenLastUsedDirectory = argc == 1; - GetSettings( reopenLastUsedDirectory ); + start_common(); - if( fn.IsOk() && fn.DirExists() ) - wxSetWorkingDirectory( fn.GetPath() ); + // Must be called before creating the main frame in order to + // display the real hotkeys in menus or tool tips + ReadHotkeyConfig( wxT( "PcbFrame" ), g_Board_Editor_Hokeys_Descr ); + + // Set 3D shape path from environment variable KISYS3DMOD + set3DShapesPath( wxT(KISYS3DMOD) ); + + /* Now that there are no *.mod files in the standard library, this function + has no utility. User should simply set the variable manually. + Looking for *.mod files which do not exist is fruitless. + + SetFootprintLibTablePath(); + */ g_DrawBgColor = BLACK; - /* Must be called before creating the main frame in order to - * display the real hotkeys in menus or tool tips */ - ReadHotkeyConfig( wxT( "PcbFrame" ), g_Board_Editor_Hokeys_Descr ); - - // Set any environment variables before loading FP_LIB_TABLE - SetFootprintLibTablePath(); - - // Set 3D shape path from environment variable KISYS3DMOD - Set3DShapesPath( wxT(KISYS3DMOD) ); - - frame = new PCB_EDIT_FRAME( NULL, wxT( "Pcbnew" ), wxPoint( 0, 0 ), wxSize( 600, 400 ) ); - -#ifdef KICAD_SCRIPTING - ScriptingSetPcbEditFrame(frame); /* give the scripting helpers access to our frame */ -#endif - - frame->UpdateTitle(); - - SetTopWindow( frame ); - frame->Show( true ); - - CreateServer( frame, KICAD_PCB_PORT_SERVICE_NUMBER ); - - frame->Zoom_Automatique( true ); - - // Load config and default values before loading a board file - // Some will be overwritten after loading the board file - frame->LoadProjectSettings( fn.GetFullPath() ); - - /* Load file specified in the command line. */ - if( fn.IsOk() ) + try { - /* Note the first time Pcbnew is called after creating a new project - * the board file may not exist so we load settings only. - * However, because legacy board files are named *.brd, - * and new files are named *.kicad_pcb, - * for all previous projects ( before 2012, december 14 ), - * because KiCad manager ask to load a .kicad_pcb file - * if this file does not exist, it is certainly useful - * to test if a legacy file is existing, - * under the same name, and therefore if the user want to load it - */ - bool file_exists = false; + // The global table is not related to a specific project. All projects + // will use the same global table. So the KIFACE::OnKifaceStart() contract + // of avoiding anything project specific is not violated here. - if( fn.FileExists() ) + if( !FP_LIB_TABLE::LoadGlobalTable( GFootprintTable ) ) { - file_exists = true; - frame->LoadOnePcbFile( fn.GetFullPath() ); - } - else if( fn.GetExt() == KiCadPcbFileExtension ) - { - // Try to find a legacy file with the same name: - wxFileName fn_legacy = fn; - fn_legacy.SetExt( LegacyPcbFileExtension ); - - if( fn_legacy.FileExists() ) - { - msg.Printf( _( "File <%s> does not exist.\n" - "However a legacy file <%s> exists.\n" - "Do you want to load it?\n" - "It will be saved under the new file format." ), - GetChars( fn.GetFullPath() ), - GetChars( fn_legacy.GetFullPath() ) ); - - if( IsOK( frame, msg ) ) - { - file_exists = true; - frame->LoadOnePcbFile( fn_legacy.GetFullPath() ); - wxString filename = fn.GetFullPath(); - filename.Replace( WIN_STRING_DIR_SEP, UNIX_STRING_DIR_SEP ); - frame->GetBoard()->SetFileName( filename ); - frame->UpdateTitle(); - frame->OnModify(); // Ready to save the board under the new format - } - } - } - - if( ! file_exists ) - { - // File does not exists: prepare an empty board - if( ! fn.GetPath().IsEmpty() ) - wxSetWorkingDirectory( fn.GetPath() ); - - frame->GetBoard()->SetFileName( fn.GetFullPath( wxPATH_UNIX ) ); - frame->UpdateTitle(); - frame->UpdateFileHistory( frame->GetBoard()->GetFileName() ); - frame->OnModify(); // Ready to save the new empty board - - msg.Printf( _( "File <%s> does not exist.\nThis is normal for a new project" ), - GetChars( frame->GetBoard()->GetFileName() ) ); - wxMessageBox( msg ); + DisplayInfoMessage( NULL, wxT( + "You have run Pcbnew for the first time using the " + "new footprint library table method for finding " + "footprints. Pcbnew has either copied the default " + "table or created an empty table in your home " + "folder. You must first configure the library " + "table to include all footprint libraries not " + "included with KiCad. See the \"Footprint Library " + "Table\" section of the CvPcb documentation for " + "more information." ) ); } } + catch( const IO_ERROR& ioe ) + { + wxString msg = wxString::Format( _( + "An error occurred attempting to load the global footprint library " + "table:\n\n%s" ), + GetChars( ioe.errorText ) + ); + DisplayError( NULL, msg ); + return false; + } - else - // No file to open: initialize a new empty board - // using default values for design settings: - frame->Clear_Pcb( false ); - - // update the layer names in the listbox - frame->ReCreateLayerBox( false ); - - /* For an obscure reason the focus is lost after loading a board file - * when starting (i.e. only at this point) - * (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. - */ - frame->SetFocus(); - frame->GetCanvas()->SetFocus(); +#ifdef KICAD_SCRIPTING + scriptingSetup(); +#endif return true; } -#if 0 -// for some reason KiCad classes do not implement OnExit -// if I add it in the declaration, I need to fix it in every application -// so for now make a note TODO TODO -// we need to clean up python when the application exits -int EDA_APP::OnExit() +void IFACE::OnKifaceEnd() { - // Restore the thread state and tell Python to cleanup after itself. - // wxPython will do its own cleanup as part of that process. This is done - // in OnExit instead of ~MyApp because OnExit is only called if OnInit is - // successful. + end_common(); + #if KICAD_SCRIPTING_WXPYTHON + // Restore the thread state and tell Python to cleanup after itself. + // wxPython will do its own cleanup as part of that process. + // This should only be called if python was setup correctly. + pcbnewFinishPythonScripting(); -#endif - return 0; -} #endif +} diff --git a/pcbnew/pcbnew_config.cpp b/pcbnew/pcbnew_config.cpp index 46315ab1da..0a8934f528 100644 --- a/pcbnew/pcbnew_config.cpp +++ b/pcbnew/pcbnew_config.cpp @@ -29,7 +29,9 @@ */ #include -#include +//#include +#include +#include #include #include #include @@ -80,13 +82,13 @@ void PCB_EDIT_FRAME::Process_Config( wxCommandEvent& event ) 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(); + 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: InstallDialogLayerSetup(); @@ -95,21 +97,24 @@ void PCB_EDIT_FRAME::Process_Config( wxCommandEvent& event ) case ID_PCB_LIB_TABLE_EDIT: { bool tableChanged = false; - int r = InvokePcbLibTableEditor( this, m_globalFootprintTable, m_footprintLibTable ); + int r = InvokePcbLibTableEditor( this, &GFootprintTable, FootprintLibs() ); if( r & 1 ) { try { FILE_OUTPUTFORMATTER sf( FP_LIB_TABLE::GetGlobalTableFileName() ); - m_globalFootprintTable->Format( &sf, 0 ); + + GFootprintTable.Format( &sf, 0 ); tableChanged = true; } - catch( IO_ERROR& ioe ) + catch( const IO_ERROR& ioe ) { - wxString msg; - msg.Printf( _( "Error occurred saving the global footprint library " - "table:\n\n%s" ), ioe.errorText.GetData() ); + 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 ); } } @@ -118,25 +123,29 @@ void PCB_EDIT_FRAME::Process_Config( wxCommandEvent& event ) // is kept in memory and created in the path when the new board is saved. if( (r & 2) && !GetBoard()->GetFileName().IsEmpty() ) { - wxFileName fn = GetBoard()->GetFileName(); + wxString tblName = Prj().FootprintLibTblName(); try { - m_footprintLibTable->Save( fn ); + FootprintLibs()->Save( tblName ); tableChanged = true; } - catch( IO_ERROR& ioe ) + catch( const IO_ERROR& ioe ) { - wxString msg; - msg.Printf( _( "Error occurred saving project specific footprint library " - "table:\n\n%s" ), ioe.errorText.GetData() ); + 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 ); } } - if( tableChanged && FOOTPRINT_VIEWER_FRAME::GetActiveFootprintViewer() != NULL ) + FOOTPRINT_VIEWER_FRAME* viewer; + + if( tableChanged && (viewer = FOOTPRINT_VIEWER_FRAME::GetActiveFootprintViewer( this )) != NULL ) { - FOOTPRINT_VIEWER_FRAME::GetActiveFootprintViewer()->ReCreateLibraryList(); + viewer->ReCreateLibraryList(); } } break; @@ -164,27 +173,27 @@ void PCB_EDIT_FRAME::Process_Config( wxCommandEvent& event ) 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; - msg.Printf( _( "File %s not found" ), GetChars( dlg.GetPath() ) ); - DisplayError( this, msg ); - break; - } + fn = GetBoard()->GetFileName(); + fn.SetExt( ProjectFileExtension ); - LoadProjectSettings( dlg.GetPath() ); - } + 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; + msg.Printf( _( "File %s not found" ), GetChars( dlg.GetPath() ) ); + DisplayError( this, msg ); + break; + } + + LoadProjectSettings( dlg.GetPath() ); + } break; // Hotkey IDs @@ -222,19 +231,15 @@ void PCB_EDIT_FRAME::Process_Config( wxCommandEvent& event ) bool PCB_EDIT_FRAME::LoadProjectSettings( const wxString& aProjectFileName ) { - wxLogDebug( wxT( "Loading project <%s> settings." ), GetChars( aProjectFileName ) ); + wxLogDebug( wxT( "Loading project '%s' settings." ), GetChars( aProjectFileName ) ); - wxFileName fn = aProjectFileName; + wxFileName fn = aProjectFileName; if( fn.GetExt() != ProjectFileExtension ) fn.SetExt( ProjectFileExtension ); - wxGetApp().RemoveLibraryPath( g_UserLibDirBuffer ); - - wxGetApp().ReadProjectConfig( fn.GetFullPath(), GROUP, GetProjectFileParameters(), false ); - - // User library path takes precedent over default library search paths. - wxGetApp().InsertLibraryPath( g_UserLibDirBuffer, 1 ); + // was: wxGetApp().ReadProjectConfig( fn.GetFullPath(), GROUP, GetProjectFileParameters(), false ); + Prj().ConfigLoad( Kiface().KifaceSearch(), fn.GetFullPath(), GROUP, GetProjectFileParameters(), false ); // Dick 5-Feb-2012: I don't agree with this, the BOARD contents should dictate // what is visible or not, even initially. And since PCB_EDIT_FRAME projects settings @@ -255,38 +260,19 @@ bool PCB_EDIT_FRAME::LoadProjectSettings( const wxString& aProjectFileName ) SetElementVisibility( RATSNEST_VISIBLE, showRats ); #endif - fn = GetBoard()->GetFileName(); + wxString projectFpLibTableFileName = Prj().FootprintLibTblName(); - // Check if a project footprint table is defined and load it. If no project footprint - // table is defined, then the global library table is the footprint library table. - FP_LIB_TABLE::SetProjectPathEnvVariable( fn ); - - delete m_footprintLibTable; - - wxFileName projectFpLibTableFileName; - - projectFpLibTableFileName = FP_LIB_TABLE::GetProjectFileName( fn ); - m_footprintLibTable = new FP_LIB_TABLE(); + FootprintLibs()->Clear(); try { - m_footprintLibTable->Load( projectFpLibTableFileName, m_globalFootprintTable ); + FootprintLibs()->Load( projectFpLibTableFileName ); } - catch( IO_ERROR ioe ) + catch( const IO_ERROR& ioe ) { DisplayError( this, ioe.errorText ); } - FOOTPRINT_EDIT_FRAME* editFrame = FOOTPRINT_EDIT_FRAME::GetActiveFootprintEditor(); - - if( editFrame ) - editFrame->SetFootprintLibTable( m_footprintLibTable ); - - FOOTPRINT_VIEWER_FRAME* viewFrame = FOOTPRINT_VIEWER_FRAME::GetActiveFootprintViewer(); - - if( viewFrame ) - viewFrame->SetFootprintLibTable( m_footprintLibTable ); - // Load the page layout decr file, from the filename stored in // BASE_SCREEN::m_PageLayoutDescrFileName, read in config project file // If empty, the default descr is loaded @@ -313,11 +299,12 @@ void PCB_EDIT_FRAME::SaveProjectSettings( bool aAskForSave ) if( dlg.ShowModal() == wxID_CANCEL ) return; - wxGetApp().WriteProjectConfig( dlg.GetPath(), GROUP, GetProjectFileParameters() ); + fn = dlg.GetPath(); } - else - wxGetApp().WriteProjectConfig( fn.GetFullPath(), GROUP, GetProjectFileParameters() ); + SEARCH_STACK& search = Kiface().KifaceSearch(); + + Prj().ConfigSave( search, fn.GetFullPath(), GROUP, GetProjectFileParameters() ); } diff --git a/pcbnew/pcbnew_config.h b/pcbnew/pcbnew_config.h index 7f430b2a88..a0b0006bbd 100644 --- a/pcbnew/pcbnew_config.h +++ b/pcbnew/pcbnew_config.h @@ -6,7 +6,7 @@ #ifndef _PCBNEW_CONFIG_H_ #define _PCBNEW_CONFIG_H_ -#include +#include #include #define GROUP wxT( "/pcbnew" ) diff --git a/pcbnew/plot_brditems_plotter.cpp b/pcbnew/plot_brditems_plotter.cpp index 8e891fbe8e..32f9209938 100644 --- a/pcbnew/plot_brditems_plotter.cpp +++ b/pcbnew/plot_brditems_plotter.cpp @@ -66,7 +66,7 @@ EDA_COLOR_T BRDITEMS_PLOTTER::getColor( LAYER_NUM aLayer ) void BRDITEMS_PLOTTER::PlotPad( D_PAD* aPad, EDA_COLOR_T aColor, EDA_DRAW_MODE_T aPlotMode ) { - wxPoint shape_pos = aPad->ReturnShapePos(); + wxPoint shape_pos = aPad->ShapePos(); // Set plot color (change WHITE to LIGHTGRAY because // the white items are not seen on a white paper or screen diff --git a/pcbnew/printout_controler.cpp b/pcbnew/printout_controler.cpp index 3ee6e390f0..092304298c 100644 --- a/pcbnew/printout_controler.cpp +++ b/pcbnew/printout_controler.cpp @@ -32,7 +32,7 @@ #define wxTEST_POSTSCRIPT_IN_MSW 1 #include -#include +#include #include #include #include diff --git a/pcbnew/printout_controler.h b/pcbnew/printout_controler.h index a31ccad559..83745c70e1 100644 --- a/pcbnew/printout_controler.h +++ b/pcbnew/printout_controler.h @@ -34,6 +34,8 @@ #include #include +#include + #define DEFAULT_ORIENTATION_PAPER wxLANDSCAPE // other option is wxPORTRAIT @@ -98,7 +100,6 @@ public: * is a class derived from wxPrintout to handle the necessary information to control a printer * when printing a board */ - class BOARD_PRINTOUT_CONTROLLER : public wxPrintout { private: diff --git a/pcbnew/router/pns_line_placer.cpp b/pcbnew/router/pns_line_placer.cpp index a03183c45c..4b9b616f3e 100644 --- a/pcbnew/router/pns_line_placer.cpp +++ b/pcbnew/router/pns_line_placer.cpp @@ -31,6 +31,8 @@ using boost::optional; +const double PNS_LINE_PLACER::m_shoveLengthThreshold = 1.7; + PNS_LINE_PLACER::PNS_LINE_PLACER( PNS_NODE* aWorld ) { m_initial_direction = DIRECTION_45( DIRECTION_45::N ); diff --git a/pcbnew/router/pns_line_placer.h b/pcbnew/router/pns_line_placer.h index e4ab966e59..625e6451b2 100644 --- a/pcbnew/router/pns_line_placer.h +++ b/pcbnew/router/pns_line_placer.h @@ -111,7 +111,7 @@ public: PNS_NODE* GetCurrentNode() const; private: - static const double m_shoveLengthThreshold = 1.7; + static const double m_shoveLengthThreshold; bool handleViaPlacement( PNS_LINE& aHead ); diff --git a/pcbnew/scripting/pcbnew_footprint_wizards.cpp b/pcbnew/scripting/pcbnew_footprint_wizards.cpp index 8b74d4ac70..70e2238d34 100644 --- a/pcbnew/scripting/pcbnew_footprint_wizards.cpp +++ b/pcbnew/scripting/pcbnew_footprint_wizards.cpp @@ -81,7 +81,9 @@ PyObject* PYTHON_FOOTPRINT_WIZARD::CallMethod( const char* aMethod, PyObject* aA } if( pFunc ) + { Py_XDECREF( pFunc ); + } return NULL; } diff --git a/pcbnew/scripting/plugins/FPC_(SMD_type)_footprintwizard.py b/pcbnew/scripting/plugins/FPC_(SMD_type)_footprintwizard.py index 0cace0dfb1..f751c47f38 100644 --- a/pcbnew/scripting/plugins/FPC_(SMD_type)_footprintwizard.py +++ b/pcbnew/scripting/plugins/FPC_(SMD_type)_footprintwizard.py @@ -104,10 +104,13 @@ class FPCFootprintWizard(FootprintWizardPlugin): module.Add(pad) + # Mechanical shield pads: left pad and right pad xpos = -shl_to_pad-offsetX - pad_s0 = self.smdRectPad(module, size_shld, wxPoint(xpos,shl_from_top), "0") + pad_s0_pos = wxPoint(xpos,shl_from_top) + pad_s0 = self.smdRectPad(module, size_shld, pad_s0_pos, "0") xpos = (pads-1)*pad_pitch+shl_to_pad-offsetX - pad_s1 = self.smdRectPad(module, size_shld, wxPoint(xpos,shl_from_top), "0") + pad_s1_pos = wxPoint(xpos,shl_from_top) + pad_s1 = self.smdRectPad(module, size_shld, pad_s1_pos, "0") module.Add(pad_s0) module.Add(pad_s1) @@ -115,21 +118,81 @@ class FPCFootprintWizard(FootprintWizardPlugin): #add outline outline = EDGE_MODULE(module) linewidth = FromMM(0.2) - posy = -pad_height/2 - linewidth/2 -FromMM(0.2) - outline.SetStartEnd(wxPoint(pad_pitch * pads - pad_pitch*0.5-offsetX, posy), - wxPoint( - pad_pitch*0.5-offsetX, posy)) outline.SetWidth(linewidth) + margin = FromMM(0.2) + + # upper line + posy = -pad_height/2 - linewidth/2 - margin + xstart = - pad_pitch*0.5-offsetX + xend = pad_pitch * pads + xstart; + outline.SetStartEnd( wxPoint(xstart, posy), wxPoint( xend, posy) ) outline.SetLayer(SILKSCREEN_N_FRONT) #default: not needed outline.SetShape(S_SEGMENT) module.Add(outline) + # lower line outline1 = EDGE_MODULE(module) outline1.Copy(outline) #copy all settings from outline - posy = pad_height/2 + linewidth/2 +FromMM(0.2) - outline1.SetStartEnd(wxPoint(pad_pitch * pads - pad_pitch*0.5-offsetX, posy), - wxPoint( - pad_pitch*0.5-offsetX, posy)) + posy = pad_height/2 + linewidth/2 + margin + outline1.SetStartEnd(wxPoint(xstart, posy), wxPoint( xend, posy)) module.Add(outline1) + # around left mechanical pad (the outline around right pad is mirrored/y axix) + outline2 = EDGE_MODULE(module) # vertical segment + outline2.Copy(outline) + yend = pad_s0_pos.y + shl_height/2 + margin + outline2.SetStartEnd(wxPoint(xstart, posy), wxPoint( xstart, yend)) + module.Add(outline2) + outline2_d = EDGE_MODULE(module) # right pad side + outline2_d.Copy(outline2) + outline2_d.SetStartEnd(wxPoint(-xstart, posy), wxPoint( -xstart, yend)) + module.Add(outline2_d) + + outline3 = EDGE_MODULE(module) # horizontal segment below the pad + outline3.Copy(outline) + posy = yend + xend = pad_s0_pos.x - (shl_width/2 + linewidth + margin*2) + outline3.SetStartEnd(wxPoint(xstart, posy), wxPoint( xend, posy)) + module.Add(outline3) + outline3_d = EDGE_MODULE(module) # right pad side + outline3_d.Copy(outline3) + outline3_d.SetStartEnd(wxPoint(-xstart, posy), wxPoint( -xend, yend)) + module.Add(outline3_d) + + outline4 = EDGE_MODULE(module) # vertical segment at left of the pad + outline4.Copy(outline) + xstart = xend + yend = posy - (shl_height + linewidth + margin*2) + outline4.SetStartEnd(wxPoint(xstart, posy), wxPoint( xend, yend)) + module.Add(outline4) + outline4_d = EDGE_MODULE(module) # right pad side + outline4_d.Copy(outline4) + outline4_d.SetStartEnd(wxPoint(-xstart, posy), wxPoint( -xend, yend)) + module.Add(outline4_d) + + outline5 = EDGE_MODULE(module) # horizontal segment above the pad + outline5.Copy(outline) + xstart = xend + xend = - pad_pitch*0.5-offsetX + posy = yend + outline5.SetStartEnd(wxPoint(xstart, posy), wxPoint( xend, yend)) + module.Add(outline5) + outline5_d = EDGE_MODULE(module) # right pad side + outline5_d.Copy(outline5) + outline5_d.SetStartEnd(wxPoint(-xstart, posy), wxPoint( -xend, yend)) + module.Add(outline5_d) + + outline6 = EDGE_MODULE(module) # vertical segment above the pad + outline6.Copy(outline) + xstart = xend + yend = -pad_height/2 - linewidth/2 - margin + outline6.SetStartEnd(wxPoint(xstart, posy), wxPoint( xend, yend)) + module.Add(outline6) + outline6_d = EDGE_MODULE(module) # right pad side + outline6_d.Copy(outline6) + outline6_d.SetStartEnd(wxPoint(-xstart, posy), wxPoint( -xend, yend)) + module.Add(outline6_d) + # create our footprint wizard fpc_wizard = FPCFootprintWizard() diff --git a/pcbnew/specctra_export.cpp b/pcbnew/specctra_export.cpp index 2ac40ef5af..c9a85591d6 100644 --- a/pcbnew/specctra_export.cpp +++ b/pcbnew/specctra_export.cpp @@ -132,6 +132,11 @@ void PCB_EDIT_FRAME::ExportToSpecctra( wxCommandEvent& event ) if( fullFileName == wxEmptyString ) return; + ExportSpecctraFile( fullFileName ); +} + +bool PCB_EDIT_FRAME::ExportSpecctraFile( const wxString& aFullFilename ) +{ SPECCTRA_DB db; bool ok = true; wxString errorText; @@ -152,7 +157,7 @@ void PCB_EDIT_FRAME::ExportToSpecctra( wxCommandEvent& event ) { GetBoard()->SynchronizeNetsAndNetClasses(); db.FromBOARD( GetBoard() ); - db.ExportPCB( fullFileName, true ); + db.ExportPCB( aFullFilename, true ); // if an exception is thrown by FromBOARD or ExportPCB(), then // ~SPECCTRA_DB() will close the file. @@ -184,6 +189,8 @@ void PCB_EDIT_FRAME::ExportToSpecctra( wxCommandEvent& event ) errorText += _( "Unable to export, please fix and try again." ); DisplayError( this, errorText ); } + + return ok; } @@ -832,7 +839,7 @@ PADSTACK* SPECCTRA_DB::makeVia( const SEGVIA* aVia ) LAYER_NUM topLayerNum; LAYER_NUM botLayerNum; - aVia->ReturnLayerPair( &topLayerNum, &botLayerNum ); + aVia->LayerPair( &topLayerNum, &botLayerNum ); int topLayer = kicadLayer2pcb[topLayerNum]; int botLayer = kicadLayer2pcb[botLayerNum]; diff --git a/pcbnew/swap_layers.cpp b/pcbnew/swap_layers.cpp index 73d3347efa..11180b107b 100644 --- a/pcbnew/swap_layers.cpp +++ b/pcbnew/swap_layers.cpp @@ -367,7 +367,7 @@ void PCB_EDIT_FRAME::Swap_Layers( wxCommandEvent& event ) LAYER_NUM top_layer, bottom_layer; - Via->ReturnLayerPair( &top_layer, &bottom_layer ); + Via->LayerPair( &top_layer, &bottom_layer ); if( New_Layer[bottom_layer] >= 0 && New_Layer[bottom_layer] < LAYER_NO_CHANGE ) bottom_layer = New_Layer[bottom_layer]; diff --git a/pcbnew/target_edit.cpp b/pcbnew/target_edit.cpp index 75989719c9..5a0d860d30 100644 --- a/pcbnew/target_edit.cpp +++ b/pcbnew/target_edit.cpp @@ -99,11 +99,11 @@ TARGET_PROPERTIES_DIALOG_EDITOR::TARGET_PROPERTIES_DIALOG_EDITOR( PCB_EDIT_FRAME // Size: m_staticTextSizeUnits->SetLabel( GetUnitsLabel( g_UserUnit ) ); - m_TargetSizeCtrl->SetValue( ReturnStringFromValue( g_UserUnit, m_Target->GetSize() ) ); + m_TargetSizeCtrl->SetValue( StringFromValue( g_UserUnit, m_Target->GetSize() ) ); // Thickness: m_staticTextThicknessUnits->SetLabel( GetUnitsLabel( g_UserUnit ) ); - m_TargetThicknessCtrl->SetValue( ReturnStringFromValue( g_UserUnit, m_Target->GetWidth() ) ); + m_TargetThicknessCtrl->SetValue( StringFromValue( g_UserUnit, m_Target->GetWidth() ) ); // Shape m_TargetShape->SetSelection( m_Target->GetShape() ? 1 : 0 ); @@ -138,10 +138,10 @@ void TARGET_PROPERTIES_DIALOG_EDITOR::OnOkClick( wxCommandEvent& event ) m_Target->SetFlags( IN_EDIT ); // set flag in edit to force // undo/redo/abort proper operation - int tmp = ReturnValueFromString( g_UserUnit, m_TargetThicknessCtrl->GetValue() ); + int tmp = ValueFromString( g_UserUnit, m_TargetThicknessCtrl->GetValue() ); m_Target->SetWidth( tmp ); - MireDefaultSize = ReturnValueFromString( g_UserUnit, m_TargetSizeCtrl->GetValue() ); + MireDefaultSize = ValueFromString( g_UserUnit, m_TargetSizeCtrl->GetValue() ); m_Target->SetSize( MireDefaultSize ); m_Target->SetShape( m_TargetShape->GetSelection() ? 1 : 0 ); diff --git a/pcbnew/toolbars_update_user_interface.cpp b/pcbnew/toolbars_update_user_interface.cpp index b65328dcf5..ac2f65a490 100644 --- a/pcbnew/toolbars_update_user_interface.cpp +++ b/pcbnew/toolbars_update_user_interface.cpp @@ -30,7 +30,7 @@ */ #include -#include +#include #include #include #include <3d_viewer.h> diff --git a/pcbnew/tools/bright_box.cpp b/pcbnew/tools/bright_box.cpp index 689b6169b5..7901de2995 100644 --- a/pcbnew/tools/bright_box.cpp +++ b/pcbnew/tools/bright_box.cpp @@ -28,6 +28,9 @@ using namespace KIGFX; +const double BRIGHT_BOX::LINE_WIDTH = 100000.0; +const COLOR4D BRIGHT_BOX::BOX_COLOR = KIGFX::COLOR4D( 0.0, 1.0, 0.0, 1.0 ); + BRIGHT_BOX::BRIGHT_BOX( BOARD_ITEM* aItem ) : EDA_ITEM( NOT_USED ), // this item is never added to a BOARD so it needs no type m_item( aItem ) @@ -56,5 +59,3 @@ void BRIGHT_BOX::ViewDraw( int aLayer, GAL* aGal ) const } } - -const COLOR4D BRIGHT_BOX::BOX_COLOR = KIGFX::COLOR4D( 0.0, 1.0, 0.0, 1.0 ); diff --git a/pcbnew/tools/bright_box.h b/pcbnew/tools/bright_box.h index 8a6a583335..f75a7d0115 100644 --- a/pcbnew/tools/bright_box.h +++ b/pcbnew/tools/bright_box.h @@ -61,7 +61,7 @@ public: private: static const KIGFX::COLOR4D BOX_COLOR; - static const double LINE_WIDTH = 100000.0; + static const double LINE_WIDTH; BOARD_ITEM* m_item; }; diff --git a/pcbnew/tools/drawing_tool.cpp b/pcbnew/tools/drawing_tool.cpp index 30283cca17..61b3064783 100644 --- a/pcbnew/tools/drawing_tool.cpp +++ b/pcbnew/tools/drawing_tool.cpp @@ -696,7 +696,7 @@ int DRAWING_TOOL::PlaceModule( TOOL_EVENT& aEvent ) { // Init the new item attributes module = m_frame->LoadModuleFromLibrary( wxEmptyString, - m_frame->GetFootprintLibraryTable(), + m_frame->FootprintLibs(), true, NULL ); if( module == NULL ) continue; diff --git a/pcbnew/tools/selection_tool.cpp b/pcbnew/tools/selection_tool.cpp index 14f430fcca..cb37b23cdc 100644 --- a/pcbnew/tools/selection_tool.cpp +++ b/pcbnew/tools/selection_tool.cpp @@ -511,7 +511,7 @@ bool SELECTION_TOOL::selectable( const BOARD_ITEM* aItem ) const { // For vias it is enough if only one of layers is visible LAYER_NUM top, bottom; - static_cast( aItem )->ReturnLayerPair( &top, &bottom ); + static_cast( aItem )->LayerPair( &top, &bottom ); return board->IsLayerVisible( top ) || board->IsLayerVisible( bottom ); } diff --git a/pcbnew/xchgmod.cpp b/pcbnew/xchgmod.cpp index 74b5a58e0c..9f3c31f404 100644 --- a/pcbnew/xchgmod.cpp +++ b/pcbnew/xchgmod.cpp @@ -492,7 +492,7 @@ void DIALOG_EXCHANGE_MODULE::BrowseAndSelectFootprint( wxCommandEvent& event ) wxString newname; newname = m_parent->SelectFootprint( m_parent, wxEmptyString, wxEmptyString, wxEmptyString, - m_parent->GetFootprintLibraryTable() ); + m_parent->FootprintLibs() ); if( newname != wxEmptyString ) m_NewModule->SetValue( newname ); diff --git a/pcbnew/zones_by_polygon.cpp b/pcbnew/zones_by_polygon.cpp index 81719711f6..27a21869b4 100644 --- a/pcbnew/zones_by_polygon.cpp +++ b/pcbnew/zones_by_polygon.cpp @@ -29,7 +29,8 @@ */ #include -#include +//#include +#include #include #include #include @@ -205,8 +206,14 @@ static void Abort_Zone_Create_Outline( EDA_DRAW_PANEL* Panel, wxDC* DC ) if( zone ) { zone->DrawWhileCreateOutline( Panel, DC, GR_XOR ); - zone->ClearFlags(); zone->RemoveAllContours(); + if( zone->IsNew() ) + { + delete zone; + pcbframe->GetBoard()->m_CurrentZoneContour = NULL; + } + else + zone->ClearFlags(); } pcbframe->SetCurItem( NULL ); @@ -511,21 +518,26 @@ int PCB_EDIT_FRAME::Begin_Zone( wxDC* DC ) s_CurrentZone = NULL; } - // If no zone contour in progress, a new zone is being created: - if( !GetBoard()->m_CurrentZoneContour ) + ZONE_CONTAINER* zone = GetBoard()->m_CurrentZoneContour; + + // Verify if a new zone is allowed on this layer: + if( zone == NULL ) { - if( GetToolId() == ID_PCB_KEEPOUT_AREA_BUTT && - GetActiveLayer() >= FIRST_NON_COPPER_LAYER ) + if( GetToolId() == ID_PCB_KEEPOUT_AREA_BUTT && !IsCopperLayer( GetActiveLayer() ) ) { 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 no zone contour in progress, a new zone is being created, + if( zone == NULL ) + { + zone = GetBoard()->m_CurrentZoneContour = new ZONE_CONTAINER( GetBoard() ); + zone->SetFlags( IS_NEW ); + zone->SetTimeStamp( GetNewTimeStamp() ); + } if( zone->GetNumCorners() == 0 ) // Start a new contour: init zone params (net, layer ...) { @@ -545,26 +557,25 @@ int PCB_EDIT_FRAME::Begin_Zone( wxDC* DC ) if( GetBoard()->GetHighLightNetCode() > 0 ) { zoneInfo.m_NetcodeSelection = GetBoard()->GetHighLightNetCode(); - zone->SetNetCode( zoneInfo.m_NetcodeSelection ); } + double tmp = ZONE_THERMAL_RELIEF_GAP_MIL; - wxGetApp().GetSettings()->Read( ZONE_THERMAL_RELIEF_GAP_STRING_KEY, &tmp ); + + wxConfigBase* cfg = Kiface().KifaceSettings(); + cfg->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 ); + cfg->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 ); + cfg->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 ); + cfg->Read( ZONE_MIN_THICKNESS_WIDTH_STRING_KEY, &tmp ); zoneInfo.m_ZoneMinThickness = KiROUND( tmp * IU_PER_MILS ); zoneInfo.m_CurrentZone_Layer = zone->GetLayer(); @@ -594,11 +605,14 @@ int PCB_EDIT_FRAME::Begin_Zone( wxDC* DC ) m_canvas->SetIgnoreMouseEvents( false ); if( edited == ZONE_ABORT ) + { + GetBoard()->m_CurrentZoneContour = NULL; + delete zone; return 0; + } // Switch active layer to the selected zone layer SetActiveLayer( zoneInfo.m_CurrentZone_Layer ); - SetZoneSettings( zoneInfo ); } else @@ -615,8 +629,8 @@ int PCB_EDIT_FRAME::Begin_Zone( wxDC* DC ) } // Show the Net for zones on copper layers - if( zoneInfo.m_CurrentZone_Layer < FIRST_NON_COPPER_LAYER && - ! zoneInfo.GetIsKeepout() ) + if( IsCopperLayer( zoneInfo.m_CurrentZone_Layer ) && + !zoneInfo.GetIsKeepout() ) { if( s_CurrentZone ) { @@ -640,9 +654,6 @@ int PCB_EDIT_FRAME::Begin_Zone( wxDC* DC ) // if first segment if( zone->GetNumCorners() == 0 ) { - zone->SetFlags( IS_NEW ); - zone->SetTimeStamp( GetNewTimeStamp() ); - zoneInfo.ExportSetting( *zone ); zone->Outline()->Start( zoneInfo.m_CurrentZone_Layer, diff --git a/pcbnew/zones_by_polygon_fill_functions.cpp b/pcbnew/zones_by_polygon_fill_functions.cpp index 3146786a6b..ca1155a2fd 100644 --- a/pcbnew/zones_by_polygon_fill_functions.cpp +++ b/pcbnew/zones_by_polygon_fill_functions.cpp @@ -29,7 +29,7 @@ #include #include -#include +#include #include #include #include diff --git a/pcbnew/zones_convert_to_polygons_aux_functions.cpp b/pcbnew/zones_convert_to_polygons_aux_functions.cpp index 16549b2ed4..be02fd0d40 100644 --- a/pcbnew/zones_convert_to_polygons_aux_functions.cpp +++ b/pcbnew/zones_convert_to_polygons_aux_functions.cpp @@ -235,7 +235,7 @@ void BuildUnconnectedThermalStubsPolygonList( CPOLYGONS_LIST& aCornerBuffer, RotatePoint( &ptTest[i], fAngle ); // translate point - ptTest[i] += pad->ReturnShapePos(); + ptTest[i] += pad->ShapePos(); if( aZone->HitTestFilledArea( ptTest[i] ) ) continue; @@ -280,7 +280,7 @@ void BuildUnconnectedThermalStubsPolygonList( CPOLYGONS_LIST& aCornerBuffer, { wxPoint cpos = corners_buffer[ic]; RotatePoint( &cpos, fAngle ); // Rotate according to module orientation - cpos += pad->ReturnShapePos(); // Shift origin to position + cpos += pad->ShapePos(); // Shift origin to position CPolyPt corner; corner.x = cpos.x; corner.y = cpos.y; diff --git a/pcbnew/zones_functions_for_undo_redo.cpp b/pcbnew/zones_functions_for_undo_redo.cpp index 5710937208..86ecfee29f 100644 --- a/pcbnew/zones_functions_for_undo_redo.cpp +++ b/pcbnew/zones_functions_for_undo_redo.cpp @@ -43,7 +43,7 @@ */ #include -#include +#include #include #include diff --git a/pcbnew/zones_non_copper_type_functions.cpp b/pcbnew/zones_non_copper_type_functions.cpp index f6b2594bff..a8420eaaa2 100644 --- a/pcbnew/zones_non_copper_type_functions.cpp +++ b/pcbnew/zones_non_copper_type_functions.cpp @@ -3,7 +3,8 @@ */ #include -#include +//#include +#include #include #include #include @@ -77,7 +78,7 @@ void DIALOG_NON_COPPER_ZONES_EDITOR::Init() SetReturnCode( ZONE_ABORT ); // Will be changed on button click AddUnitSymbol( *m_MinThicknessValueTitle, g_UserUnit ); - wxString msg = ReturnStringFromValue( g_UserUnit, m_settings.m_ZoneMinThickness ); + wxString msg = StringFromValue( g_UserUnit, m_settings.m_ZoneMinThickness ); m_ZoneMinThicknessCtrl->SetValue( msg ); if( m_settings.m_Zone_45_Only ) @@ -127,7 +128,7 @@ void DIALOG_NON_COPPER_ZONES_EDITOR::OnOkClick( wxCommandEvent& event ) { wxString txtvalue = m_ZoneMinThicknessCtrl->GetValue(); - m_settings.m_ZoneMinThickness = ReturnValueFromString( g_UserUnit, txtvalue ); + m_settings.m_ZoneMinThickness = ValueFromString( g_UserUnit, txtvalue ); if( m_settings.m_ZoneMinThickness < 10 ) { @@ -153,11 +154,10 @@ void DIALOG_NON_COPPER_ZONES_EDITOR::OnOkClick( wxCommandEvent& event ) break; } - if( wxGetApp().GetSettings() ) - { - wxGetApp().GetSettings()->Write( ZONE_NET_OUTLINES_HATCH_OPTION_KEY, - (long) m_settings.m_Zone_HatchingStyle ); - } + wxConfigBase* cfg = Kiface().KifaceSettings(); + wxASSERT( cfg ); + + cfg->Write( ZONE_NET_OUTLINES_HATCH_OPTION_KEY, (long) m_settings.m_Zone_HatchingStyle ); if( m_OrientEdgesOpt->GetSelection() == 0 ) m_settings.m_Zone_45_Only = false; diff --git a/pcbnew/zones_polygons_test_connections.cpp b/pcbnew/zones_polygons_test_connections.cpp index fd277f2a63..ce9c948c46 100644 --- a/pcbnew/zones_polygons_test_connections.cpp +++ b/pcbnew/zones_polygons_test_connections.cpp @@ -171,7 +171,7 @@ void BOARD::Test_Connections_To_Copper_Areas( int aNetcode ) // the pad position, because the zones are connected // to the center of the shape, not the pad position // (this is important for pads with thermal relief) - pos1 = pos2 = ( (D_PAD*) item )->ReturnShapePos(); + pos1 = pos2 = ( (D_PAD*) item )->ShapePos(); } else if( item->Type() == PCB_VIA_T ) { diff --git a/resources/linux/mime/applications/pcbcalculator.desktop b/resources/linux/mime/applications/pcbcalculator.desktop index 7c449f3fef..4ae5e3e841 100644 --- a/resources/linux/mime/applications/pcbcalculator.desktop +++ b/resources/linux/mime/applications/pcbcalculator.desktop @@ -2,7 +2,7 @@ [Desktop Entry] Categories=Development;Electronics Comment=Design a printed circuit board -Exec=pcbcalculator +Exec=pcb_calculator GenericName=EDA Suite Icon=pcbcalculator MimeType=application/x-pcbcalculator-project; diff --git a/scripting/python_scripting.cpp b/scripting/python_scripting.cpp index 31a725d8e8..494195cf3d 100644 --- a/scripting/python_scripting.cpp +++ b/scripting/python_scripting.cpp @@ -172,7 +172,7 @@ bool pcbnewInitPythonScripting( const char * aUserPluginsPath ) } -void pcbnewFinishPythonScripting( char ) +void pcbnewFinishPythonScripting() { #ifdef KICAD_SCRIPTING_WXPYTHON wxPyEndAllowThreads( g_PythonMainTState ); diff --git a/scripting/wx_python_helpers.cpp b/scripting/wx_python_helpers.cpp index a97314b355..8ee7bba28b 100644 --- a/scripting/wx_python_helpers.cpp +++ b/scripting/wx_python_helpers.cpp @@ -102,10 +102,14 @@ wxString* newWxStringFromPy( PyObject* src ) } if( must_unref_str ) + { Py_DECREF( uni_str ); + } if( must_unref_obj ) + { Py_DECREF( obj ); + } #else // normal string (or object) to normal python string @@ -136,7 +140,9 @@ wxString* newWxStringFromPy( PyObject* src ) result = new wxString( str_ptr, str_size ); if( must_unref_str ) + { Py_DECREF( str ); + } #endif diff --git a/scripts/kicad-install-no_launchpad_account.sh b/scripts/kicad-install-no_launchpad_account.sh new file mode 100644 index 0000000000..3a0d2d0078 --- /dev/null +++ b/scripts/kicad-install-no_launchpad_account.sh @@ -0,0 +1,327 @@ +#!/bin/bash -e +# Install KiCad from source onto either: +# -> a Ubuntu/Debian/Mint or +# -> a Red Hat +# compatible linux system. +# +# The "install_prerequisites" step is the only "distro dependent" one. That step could be modified +# for other linux distros. +# +# There are 3 package groups in a KiCad install: +# 1) Compiled source code in the form of executable programs. +# 2) User manuals and other documentation typically as *.pdf files. +# 3) a) Schematic parts, b) layout footprints, and c) 3D models for footprints. +# +# To achieve 1) source is checked out from its repo and compiled by this script then executables +# are installed using CMake. +# To achieve 2) documentation is checked out from its repo and installed using CMake. +# TO achieve 3a) and 3c) they are checked out from their repos and installed using CMake. +# To achieve 3b) a global fp-lib-table is put into your home directory which points to +# http://github.com/KiCad. No actual footprints are installed locally, internet access is used +# during program operation to fetch footprints from github as if it was a remote drive in the cloud. +# If you want to install those same KiCad footprints locally, you may run a separate script +# named library-repos-install.sh found in this same directory. That script requires that "git" be on +# your system whereas this script does not. The footprints require some means to download them and +# bzr-git seems not up to the task. wget or curl would also work. + + +# Since bash is invoked with -e by the first line of this script, all the steps in this script +# must succeed otherwise bash will abort at the first non-zero error code. Therefore any script +# functions must be crafted to anticipate numerous conditions, such that no command fails unless it +# is a serious situation. + + +# Set where the 3 source trees will go, use a full path +WORKING_TREES=~/kicad_sources + +# CMake Options +OPTS="$OPTS -DCMAKE_BUILD_TYPE=Release" +OPTS="$OPTS -DBUILD_GITHUB_PLUGIN=ON" + +# Python scripting, uncomment to enable +#OPTS="$OPTS -DKICAD_SCRIPTING=ON -DKICAD_SCRIPTING_MODULES=ON -DKICAD_SCRIPTING_WXPYTHON=ON" + +#a connection to https://code.launchpad.net does not request a launchpad account +#but, obviously, you cannot commit anything +REPOS=https://code.launchpad.net +LEGACY_LIB_REPO=$REPOS/~dickelbeck/kicad/library-read-only +SRCS_REPO=$REPOS/~kicad-product-committers/kicad/product +DOCS_REPO=$REPOS/~kicad-developers/kicad/doc + + +usage() +{ + echo "" + echo " usage:" + echo "" + echo "./kicad-install.sh " + echo " where is one of:" + echo " --install-or-update (does full installation or update.)" + echo " --remove-sources (removes source trees for another attempt.)" + echo " --uninstall-libraries (removes KiCad supplied libraries.)" + echo " --uninstall-kicad (uninstalls all of KiCad but leaves source trees.)" + echo "" + echo "example:" + echo ' $ ./kicad-install.sh --install-or-update' +} + + +install_prerequisites() +{ + # Find a package manager, PM + PM=$( command -v yum || command -v apt-get ) + + # assume all these Debian, Mint, Ubuntu systems have same prerequisites + if [ "$(expr match "$PM" '.*\(apt-get\)')" == "apt-get" ]; then + #echo "debian compatible system" + sudo apt-get install \ + bzr \ + bzrtools \ + build-essential \ + cmake \ + cmake-curses-gui \ + debhelper \ + doxygen \ + grep \ + libbz2-dev \ + libcairo2-dev \ + libglew-dev \ + libssl-dev \ + libwxgtk2.8-dev \ + python-wxgtk2.8 + + # assume all yum systems have same prerequisites + elif [ "$(expr match "$PM" '.*\(yum\)')" == "yum" ]; then + #echo "red hat compatible system" + # Note: if you find this list not to be accurate, please submit a patch: + sudo yum groupinstall "Development Tools" + sudo yum install \ + bzr \ + bzrtools \ + bzip2-libs \ + bzip2-devel \ + cmake \ + cmake-gui \ + doxygen \ + cairo-devel \ + glew-devel \ + grep \ + openssl-devel \ + wxGTK-devel \ + wxPython + else + echo + echo "Incompatible System. Neither 'yum' nor 'apt-get' found. Not possible to continue." + echo + exit 1 + fi + + # ensure bzr name and email are set. No message since bzr prints an excellent diagnostic. + bzr whoami || exit 2 +} + + +rm_build_dir() +{ + local dir="$1" + + echo "removing directory $dir" + + if [ -e "$dir/install_manifest.txt" ]; then + # this file is often created as root, so remove as root + sudo rm "$dir/install_manifest.txt" 2> /dev/null + fi + + if [ -d "$dir" ]; then + rm -rf "$dir" + fi +} + + +cmake_uninstall() +{ + # assume caller set the CWD, and is only telling us about it in $1 + local dir="$1" + + cwd=`pwd` + if [ "$cwd" != "$dir" ]; then + echo "missing dir $dir" + elif [ ! -e install_manifest.txt ]; then + echo + echo "Missing file $dir/install_manifest.txt." + else + echo "uninstalling from $dir" + sudo make uninstall + sudo rm install_manifest.txt + fi +} + + +# Function set_env_var +# sets an environment variable globally. +set_env_var() +{ + local var=$1 + local val=$2 + + if [ -d /etc/profile.d ]; then + if [ ! -e /etc/profile.d/kicad.sh ] || ! grep "$var" /etc/profile.d/kicad.sh >> /dev/null; then + echo + echo "Adding environment variable $var to file /etc/profile.d/kicad.sh" + echo "Please logout and back in after this script completes for environment" + echo "variable to get set into environment." + sudo sh -c "echo export $var=$val >> /etc/profile.d/kicad.sh" + fi + + elif [ -e /etc/environment ]; then + if ! grep "$var" /etc/environment >> /dev/null; then + echo + echo "Adding environment variable $var to file /etc/environment" + echo "Please reboot after this script completes for environment variable to get set into environment." + sudo sh -c "echo $var=$val >> /etc/environment" + fi + fi +} + + +install_or_update() +{ + echo "step 1) installing pre-requisites" + install_prerequisites + + + echo "step 2) make $WORKING_TREES if it does not exist" + if [ ! -d "$WORKING_TREES" ]; then + sudo mkdir -p "$WORKING_TREES" + echo " mark $WORKING_TREES as owned by me" + sudo chown -R `whoami` "$WORKING_TREES" + fi + cd $WORKING_TREES + + + echo "step 3) checking out the source code from launchpad repo..." + if [ ! -d "$WORKING_TREES/kicad.bzr" ]; then + bzr checkout $SRCS_REPO kicad.bzr + echo " source repo to local working tree." + else + cd kicad.bzr + bzr up + echo " local source working tree updated." + cd ../ + fi + + if [ ! -d "$WORKING_TREES/kicad-lib.bzr" ]; then + bzr checkout $LEGACY_LIB_REPO kicad-lib.bzr + echo ' kicad-lib checked out.' + else + cd kicad-lib.bzr + bzr up + echo ' kicad-lib repo updated.' + cd ../ + fi + + echo "step 5) checking out the documentation from launchpad repo..." + if [ ! -d "$WORKING_TREES/kicad-doc.bzr" ]; then + bzr checkout $DOCS_REPO kicad-doc.bzr + echo " docs checked out." + else + cd kicad-doc.bzr + bzr up + echo " docs working tree updated." + cd ../ + fi + + + echo "step 6) compiling source code..." + cd kicad.bzr + if [ ! -d "build" ]; then + mkdir build && cd build + cmake $OPTS ../ + else + cd build + # Although a "make clean" is sometimes needed, more often than not it slows down the update + # more than it is worth. Do it manually if you need to in this directory. + # make clean + fi + make -j4 + echo " kicad compiled." + + + echo "step 7) installing KiCad program files..." + sudo make install + echo " kicad program files installed." + + + echo "step 8) installing libraries..." + cd ../../kicad-lib.bzr + rm_build_dir build + mkdir build && cd build + cmake ../ + sudo make install + echo " kicad-lib.bzr installed." + + + echo "step 9) as non-root, install user configuration files..." + # install ~/fp-lib-table + make install_github_fp-lib-table + echo " kicad user-configuration files installed." + + + echo "step 10) installing documentation..." + cd ../../kicad-doc.bzr + rm_build_dir build + mkdir build && cd build + cmake ../ + sudo make install + echo " kicad-doc.bzr installed." + + echo "step 11) check for environment variables..." + if [ -z "${KIGITHUB}" ]; then + set_env_var KIGITHUB https://github.com/KiCad + fi + + echo + echo 'All KiCad "--install-or-update" steps completed, you are up to date.' + echo +} + + +if [ $# -eq 1 -a "$1" == "--remove-sources" ]; then + echo "deleting $WORKING_TREES" + rm_build_dir "$WORKING_TREES/kicad.bzr/build" + rm_build_dir "$WORKING_TREES/kicad-lib.bzr/build" + rm_build_dir "$WORKING_TREES/kicad-doc.bzr/build" + rm -rf "$WORKING_TREES" + exit +fi + + +if [ $# -eq 1 -a "$1" == "--install-or-update" ]; then + install_or_update + exit +fi + + +if [ $# -eq 1 -a "$1" == "--uninstall-libraries" ]; then + cd "$WORKING_TREES/kicad-lib.bzr/build" + cmake_uninstall "$WORKING_TREES/kicad-lib.bzr/build" + exit +fi + + +if [ $# -eq 1 -a "$1" == "--uninstall-kicad" ]; then + cd "$WORKING_TREES/kicad.bzr/build" + cmake_uninstall "$WORKING_TREES/kicad.bzr/build" + + cd "$WORKING_TREES/kicad-lib.bzr/build" + cmake_uninstall "$WORKING_TREES/kicad-lib.bzr/build" + + # this may fail since "uninstall" support is a recent feature of this repo: + cd "$WORKING_TREES/kicad-doc.bzr/build" + cmake_uninstall "$WORKING_TREES/kicad-doc.bzr/build" + + exit +fi + + +usage diff --git a/scripts/kicad-install.sh b/scripts/kicad-install.sh index 5c6168f520..6dab247203 100755 --- a/scripts/kicad-install.sh +++ b/scripts/kicad-install.sh @@ -41,7 +41,7 @@ OPTS="$OPTS -DBUILD_GITHUB_PLUGIN=ON" # Python scripting, uncomment to enable #OPTS="$OPTS -DKICAD_SCRIPTING=ON -DKICAD_SCRIPTING_MODULES=ON -DKICAD_SCRIPTING_WXPYTHON=ON" -LIB_REPO=~kicad-product-committers/kicad/library +LIB_REPO=~dickelbeck/kicad/library-read-only usage() diff --git a/tools/CMakeLists.txt b/tools/CMakeLists.txt index eaa8a7f4d5..67c4cc363f 100644 --- a/tools/CMakeLists.txt +++ b/tools/CMakeLists.txt @@ -77,57 +77,3 @@ target_link_libraries( property_tree ${wxWidgets_LIBRARIES} ) - -#-------------------------------------------------- - -# The small launcher, it sets up wxWidgets library and loads a MODULE by the same name -# but with extension ${KIFACE_SUFFIX}. - -set( PAIR_BASE kiway_test ) - -add_executable( ${PAIR_BASE} WIN32 MACOSX_BUNDLE - EXCLUDE_FROM_ALL - ../common/single_top.cpp - ) -target_link_libraries( ${PAIR_BASE} - common - ${wxWidgets_LIBRARIES} - ) -if( APPLE ) - set_target_properties( ${PAIR_BASE} PROPERTIES - MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/Info.plist - ) -endif() - - -# make a KIFACE top level DLL/DSO -add_library( ${PAIR_BASE}_kiface MODULE - EXCLUDE_FROM_ALL - kiface_test.cpp - ) -target_link_libraries( ${PAIR_BASE}_kiface - common - ${wxWidgets_LIBRARIES} - ) -set_target_properties( ${PAIR_BASE}_kiface PROPERTIES - OUTPUT_NAME ${PAIR_BASE} - PREFIX ${KIFACE_PREFIX} - SUFFIX ${KIFACE_SUFFIX} - ) - -# if you build ${PAIR_BASE}, then also build ${PAIR_BASE}_kiface if out of date. -add_dependencies( ${PAIR_BASE} ${PAIR_BASE}_kiface ) - -if( MAKE_LINK_MAPS ) - - # generate a link maps with cross reference - - set_target_properties( ${PAIR_BASE}_kiface PROPERTIES - LINK_FLAGS "${TO_LINKER},-cref ${TO_LINKER},-Map=${KIFACE_PREFIX}${PAIR_BASE}${KIFACE_SUFFIX}.map" - ) - - set_target_properties( ${PAIR_BASE} PROPERTIES - LINK_FLAGS "${TO_LINKER},-cref ${TO_LINKER},-Map=${PAIR_BASE}.map" - ) - -endif() diff --git a/tools/kiface_test.cpp b/tools/kiface_test.cpp deleted file mode 100644 index a7a5d89797..0000000000 --- a/tools/kiface_test.cpp +++ /dev/null @@ -1,60 +0,0 @@ - -#include -#include -#include - - -// test static initialization, and translation in the DSO: -wxString GlobalTitle = _( "Some Translatable Window Title Text" ); - -/// Implement a KIFACE, and create a static instance of one. -static struct SCH_FACE : public KIFACE -{ - wxWindow* CreateWindow( int aClassId, KIWAY* aKIWAY, int aCtlBits = 0 ) - { - switch( aClassId ) - { - // for now, I have no class: - default: - return new wxFrame( NULL, 0, GlobalTitle, wxPoint( 0, 0 ), wxSize( 600, 400 ) ); - } - } - - /** - * Function IfaceOrAddress - * return a pointer to the requested object. The safest way to use this - * is to retrieve a pointer to a static instance of an interface, similar to - * how the KIFACE interface is exported. But if you know what you are doing - * use it to retrieve anything you want. - * - * @param aDataId identifies which object you want the address of. - * - * @return void* - and must be cast into the known type. - */ - void* IfaceOrAddress( int aDataId ) - { - return NULL; - } - -} kiface_impl; - - -static wxApp* app; - -extern "C" KIFACE* KIFACE_GETTER( int* aKIFACEversion, int aKIWAYversion, wxApp* aProcess ); - -MY_API( KIFACE* ) KIFACE_GETTER( int* aKIFACEversion, int aKIWAYversion, wxApp* aProcess ) -{ - // record the app's address. - app = aProcess; - - // return a pointer to the KIFACE implementation. - return &kiface_impl; -} - - -wxApp& wxGetApp() -{ - return *app; -} -