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 #include <wx/log.h>
27 
28 #include <build_version.h>
29 #include <board.h>
30 #include <pad.h>
31 #include <pcb_group.h>
32 #include <pcb_shape.h>
33 #include <pcb_text.h>
34 #include <fp_text.h>
35 #include <zone.h>
36 #include <locale_io.h>
37 #include <netinfo.h>
39 
41 #include <kicad_clipboard.h>
42 
45  m_formatter()
46 {
47  m_out = &m_formatter;
48 }
49 
50 
52 {
53 }
54 
55 
57 {
58  m_board = aBoard;
59 }
60 
61 
62 void CLIPBOARD_IO::SaveSelection( const PCB_SELECTION& aSelected, bool isFootprintEditor )
63 {
64  VECTOR2I refPoint( 0, 0 );
65 
66  // dont even start if the selection is empty
67  if( aSelected.Empty() )
68  return;
69 
70  if( aSelected.HasReferencePoint() )
71  refPoint = aSelected.GetReferencePoint();
72 
73  // Prepare net mapping that assures that net codes saved in a file are consecutive integers
75 
76  if( aSelected.Size() == 1 && aSelected.Front()->Type() == PCB_FOOTPRINT_T )
77  {
78  // make the footprint safe to transfer to other pcbs
79  const FOOTPRINT* footprint = static_cast<FOOTPRINT*>( aSelected.Front() );
80  // Do not modify existing board
81  FOOTPRINT newFootprint( *footprint );
82 
83  for( PAD* pad : newFootprint.Pads() )
84  pad->SetNetCode( 0 );
85 
86  // locked means "locked in place"; copied items therefore can't be locked
87  newFootprint.SetLocked( false );
88 
89  // locate the reference point at (0, 0) in the copied items
90  newFootprint.Move( wxPoint( -refPoint.x, -refPoint.y ) );
91 
92  Format( static_cast<BOARD_ITEM*>( &newFootprint ) );
93  }
94  else if( isFootprintEditor )
95  {
96  FOOTPRINT partialFootprint( m_board );
97 
98  // Useful to copy the selection to the board editor (if any), and provides
99  // a dummy lib id.
100  // Perhaps not a good Id, but better than a empty id
101  KIID dummy;
102  LIB_ID id( "clipboard", dummy.AsString() );
103  partialFootprint.SetFPID( id );
104 
105  for( const EDA_ITEM* item : aSelected )
106  {
107  const PCB_GROUP* group = dynamic_cast<const PCB_GROUP*>( item );
108  BOARD_ITEM* clone;
109 
110  if( group )
111  clone = static_cast<BOARD_ITEM*>( group->DeepClone() );
112  else
113  clone = static_cast<BOARD_ITEM*>( item->Clone() );
114 
115  // If it is only a footprint, clear the nets from the pads
116  if( PAD* pad = dyn_cast<PAD*>( clone ) )
117  pad->SetNetCode( 0 );
118 
119  // Add the pad to the new footprint before moving to ensure the local coords are
120  // correct
121  partialFootprint.Add( clone );
122 
123  if( group )
124  {
125  static_cast<PCB_GROUP*>( clone )->RunOnDescendants(
126  [&]( BOARD_ITEM* descendant )
127  {
128  partialFootprint.Add( descendant );
129  } );
130  }
131 
132  // locate the reference point at (0, 0) in the copied items
133  clone->Move( (wxPoint) -refPoint );
134  }
135 
136  // Set the new relative internal local coordinates of copied items
137  FOOTPRINT* editedFootprint = m_board->Footprints().front();
138  wxPoint moveVector = partialFootprint.GetPosition() + editedFootprint->GetPosition();
139 
140  partialFootprint.MoveAnchorPosition( moveVector );
141 
142  Format( &partialFootprint, 0 );
143  }
144  else
145  {
146  // we will fake being a .kicad_pcb to get the full parser kicking
147  // This means we also need layers and nets
148  LOCALE_IO io;
149 
150  m_formatter.Print( 0, "(kicad_pcb (version %d) (generator pcbnew)\n",
152 
153  m_formatter.Print( 0, "\n" );
154 
157 
158  m_formatter.Print( 0, "\n" );
159 
160  for( EDA_ITEM* i : aSelected )
161  {
162  BOARD_ITEM* item = static_cast<BOARD_ITEM*>( i );
163  BOARD_ITEM* copy = nullptr;
164 
165  if( item->Type() == PCB_FP_SHAPE_T )
166  {
167  // Convert to PCB_SHAPE_T
168  copy = (BOARD_ITEM*) reinterpret_cast<PCB_SHAPE*>( item )->Clone();
169  copy->SetLayer( item->GetLayer() );
170  }
171  else if( item->Type() == PCB_FP_TEXT_T )
172  {
173  // Convert to PCB_TEXT_T
174  FOOTPRINT* footprint = static_cast<FOOTPRINT*>( item->GetParent() );
175  FP_TEXT* fp_text = static_cast<FP_TEXT*>( item );
176  PCB_TEXT* pcb_text = new PCB_TEXT( m_board );
177 
178  if( fp_text->GetText() == "${VALUE}" )
179  pcb_text->SetText( footprint->GetValue() );
180  else if( fp_text->GetText() == "${REFERENCE}" )
181  pcb_text->SetText( footprint->GetReference() );
182  else
183  pcb_text->CopyText( *fp_text );
184 
185  pcb_text->SetEffects( *fp_text );
186  pcb_text->SetLayer( fp_text->GetLayer() );
187  copy = pcb_text;
188  }
189  else if( item->Type() == PCB_PAD_T )
190  {
191  // Create a parent to own the copied pad
192  FOOTPRINT* footprint = new FOOTPRINT( m_board );
193  PAD* pad = (PAD*) item->Clone();
194 
195  footprint->SetPosition( pad->GetPosition() );
196  pad->SetPos0( wxPoint() );
197  footprint->Add( pad );
198  copy = footprint;
199  }
200  else if( item->Type() == PCB_FP_ZONE_T )
201  {
202  // Convert to PCB_ZONE_T
203  ZONE* zone = new ZONE( m_board );
204  zone->InitDataFromSrcInCopyCtor( *static_cast<ZONE*>( item ) );
205  copy = zone;
206  }
207  else if( item->Type() == PCB_GROUP_T )
208  {
209  copy = static_cast<PCB_GROUP*>( item )->DeepClone();
210  }
211  else
212  {
213  copy = static_cast<BOARD_ITEM*>( item->Clone() );
214  }
215 
216  auto prepItem = [&]( BOARD_ITEM* aItem )
217  {
218  aItem->SetLocked( false );
219  };
220 
221  if( copy )
222  {
223  prepItem( copy );
224 
225  // locate the reference point at (0, 0) in the copied items
226  copy->Move( (wxPoint) -refPoint );
227 
228  Format( copy, 1 );
229 
230  if( copy->Type() == PCB_GROUP_T )
231  {
232  static_cast<PCB_GROUP*>( copy )->RunOnDescendants( prepItem );
233  static_cast<PCB_GROUP*>( copy )->RunOnDescendants( [&]( BOARD_ITEM* titem )
234  {
235  Format( titem, 1 );
236  } );
237  }
238 
239  delete copy;
240  }
241  }
242  m_formatter.Print( 0, "\n)" );
243  }
244 
245  // These are placed at the end to minimize the open time of the clipboard
246  wxLogNull doNotLog; // disable logging of failed clipboard actions
247  auto clipboard = wxTheClipboard;
248  wxClipboardLocker clipboardLock( clipboard );
249 
250  if( !clipboardLock || !clipboard->IsOpened() )
251  return;
252 
253  clipboard->SetData( new wxTextDataObject( wxString( m_formatter.GetString().c_str(),
254  wxConvUTF8 ) ) );
255 
256  clipboard->Flush();
257 
258  #ifndef __WXOSX__
259  // This section exists to return the clipboard data, ensuring it has fully
260  // been processed by the system clipboard. This appears to be needed for
261  // extremely large clipboard copies on asynchronous linux clipboard managers
262  // such as KDE's Klipper. However, a read back of the data on OSX before the
263  // clipboard is closed seems to cause an ASAN error (heap-buffer-overflow)
264  // since it uses the cached version of the clipboard data and not the system
265  // clipboard data.
266  if( clipboard->IsSupported( wxDF_TEXT ) )
267  {
268  wxTextDataObject data;
269  clipboard->GetData( data );
270  ( void )data.GetText(); // Keep unused variable
271  }
272  #endif
273 }
274 
275 
277 {
278  BOARD_ITEM* item;
279  wxString result;
280 
281  wxLogNull doNotLog; // disable logging of failed clipboard actions
282 
283  auto clipboard = wxTheClipboard;
284  wxClipboardLocker clipboardLock( clipboard );
285 
286  if( !clipboardLock )
287  return nullptr;
288 
289  if( clipboard->IsSupported( wxDF_TEXT ) )
290  {
291  wxTextDataObject data;
292  clipboard->GetData( data );
293  result = data.GetText();
294  }
295 
296  try
297  {
298  item = PCB_IO::Parse( result );
299  }
300  catch (...)
301  {
302  item = nullptr;
303  }
304 
305  return item;
306 }
307 
308 
309 void CLIPBOARD_IO::Save( const wxString& aFileName, BOARD* aBoard,
310  const PROPERTIES* aProperties )
311 {
312  init( aProperties );
313 
314  m_board = aBoard; // after init()
315 
316  // Prepare net mapping that assures that net codes saved in a file are consecutive integers
317  m_mapping->SetBoard( aBoard );
318 
319  STRING_FORMATTER formatter;
320 
321  m_out = &formatter;
322 
323  m_out->Print( 0, "(kicad_pcb (version %d) (generator pcbnew)\n", SEXPR_BOARD_FILE_VERSION );
324 
325  Format( aBoard, 1 );
326 
327  m_out->Print( 0, ")\n" );
328 
329  wxLogNull doNotLog; // disable logging of failed clipboard actions
330 
331  auto clipboard = wxTheClipboard;
332  wxClipboardLocker clipboardLock( clipboard );
333 
334  if( !clipboardLock )
335  return;
336 
337  clipboard->SetData( new wxTextDataObject(
338  wxString( m_formatter.GetString().c_str(), wxConvUTF8 ) ) );
339  clipboard->Flush();
340 
341  // This section exists to return the clipboard data, ensuring it has fully
342  // been processed by the system clipboard. This appears to be needed for
343  // extremely large clipboard copies on asynchronous linux clipboard managers
344  // such as KDE's Klipper
345  if( clipboard->IsSupported( wxDF_TEXT ) )
346  {
347  wxTextDataObject data;
348  clipboard->GetData( data );
349  ( void )data.GetText(); // Keep unused variable
350  }
351 }
352 
353 
354 BOARD* CLIPBOARD_IO::Load( const wxString& aFileName, BOARD* aAppendToMe,
355  const PROPERTIES* aProperties, PROJECT* aProject )
356 {
357  std::string result;
358 
359  wxLogNull doNotLog; // disable logging of failed clipboard actions
360 
361  auto clipboard = wxTheClipboard;
362  wxClipboardLocker clipboardLock( clipboard );
363 
364  if( !clipboardLock )
365  return nullptr;
366 
367  if( clipboard->IsSupported( wxDF_TEXT ) )
368  {
369  wxTextDataObject data;
370  clipboard->GetData( data );
371 
372  result = data.GetText().mb_str();
373  }
374 
375  STRING_LINE_READER reader(result, wxT( "clipboard" ) );
376 
377  init( aProperties );
378 
379  m_parser->SetLineReader( &reader );
380  m_parser->SetBoard( aAppendToMe );
381 
382  BOARD_ITEM* item;
383  BOARD* board;
384 
385  try
386  {
387  item = m_parser->Parse();
388  }
389  catch( const FUTURE_FORMAT_ERROR& )
390  {
391  // Don't wrap a FUTURE_FORMAT_ERROR in another
392  throw;
393  }
394  catch( const PARSE_ERROR& parse_error )
395  {
396  if( m_parser->IsTooRecent() )
397  throw FUTURE_FORMAT_ERROR( parse_error, m_parser->GetRequiredVersion() );
398  else
399  throw;
400  }
401 
402  if( item->Type() != PCB_T )
403  {
404  // The parser loaded something that was valid, but wasn't a board.
405  THROW_PARSE_ERROR( _( "Clipboard content is not KiCad compatible" ),
406  m_parser->CurSource(), m_parser->CurLine(),
407  m_parser->CurLineNumber(), m_parser->CurOffset() );
408  }
409  else
410  {
411  board = dynamic_cast<BOARD*>( item );
412  }
413 
414  // Give the filename to the board if it's new
415  if( board && !aAppendToMe )
416  board->SetFileName( aFileName );
417 
418  return board;
419 }
VECTOR2I GetReferencePoint() const
Definition: selection.h:181
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:443
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:121
virtual void SetLayer(PCB_LAYER_ID aLayer)
Set the layer this item is on.
Definition: board_item.h:192
A base class for any item which can be embedded within the BOARD container class, and therefore insta...
Definition: board_item.h:80
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:129
class FP_SHAPE, a footprint edge
Definition: typeinfo.h:93
class PAD, a pad in a footprint
Definition: typeinfo.h:89
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:83
void SetBoard(const BOARD *aBoard)
Set a BOARD object that is used to prepare the net code map.
Definition: netinfo.h:193
static LIB_SYMBOL * dummy()
Used to draw a dummy shape when a LIB_SYMBOL is not found in library.
Definition: sch_symbol.cpp:70
#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:222
#define THROW_PARSE_ERROR(aProblem, aSource, aInputLine, aLineNumber, aByteIndex)
Definition: ki_exception.h:164
void SetBoard(BOARD *aBoard)
Definition: pcb_parser.h:95
virtual void SetText(const wxString &aText)
Definition: eda_text.cpp:114
FOOTPRINTS & Footprints()
Definition: board.h:233
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:107
const wxString & GetReference() const
Definition: footprint.h:421
#define _(s)
void MoveAnchorPosition(const wxPoint &aMoveVector)
Move the reference point of the footprint.
Definition: footprint.cpp:1488
Handle 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:226
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:516
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:88
bool Empty() const
Checks if there is anything selected.
Definition: selection.h:97
class FOOTPRINT, a footprint
Definition: typeinfo.h:88
void SetFPID(const LIB_ID &aFPID)
Definition: footprint.h:186
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:117
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:176
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.
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:103
A base class for most all the KiCad significant classes used in schematics and boards.
Definition: eda_item.h:100
wxPoint GetPosition() const override
Definition: footprint.h:177
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:472
int PRINTF_FUNC Print(int nestLevel, const char *fmt,...)
Format and write text to the output stream.
Definition: richio.cpp:408
Definition: pad.h:57
void SetPosition(const wxPoint &aPos) override
Definition: footprint.cpp:1442
void SaveSelection(const PCB_SELECTION &selected, bool isFootprintEditor)
BOARD_ITEM_CONTAINER * GetParent() const
Definition: board_item.h:166
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:171
EDA_ITEM * Front() const
Definition: selection.h:144
KICAD_T Type() const
Returns the type of object.
Definition: eda_item.h:113