KiCad PCB EDA Suite
kicad_clipboard.cpp
Go to the documentation of this file.
1 /*
2  * This program source code file is part of KiCad, a free EDA CAD application.
3  *
4  * Copyright (C) 2017 KiCad Developers, see CHANGELOG.TXT for contributors.
5  * @author Kristoffer Ödmark
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, you may find one here:
19  * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
20  * or you may search the http://www.gnu.org website for the version 2 license,
21  * or you may write to the Free Software Foundation, Inc.,
22  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23  */
24 
25 #include <wx/clipbrd.h>
26 
27 #include <build_version.h>
28 #include <board.h>
29 #include <track.h>
30 #include <pcb_shape.h>
31 #include <pcb_text.h>
32 #include <fp_text.h>
33 #include <locale_io.h>
34 #include <netinfo.h>
36 
38 #include <kicad_clipboard.h>
39 
42  m_formatter()
43 {
44  m_out = &m_formatter;
45 }
46 
47 
49 {
50 }
51 
52 
54 {
55  m_board = aBoard;
56 }
57 
58 
59 void CLIPBOARD_IO::SaveSelection( const PCB_SELECTION& aSelected, bool isFootprintEditor )
60 {
61  VECTOR2I refPoint( 0, 0 );
62 
63  // dont even start if the selection is empty
64  if( aSelected.Empty() )
65  return;
66 
67  if( aSelected.HasReferencePoint() )
68  refPoint = aSelected.GetReferencePoint();
69 
70  // Prepare net mapping that assures that net codes saved in a file are consecutive integers
72 
73  if( aSelected.Size() == 1 && aSelected.Front()->Type() == PCB_FOOTPRINT_T )
74  {
75  // make the footprint safe to transfer to other pcbs
76  const FOOTPRINT* footprint = static_cast<FOOTPRINT*>( aSelected.Front() );
77  // Do not modify existing board
78  FOOTPRINT newFootprint( *footprint );
79 
80  for( PAD* pad : newFootprint.Pads() )
81  pad->SetNetCode( 0 );
82 
83  // locked means "locked in place"; copied items therefore can't be locked
84  newFootprint.SetLocked( false );
85 
86  // locate the reference point at (0, 0) in the copied items
87  newFootprint.Move( wxPoint( -refPoint.x, -refPoint.y ) );
88 
89  Format( static_cast<BOARD_ITEM*>( &newFootprint ) );
90  }
91  else if( isFootprintEditor )
92  {
93  FOOTPRINT partialFootprint( m_board );
94 
95  // Usefull to copy the selection to the board editor (if any), and provides
96  // a dummy lib id.
97  // Perhaps not a good Id, but better than a empty id
98  KIID dummy;
99  LIB_ID id( "clipboard", dummy.AsString() );
100  partialFootprint.SetFPID( id );
101 
102  for( const EDA_ITEM* item : aSelected )
103  {
104  const PCB_GROUP* group = dynamic_cast<const PCB_GROUP*>( item );
105  BOARD_ITEM* clone;
106 
107  if( group )
108  clone = static_cast<BOARD_ITEM*>( group->DeepClone() );
109  else
110  clone = static_cast<BOARD_ITEM*>( item->Clone() );
111 
112  // If it is only a footprint, clear the nets from the pads
113  if( PAD* pad = dyn_cast<PAD*>( clone ) )
114  pad->SetNetCode( 0 );
115 
116  // Add the pad to the new footprint before moving to ensure the local coords are
117  // correct
118  partialFootprint.Add( clone );
119 
120  if( group )
121  {
122  static_cast<PCB_GROUP*>( clone )->RunOnDescendants(
123  [&]( BOARD_ITEM* descendant )
124  {
125  partialFootprint.Add( descendant );
126  } );
127  }
128 
129  // locate the reference point at (0, 0) in the copied items
130  clone->Move( (wxPoint) -refPoint );
131  }
132 
133  // Set the new relative internal local coordinates of copied items
134  FOOTPRINT* editedFootprint = m_board->Footprints().front();
135  wxPoint moveVector = partialFootprint.GetPosition() + editedFootprint->GetPosition();
136 
137  partialFootprint.MoveAnchorPosition( moveVector );
138 
139  Format( &partialFootprint, 0 );
140  }
141  else
142  {
143  // we will fake being a .kicad_pcb to get the full parser kicking
144  // This means we also need layers and nets
145  LOCALE_IO io;
146 
147  m_formatter.Print( 0, "(kicad_pcb (version %d) (generator pcbnew)\n",
149 
150  m_formatter.Print( 0, "\n" );
151 
154 
155  m_formatter.Print( 0, "\n" );
156 
157  for( EDA_ITEM* i : aSelected )
158  {
159  BOARD_ITEM* item = static_cast<BOARD_ITEM*>( i );
160  BOARD_ITEM* copy = nullptr;
161 
162  if( item->Type() == PCB_FP_SHAPE_T )
163  {
164  // Convert to PCB_SHAPE_T
165  copy = (BOARD_ITEM*) reinterpret_cast<PCB_SHAPE*>( item )->Clone();
166  copy->SetLayer( item->GetLayer() );
167  }
168  else if( item->Type() == PCB_FP_TEXT_T )
169  {
170  // Convert to PCB_TEXT_T
171  FOOTPRINT* footprint = static_cast<FOOTPRINT*>( item->GetParent() );
172  FP_TEXT* fp_text = static_cast<FP_TEXT*>( item );
173  PCB_TEXT* pcb_text = new PCB_TEXT( m_board );
174 
175  if( fp_text->GetText() == "${VALUE}" )
176  pcb_text->SetText( footprint->GetValue() );
177  else if( fp_text->GetText() == "${REFERENCE}" )
178  pcb_text->SetText( footprint->GetReference() );
179  else
180  pcb_text->CopyText( *fp_text );
181 
182  pcb_text->SetEffects( *fp_text );
183  pcb_text->SetLayer( fp_text->GetLayer() );
184  copy = pcb_text;
185  }
186  else if( item->Type() == PCB_PAD_T )
187  {
188  // Create a parent to own the copied pad
189  FOOTPRINT* footprint = new FOOTPRINT( m_board );
190  PAD* pad = (PAD*) item->Clone();
191 
192  footprint->SetPosition( pad->GetPosition() );
193  pad->SetPos0( wxPoint() );
194  footprint->Add( pad );
195  copy = footprint;
196  }
197  else if( item->Type() == PCB_FP_ZONE_T )
198  {
199  // Convert to PCB_ZONE_T
200  ZONE* zone = new ZONE( m_board );
201  zone->InitDataFromSrcInCopyCtor( *static_cast<ZONE*>( item ) );
202  copy = zone;
203  }
204  else if( item->Type() == PCB_GROUP_T )
205  {
206  copy = static_cast<PCB_GROUP*>( item )->DeepClone();
207  }
208  else
209  {
210  copy = static_cast<BOARD_ITEM*>( item->Clone() );
211  }
212 
213  auto prepItem = [&]( BOARD_ITEM* aItem )
214  {
215  aItem->SetLocked( false );
216  };
217 
218  if( copy )
219  {
220  prepItem( copy );
221 
222  // locate the reference point at (0, 0) in the copied items
223  copy->Move( (wxPoint) -refPoint );
224 
225  Format( copy, 1 );
226 
227  if( copy->Type() == PCB_GROUP_T )
228  {
229  static_cast<PCB_GROUP*>( copy )->RunOnDescendants( prepItem );
230  static_cast<PCB_GROUP*>( copy )->RunOnDescendants( [&]( BOARD_ITEM* titem )
231  {
232  Format( titem, 1 );
233  } );
234  }
235 
236  delete copy;
237  }
238  }
239  m_formatter.Print( 0, "\n)" );
240  }
241 
242  // These are placed at the end to minimize the open time of the clipboard
243  wxLogNull doNotLog; // disable logging of failed clipboard actions
244  auto clipboard = wxTheClipboard;
245  wxClipboardLocker clipboardLock( clipboard );
246 
247  if( !clipboardLock || !clipboard->IsOpened() )
248  return;
249 
250  clipboard->SetData( new wxTextDataObject( wxString( m_formatter.GetString().c_str(),
251  wxConvUTF8 ) ) );
252 
253  clipboard->Flush();
254 
255  #ifndef __WXOSX__
256  // This section exists to return the clipboard data, ensuring it has fully
257  // been processed by the system clipboard. This appears to be needed for
258  // extremely large clipboard copies on asynchronous linux clipboard managers
259  // such as KDE's Klipper. However, a read back of the data on OSX before the
260  // clipboard is closed seems to cause an ASAN error (heap-buffer-overflow)
261  // since it uses the cached version of the clipboard data and not the system
262  // clipboard data.
263  if( clipboard->IsSupported( wxDF_TEXT ) )
264  {
265  wxTextDataObject data;
266  clipboard->GetData( data );
267  ( void )data.GetText(); // Keep unused variable
268  }
269  #endif
270 }
271 
272 
274 {
275  BOARD_ITEM* item;
276  wxString result;
277 
278  wxLogNull doNotLog; // disable logging of failed clipboard actions
279 
280  auto clipboard = wxTheClipboard;
281  wxClipboardLocker clipboardLock( clipboard );
282 
283  if( !clipboardLock )
284  return nullptr;
285 
286  if( clipboard->IsSupported( wxDF_TEXT ) )
287  {
288  wxTextDataObject data;
289  clipboard->GetData( data );
290  result = data.GetText();
291  }
292 
293  try
294  {
295  item = PCB_IO::Parse( result );
296  }
297  catch (...)
298  {
299  item = nullptr;
300  }
301 
302  return item;
303 }
304 
305 
306 void CLIPBOARD_IO::Save( const wxString& aFileName, BOARD* aBoard,
307  const PROPERTIES* aProperties )
308 {
309  init( aProperties );
310 
311  m_board = aBoard; // after init()
312 
313  // Prepare net mapping that assures that net codes saved in a file are consecutive integers
314  m_mapping->SetBoard( aBoard );
315 
316  STRING_FORMATTER formatter;
317 
318  m_out = &formatter;
319 
320  m_out->Print( 0, "(kicad_pcb (version %d) (generator pcbnew)\n", SEXPR_BOARD_FILE_VERSION );
321 
322  Format( aBoard, 1 );
323 
324  m_out->Print( 0, ")\n" );
325 
326  wxLogNull doNotLog; // disable logging of failed clipboard actions
327 
328  auto clipboard = wxTheClipboard;
329  wxClipboardLocker clipboardLock( clipboard );
330 
331  if( !clipboardLock )
332  return;
333 
334  clipboard->SetData( new wxTextDataObject(
335  wxString( m_formatter.GetString().c_str(), wxConvUTF8 ) ) );
336  clipboard->Flush();
337 
338  // This section exists to return the clipboard data, ensuring it has fully
339  // been processed by the system clipboard. This appears to be needed for
340  // extremely large clipboard copies on asynchronous linux clipboard managers
341  // such as KDE's Klipper
342  if( clipboard->IsSupported( wxDF_TEXT ) )
343  {
344  wxTextDataObject data;
345  clipboard->GetData( data );
346  ( void )data.GetText(); // Keep unused variable
347  }
348 }
349 
350 
351 BOARD* CLIPBOARD_IO::Load( const wxString& aFileName, BOARD* aAppendToMe,
352  const PROPERTIES* aProperties, PROJECT* aProject )
353 {
354  std::string result;
355 
356  wxLogNull doNotLog; // disable logging of failed clipboard actions
357 
358  auto clipboard = wxTheClipboard;
359  wxClipboardLocker clipboardLock( clipboard );
360 
361  if( !clipboardLock )
362  return nullptr;
363 
364  if( clipboard->IsSupported( wxDF_TEXT ) )
365  {
366  wxTextDataObject data;
367  clipboard->GetData( data );
368 
369  result = data.GetText().mb_str();
370  }
371 
372  STRING_LINE_READER reader(result, wxT( "clipboard" ) );
373 
374  init( aProperties );
375 
376  m_parser->SetLineReader( &reader );
377  m_parser->SetBoard( aAppendToMe );
378 
379  BOARD_ITEM* item;
380  BOARD* board;
381 
382  try
383  {
384  item = m_parser->Parse();
385  }
386  catch( const FUTURE_FORMAT_ERROR& )
387  {
388  // Don't wrap a FUTURE_FORMAT_ERROR in another
389  throw;
390  }
391  catch( const PARSE_ERROR& parse_error )
392  {
393  if( m_parser->IsTooRecent() )
394  throw FUTURE_FORMAT_ERROR( parse_error, m_parser->GetRequiredVersion() );
395  else
396  throw;
397  }
398 
399  if( item->Type() != PCB_T )
400  {
401  // The parser loaded something that was valid, but wasn't a board.
402  THROW_PARSE_ERROR( _( "Clipboard content is not KiCad compatible" ),
403  m_parser->CurSource(), m_parser->CurLine(),
404  m_parser->CurLineNumber(), m_parser->CurOffset() );
405  }
406  else
407  {
408  board = dynamic_cast<BOARD*>( item );
409  }
410 
411  // Give the filename to the board if it's new
412  if( board && !aAppendToMe )
413  board->SetFileName( aFileName );
414 
415  return board;
416 }
VECTOR2I GetReferencePoint() const
Definition: selection.h:259
BOARD_ITEM * Parse()
OUTPUTFORMATTER * m_out
output any Format()s to this, no ownership
Definition: typeinfo.h:84
BOARD_ITEM * Parse(const wxString &aClipboardSourceInput)
A PLUGIN derivation for saving and loading Pcbnew s-expression formatted files.
class FP_TEXT, text in a footprint
Definition: typeinfo.h:92
Container for project specific data.
Definition: project.h:62
void formatBoardLayers(const BOARD *aBoard, int aNestLevel=0) const
formats the board layer information
const wxString & GetValue() const
Definition: footprint.h:445
Instantiate the current locale within a scope in which you are expecting exceptions to be thrown.
Definition: locale_io.h:40
void CopyText(const EDA_TEXT &aSrc)
Definition: eda_text.cpp:129
virtual void SetLayer(PCB_LAYER_ID aLayer)
Set the layer this item is on.
Definition: board_item.h:194
A base class for any item which can be embedded within the BOARD container class, and therefore insta...
Definition: board_item.h:82
class PCB_GROUP, a set of BOARD_ITEMs
Definition: typeinfo.h:108
void Save(const wxString &aFileName, BOARD *aBoard, const PROPERTIES *aProperties=nullptr) override
Write aBoard to a storage file in a format that this PLUGIN implementation knows about or it can be u...
A set of BOARD_ITEMs (i.e., without duplicates).
Definition: pcb_group.h:50
void init(const PROPERTIES *aProperties)
void SetEffects(const EDA_TEXT &aSrc)
Set the text effects from another instance.
Definition: eda_text.cpp:137
static LIB_PART * dummy()
Used to draw a dummy shape when a LIB_PART is not found in library.
Definition: sch_symbol.cpp:69
PCB_GROUP * DeepClone() const
Definition: pcb_group.cpp:136
class FP_SHAPE, a footprint edge
Definition: typeinfo.h:93
class PAD, a pad in a footprint
Definition: typeinfo.h:89
virtual void SetLocked(bool aLocked)
Modify the 'lock' status for of the item.
Definition: board_item.h:257
STRING_FORMATTER m_formatter
A logical library item identifier and consists of various portions much like a URI.
Definition: lib_id.h:51
A name/value tuple with unique names and optional values.
Definition: properties.h:33
void SetBoard(BOARD *aBoard)
virtual EDA_ITEM * Clone() const
Create a duplicate of this item with linked list members set to NULL.
Definition: eda_item.cpp:97
void SetBoard(const BOARD *aBoard)
Set a BOARD object that is used to prepare the net code map.
Definition: netinfo.h:193
#define CTL_FOR_CLIPBOARD
Format output for the clipboard instead of footprint library or BOARD.
Definition: kiid.h:44
wxString GetRequiredVersion()
Return a string representing the version of KiCad required to open this file.
Definition: pcb_parser.cpp:184
#define THROW_PARSE_ERROR(aProblem, aSource, aInputLine, aLineNumber, aByteIndex)
Definition: ki_exception.h:164
void SetBoard(BOARD *aBoard)
Definition: pcb_parser.h:94
virtual void SetText(const wxString &aText)
Definition: eda_text.cpp:121
void SetPos0(const wxPoint &aPos)
Definition: pad.h:225
virtual void Move(const wxPoint &aMoveVector)
Move this object.
Definition: board_item.h:277
FOOTPRINTS & Footprints()
Definition: board.h:303
void formatNetInformation(const BOARD *aBoard, int aNestLevel=0) const
formats the Nets and Netclasses
void InitDataFromSrcInCopyCtor(const ZONE &aZone)
Copy aZone data to me.
Definition: zone.cpp:105
const wxString & GetReference() const
Definition: footprint.h:423
void MoveAnchorPosition(const wxPoint &aMoveVector)
Move the reference point of the footprint.
Definition: footprint.cpp:1483
ZONE handles a list of polygons defining a copper zone.
Definition: zone.h:57
const std::string & GetString()
Definition: richio.h:435
void SetFileName(const wxString &aFileName)
Definition: board.h:296
BOARD * Load(const wxString &aFileName, BOARD *aAppendToMe, const PROPERTIES *aProperties=nullptr, PROJECT *aProject=nullptr) override
Load information from some input file format that this PLUGIN implementation knows about into either ...
BOARD_ITEM * Parse()
Definition: pcb_parser.cpp:473
NETINFO_MAPPING * m_mapping
mapping for net codes, so only not empty net codes are stored with consecutive integers as net codes
LINE_READER * SetLineReader(LINE_READER *aReader)
Set aLineReader into the parser, and returns the previous one, if any.
Definition: pcb_parser.h:87
bool Empty() const
Checks if there is anything selected.
Definition: selection.h:122
class FOOTPRINT, a footprint
Definition: typeinfo.h:88
void SetFPID(const LIB_ID &aFPID)
Definition: footprint.h:191
void Format(const BOARD_ITEM *aItem, int aNestLevel=0) const
Output aItem to aFormatter in s-expression format.
bool IsTooRecent()
Return whether a version number, if any was parsed, was too recent.
Definition: pcb_parser.h:116
A filename or source description, a problem input line, a line number, a byte offset,...
Definition: ki_exception.h:118
bool HasReferencePoint() const
Definition: selection.h:254
wxPoint GetPosition() const override
Definition: pad.h:177
Information pertinent to a Pcbnew printed circuit board.
Definition: board.h:190
#define SEXPR_BOARD_FILE_VERSION
Current s-expression file format version. 2 was the last legacy format version.
#define _(s)
Definition: 3d_actions.cpp:33
class ZONE, managed by a footprint
Definition: typeinfo.h:94
BOARD * m_board
which BOARD, no ownership here
int Size() const
Returns the number of selected parts.
Definition: selection.h:128
A base class for most all the KiCad significant classes used in schematics and boards.
Definition: eda_item.h:149
wxPoint GetPosition() const override
Definition: footprint.h:182
Pcbnew s-expression file format parser definition.
Variant of PARSE_ERROR indicating that a syntax or related error was likely caused by a file generate...
Definition: ki_exception.h:174
void Add(BOARD_ITEM *aItem, ADD_MODE aMode=ADD_MODE::INSERT) override
Removes an item from the container.
Definition: footprint.cpp:467
int PRINTF_FUNC Print(int nestLevel, const char *fmt,...)
Format and write text to the output stream.
Definition: richio.cpp:408
Definition: pad.h:60
void SetPosition(const wxPoint &aPos) override
Definition: footprint.cpp:1437
void SaveSelection(const PCB_SELECTION &selected, bool isFootprintEditor)
BOARD_ITEM_CONTAINER * GetParent() const
Definition: board_item.h:168
Is a LINE_READER that reads from a multiline 8 bit wide std::string.
Definition: richio.h:237
Implement an OUTPUTFORMATTER to a memory buffer.
Definition: richio.h:411
virtual PCB_LAYER_ID GetLayer() const
Return the primary layer this item is on.
Definition: board_item.h:173
EDA_ITEM * Front() const
Definition: selection.h:203
KICAD_T Type() const
Returns the type of object.
Definition: eda_item.h:162