KiCad PCB EDA Suite
common.h File Reference

The common library. More...

#include <vector>
#include <boost/cstdint.hpp>
#include <wx/wx.h>
#include <wx/confbase.h>
#include <wx/fileconf.h>
#include <richio.h>
#include <gal/color4d.h>
#include <atomic>
#include "make_unique.h"

Go to the source code of this file.

Classes

class  LOCALE_IO
 Class LOCALE_IO is a class that can be instantiated within a scope in which you are expecting exceptions to be thrown. More...
 

Macros

#define EDA_KEY_C   UINT32_C
 
#define GR_KB_RIGHTSHIFT   ( EDA_KEY_C( 0x01000000 ) )
 
#define GR_KB_LEFTSHIFT   ( EDA_KEY_C( 0x02000000 ) )
 
#define GR_KB_CTRL   ( EDA_KEY_C( 0x04000000 ) )
 
#define GR_KB_ALT   ( EDA_KEY_C( 0x08000000 ) )
 
#define GR_KB_SHIFT   ( GR_KB_LEFTSHIFT | GR_KB_RIGHTSHIFT )
 
#define GR_KB_SHIFTCTRL   ( GR_KB_SHIFT | GR_KB_CTRL )
 
#define MOUSE_MIDDLE   ( EDA_KEY_C( 0x10000000 ) )
 
#define GR_KEY_INVALID   ( EDA_KEY_C( 0x80000000 ) )
 
#define GR_KEY_NONE   ( EDA_KEY_C( 0 ) )
 
#define NAMELESS_PROJECT   wxT( "noname" )
 default name for nameless projects More...
 
#define ESC   27
 
#define TEXT_ANGLE_HORIZ   0
 Frequent text rotations, used with {Set,Get}TextAngle(), in 0.1 degrees for now, hoping to migrate to degrees eventually. More...
 
#define TEXT_ANGLE_VERT   900
 
#define KIROUND(v)   int( (v) < 0 ? (v) - 0.5 : (v) + 0.5 )
 KIROUND: a macro so compiler can pre-compute constants. More...
 

Typedefs

typedef uint32_t EDA_KEY
 

Enumerations

enum  pseudokeys {
  EDA_PANNING_UP_KEY = 1, EDA_PANNING_DOWN_KEY, EDA_PANNING_LEFT_KEY, EDA_PANNING_RIGHT_KEY,
  EDA_ZOOM_IN_FROM_MOUSE, EDA_ZOOM_OUT_FROM_MOUSE, EDA_ZOOM_CENTER_FROM_MOUSE
}
 Pseudo key codes for command panning. More...
 
enum  EDA_UNITS_T { INCHES = 0, MILLIMETRES = 1, UNSCALED_UNITS = 2, DEGREES = 3 }
 

Functions

static int KiROUND (double v)
 KiROUND rounds a floating point number to an int using "round halfway cases away from zero". More...
 
wxSize GetTextSize (const wxString &aSingleLine, wxWindow *aWindow)
 Function GetTextSize returns the size of aSingleLine of text when it is rendered in aWindow using whatever font is currently set in that window. More...
 
bool EnsureTextCtrlWidth (wxTextCtrl *aCtrl, const wxString *aString=NULL)
 Function EnsureTextCtrlWidth sets the minimum pixel width on a text control in order to make a text string be fully visible within it. More...
 
int ProcessExecute (const wxString &aCommandLine, int aFlags=wxEXEC_ASYNC, wxProcess *callback=NULL)
 Function ProcessExecute runs a child process. More...
 
time_t GetNewTimeStamp ()
 
int GetCommandOptions (const int argc, const char **argv, const char *stringtst, const char **optarg, int *optind)
 
double RoundTo0 (double x, double precision)
 Round to the nearest precision. More...
 
void wxStringSplit (const wxString &aText, wxArrayString &aStrings, wxChar aSplitter)
 Function wxStringSplit splits aString to a string list separated at aSplitter. More...
 
wxString SearchHelpFileFullPath (const SEARCH_STACK &aSearchStack, const wxString &aBaseName)
 Function SearchHelpFileFullPath returns the help file's full path. More...
 
bool EnsureFileDirectoryExists (wxFileName *aTargetFullFileName, const wxString &aBaseFilename, REPORTER *aReporter=NULL)
 Helper function EnsureFileDirectoryExists make aTargetFullFileName absolute and creates the path of this file if it doesn't yet exist. More...
 
const wxString PrePendPath (const wxString &aEnvVar, const wxString &aPriorityPath)
 Put aPriorityPath in front of all paths in the value of aEnvVar. More...
 
wxConfigBase * GetNewConfig (const wxString &aProgName)
 Function GetNewConfig. More...
 
wxString GetKicadConfigPath ()
 Function GetKicadConfigPath. More...
 
const wxString ExpandEnvVarSubstitutions (const wxString &aString)
 Function ExpandEnvVarSubstitutions replaces any environment variable references with their values. More...
 

Variables

EDA_UNITS_T g_UserUnit
 display units More...
 
KIGFX::COLOR4D g_GhostColor
 Draw color for moving objects. More...
 

Detailed Description

The common library.

Definition in file common.h.

Macro Definition Documentation

#define EDA_KEY_C   UINT32_C

Definition at line 60 of file common.h.

Referenced by FOOTPRINT_EDIT_FRAME::BlockCommand(), and LIB_EDIT_FRAME::BlockCommand().

#define ESC   27

Definition at line 87 of file common.h.

Referenced by PCB_EDIT_FRAME::AutoPlaceModule(), and getOptimalModulePlacement().

#define GR_KB_LEFTSHIFT   ( EDA_KEY_C( 0x02000000 ) )

Definition at line 63 of file common.h.

#define GR_KB_RIGHTSHIFT   ( EDA_KEY_C( 0x01000000 ) )

Definition at line 62 of file common.h.

#define GR_KEY_INVALID   ( EDA_KEY_C( 0x80000000 ) )

Definition at line 69 of file common.h.

Referenced by FOOTPRINT_EDIT_FRAME::BlockCommand(), and LIB_EDIT_FRAME::BlockCommand().

#define GR_KEY_NONE   ( EDA_KEY_C( 0 ) )

Definition at line 70 of file common.h.

Referenced by LIB_EDIT_FRAME::BlockCommand().

#define KIROUND (   v)    int( (v) < 0 ? (v) - 0.5 : (v) + 0.5 )

KIROUND: a macro so compiler can pre-compute constants.

Use this with compile time constants rather than the inline function above.

Definition at line 114 of file common.h.

#define NAMELESS_PROJECT   wxT( "noname" )

Typedef Documentation

typedef uint32_t EDA_KEY

Definition at line 52 of file common.h.

Enumeration Type Documentation

Enumerator
INCHES 
MILLIMETRES 
UNSCALED_UNITS 
DEGREES 

Definition at line 144 of file common.h.

144  {
145  INCHES = 0,
146  MILLIMETRES = 1,
147  UNSCALED_UNITS = 2,
148  DEGREES = 3,
149 };
Definition: common.h:145
enum pseudokeys

Pseudo key codes for command panning.

Enumerator
EDA_PANNING_UP_KEY 
EDA_PANNING_DOWN_KEY 
EDA_PANNING_LEFT_KEY 
EDA_PANNING_RIGHT_KEY 
EDA_ZOOM_IN_FROM_MOUSE 
EDA_ZOOM_OUT_FROM_MOUSE 
EDA_ZOOM_CENTER_FROM_MOUSE 

Definition at line 77 of file common.h.

Function Documentation

bool EnsureFileDirectoryExists ( wxFileName *  aTargetFullFileName,
const wxString &  aBaseFilename,
REPORTER aReporter = NULL 
)

Helper function EnsureFileDirectoryExists make aTargetFullFileName absolute and creates the path of this file if it doesn't yet exist.

Parameters
aTargetFullFileNamethe wxFileName containing the full path and file name to modify. The path may be absolute or relative to aBaseFilename .
aBaseFilenamea full filename. Only its path is used to set the aTargetFullFileName path.
aReportera point to a REPORTER object use to show messages (can be NULL)
Returns
true if aOutputDir already exists or was successfully created.

Definition at line 267 of file common.cpp.

References GetChars(), REPORTER::Report(), REPORTER::RPT_ERROR, and REPORTER::RPT_INFO.

Referenced by DIALOG_GEN_MODULE_POSITION::CreateFiles(), DIALOG_PLOT_SCHEMATIC::createPlotFileName(), DIALOG_SVG_PRINT::ExportSVGFile(), PLOT_CONTROLLER::OpenPlotfile(), and DIALOG_PLOT::Plot().

270 {
271  wxString msg;
272  wxString baseFilePath = wxFileName( aBaseFilename ).GetPath();
273 
274  // make aTargetFullFileName path, which is relative to aBaseFilename path (if it is not
275  // already an absolute path) absolute:
276  if( !aTargetFullFileName->MakeAbsolute( baseFilePath ) )
277  {
278  if( aReporter )
279  {
280  msg.Printf( _( "Cannot make path '%s' absolute with respect to '%s'." ),
281  GetChars( aTargetFullFileName->GetPath() ),
282  GetChars( baseFilePath ) );
283  aReporter->Report( msg, REPORTER::RPT_ERROR );
284  }
285 
286  return false;
287  }
288 
289  // Ensure the path of aTargetFullFileName exists, and create it if needed:
290  wxString outputPath( aTargetFullFileName->GetPath() );
291 
292  if( !wxFileName::DirExists( outputPath ) )
293  {
294  if( wxMkdir( outputPath ) )
295  {
296  if( aReporter )
297  {
298  msg.Printf( _( "Output directory '%s' created.\n" ), GetChars( outputPath ) );
299  aReporter->Report( msg, REPORTER::RPT_INFO );
300  return true;
301  }
302  }
303  else
304  {
305  if( aReporter )
306  {
307  msg.Printf( _( "Cannot create output directory '%s'.\n" ),
308  GetChars( outputPath ) );
309  aReporter->Report( msg, REPORTER::RPT_ERROR );
310  }
311 
312  return false;
313  }
314  }
315 
316  return true;
317 }
static const wxChar * GetChars(const wxString &s)
Function GetChars returns a wxChar* to the actual wxChar* data within a wxString, and is helpful for ...
Definition: macros.h:92
virtual REPORTER & Report(const wxString &aText, SEVERITY aSeverity=RPT_UNDEFINED)=0
Function Report is a pure virtual function to override in the derived object.
bool EnsureTextCtrlWidth ( wxTextCtrl *  aCtrl,
const wxString *  aString = NULL 
)

Function EnsureTextCtrlWidth sets the minimum pixel width on a text control in order to make a text string be fully visible within it.

The current font within the text control is considered. The text can come either from the control or be given as an argument. If the text control is larger than needed, then nothing is done.

Parameters
aCtrlthe text control to potentially make wider.
aStringthe text that is used in sizing the control's pixel width. If NULL, then the text already within the control is used.
Returns
bool - true if the aCtrl had its size changed, else false.

Definition at line 108 of file common.cpp.

References GetTextSize().

Referenced by SCH_EDIT_FRAME::EditComponent(), DIALOG_LABEL_EDITOR::InitDialog(), and GERBVIEW_FRAME::UpdateTitleAndInfo().

109 {
110  wxWindow* window = aCtrl->GetParent();
111 
112  if( !window )
113  window = aCtrl;
114 
115  wxString ctrlText;
116 
117  if( !aString )
118  {
119  ctrlText = aCtrl->GetValue();
120  aString = &ctrlText;
121  }
122 
123  wxSize textz = GetTextSize( *aString, window );
124  wxSize ctrlz = aCtrl->GetSize();
125 
126  if( ctrlz.GetWidth() < textz.GetWidth() + 10 )
127  {
128  ctrlz.SetWidth( textz.GetWidth() + 10 );
129  aCtrl->SetSizeHints( ctrlz );
130  return true;
131  }
132 
133  return false;
134 }
wxSize GetTextSize(const wxString &aSingleLine, wxWindow *aWindow)
Function GetTextSize returns the size of aSingleLine of text when it is rendered in aWindow using wha...
Definition: common.cpp:93
const wxString ExpandEnvVarSubstitutions ( const wxString &  aString)

Function ExpandEnvVarSubstitutions replaces any environment variable references with their values.

Parameters
aString= a string containing (perhaps) references to env var
Returns
a string where env var are replaced by their value

Definition at line 254 of file common.cpp.

Referenced by S3D_FILENAME_RESOLVER::addPath(), S3D_FILENAME_RESOLVER::checkEnvVarPath(), S3D_PLUGIN_MANAGER::checkPluginName(), S3D_PLUGIN_MANAGER::checkPluginPath(), S3D_FILENAME_RESOLVER::createPathList(), LIB_TABLE::ExpandSubstitutions(), S3D_CACHE::Get3DConfigDir(), WORKSHEET_LAYOUT::MakeFullFileName(), S3D_FILENAME_RESOLVER::ResolvePath(), S3D_FILENAME_RESOLVER::Set3DConfigDir(), S3D_CACHE::Set3DConfigDir(), S3D_FILENAME_RESOLVER::SetProjectDir(), S3D_FILENAME_RESOLVER::ShortenPath(), and DLG_3D_PATH_CONFIG::updateEnvVars().

255 {
256  // wxGetenv( wchar_t* ) is not re-entrant on linux.
257  // Put a lock on multithreaded use of wxGetenv( wchar_t* ), called from wxEpandEnvVars(),
258  static MUTEX getenv_mutex;
259 
260  MUTLOCK lock( getenv_mutex );
261 
262  // We reserve the right to do this another way, by providing our own member
263  // function.
264  return wxExpandEnvVars( aString );
265 }
boost::interprocess::interprocess_mutex MUTEX
Establish KiCad MUTEX choices here in this file: typedef MUTEX and typedef MUTLOCK.
Definition: ki_mutex.h:42
boost::interprocess::scoped_lock< MUTEX > MUTLOCK
Definition: ki_mutex.h:43
int GetCommandOptions ( const int  argc,
const char **  argv,
const char *  stringtst,
const char **  optarg,
int *  optind 
)
wxString GetKicadConfigPath ( )

Function GetKicadConfigPath.

Returns
A wxString containing the config path for Kicad

Definition at line 217 of file common.cpp.

Referenced by FP_LIB_TABLE::GetGlobalTableFileName(), SYMBOL_LIB_TABLE::GetGlobalTableFileName(), and GetNewConfig().

218 {
219  wxFileName cfgpath;
220 
221  // From the wxWidgets wxStandardPaths::GetUserConfigDir() help:
222  // Unix: ~ (the home directory)
223  // Windows: "C:\Documents and Settings\username\Application Data"
224  // Mac: ~/Library/Preferences
225  cfgpath.AssignDir( wxStandardPaths::Get().GetUserConfigDir() );
226 
227 #if !defined( __WINDOWS__ ) && !defined( __WXMAC__ )
228  wxString envstr;
229 
230  if( !wxGetEnv( wxT( "XDG_CONFIG_HOME" ), &envstr ) || envstr.IsEmpty() )
231  {
232  // XDG_CONFIG_HOME is not set, so use the fallback
233  cfgpath.AppendDir( wxT( ".config" ) );
234  }
235  else
236  {
237  // Override the assignment above with XDG_CONFIG_HOME
238  cfgpath.AssignDir( envstr );
239  }
240 #endif
241 
242  cfgpath.AppendDir( wxT( "kicad" ) );
243 
244  if( !cfgpath.DirExists() )
245  {
246  cfgpath.Mkdir( wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL );
247  }
248 
249  return cfgpath.GetPath();
250 }
wxConfigBase* GetNewConfig ( const wxString &  aProgName)

Function GetNewConfig.

Use this function instead of creating a new wxConfig so we can put config files in a more proper place for each platform. This is generally $HOME/.config/kicad/ in Linux according to the FreeDesktop specification at http://standards.freedesktop.org/basedir-spec/basedir-spec-0.6.html The config object created here should be destroyed by the caller.

Parameters
aProgNameis the name of the program calling this function - can be obtained by calling Pgm().App().GetAppName(). This will be the actual file name of the config file.
Returns
A pointer to a new wxConfigBase derived object is returned. The caller is in charge of deleting it.

Definition at line 205 of file common.cpp.

References GetKicadConfigPath().

Referenced by BIN_MOD::Init(), PGM_BASE::InitPgm(), ReadHotkeyConfig(), and EDA_BASE_FRAME::WriteHotkeyConfig().

206 {
207  wxConfigBase* cfg = 0;
208  wxFileName configname;
209  configname.AssignDir( GetKicadConfigPath() );
210  configname.SetFullName( aProgName );
211 
212  cfg = new wxFileConfig( wxT( "" ), wxT( "" ), configname.GetFullPath() );
213  return cfg;
214 }
wxString GetKicadConfigPath()
Function GetKicadConfigPath.
Definition: common.cpp:217
wxSize GetTextSize ( const wxString &  aSingleLine,
wxWindow *  aWindow 
)

Function GetTextSize returns the size of aSingleLine of text when it is rendered in aWindow using whatever font is currently set in that window.

Definition at line 93 of file common.cpp.

Referenced by EDA_DRAW_FRAME::EDA_DRAW_FRAME(), EnsureTextCtrlWidth(), DIALOG_NON_COPPER_ZONES_EDITOR::Init(), DIALOG_COPPER_ZONE::initDialog(), PL_EDITOR_FRAME::PL_EDITOR_FRAME(), DIALOG_FP_CONFLICT_ASSIGNMENT_SELECTOR::recalculateColumns(), and PL_EDITOR_FRAME::ReCreateHToolbar().

94 {
95  wxCoord width;
96  wxCoord height;
97 
98  {
99  wxClientDC dc( aWindow );
100  dc.SetFont( aWindow->GetFont() );
101  dc.GetTextExtent( aSingleLine, &width, &height );
102  }
103 
104  return wxSize( width, height );
105 }
static int KiROUND ( double  v)
inlinestatic

KiROUND rounds a floating point number to an int using "round halfway cases away from zero".

In Debug build an assert fires if will not fit into an int.KiROUND: a function so v is not evaluated twice. Unfortunately, compiler is unable to pre-compute constants using this.

Definition at line 107 of file common.h.

Referenced by PCB_EDIT_FRAME::Add45DegreeSegment(), PCAD2KICAD::PCB_POLYGON::AddToBoard(), DIMENSION::AdjustDimensionDetails(), EDA_DRAW_FRAME::AdjustScrollBars(), GRID_HELPER::Align(), GRID_HELPER::AlignToSegment(), CPolyLine::AppendArc(), EC_45DEGREE::Apply(), PLOTTER::Arc(), HPGL_PLOTTER::Arc(), PDF_PLOTTER::Arc(), GERBER_PLOTTER::Arc(), PCB_EDIT_FRAME::Begin_Zone(), LEGACY_PLUGIN::biuParse(), D_PAD::boundingRadius(), build_pad_testpoints(), BuildCornersList_S_Shape(), D_PAD::BuildPadPolygon(), BuildUnconnectedThermalStubsPolygonList(), WS_DRAW_ITEM_LIST::BuildWorkSheetGraphicList(), LIB_CIRCLE::calcEdit(), LIB_ARC::calcRadiusAngles(), PCAD2KICAD::CalculateTextLengthSize(), KIGFX::WX_VIEW_CONTROLS::CenterOnCursor(), CPolyLine::Chamfer(), SHAPE_POLY_SET::chamferFilletPolygon(), DRC::checkClearancePadToPad(), Clamp_Text_PenSize(), ClipAndDrawPoly(), Collect_TrackSegmentsToDrag(), ConfigureHPGLPenSizes(), AM_PRIMITIVE::ConvertShapeToPolygon(), D_CODE::ConvertShapeToPolygon(), PCAD2KICAD::CorrectTextPosition(), PCB_EDIT_FRAME::Create_MuWaveComponent(), PCB_EDIT_FRAME::Create_MuWavePolygonShape(), SCH_GLOBALLABEL::CreateGraphicShape(), BOARD::CreateLockPoint(), MWAVE::CreateMicrowaveInductor(), CreateThermalReliefPadPolygon(), PCBNEW_CONTROL::CursorControl(), CPolyLine::Distance(), EDGE_MODULE::Draw(), DRAWSEGMENT::Draw(), GERBER_DRAW_ITEM::Draw(), AM_PRIMITIVE::DrawBasicShape(), BITMAP_BASE::DrawBitmap(), KIGFX::OPENGL_GAL::DrawGrid(), EDA_DRAW_PANEL::DrawGrid(), KIGFX::GAL::DrawGrid(), BOARD_PRINTOUT_CONTROLLER::DrawPage(), TRACK::DrawShortNetname(), GERBER_PLOTTER::emitDcode(), GERBER_FILE_IMAGE::ExecuteRS274XCommand(), CPolyLine::Fillet(), HPGL_PLOTTER::FlashPadCircle(), HPGL_PLOTTER::FlashPadOval(), HPGL_PLOTTER::FlashPadRect(), HPGL_PLOTTER::FlashPadRoundRect(), FootprintWriteShape(), DSN::SPECCTRA_DB::FromSESSION(), gen_arc(), EXCELLON_WRITER::GenDrillMapFile(), PCB_EDIT_FRAME::GeneralControl(), EDA_DRAW_FRAME::GeneralControlKeyMovement(), C3D_RENDER_OGL_LEGACY::generate_new_3DGrid(), GERBER_DRAW_ITEM::GetABPosition(), LIB_PIN::GetBoundingBox(), SCH_SHEET::GetBoundingBox(), GetClearanceBetweenSegments(), BASE_SCREEN::getCrossHairScreenPosition(), DIALOG_PAGES_SETTINGS::GetCustomSizeMilsFromDialog(), WORKSHEET_DATAITEM::GetEndPosUi(), GRID_HELPER::GetGrid(), DIALOG_SET_GRID::getGridOrigin(), KIGFX::GAL::GetGridPoint(), KIGFX::STROKE_FONT::getInterline(), EDA_TEXT::GetInterline(), WORKSHEET_DATAITEM::GetMarkerSizeUi(), BASE_SCREEN::getNearestGridPosition(), GetPenSizeForBold(), WORKSHEET_DATAITEM::GetPenSizeUi(), WORKSHEET_DATAITEM_POLYPOLYGON::GetPenSizeUi(), WORKSHEET_DATAITEM_TEXT::GetPenSizeUi(), DRAWSEGMENT::GetRadius(), BITMAP_BASE::GetSize(), D_PAD::GetSolderPasteMargin(), WORKSHEET_DATAITEM::GetStartPosUi(), EDA_TEXT::GetTextBox(), GERBER_DRAW_ITEM::GetXYPosition(), GraphicTextWidth(), GRArc1(), CPolyLine::Hatch(), ZONE_CONTAINER::Hatch(), LIB_CIRCLE::HitTest(), LIB_ARC::HitTest(), DRAWSEGMENT::HitTest(), D_PAD::HitTest(), CPolyLine::HitTestForEdge(), DIALOG_PLOT::Init_Dialog(), initializePlotter(), TRACK::IsPointOnEnds(), iu_to_d356(), Join(), EAGLE_PLUGIN::kicad(), EDA_TEXT::LenSize(), EAGLE_PLUGIN::Load(), EAGLE_PLUGIN::loadSignals(), DSN::SPECCTRA_DB::makeIMAGE(), TRANSFORM::MapAngles(), PLOTTER::markerSquare(), Mils2mm(), Mm2mils(), EDA_DRAW_PANEL::OnMouseEvent(), EDA_DRAW_PANEL::OnPan(), DIALOG_MOVE_EXACT::OnPolarChanged(), EDA_DRAW_PANEL::OnScroll(), EAGLE_PLUGIN::packagePad(), PCB_PLOT_PARAMS_PARSER::Parse(), PCAD2KICAD::PCB_ARC::Parse(), PCB_PARSER::parseBoardUnits(), parseInt(), GPCB_FPL_CACHE::parseMODULE(), BRDITEMS_PLOTTER::Plot_1_EdgeModule(), BRDITEMS_PLOTTER::PlotDrawSegment(), PSLIKE_PLOTTER::postscriptOverlinePositions(), Project(), PushTrack(), GERBER_FILE_IMAGE::ReadIJCoord(), PARAM_CFG_INT_WITH_SCALE::ReadParam(), EXCELLON_IMAGE::readToolInformation(), GERBER_FILE_IMAGE::ReadXYCoord(), resizeSheetWithMouseCursor(), PSLIKE_PLOTTER::returnPostscriptTextWidth(), RotatePoint(), RoundTo0(), DSN::scale(), scaletoIU(), CONNECTIONS::SearchConnectedTracks(), PLOTTER::segmentAsOval(), EDA_3D_VIEWER::Set3DColorFromUser(), EDA_DRAW_PANEL::SetClipBox(), WORKSHEET_DATAITEM_TEXT::SetConstrainedTextSize(), KIGFX::PREVIEW::TWO_POINT_GEOMETRY_MANAGER::SetEnd(), PCAD2KICAD::SetTextSizeFromStrokeFontHeight(), Show_Drag_Track_Segment_With_Cte_Slope(), ShowBoundingBoxMicroWaveInductor(), snapAngle(), PS_PLOTTER::StartPlot(), PCAD2KICAD::StrToInt1Units(), PCAD2KICAD::StrToIntUnits(), TestForIntersectionOfStraightLineSegments(), PS_PLOTTER::Text(), PDF_PLOTTER::Text(), TraceArc(), TraceCircle(), TraceFilledRectangle(), DialogEditModuleText::TransferDataFromWindow(), DIALOG_MODULE_BOARD_EDITOR::TransferDataFromWindow(), TransformRoundedEndsSegmentToPolygon(), TRACK::TransformShapeWithClearanceToPolygon(), D_PAD::TransformShapeWithClearanceToPolygon(), DIALOG_PAGES_SETTINGS::UpdatePageLayoutExample(), USCALE(), ValueFromString(), and EXCELLON_WRITER::writeCoordinates().

108 {
109  return int( v < 0 ? v - 0.5 : v + 0.5 );
110 }
const wxString PrePendPath ( const wxString &  aEnvVar,
const wxString &  aPriorityPath 
)

Put aPriorityPath in front of all paths in the value of aEnvVar.

Definition at line 32 of file prependpath.cpp.

33 {
34  wxPathList paths;
35 
36  paths.AddEnvList( aEnvVar );
37  paths.Insert( aPriorityPath, 0 );
38 
39  return wxJoin( paths, wxPATH_SEP[0] );
40 }
int ProcessExecute ( const wxString &  aCommandLine,
int  aFlags = wxEXEC_ASYNC,
wxProcess *  callback = NULL 
)

Function ProcessExecute runs a child process.

Parameters
aCommandLineThe process and any arguments to it all in a single string.
aFlagsThe same args as allowed for wxExecute()
callbackwxProcess implementing OnTerminate to be run when the child process finishes
Returns
int - pid of process, 0 in case of error (like return values of wxExecute())

Definition at line 160 of file common.cpp.

Referenced by ExecuteFile(), GetAssociatedDocument(), DIALOG_FREEROUTE::OnLaunchButtonClick(), OpenFile(), OpenPDF(), and SCH_EDIT_FRAME::WriteNetListFile().

161 {
162  return wxExecute( aCommandLine, aFlags, callback );
163 }
double RoundTo0 ( double  x,
double  precision 
)

Round to the nearest precision.

Try to approximate a coordinate using a given precision to prevent rounding errors when converting from inches to mm.

ie round the unit value to 0 if unit is 1 or 2, or 8 or 9

Definition at line 182 of file common.cpp.

References KiROUND().

Referenced by SCH_BASE_FRAME::UpdateStatusBar().

183 {
184  assert( precision != 0 );
185 
186  long long ix = KiROUND( x * precision );
187 
188  if ( x < 0.0 )
189  ix = -ix;
190 
191  int remainder = ix % 10; // remainder is in precision mm
192 
193  if( remainder <= 2 )
194  ix -= remainder; // truncate to the near number
195  else if( remainder >= 8 )
196  ix += 10 - remainder; // round to near number
197 
198  if ( x < 0 )
199  ix = -ix;
200 
201  return (double) ix / precision;
202 }
static int KiROUND(double v)
KiROUND rounds a floating point number to an int using "round halfway cases away from zero"...
Definition: common.h:107
wxString SearchHelpFileFullPath ( const SEARCH_STACK aSearchStack,
const wxString &  aBaseName 
)

Function SearchHelpFileFullPath returns the help file's full path.

Return the KiCad help file with path and extension. Help files can be html (.html ext) or pdf (.pdf ext) files. A <BaseName>.html file is searched and if not found, <BaseName>.pdf file is searched in the same path. If the help file for the current locale is not found, an attempt to find the English version of the help file is made. Help file is searched in directories in this order: help/<canonical name> like help/en_GB help/<short name> like help/en help/en

Parameters
aSearchStackcontains some possible base dirs that may be above the the one actually holding aBaseName. These are starting points for nested searches.
aBaseNameis the name of the help file to search for,

without extension

.

Returns
wxEmptyString is returned if aBaseName is not found, else the full path & filename.

Definition at line 66 of file searchhelpfilefullpath.cpp.

References SEARCH_STACK::AddPaths(), FindFileInSearchPaths(), GetChars(), PGM_BASE::GetLocale(), and Pgm().

Referenced by EDA_BASE_FRAME::GetKicadHelp().

67 {
68  wxArrayString subdirs;
69  wxArrayString altsubdirs;
70  SEARCH_STACK ss = aSStack;
71 
72  // It might already be in aSStack, but why depend on other code
73  // far away when it's so easy to add it again (to our copy) as the first place to look.
74 
75  // This is CMAKE_INSTALL_PREFIX unless DEFAULT_INSTALL_PATH was defined during
76  // build configuration:
77  ss.AddPaths( wxT( DEFAULT_INSTALL_PATH ), 0 );
78 
79 #if defined(__WXMAC__)
80  ss.AddPaths( GetOSXKicadMachineDataDir() );
81  ss.AddPaths( Pgm().GetExecutablePath(), 0 );
82 
83  // OS X packages can have the help files in
84  // /Library/Application\ Support/kicad/help,
85  // and in Contents/SharedSupport/help inside the
86  // bundle.
87  // Below we account for an international subdirectory.
88  subdirs.Add( wxT( "help" ) );
89  altsubdirs.Add( wxT( "Contents" ) );
90  altsubdirs.Add( wxT( "SharedSupport" ) );
91  altsubdirs.Add( wxT( "help" ) );
92 #endif
93 
94 #if ! defined(__WXMAC__) // && defined(__linux__)
95  // This is the executable path minus the trailing bin directory used on Windows and Linux.
96  wxFileName tmp( Pgm().GetExecutablePath(), wxEmptyString );
97  wxArrayString binDirs = tmp.GetDirs();
98 
99  if( !binDirs.IsEmpty() && binDirs[ binDirs.GetCount() - 1 ].CmpNoCase( wxT( "bin" ) ) == 0 )
100  tmp.RemoveLastDir();
101 
102  ss.AddPaths( tmp.GetPath(), 0 );
103 
104  // Based on kicad-doc.bzr/CMakeLists.txt, line 20, the help files are
105  // installed into "<CMAKE_INSTALL_PREFIX>/share/doc/kicad/help" for linux.
106  // This is ${KICAD_HELP} var in that CMakeLists.txt file.
107  // Below we account for an international subdirectory.
108  subdirs.Add( wxT( "share" ) );
109  subdirs.Add( wxT( "doc" ) );
110  subdirs.Add( wxT( "kicad" ) );
111  subdirs.Add( wxT( "help" ) );
112 
113  // Based on kicad-doc.bzr/CMakeLists.txt, line 35, the help files are
114  // installed into "<CMAKE_INSTALL_PREFIX>/doc/help" for Windows.
115  // This is ${KICAD_HELP} var in that CMakeLists.txt file.
116  // Below we account for an international subdirectory.
117  altsubdirs.Add( wxT( "doc" ) );
118  altsubdirs.Add( wxT( "help" ) );
119 #endif
120 
121  // If there's a KICAD environment variable set, always use that guy's path first.
122  if( !Pgm().GetKicadEnvVariable().IsEmpty() )
123  ss.AddPaths( Pgm().GetKicadEnvVariable(), 0 );
124 
125  /* Search for a help file.
126  * we *must* find a help file.
127  * so help is searched in directories in this order:
128  * help/<canonical name> like help/en_GB
129  * help/<short name> like help/en
130  * help/en
131  */
132 
133  wxLocale* i18n = Pgm().GetLocale();
134 
135  // We try to find help file in help/<canonical name>
136  // If fails, try to find help file in help/<short canonical name>
137  // If fails, try to find help file in help/en
138  wxArrayString locale_name_dirs;
139  locale_name_dirs.Add( i18n->GetCanonicalName() ); // canonical name like fr_FR
140 
141  // wxLocale::GetName() does not return always the short name
142  locale_name_dirs.Add( i18n->GetName().BeforeLast( '_' ) ); // short canonical name like fr
143  locale_name_dirs.Add( wxT( "en" ) ); // default (en)
144 
145 #if defined(DEBUG) && 1
146  ss.Show( wxString( __func__ ) );
147  wxLogDebug( wxT( "%s: m_help_file:'%s'" ), __func__, GetChars( aBaseName ) );
148 #endif
149 
150  wxLogDebug( wxT( "Checking SEARCH_STACK for file %s" ), GetChars( aBaseName ) );
151 
152  // Help files can be html (.html ext) or pdf (.pdf ext) files.
153  // Therefore, <BaseName>.html file is searched and if not found,
154  // <BaseName>.pdf file is searched in the same paths
155  wxString fn;
156 
157  for( unsigned ii = 0; ii < locale_name_dirs.GetCount(); ii++ )
158  {
159  subdirs.Add( locale_name_dirs[ii] );
160  altsubdirs.Add( locale_name_dirs[ii] );
161 
162  fn = FindFileInSearchPaths( ss, aBaseName + wxT( ".html" ), &altsubdirs );
163 
164  if( !fn.IsEmpty() )
165  break;
166 
167  fn = FindFileInSearchPaths( ss, aBaseName + wxT( ".pdf" ), &altsubdirs );
168 
169  if( !fn.IsEmpty() )
170  break;
171 
172  fn = FindFileInSearchPaths( ss, aBaseName + wxT( ".html" ), &subdirs );
173 
174  if( !fn.IsEmpty() )
175  break;
176 
177  fn = FindFileInSearchPaths( ss, aBaseName + wxT( ".pdf" ), &subdirs );
178 
179  if( !fn.IsEmpty() )
180  break;
181 
182  subdirs.RemoveAt( subdirs.GetCount() - 1 );
183  altsubdirs.RemoveAt( altsubdirs.GetCount() - 1 );
184  }
185 
186  return fn;
187 }
PGM_BASE & Pgm()
The global Program "get" accessor.
Definition: kicad.cpp:65
Class SEARCH_STACK looks for files in a number of places.
Definition: search_stack.h:41
VTBL_ENTRY wxLocale * GetLocale()
Definition: pgm_base.h:175
wxString FindFileInSearchPaths(const SEARCH_STACK &aStack, const wxString &aFilename, const wxArrayString *aSubdirs)
Function FindFileInSearchPaths looks in "this" for aFilename, but first modifies every search path by...
static const wxChar * GetChars(const wxString &s)
Function GetChars returns a wxChar* to the actual wxChar* data within a wxString, and is helpful for ...
Definition: macros.h:92
void AddPaths(const wxString &aPaths, int aIndex=-1)
Function AddPaths insert or append path(s)
void wxStringSplit ( const wxString &  aText,
wxArrayString &  aStrings,
wxChar  aSplitter 
)

Function wxStringSplit splits aString to a string list separated at aSplitter.

Parameters
aTextis the text to split
aStringswill contain the splitted lines
aSplitteris the 'split' character

Definition at line 137 of file common.cpp.

Referenced by CINFO3D_VISU::AddShapeWithClearanceToContainer(), EDA_TEXT::Draw(), export_vrml_pcbtext(), EDA_TEXT::GetTextBox(), HTML_MESSAGE_BOX::ListSet(), DIALOG_FOOTPRINT_WIZARD_LIST::onShowTrace(), SCH_TEXT::Plot(), BRDITEMS_PLOTTER::PlotTextePcb(), TEXTE_PCB::TransformShapeWithClearanceToPolygonSet(), and EDA_TEXT::TransformTextShapeToSegmentList().

138 {
139  wxString tmp;
140 
141  for( unsigned ii = 0; ii < aText.Length(); ii++ )
142  {
143  if( aText[ii] == aSplitter )
144  {
145  aStrings.Add( tmp );
146  tmp.Clear();
147  }
148 
149  else
150  tmp << aText[ii];
151  }
152 
153  if( !tmp.IsEmpty() )
154  {
155  aStrings.Add( tmp );
156  }
157 }

Variable Documentation

KIGFX::COLOR4D g_GhostColor
EDA_UNITS_T g_UserUnit

display units

display units

TODO: All of these variables should be moved into the class were they are defined and used. Most of them probably belong in the application class.

Definition at line 56 of file common.cpp.

Referenced by DIALOG_COPPER_ZONE::AcceptOptions(), EDA_DRAW_FRAME::AddMenuZoomAndGrid(), Append_Track_Width_List(), TRACK_VIA_SIZE_MENU::AppendSizes(), DIALOG_PLOT::applyPlotSettings(), DIALOG_CREATE_ARRAY::calculateCircularArrayProperties(), class2gridRow(), DIALOG_DESIGN_RULES::CopyDimensionsListsToBoard(), DIALOG_EDIT_COMPONENT_IN_SCHEMATIC::copyPanelToSelectedField(), DIALOG_EDIT_LIBENTRY_FIELDS_IN_LIB::copyPanelToSelectedField(), DIALOG_EDIT_COMPONENT_IN_SCHEMATIC::copySelectedFieldToPanel(), DIALOG_EDIT_LIBENTRY_FIELDS_IN_LIB::copySelectedFieldToPanel(), PCB_EDIT_FRAME::Create_MuWaveComponent(), MWAVE::CreateMicrowaveInductor(), DIALOG_CREATE_ARRAY::DIALOG_CREATE_ARRAY(), DIALOG_EDIT_COMPONENT_IN_SCHEMATIC::DIALOG_EDIT_COMPONENT_IN_SCHEMATIC(), DIALOG_LABEL_EDITOR::DIALOG_LABEL_EDITOR(), DIALOG_LAYERS_SETUP::DIALOG_LAYERS_SETUP(), DIALOG_MOVE_EXACT::DIALOG_MOVE_EXACT(), DIALOG_DRC_CONTROL::DisplayDRCValues(), GERBER_FILE_IMAGE::DisplayImageInfo(), EDA_DRAW_FRAME::DisplayUnitsMsg(), drawCursorStrings(), drawTicksAlongLine(), PCB_EDIT_FRAME::Edit_Gap(), LIB_EDIT_FRAME::EditGraphicSymbol(), SCH_EDIT_FRAME::EditSheet(), SCH_EDIT_FRAME::EditSheetPin(), FOOTPRINT_EDIT_FRAME::Enter_Edge_Width(), PCB_EDIT_FRAME::GenFootprintsReport(), FOOTPRINT_EDIT_FRAME::GetConfigurationSettings(), PL_EDITOR_FRAME::GetConfigurationSettings(), SCH_EDIT_FRAME::GetConfigurationSettings(), PCB_EDIT_FRAME::GetConfigurationSettings(), GERBVIEW_FRAME::GetConfigurationSettings(), DIALOG_PAGES_SETTINGS::GetCustomSizeMilsFromDialog(), DIALOG_SET_GRID::getGridOrigin(), LIB_CIRCLE::GetMsgPanelInfo(), LIB_RECTANGLE::GetMsgPanelInfo(), LIB_POLYLINE::GetMsgPanelInfo(), LIB_TEXT::GetMsgPanelInfo(), LIB_BEZIER::GetMsgPanelInfo(), LIB_ARC::GetMsgPanelInfo(), LIB_PIN::GetMsgPanelInfo(), LIB_FIELD::GetMsgPanelInfo(), SCH_TEXT::GetMsgPanelInfo(), LIB_PIN::getMsgPanelInfoBase(), PANEL_PREV_3D::getOrientationVars(), getTickFormatForScale(), GRID_MENU::GRID_MENU(), DIALOG_GENERALOPTIONS::init(), DIALOG_NON_COPPER_ZONES_EDITOR::Init(), DIALOG_PLOT::Init_Dialog(), DIALOG_MODULE_BOARD_EDITOR::InitBoardProperties(), DIALOG_SVG_PRINT::initDialog(), DIALOG_GLOBAL_MODULES_FIELDS_EDITION::initDialog(), DIALOG_PAGES_SETTINGS::initDialog(), DIALOG_LABEL_EDITOR::InitDialog(), DIALOG_COPPER_ZONE::initDialog(), DIALOG_DESIGN_RULES::InitDimensionsLists(), DIALOG_LIB_EDIT_TEXT::initDlg(), DIALOG_PLOT_SCHEMATIC::initDlg(), DIALOG_DESIGN_RULES::InitGlobalRules(), DIALOG_MODULE_MODULE_EDITOR::initModeditProperties(), DIALOG_DISPLAY_OPTIONS::initOptDialog(), DIALOG_MODEDIT_OPTIONS::initValues(), DIALOG_PAD_PROPERTIES::initValues(), DIALOG_PRINT_USING_PRINTER::initValues(), LengthDoubleToString(), GERBVIEW_FRAME::Liste_D_Codes(), MWAVE_POLYGONAL_SHAPE_DLG::MWAVE_POLYGONAL_SHAPE_DLG(), DIALOG_PADS_MASK_CLEARANCE::myInit(), DIALOG_PAD_PROPERTIES::onCornerSizePercentChange(), DIALOG_COPPER_ZONE::OnCornerSmoothingModeChoice(), PANEL_PREV_3D::onDecrementOffset(), LIB_EDIT_FRAME::OnEditPin(), SCH_EDIT_FRAME::OnFindDrcMarker(), FOOTPRINT_VIEWER_FRAME::OnHotKey(), FOOTPRINT_EDIT_FRAME::OnHotKey(), PCB_EDIT_FRAME::OnHotKey(), GERBVIEW_FRAME::OnHotKey(), PANEL_PREV_3D::onIncrementOffset(), DIALOG_EDIT_LIBENTRY_FIELDS_IN_LIB::OnInitDialog(), PGE::IFACE::OnKifaceStart(), PANEL_PREV_3D::onMouseWheelOffset(), DIALOG_DISPLAY_OPTIONS::OnOKBUttonClick(), DIALOG_GENERALOPTIONS::OnOkClick(), DIALOG_LIB_EDIT_TEXT::OnOkClick(), DIALOG_NON_COPPER_ZONES_EDITOR::OnOkClick(), TARGET_PROPERTIES_DIALOG_EDITOR::OnOkClick(), DIALOG_DIMENSION_EDITOR::OnOKClick(), DIALOG_CREATE_ARRAY::OnOkClick(), SCH_EDIT_FRAME::OnPreferencesOptions(), DIALOG_LIB_EDIT_PIN::OnPropertiesChange(), EDA_DRAW_FRAME::OnSelectUnits(), EDA_DRAW_FRAME::OnUpdateUnits(), PutValueInLocalUnits(), DIALOG_PAGES_SETTINGS::SavePageSettings(), DIALOG_DESIGN_RULES::SetDataValidators(), PANEL_PREV_3D::SetModelDataIdx(), DIALOG_SVG_PRINT::SetPenWidth(), DIALOG_PRINT_USING_PRINTER::SetPenWidth(), WX_UNIT_TEXT::SetUnits(), PCBNEW_CONTROL::SwitchUnits(), TARGET_PROPERTIES_DIALOG_EDITOR::TARGET_PROPERTIES_DIALOG_EDITOR(), DIALOG_DESIGN_RULES::TestDataValidity(), DIALOG_LABEL_EDITOR::TextPropertiesAccept(), DialogEditModuleText::TransferDataFromWindow(), DIALOG_EDIT_ONE_FIELD::TransferDataFromWindow(), DIALOG_PCB_TEXT_PROPERTIES::TransferDataFromWindow(), DIALOG_MODEDIT_FP_BODY_ITEM_PROPERTIES::TransferDataFromWindow(), DIALOG_GRAPHIC_ITEM_PROPERTIES::TransferDataFromWindow(), DIALOG_EDIT_ONE_FIELD::TransferDataToWindow(), GERBVIEW_FRAME::updateDCodeSelectBox(), DIALOG_MOVE_EXACT::updateDlgTexts(), PCB_BASE_FRAME::updateGridSelectBox(), DIALOG_GLOBAL_EDIT_TRACKS_AND_VIAS::updateNetInfo(), DIALOG_PAD_PROPERTIES::updateRoundRectCornerValues(), SCH_BASE_FRAME::UpdateStatusBar(), PL_EDITOR_FRAME::UpdateStatusBar(), PCB_BASE_FRAME::UpdateStatusBar(), GERBVIEW_FRAME::UpdateStatusBar(), PCB_EDIT_FRAME::updateTraceWidthSelectBox(), PCB_EDIT_FRAME::updateViaSizeSelectBox(), DIALOG_MODEDIT_FP_BODY_ITEM_PROPERTIES::Validate(), DIALOG_GRAPHIC_ITEM_PROPERTIES::Validate(), ValueFromString(), ValueFromTextCtrl(), KIGFX::PREVIEW::ARC_ASSISTANT::ViewDraw(), and WX_UNIT_TEXT::WX_UNIT_TEXT().