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 <class_board.h>
29 #include <class_track.h>
30 #include <common.h>
31 #include <netinfo.h>
32 #include <pcb_parser.h>
33 
34 #include <kicad_plugin.h>
35 #include <kicad_clipboard.h>
36 
39  m_formatter(),
40  m_parser( new CLIPBOARD_PARSER() )
41 {
42  m_out = &m_formatter;
43 }
44 
45 
47 {
48  delete m_parser;
49 }
50 
51 
53 {
54  return &m_formatter;
55 }
56 
57 
59 {
60  m_board = aBoard;
61 }
62 
63 
65 {
66  VECTOR2I refPoint( 0, 0 );
67 
68  // dont even start if the selection is empty
69  if( aSelected.Empty() )
70  return;
71 
72  if( aSelected.HasReferencePoint() )
73  refPoint = aSelected.GetReferencePoint();
74 
75  // Prepare net mapping that assures that net codes saved in a file are consecutive integers
77 
78  // Differentiate how it is formatted depending on what selection contains
79  bool onlyModuleParts = true;
80  for( const auto i : aSelected )
81  {
82  // check if it not one of the module primitives
83  if( ( i->Type() != PCB_MODULE_EDGE_T ) &&
84  ( i->Type() != PCB_MODULE_TEXT_T ) &&
85  ( i->Type() != PCB_PAD_T ) )
86  {
87  onlyModuleParts = false;
88  break;
89  }
90  }
91 
92  // if there is only parts of a module selected, format it as a new module else
93  // format it as an entire board
94  MODULE partialModule( m_board );
95 
96  // only a module selected.
97  if( aSelected.Size() == 1 && aSelected.Front()->Type() == PCB_MODULE_T )
98  {
99  // make the module safe to transfer to other pcbs
100  const MODULE* mod = static_cast<MODULE*>( aSelected.Front() );
101  // Do not modify existing board
102  MODULE newModule( *mod );
103 
104  for( D_PAD* pad : newModule.Pads() )
105  pad->SetNetCode( 0 );
106 
107  // locked means "locked in place"; copied items therefore can't be locked
108  newModule.SetLocked( false );
109 
110  // locate the reference point at (0, 0) in the copied items
111  newModule.Move( wxPoint( -refPoint.x, -refPoint.y ) );
112 
113  Format( static_cast<BOARD_ITEM*>( &newModule ) );
114  }
115  // partial module selected.
116  else if( onlyModuleParts )
117  {
118  for( const auto item : aSelected )
119  {
120  BOARD_ITEM* clone = static_cast<BOARD_ITEM*>( item->Clone() );
121 
122  // Do not add reference/value - convert them to the common type
123  if( TEXTE_MODULE* text = dyn_cast<TEXTE_MODULE*>( clone ) )
124  text->SetType( TEXTE_MODULE::TEXT_is_DIVERS );
125 
126  // If it is only a module, clear the nets from the pads
127  if( D_PAD* pad = dyn_cast<D_PAD*>( clone ) )
128  pad->SetNetCode( 0 );
129 
130  // Add the pad to the new module before moving to ensure the local coords are correct
131  partialModule.Add( clone );
132 
133  // locate the reference point at (0, 0) in the copied items
134  clone->Move( (wxPoint) -refPoint );
135  }
136 
137  // Set the new relative internal local coordinates of copied items
138  MODULE* editedModule = m_board->Modules().front();
139  wxPoint moveVector = partialModule.GetPosition() + editedModule->GetPosition();
140 
141  partialModule.MoveAnchorPosition( moveVector );
142 
143  Format( &partialModule, 0 );
144 
145  }
146  // lots of stuff selected
147  else
148  {
149  // we will fake being a .kicad_pcb to get the full parser kicking
150  // This means we also need layers and nets
151  LOCALE_IO io;
152 
153  m_formatter.Print( 0, "(kicad_pcb (version %d) (host pcbnew %s)\n",
155 
156 
157  m_formatter.Print( 0, "\n" );
158 
161 
162  m_formatter.Print( 0, "\n" );
163 
164 
165  for( const auto i : aSelected )
166  {
167  // Dont format stuff that cannot exist standalone!
168  if( ( i->Type() != PCB_MODULE_EDGE_T ) &&
169  ( i->Type() != PCB_MODULE_TEXT_T ) &&
170  ( i->Type() != PCB_PAD_T ) )
171  {
172  auto item = static_cast<BOARD_ITEM*>( i );
173  std::unique_ptr<BOARD_ITEM> clone( static_cast<BOARD_ITEM*> ( item->Clone() ) );
174 
175  // locked means "locked in place"; copied items therefore can't be locked
176  if( MODULE* module = dyn_cast<MODULE*>( clone.get() ) )
177  module->SetLocked( false );
178  else if( TRACK* track = dyn_cast<TRACK*>( clone.get() ) )
179  track->SetLocked( false );
180 
181  // locate the reference point at (0, 0) in the copied items
182  clone->Move( (wxPoint) -refPoint );
183 
184  Format( clone.get(), 1 );
185  }
186  }
187  m_formatter.Print( 0, "\n)" );
188  }
189 
190  // These are placed at the end to minimize the open time of the clipboard
191  auto clipboard = wxTheClipboard;
192  wxClipboardLocker clipboardLock( clipboard );
193 
194  if( !clipboardLock || !clipboard->IsOpened() )
195  return;
196 
197  clipboard->SetData( new wxTextDataObject(
198  wxString( m_formatter.GetString().c_str(), wxConvUTF8 ) ) );
199 
200  clipboard->Flush();
201 
202  // This section exists to return the clipboard data, ensuring it has fully
203  // been processed by the system clipboard. This appears to be needed for
204  // extremely large clipboard copies on asynchronous linux clipboard managers
205  // such as KDE's Klipper
206  {
207  wxTextDataObject data;
208  clipboard->GetData( data );
209  ( void )data.GetText(); // Keep unused variable
210  }
211 }
212 
213 
215 {
216  BOARD_ITEM* item;
217  wxString result;
218 
219  auto clipboard = wxTheClipboard;
220  wxClipboardLocker clipboardLock( clipboard );
221 
222  if( !clipboardLock )
223  return nullptr;
224 
225 
226  if( clipboard->IsSupported( wxDF_TEXT ) )
227  {
228  wxTextDataObject data;
229  clipboard->GetData( data );
230  result = data.GetText();
231  }
232 
233  try
234  {
235  item = PCB_IO::Parse( result );
236  }
237  catch (...)
238  {
239  item = nullptr;
240  }
241 
242  return item;
243 }
244 
245 
246 void CLIPBOARD_IO::Save( const wxString& aFileName, BOARD* aBoard,
247  const PROPERTIES* aProperties )
248 {
249  init( aProperties );
250 
251  m_board = aBoard; // after init()
252 
253  // Prepare net mapping that assures that net codes saved in a file are consecutive integers
254  m_mapping->SetBoard( aBoard );
255 
256  STRING_FORMATTER formatter;
257 
258  m_out = &formatter;
259 
260  m_out->Print( 0, "(kicad_pcb (version %d) (host pcbnew %s)\n", SEXPR_BOARD_FILE_VERSION,
261  formatter.Quotew( GetBuildVersion() ).c_str() );
262 
263  Format( aBoard, 1 );
264 
265  m_out->Print( 0, ")\n" );
266 
267  auto clipboard = wxTheClipboard;
268  wxClipboardLocker clipboardLock( clipboard );
269 
270  if( !clipboardLock )
271  return;
272 
273  clipboard->SetData( new wxTextDataObject(
274  wxString( m_formatter.GetString().c_str(), wxConvUTF8 ) ) );
275  clipboard->Flush();
276 
277  // This section exists to return the clipboard data, ensuring it has fully
278  // been processed by the system clipboard. This appears to be needed for
279  // extremely large clipboard copies on asynchronous linux clipboard managers
280  // such as KDE's Klipper
281  {
282  wxTextDataObject data;
283  clipboard->GetData( data );
284  ( void )data.GetText(); // Keep unused variable
285  }
286 }
287 
288 
289 BOARD* CLIPBOARD_IO::Load( const wxString& aFileName,
290  BOARD* aAppendToMe, const PROPERTIES* aProperties )
291 {
292  std::string result;
293 
294  auto clipboard = wxTheClipboard;
295  wxClipboardLocker clipboardLock( clipboard );
296 
297  if( !clipboardLock )
298  return nullptr;
299 
300  if( clipboard->IsSupported( wxDF_TEXT ) )
301  {
302  wxTextDataObject data;
303  clipboard->GetData( data );
304 
305  result = data.GetText().mb_str();
306  }
307 
308  STRING_LINE_READER reader(result, wxT( "clipboard" ) );
309 
310  init( aProperties );
311 
312  m_parser->SetLineReader( &reader );
313  m_parser->SetBoard( aAppendToMe );
314 
315  BOARD_ITEM* item;
316  BOARD* board;
317 
318  try
319  {
320  item = m_parser->Parse();
321  }
322  catch( const FUTURE_FORMAT_ERROR& )
323  {
324  // Don't wrap a FUTURE_FORMAT_ERROR in another
325  throw;
326  }
327  catch( const PARSE_ERROR& parse_error )
328  {
329  if( m_parser->IsTooRecent() )
330  throw FUTURE_FORMAT_ERROR( parse_error, m_parser->GetRequiredVersion() );
331  else
332  throw;
333  }
334 
335  if( item->Type() != PCB_T )
336  {
337  // The parser loaded something that was valid, but wasn't a board.
338  THROW_PARSE_ERROR( _( "Clipboard content is not KiCad compatible" ),
339  m_parser->CurSource(), m_parser->CurLine(),
340  m_parser->CurLineNumber(), m_parser->CurOffset() );
341  }
342  else
343  {
344  board = dynamic_cast<BOARD*>( item );
345  }
346 
347  // Give the filename to the board if it's new
348  if( board && !aAppendToMe )
349  board->SetFileName( aFileName );
350 
351  return board;
352 }
BOARD * Load(const wxString &aFileName, BOARD *aAppendToMe, const PROPERTIES *aProperties=NULL) override
Function Load loads information from some input file format that this PLUGIN implementation knows abo...
VECTOR2I GetReferencePoint() const
Definition: selection.h:239
BOARD_ITEM * Parse()
OUTPUTFORMATTER * m_out
output any Format()s to this, no ownership
STRING_FORMATTER * GetFormatter()
Definition: typeinfo.h:85
BOARD_ITEM * Parse(const wxString &aClipboardSourceInput)
PCB_IO is a PLUGIN derivation for saving and loading Pcbnew s-expression formatted files.
Instantiate the current locale within a scope in which you are expecting exceptions to be thrown.
Definition: common.h:202
BOARD_ITEM is a base class for any item which can be embedded within the BOARD container class,...
void init(const PROPERTIES *aProperties)
#define SEXPR_BOARD_FILE_VERSION
Current s-expression file format version. 2 was the last legacy format version.
void formatNetInformation(BOARD *aBoard, int aNestLevel=0) const
formats the Nets and Netclasses
class D_PAD, a pad in a footprint
Definition: typeinfo.h:90
STRING_FORMATTER m_formatter
PROPERTIES is a name/value tuple with unique names and optional values.
Definition: properties.h:34
void MoveAnchorPosition(const wxPoint &aMoveVector)
Function MoveAnchorPosition Move the reference point of the footprint It looks like a move footprint:...
void SetBoard(BOARD *aBoard)
class EDGE_MODULE, a footprint edge
Definition: typeinfo.h:94
Definitions for tracks, vias and zones.
void SetBoard(const BOARD *aBoard)
Function SetBoard Sets a BOARD object that is used to prepare the net code map.
Definition: netinfo.h:282
class MODULE, a footprint
Definition: typeinfo.h:89
wxString GetRequiredVersion()
Return a string representing the version of kicad required to open this file.
Definition: pcb_parser.cpp:207
void SetBoard(BOARD *aBoard)
Definition: pcb_parser.h:342
MODULES & Modules()
Definition: class_board.h:229
wxString GetBuildVersion()
Get the full KiCad version string.
virtual void Move(const wxPoint &aMoveVector)
Function Move move this object.
void Save(const wxString &aFileName, BOARD *aBoard, const PROPERTIES *aProperties=NULL) override
Function Save will write aBoard to a storage file in a format that this PLUGIN implementation knows a...
const std::string & GetString()
Definition: richio.h:475
std::string Quotew(const wxString &aWrapee)
Definition: richio.cpp:472
void SetFileName(const wxString &aFileName)
Definition: class_board.h:216
#define THROW_PARSE_ERROR(aProblem, aSource, aInputLine, aLineNumber, aByteIndex)
BOARD_ITEM * Parse()
Definition: pcb_parser.cpp:467
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)
Function SetLineReader sets aLineReader into the parser, and returns the previous one,...
Definition: pcb_parser.h:335
bool Empty() const
Checks if there is anything selected.
Definition: selection.h:120
void Add(BOARD_ITEM *aItem, ADD_MODE aMode=ADD_MODE::INSERT) override
CLIPBOARD_PARSER * m_parser
class TEXTE_MODULE, text in a footprint
Definition: typeinfo.h:93
void formatBoardLayers(BOARD *aBoard, int aNestLevel=0) const
formats the board layer information
void SaveSelection(const PCBNEW_SELECTION &selected)
bool IsTooRecent()
Return whether a version number, if any was parsed, was too recent.
Definition: pcb_parser.h:360
Struct PARSE_ERROR contains a filename or source description, a problem input line,...
Definition: ki_exception.h:123
bool HasReferencePoint() const
Definition: selection.h:234
BOARD holds information pertinent to a Pcbnew printed circuit board.
Definition: class_board.h:163
#define _(s)
Definition: 3d_actions.cpp:33
#define CTL_STD_LAYER_NAMES
Use English Standard layer names.
BOARD * m_board
which BOARD, no ownership here
The common library.
Pcbnew s-expression file format parser definition.
Struct FUTURE_FORMAT_ERROR variant of PARSE_ERROR indicating that a syntax or related error was likel...
Definition: ki_exception.h:172
int PRINTF_FUNC Print(int nestLevel, const char *fmt,...)
Function Print formats and writes text to the output stream.
Definition: richio.cpp:404
void Format(BOARD_ITEM *aItem, int aNestLevel=0) const
Function Format outputs aItem to aFormatter in s-expression format.
STRING_LINE_READER is a LINE_READER that reads from a multiline 8 bit wide std::string.
Definition: richio.h:254
STRING_FORMATTER implements OUTPUTFORMATTER to a memory buffer.
Definition: richio.h:445
const wxPoint GetPosition() const override
Definition: class_module.h:210
KICAD_T Type() const
Function Type()
Definition: base_struct.h:212