You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1296 lines
39 KiB

4 years ago
2 years ago
Make the new schematic and symbol library file formats the default. This is a very large and potentially disruptive change so this will be an unusually long and detailed commit message. The new file formats are now the default in both the schematic and symbol library editors. Existing symbol libraries will be saved in their current format until new features are added to library symbols. Once this happens, both the legacy schematic and symbol file formats will be no longer be savable and existing libraries will have to be converted. Saving to the legacy file formats is still available for round robin testing and should not be used for normal editing. When loading the legacy schematic file, it is imperative that the schematic library symbols are rescued and/or remapped to valid library identifiers. Otherwise, there will be no way to link to the original library symbol and the user will be required manually set the library identifier. The cached symbol will be saved in the schematic file so the last library symbol in the cache will still be used but there will be no way to update it from the original library. The next save after loading a legacy schematic file will be converted to the s-expression file format. Schematics with hierarchical sheets will automatically have all sheet file name extensions changed to .kicad_sym and saved to the new format as well. Appending schematics requires that the schematic to append has already been converted to the new file format. This is required to ensure that library symbols are guaranteed to be valid for the appended schematic. The schematic symbol library symbol link resolution has been moved out of the SCH_COMPONENT object and move into the SCH_SCREEN object that owns the symbol. This was done to ensure that there is a single place where the library symbol links get resolved rather than the dozen or so different code paths that previously existed. It also removes the necessity of the SCH_COMPONENT object of requiring any knowledge of the symbol library table and/or the cache library. When opening an s-expression schematic, the legacy cache library is not loaded so any library symbols not rescued cannot be loaded. Broken library symbol links will have to be manually resolved by adding the cache library to the symbol library table and changing the links in the schematic symbol. Now that the library symbols are embedded in the schematic file, the SCH_SCREEN object maintains the list of library symbols for the schematic automatically. No external manipulation of this library cache should ever occur. ADDED: S-expression schematic and symbol library file formats.
6 years ago
* KIWAY Milestone A): Make major modules into DLL/DSOs. ! The initial testing of this commit should be done using a Debug build so that all the wxASSERT()s are enabled. Also, be sure and keep enabled the USE_KIWAY_DLLs option. The tree won't likely build without it. Turning it off is senseless anyways. If you want stable code, go back to a prior version, the one tagged with "stable". * Relocate all functionality out of the wxApp derivative into more finely targeted purposes: a) DLL/DSO specific b) PROJECT specific c) EXE or process specific d) configuration file specific data e) configuration file manipulations functions. All of this functionality was blended into an extremely large wxApp derivative and that was incompatible with the desire to support multiple concurrently loaded DLL/DSO's ("KIFACE")s and multiple concurrently open projects. An amazing amount of organization come from simply sorting each bit of functionality into the proper box. * Switch to wxConfigBase from wxConfig everywhere except instantiation. * Add classes KIWAY, KIFACE, KIFACE_I, SEARCH_STACK, PGM_BASE, PGM_KICAD, PGM_SINGLE_TOP, * Remove "Return" prefix on many function names. * Remove obvious comments from CMakeLists.txt files, and from else() and endif()s. * Fix building boost for use in a DSO on linux. * Remove some of the assumptions in the CMakeLists.txt files that windows had to be the host platform when building windows binaries. * Reduce the number of wxStrings being constructed at program load time via static construction. * Pass wxConfigBase* to all SaveSettings() and LoadSettings() functions so that these functions are useful even when the wxConfigBase comes from another source, as is the case in the KICAD_MANAGER_FRAME. * Move the setting of the KIPRJMOD environment variable into class PROJECT, so that it can be moved into a project variable soon, and out of FP_LIB_TABLE. * Add the KIWAY_PLAYER which is associated with a particular PROJECT, and all its child wxFrames and wxDialogs now have a Kiway() member function which returns a KIWAY& that that window tree branch is in support of. This is like wxWindows DNA in that child windows get this member with proper value at time of construction. * Anticipate some of the needs for milestones B) and C) and make code adjustments now in an effort to reduce work in those milestones. * No testing has been done for python scripting, since milestone C) has that being largely reworked and re-thought-out.
12 years ago
* KIWAY Milestone A): Make major modules into DLL/DSOs. ! The initial testing of this commit should be done using a Debug build so that all the wxASSERT()s are enabled. Also, be sure and keep enabled the USE_KIWAY_DLLs option. The tree won't likely build without it. Turning it off is senseless anyways. If you want stable code, go back to a prior version, the one tagged with "stable". * Relocate all functionality out of the wxApp derivative into more finely targeted purposes: a) DLL/DSO specific b) PROJECT specific c) EXE or process specific d) configuration file specific data e) configuration file manipulations functions. All of this functionality was blended into an extremely large wxApp derivative and that was incompatible with the desire to support multiple concurrently loaded DLL/DSO's ("KIFACE")s and multiple concurrently open projects. An amazing amount of organization come from simply sorting each bit of functionality into the proper box. * Switch to wxConfigBase from wxConfig everywhere except instantiation. * Add classes KIWAY, KIFACE, KIFACE_I, SEARCH_STACK, PGM_BASE, PGM_KICAD, PGM_SINGLE_TOP, * Remove "Return" prefix on many function names. * Remove obvious comments from CMakeLists.txt files, and from else() and endif()s. * Fix building boost for use in a DSO on linux. * Remove some of the assumptions in the CMakeLists.txt files that windows had to be the host platform when building windows binaries. * Reduce the number of wxStrings being constructed at program load time via static construction. * Pass wxConfigBase* to all SaveSettings() and LoadSettings() functions so that these functions are useful even when the wxConfigBase comes from another source, as is the case in the KICAD_MANAGER_FRAME. * Move the setting of the KIPRJMOD environment variable into class PROJECT, so that it can be moved into a project variable soon, and out of FP_LIB_TABLE. * Add the KIWAY_PLAYER which is associated with a particular PROJECT, and all its child wxFrames and wxDialogs now have a Kiway() member function which returns a KIWAY& that that window tree branch is in support of. This is like wxWindows DNA in that child windows get this member with proper value at time of construction. * Anticipate some of the needs for milestones B) and C) and make code adjustments now in an effort to reduce work in those milestones. * No testing has been done for python scripting, since milestone C) has that being largely reworked and re-thought-out.
12 years ago
* KIWAY Milestone A): Make major modules into DLL/DSOs. ! The initial testing of this commit should be done using a Debug build so that all the wxASSERT()s are enabled. Also, be sure and keep enabled the USE_KIWAY_DLLs option. The tree won't likely build without it. Turning it off is senseless anyways. If you want stable code, go back to a prior version, the one tagged with "stable". * Relocate all functionality out of the wxApp derivative into more finely targeted purposes: a) DLL/DSO specific b) PROJECT specific c) EXE or process specific d) configuration file specific data e) configuration file manipulations functions. All of this functionality was blended into an extremely large wxApp derivative and that was incompatible with the desire to support multiple concurrently loaded DLL/DSO's ("KIFACE")s and multiple concurrently open projects. An amazing amount of organization come from simply sorting each bit of functionality into the proper box. * Switch to wxConfigBase from wxConfig everywhere except instantiation. * Add classes KIWAY, KIFACE, KIFACE_I, SEARCH_STACK, PGM_BASE, PGM_KICAD, PGM_SINGLE_TOP, * Remove "Return" prefix on many function names. * Remove obvious comments from CMakeLists.txt files, and from else() and endif()s. * Fix building boost for use in a DSO on linux. * Remove some of the assumptions in the CMakeLists.txt files that windows had to be the host platform when building windows binaries. * Reduce the number of wxStrings being constructed at program load time via static construction. * Pass wxConfigBase* to all SaveSettings() and LoadSettings() functions so that these functions are useful even when the wxConfigBase comes from another source, as is the case in the KICAD_MANAGER_FRAME. * Move the setting of the KIPRJMOD environment variable into class PROJECT, so that it can be moved into a project variable soon, and out of FP_LIB_TABLE. * Add the KIWAY_PLAYER which is associated with a particular PROJECT, and all its child wxFrames and wxDialogs now have a Kiway() member function which returns a KIWAY& that that window tree branch is in support of. This is like wxWindows DNA in that child windows get this member with proper value at time of construction. * Anticipate some of the needs for milestones B) and C) and make code adjustments now in an effort to reduce work in those milestones. * No testing has been done for python scripting, since milestone C) has that being largely reworked and re-thought-out.
12 years ago
Make the new schematic and symbol library file formats the default. This is a very large and potentially disruptive change so this will be an unusually long and detailed commit message. The new file formats are now the default in both the schematic and symbol library editors. Existing symbol libraries will be saved in their current format until new features are added to library symbols. Once this happens, both the legacy schematic and symbol file formats will be no longer be savable and existing libraries will have to be converted. Saving to the legacy file formats is still available for round robin testing and should not be used for normal editing. When loading the legacy schematic file, it is imperative that the schematic library symbols are rescued and/or remapped to valid library identifiers. Otherwise, there will be no way to link to the original library symbol and the user will be required manually set the library identifier. The cached symbol will be saved in the schematic file so the last library symbol in the cache will still be used but there will be no way to update it from the original library. The next save after loading a legacy schematic file will be converted to the s-expression file format. Schematics with hierarchical sheets will automatically have all sheet file name extensions changed to .kicad_sym and saved to the new format as well. Appending schematics requires that the schematic to append has already been converted to the new file format. This is required to ensure that library symbols are guaranteed to be valid for the appended schematic. The schematic symbol library symbol link resolution has been moved out of the SCH_COMPONENT object and move into the SCH_SCREEN object that owns the symbol. This was done to ensure that there is a single place where the library symbol links get resolved rather than the dozen or so different code paths that previously existed. It also removes the necessity of the SCH_COMPONENT object of requiring any knowledge of the symbol library table and/or the cache library. When opening an s-expression schematic, the legacy cache library is not loaded so any library symbols not rescued cannot be loaded. Broken library symbol links will have to be manually resolved by adding the cache library to the symbol library table and changing the links in the schematic symbol. Now that the library symbols are embedded in the schematic file, the SCH_SCREEN object maintains the list of library symbols for the schematic automatically. No external manipulation of this library cache should ever occur. ADDED: S-expression schematic and symbol library file formats.
6 years ago
Make the new schematic and symbol library file formats the default. This is a very large and potentially disruptive change so this will be an unusually long and detailed commit message. The new file formats are now the default in both the schematic and symbol library editors. Existing symbol libraries will be saved in their current format until new features are added to library symbols. Once this happens, both the legacy schematic and symbol file formats will be no longer be savable and existing libraries will have to be converted. Saving to the legacy file formats is still available for round robin testing and should not be used for normal editing. When loading the legacy schematic file, it is imperative that the schematic library symbols are rescued and/or remapped to valid library identifiers. Otherwise, there will be no way to link to the original library symbol and the user will be required manually set the library identifier. The cached symbol will be saved in the schematic file so the last library symbol in the cache will still be used but there will be no way to update it from the original library. The next save after loading a legacy schematic file will be converted to the s-expression file format. Schematics with hierarchical sheets will automatically have all sheet file name extensions changed to .kicad_sym and saved to the new format as well. Appending schematics requires that the schematic to append has already been converted to the new file format. This is required to ensure that library symbols are guaranteed to be valid for the appended schematic. The schematic symbol library symbol link resolution has been moved out of the SCH_COMPONENT object and move into the SCH_SCREEN object that owns the symbol. This was done to ensure that there is a single place where the library symbol links get resolved rather than the dozen or so different code paths that previously existed. It also removes the necessity of the SCH_COMPONENT object of requiring any knowledge of the symbol library table and/or the cache library. When opening an s-expression schematic, the legacy cache library is not loaded so any library symbols not rescued cannot be loaded. Broken library symbol links will have to be manually resolved by adding the cache library to the symbol library table and changing the links in the schematic symbol. Now that the library symbols are embedded in the schematic file, the SCH_SCREEN object maintains the list of library symbols for the schematic automatically. No external manipulation of this library cache should ever occur. ADDED: S-expression schematic and symbol library file formats.
6 years ago
  1. /*
  2. * This program source code file is part of KiCad, a free EDA CAD application.
  3. *
  4. * Copyright (C) 2019 Jean-Pierre Charras, jp.charras at wanadoo.fr
  5. * Copyright (C) 2008 Wayne Stambaugh <stambaughw@gmail.com>
  6. * Copyright (C) 2004-2023 KiCad Developers, see AUTHORS.txt for contributors.
  7. *
  8. * This program is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU General Public License
  10. * as published by the Free Software Foundation; either version 2
  11. * of the License, or (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program; if not, you may find one here:
  20. * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  21. * or you may search the http://www.gnu.org website for the version 2 license,
  22. * or you may write to the Free Software Foundation, Inc.,
  23. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
  24. */
  25. #include <pgm_base.h>
  26. #include <confirm.h>
  27. #include <kiway.h>
  28. #include <widgets/wx_infobar.h>
  29. #include <tools/ee_actions.h>
  30. #include <tools/symbol_editor_drawing_tools.h>
  31. #include <symbol_edit_frame.h>
  32. #include <symbol_library.h>
  33. #include <template_fieldnames.h>
  34. #include <wildcards_and_files_ext.h>
  35. #include <symbol_lib_table.h>
  36. #include <lib_symbol_library_manager.h>
  37. #include <symbol_tree_pane.h>
  38. #include <project/project_file.h>
  39. #include <widgets/lib_tree.h>
  40. #include <sch_io/kicad_legacy/sch_io_kicad_legacy.h>
  41. #include <sch_io/kicad_sexpr/sch_io_kicad_sexpr.h>
  42. #include <dialogs/dialog_lib_new_symbol.h>
  43. #include <eda_list_dialog.h>
  44. #include <wx/clipbrd.h>
  45. #include <wx/filedlg.h>
  46. #include <wx/log.h>
  47. #include <project_sch.h>
  48. #include <string_utils.h>
  49. #include "symbol_saveas_type.h"
  50. #include <widgets/symbol_filedlg_save_as.h>
  51. void SYMBOL_EDIT_FRAME::UpdateTitle()
  52. {
  53. wxString title;
  54. if( GetCurSymbol() && IsSymbolFromSchematic() )
  55. {
  56. if( GetScreen() && GetScreen()->IsContentModified() )
  57. title = wxT( "*" );
  58. title += m_reference;
  59. title += wxS( " " ) + _( "[from schematic]" );
  60. }
  61. else if( GetCurSymbol() )
  62. {
  63. if( GetScreen() && GetScreen()->IsContentModified() )
  64. title = wxT( "*" );
  65. title += UnescapeString( GetCurSymbol()->GetLibId().Format() );
  66. if( m_libMgr && m_libMgr->IsLibraryReadOnly( GetCurLib() ) )
  67. title += wxS( " " ) + _( "[Read Only Library]" );
  68. }
  69. else
  70. {
  71. title = _( "[no symbol loaded]" );
  72. }
  73. title += wxT( " \u2014 " ) + _( "Symbol Editor" );
  74. SetTitle( title );
  75. }
  76. void SYMBOL_EDIT_FRAME::SelectActiveLibrary( const wxString& aLibrary )
  77. {
  78. wxString selectedLib = aLibrary;
  79. if( selectedLib.empty() )
  80. selectedLib = SelectLibraryFromList();
  81. if( !selectedLib.empty() )
  82. SetCurLib( selectedLib );
  83. UpdateTitle();
  84. }
  85. bool SYMBOL_EDIT_FRAME::saveCurrentSymbol()
  86. {
  87. if( GetCurSymbol() )
  88. {
  89. if( IsSymbolFromSchematic() )
  90. {
  91. SCH_EDIT_FRAME* schframe = (SCH_EDIT_FRAME*) Kiway().Player( FRAME_SCH, false );
  92. if( !schframe ) // happens when the schematic editor has been closed
  93. {
  94. DisplayErrorMessage( this, _( "No schematic currently open." ) );
  95. return false;
  96. }
  97. else
  98. {
  99. schframe->SaveSymbolToSchematic( *m_symbol, m_schematicSymbolUUID );
  100. GetScreen()->SetContentModified( false );
  101. return true;
  102. }
  103. }
  104. else
  105. {
  106. const wxString& libName = GetCurSymbol()->GetLibId().GetLibNickname();
  107. if( m_libMgr->IsLibraryReadOnly( libName ) )
  108. {
  109. wxString msg = wxString::Format( _( "Symbol library '%s' is not writable." ),
  110. libName );
  111. wxString msg2 = _( "You must save to a different location." );
  112. if( OKOrCancelDialog( this, _( "Warning" ), msg, msg2 ) == wxID_OK )
  113. return saveLibrary( libName, true );
  114. }
  115. else
  116. {
  117. return saveLibrary( libName, false );
  118. }
  119. }
  120. }
  121. return false;
  122. }
  123. bool SYMBOL_EDIT_FRAME::LoadSymbol( const LIB_ID& aLibId, int aUnit, int aConvert )
  124. {
  125. LIB_ID libId = aLibId;
  126. // Some libraries can't be edited, so load the underlying chosen symbol
  127. if( SYMBOL_LIB_TABLE_ROW* lib = m_libMgr->GetLibrary( aLibId.GetLibNickname() ) )
  128. {
  129. if( lib->SchLibType() == SCH_IO_MGR::SCH_DATABASE
  130. || lib->SchLibType() == SCH_IO_MGR::SCH_CADSTAR_ARCHIVE
  131. || lib->SchLibType() == SCH_IO_MGR::SCH_HTTP )
  132. {
  133. try
  134. {
  135. LIB_SYMBOL* readOnlySym = PROJECT_SCH::SchSymbolLibTable( &Prj() )->LoadSymbol( aLibId );
  136. if( readOnlySym && readOnlySym->GetSourceLibId().IsValid() )
  137. libId = readOnlySym->GetSourceLibId();
  138. }
  139. catch( const IO_ERROR& ioe )
  140. {
  141. wxString msg;
  142. msg.Printf( _( "Error loading symbol %s from library '%s'." ),
  143. aLibId.GetUniStringLibId(), aLibId.GetUniStringLibItemName() );
  144. DisplayErrorMessage( this, msg, ioe.What() );
  145. return false;
  146. }
  147. }
  148. }
  149. if( GetCurSymbol() && !IsSymbolFromSchematic()
  150. && GetCurSymbol()->GetLibId() == libId
  151. && GetUnit() == aUnit
  152. && GetConvert() == aConvert )
  153. {
  154. return true;
  155. }
  156. if( GetCurSymbol() && IsSymbolFromSchematic() && GetScreen()->IsContentModified() )
  157. {
  158. if( !HandleUnsavedChanges( this, _( "The current symbol has been modified. Save changes?" ),
  159. [&]() -> bool
  160. {
  161. return saveCurrentSymbol();
  162. } ) )
  163. {
  164. return false;
  165. }
  166. }
  167. SelectActiveLibrary( libId.GetLibNickname() );
  168. if( LoadSymbolFromCurrentLib( libId.GetLibItemName(), aUnit, aConvert ) )
  169. {
  170. m_treePane->GetLibTree()->SelectLibId( libId );
  171. m_treePane->GetLibTree()->ExpandLibId( libId );
  172. m_centerItemOnIdle = libId;
  173. Bind( wxEVT_IDLE, &SYMBOL_EDIT_FRAME::centerItemIdleHandler, this );
  174. setSymWatcher( &libId );
  175. return true;
  176. }
  177. return false;
  178. }
  179. void SYMBOL_EDIT_FRAME::centerItemIdleHandler( wxIdleEvent& aEvent )
  180. {
  181. m_treePane->GetLibTree()->CenterLibId( m_centerItemOnIdle );
  182. Unbind( wxEVT_IDLE, &SYMBOL_EDIT_FRAME::centerItemIdleHandler, this );
  183. }
  184. bool SYMBOL_EDIT_FRAME::LoadSymbolFromCurrentLib( const wxString& aAliasName, int aUnit,
  185. int aConvert )
  186. {
  187. LIB_SYMBOL* alias = nullptr;
  188. try
  189. {
  190. alias = PROJECT_SCH::SchSymbolLibTable( &Prj() )->LoadSymbol( GetCurLib(), aAliasName );
  191. }
  192. catch( const IO_ERROR& ioe )
  193. {
  194. wxString msg;
  195. msg.Printf( _( "Error loading symbol %s from library '%s'." ),
  196. aAliasName,
  197. GetCurLib() );
  198. DisplayErrorMessage( this, msg, ioe.What() );
  199. return false;
  200. }
  201. if( !alias || !LoadOneLibrarySymbolAux( alias, GetCurLib(), aUnit, aConvert ) )
  202. return false;
  203. // Enable synchronized pin edit mode for symbols with interchangeable units
  204. m_SyncPinEdit = GetCurSymbol()->IsMulti() && !GetCurSymbol()->UnitsLocked();
  205. ClearUndoRedoList();
  206. m_toolManager->RunAction( ACTIONS::zoomFitScreen );
  207. SetShowDeMorgan( GetCurSymbol()->Flatten()->HasConversion() );
  208. if( aUnit > 0 )
  209. RebuildSymbolUnitsList();
  210. return true;
  211. }
  212. bool SYMBOL_EDIT_FRAME::LoadOneLibrarySymbolAux( LIB_SYMBOL* aEntry, const wxString& aLibrary,
  213. int aUnit, int aConvert )
  214. {
  215. bool rebuildMenuAndToolbar = false;
  216. if( !aEntry || aLibrary.empty() )
  217. return false;
  218. if( aEntry->GetName().IsEmpty() )
  219. {
  220. wxLogWarning( "Symbol in library '%s' has empty name field.", aLibrary );
  221. return false;
  222. }
  223. m_toolManager->RunAction( ACTIONS::cancelInteractive );
  224. // Symbols from the schematic are edited in place and not managed by the library manager.
  225. if( IsSymbolFromSchematic() )
  226. {
  227. delete m_symbol;
  228. m_symbol = nullptr;
  229. SCH_SCREEN* screen = GetScreen();
  230. delete screen;
  231. SetScreen( m_dummyScreen );
  232. m_isSymbolFromSchematic = false;
  233. rebuildMenuAndToolbar = true;
  234. }
  235. LIB_SYMBOL* lib_symbol = m_libMgr->GetBufferedSymbol( aEntry->GetName(), aLibrary );
  236. wxCHECK( lib_symbol, false );
  237. m_unit = aUnit > 0 ? aUnit : 1;
  238. m_convert = aConvert > 0 ? aConvert : 1;
  239. // The buffered screen for the symbol
  240. SCH_SCREEN* symbol_screen = m_libMgr->GetScreen( lib_symbol->GetName(), aLibrary );
  241. SetScreen( symbol_screen );
  242. SetCurSymbol( new LIB_SYMBOL( *lib_symbol ), true );
  243. SetCurLib( aLibrary );
  244. if( rebuildMenuAndToolbar )
  245. {
  246. ReCreateMenuBar();
  247. ReCreateHToolbar();
  248. GetInfoBar()->Dismiss();
  249. }
  250. UpdateTitle();
  251. RebuildSymbolUnitsList();
  252. SetShowDeMorgan( GetCurSymbol()->HasConversion() );
  253. ClearUndoRedoList();
  254. if( !IsSymbolFromSchematic() )
  255. {
  256. LIB_ID libId = GetCurSymbol()->GetLibId();
  257. setSymWatcher( &libId );
  258. }
  259. // Let tools add things to the view if necessary
  260. if( m_toolManager )
  261. m_toolManager->ResetTools( TOOL_BASE::MODEL_RELOAD );
  262. GetCanvas()->GetView()->UpdateAllItems( KIGFX::ALL );
  263. // Display the document information based on the entry selected just in
  264. // case the entry is an alias.
  265. UpdateMsgPanel();
  266. Refresh();
  267. return true;
  268. }
  269. void SYMBOL_EDIT_FRAME::SaveAll()
  270. {
  271. saveAllLibraries( false );
  272. m_treePane->GetLibTree()->RefreshLibTree();
  273. }
  274. void SYMBOL_EDIT_FRAME::CreateNewSymbol( const wxString& aInheritFrom )
  275. {
  276. m_toolManager->RunAction( ACTIONS::cancelInteractive );
  277. wxArrayString symbolNames;
  278. wxString lib = getTargetLib();
  279. if( !m_libMgr->LibraryExists( lib ) )
  280. {
  281. lib = SelectLibraryFromList();
  282. if( !m_libMgr->LibraryExists( lib ) )
  283. return;
  284. }
  285. m_libMgr->GetSymbolNames( lib, symbolNames );
  286. symbolNames.Sort();
  287. wxString _inheritSymbolName;
  288. wxString _infoMessage;
  289. wxString msg;
  290. // if the symbol being inherited from isn't a root symbol, find its root symbol
  291. // and use that symbol instead
  292. if( !aInheritFrom.IsEmpty() )
  293. {
  294. LIB_SYMBOL* inheritFromSymbol = m_libMgr->GetBufferedSymbol( aInheritFrom, lib );
  295. if( inheritFromSymbol )
  296. {
  297. _inheritSymbolName = aInheritFrom;
  298. _infoMessage = wxString::Format( _( "Deriving from symbol '%s'." ),
  299. _inheritSymbolName );
  300. }
  301. else
  302. {
  303. _inheritSymbolName = aInheritFrom;
  304. }
  305. }
  306. DIALOG_LIB_NEW_SYMBOL dlg( this, _infoMessage, &symbolNames, _inheritSymbolName,
  307. [&]( wxString newName )
  308. {
  309. if( newName.IsEmpty() )
  310. {
  311. wxMessageBox( _( "Symbol must have a name." ) );
  312. return false;
  313. }
  314. if( !lib.empty() && m_libMgr->SymbolExists( newName, lib ) )
  315. {
  316. msg = wxString::Format( _( "Symbol '%s' already exists in library '%s'." ),
  317. newName,
  318. lib );
  319. KIDIALOG errorDlg( this, msg, _( "Confirmation" ),
  320. wxOK | wxCANCEL | wxICON_WARNING );
  321. errorDlg.SetOKLabel( _( "Overwrite" ) );
  322. return errorDlg.ShowModal() == wxID_OK;
  323. }
  324. return true;
  325. } );
  326. dlg.SetMinSize( dlg.GetSize() );
  327. if( dlg.ShowModal() == wxID_CANCEL )
  328. return;
  329. wxString name = dlg.GetName();
  330. LIB_SYMBOL new_symbol( name ); // do not create symbol on the heap, it will be buffered soon
  331. wxString parentSymbolName = dlg.GetParentSymbolName();
  332. if( parentSymbolName.IsEmpty() )
  333. {
  334. new_symbol.GetReferenceField().SetText( dlg.GetReference() );
  335. new_symbol.SetUnitCount( dlg.GetUnitCount() );
  336. // Initialize new_symbol.m_TextInside member:
  337. // if 0, pin text is outside the body (on the pin)
  338. // if > 0, pin text is inside the body
  339. if( dlg.GetPinNameInside() )
  340. {
  341. new_symbol.SetPinNameOffset( dlg.GetPinTextPosition() );
  342. if( new_symbol.GetPinNameOffset() == 0 )
  343. new_symbol.SetPinNameOffset( 1 );
  344. }
  345. else
  346. {
  347. new_symbol.SetPinNameOffset( 0 );
  348. }
  349. ( dlg.GetPowerSymbol() ) ? new_symbol.SetPower() : new_symbol.SetNormal();
  350. new_symbol.SetShowPinNumbers( dlg.GetShowPinNumber() );
  351. new_symbol.SetShowPinNames( dlg.GetShowPinName() );
  352. new_symbol.LockUnits( !dlg.GetUnitsInterchangeable() );
  353. new_symbol.SetExcludedFromBOM( !dlg.GetIncludeInBom() );
  354. new_symbol.SetExcludedFromBoard( !dlg.GetIncludeOnBoard() );
  355. if( dlg.GetUnitCount() < 2 )
  356. new_symbol.LockUnits( false );
  357. new_symbol.SetConversion( dlg.GetAlternateBodyStyle() );
  358. }
  359. else
  360. {
  361. LIB_SYMBOL* parent = m_libMgr->GetAlias( parentSymbolName, lib );
  362. wxCHECK( parent, /* void */ );
  363. new_symbol.SetParent( parent );
  364. // Inherit the parent mandatory field attributes.
  365. for( int id = 0; id < MANDATORY_FIELDS; ++id )
  366. {
  367. LIB_FIELD* field = new_symbol.GetFieldById( id );
  368. // the MANDATORY_FIELDS are exactly that in RAM.
  369. wxCHECK( field, /* void */ );
  370. LIB_FIELD* parentField = parent->GetFieldById( id );
  371. wxCHECK( parentField, /* void */ );
  372. *field = *parentField;
  373. switch( id )
  374. {
  375. case REFERENCE_FIELD:
  376. // parent's reference already copied
  377. break;
  378. case VALUE_FIELD:
  379. if( parent->IsPower() )
  380. field->SetText( name );
  381. break;
  382. case FOOTPRINT_FIELD:
  383. case DATASHEET_FIELD:
  384. // - footprint might be the same as parent, but might not
  385. // - datasheet is most likely different
  386. // - probably best to play it safe and copy neither
  387. field->SetText( wxEmptyString );
  388. break;
  389. }
  390. field->SetParent( &new_symbol );
  391. }
  392. }
  393. m_libMgr->UpdateSymbol( &new_symbol, lib );
  394. SyncLibraries( false );
  395. LoadSymbol( name, lib, 1 );
  396. // must be called after loadSymbol, that calls SetShowDeMorgan, but
  397. // because the symbol is empty,it looks like it has no alternate body
  398. // and a derived symbol inherits its parent body.
  399. if( !new_symbol.GetParent().lock() )
  400. SetShowDeMorgan( dlg.GetAlternateBodyStyle() );
  401. else
  402. SetShowDeMorgan( new_symbol.HasConversion() );
  403. }
  404. void SYMBOL_EDIT_FRAME::Save()
  405. {
  406. wxString libName;
  407. if( IsSymbolTreeShown() )
  408. libName = GetTreeLIBID().GetUniStringLibNickname();
  409. if( libName.empty() )
  410. {
  411. saveCurrentSymbol();
  412. }
  413. else if( m_libMgr->IsLibraryReadOnly( libName ) )
  414. {
  415. wxString msg = wxString::Format( _( "Symbol library '%s' is not writable." ),
  416. libName );
  417. wxString msg2 = _( "You must save to a different location." );
  418. if( OKOrCancelDialog( this, _( "Warning" ), msg, msg2 ) == wxID_OK )
  419. saveLibrary( libName, true );
  420. }
  421. else
  422. {
  423. saveLibrary( libName, false );
  424. }
  425. if( IsSymbolTreeShown() )
  426. m_treePane->GetLibTree()->RefreshLibTree();
  427. UpdateTitle();
  428. }
  429. void SYMBOL_EDIT_FRAME::SaveLibraryAs()
  430. {
  431. wxCHECK( !GetTargetLibId().GetLibNickname().empty(), /* void */ );
  432. const wxString& libName = GetTargetLibId().GetLibNickname();
  433. saveLibrary( libName, true );
  434. m_treePane->GetLibTree()->RefreshLibTree();
  435. }
  436. void SYMBOL_EDIT_FRAME::SaveSymbolCopyAs()
  437. {
  438. saveSymbolCopyAs();
  439. m_treePane->GetLibTree()->RefreshLibTree();
  440. }
  441. static int ID_MAKE_NEW_LIBRARY = 4173;
  442. class SAVE_AS_DIALOG : public EDA_LIST_DIALOG
  443. {
  444. public:
  445. SAVE_AS_DIALOG( SYMBOL_EDIT_FRAME* aParent, const wxString& aSymbolName,
  446. const wxString& aLibraryPreselect,
  447. std::function<bool( wxString libName, wxString symbolName )> aValidator ) :
  448. EDA_LIST_DIALOG( aParent, _( "Save Symbol As" ), false ),
  449. m_validator( std::move( aValidator ) )
  450. {
  451. COMMON_SETTINGS* cfg = Pgm().GetCommonSettings();
  452. PROJECT_FILE& project = aParent->Prj().GetProjectFile();
  453. SYMBOL_LIB_TABLE* tbl = PROJECT_SCH::SchSymbolLibTable( &Prj() );
  454. std::vector<wxString> libNicknames = tbl->GetLogicalLibs();
  455. wxArrayString headers;
  456. std::vector<wxArrayString> itemsToDisplay;
  457. headers.Add( _( "Nickname" ) );
  458. headers.Add( _( "Description" ) );
  459. for( const wxString& nickname : libNicknames )
  460. {
  461. if( alg::contains( project.m_PinnedSymbolLibs, nickname )
  462. || alg::contains( cfg->m_Session.pinned_symbol_libs, nickname ) )
  463. {
  464. wxArrayString item;
  465. item.Add( LIB_TREE_MODEL_ADAPTER::GetPinningSymbol() + nickname );
  466. item.Add( tbl->GetDescription( nickname ) );
  467. itemsToDisplay.push_back( item );
  468. }
  469. }
  470. for( const wxString& nickname : libNicknames )
  471. {
  472. if( !alg::contains( project.m_PinnedSymbolLibs, nickname )
  473. && !alg::contains( cfg->m_Session.pinned_symbol_libs, nickname ) )
  474. {
  475. wxArrayString item;
  476. item.Add( nickname );
  477. item.Add( tbl->GetDescription( nickname ) );
  478. itemsToDisplay.push_back( item );
  479. }
  480. }
  481. initDialog( headers, itemsToDisplay, aLibraryPreselect );
  482. SetListLabel( _( "Save in library:" ) );
  483. SetOKLabel( _( "Save" ) );
  484. wxBoxSizer* bNameSizer = new wxBoxSizer( wxHORIZONTAL );
  485. wxStaticText* label = new wxStaticText( this, wxID_ANY, _( "Name:" ) );
  486. bNameSizer->Add( label, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT, 5 );
  487. m_symbolNameCtrl = new wxTextCtrl( this, wxID_ANY, aSymbolName );
  488. bNameSizer->Add( m_symbolNameCtrl, 1, wxALIGN_CENTER_VERTICAL|wxALL, 5 );
  489. wxButton* newLibraryButton = new wxButton( this, ID_MAKE_NEW_LIBRARY, _( "New Library..." ) );
  490. m_ButtonsSizer->Prepend( 80, 20 );
  491. m_ButtonsSizer->Prepend( newLibraryButton, 0, wxALIGN_CENTER_VERTICAL|wxLEFT|wxRIGHT, 10 );
  492. GetSizer()->Prepend( bNameSizer, 0, wxEXPAND|wxTOP|wxLEFT|wxRIGHT, 5 );
  493. Bind( wxEVT_BUTTON,
  494. [this]( wxCommandEvent& )
  495. {
  496. EndModal( ID_MAKE_NEW_LIBRARY );
  497. }, ID_MAKE_NEW_LIBRARY );
  498. // Move nameTextCtrl to the head of the tab-order
  499. if( GetChildren().DeleteObject( m_symbolNameCtrl ) )
  500. GetChildren().Insert( m_symbolNameCtrl );
  501. SetInitialFocus( m_symbolNameCtrl );
  502. SetupStandardButtons();
  503. Layout();
  504. GetSizer()->Fit( this );
  505. Centre();
  506. }
  507. wxString GetSymbolName()
  508. {
  509. wxString symbolName = m_symbolNameCtrl->GetValue();
  510. symbolName.Trim( true );
  511. symbolName.Trim( false );
  512. symbolName.Replace( " ", "_" );
  513. return symbolName;
  514. }
  515. protected:
  516. bool TransferDataFromWindow() override
  517. {
  518. return m_validator( GetTextSelection(), GetSymbolName() );
  519. }
  520. private:
  521. wxTextCtrl* m_symbolNameCtrl;
  522. std::function<bool( wxString libName, wxString symbolName )> m_validator;
  523. };
  524. void SYMBOL_EDIT_FRAME::saveSymbolCopyAs()
  525. {
  526. LIB_SYMBOL* symbol = getTargetSymbol();
  527. if( !symbol )
  528. return;
  529. LIB_ID old_lib_id = symbol->GetLibId();
  530. wxString symbolName = old_lib_id.GetLibItemName();
  531. wxString libraryName = old_lib_id.GetLibNickname();
  532. bool valueFollowsName = symbol->GetValueField().GetText() == symbolName;
  533. wxString msg;
  534. bool done = false;
  535. while( !done )
  536. {
  537. SAVE_AS_DIALOG dlg( this, symbolName, libraryName,
  538. [&]( const wxString& newLib, const wxString& newName )
  539. {
  540. if( newLib.IsEmpty() )
  541. {
  542. wxMessageBox( _( "A library must be specified." ) );
  543. return false;
  544. }
  545. if( newName.IsEmpty() )
  546. {
  547. wxMessageBox( _( "Symbol must have a name." ) );
  548. return false;
  549. }
  550. if( m_libMgr->SymbolExists( newName, newLib ) )
  551. {
  552. msg = wxString::Format( _( "Symbol '%s' already exists in library '%s'." ),
  553. newName, newLib );
  554. KIDIALOG errorDlg( this, msg, _( "Confirmation" ),
  555. wxOK | wxCANCEL | wxICON_WARNING );
  556. errorDlg.SetOKLabel( _( "Overwrite" ) );
  557. return errorDlg.ShowModal() == wxID_OK;
  558. }
  559. // @todo Either check the selecteced library to see if the parent symbol name
  560. // is in the new library and/or copy the parent symbol as well. This is
  561. // the lazy solution to ensure derived symbols do not get orphaned.
  562. if( symbol->IsAlias() && newLib != old_lib_id.GetLibNickname() )
  563. {
  564. DisplayError( this, _( "Derived symbols must be saved in the same library "
  565. "as their parent symbol." ) );
  566. return false;
  567. }
  568. return true;
  569. } );
  570. int ret = dlg.ShowModal();
  571. if( ret == wxID_CANCEL )
  572. {
  573. return;
  574. }
  575. else if( ret == wxID_OK )
  576. {
  577. symbolName = dlg.GetSymbolName();
  578. libraryName = dlg.GetTextSelection();
  579. done = true;
  580. }
  581. else if( ret == ID_MAKE_NEW_LIBRARY )
  582. {
  583. wxFileName newLibrary( AddLibraryFile( true ) );
  584. libraryName = newLibrary.GetName();
  585. }
  586. }
  587. LIB_SYMBOL new_symbol( *symbol );
  588. new_symbol.SetName( symbolName );
  589. if( valueFollowsName )
  590. new_symbol.GetValueField().SetText( symbolName );
  591. m_libMgr->UpdateSymbol( &new_symbol, libraryName );
  592. SyncLibraries( false );
  593. }
  594. void SYMBOL_EDIT_FRAME::UpdateAfterSymbolProperties( wxString* aOldName )
  595. {
  596. wxCHECK( m_symbol, /* void */ );
  597. wxString lib = GetCurLib();
  598. if( !lib.IsEmpty() && aOldName && *aOldName != m_symbol->GetName() )
  599. {
  600. // Test the current library for name conflicts
  601. if( m_libMgr->SymbolExists( m_symbol->GetName(), lib ) )
  602. {
  603. wxString msg = wxString::Format( _( "Symbol name '%s' already in use." ),
  604. UnescapeString( m_symbol->GetName() ) );
  605. DisplayErrorMessage( this, msg );
  606. m_symbol->SetName( *aOldName );
  607. }
  608. else
  609. {
  610. m_libMgr->UpdateSymbolAfterRename( m_symbol, *aOldName, lib );
  611. }
  612. // Reselect the renamed symbol
  613. m_treePane->GetLibTree()->SelectLibId( LIB_ID( lib, m_symbol->GetName() ) );
  614. }
  615. RebuildSymbolUnitsList();
  616. SetShowDeMorgan( GetCurSymbol()->Flatten()->HasConversion() );
  617. UpdateTitle();
  618. // N.B. The view needs to be rebuilt first as the Symbol Properties change may invalidate
  619. // the view pointers by rebuilting the field table
  620. RebuildView();
  621. UpdateMsgPanel();
  622. OnModify();
  623. }
  624. void SYMBOL_EDIT_FRAME::DeleteSymbolFromLibrary()
  625. {
  626. std::vector<LIB_ID> toDelete = GetSelectedLibIds();
  627. if( toDelete.empty() )
  628. toDelete.emplace_back( GetTargetLibId() );
  629. for( LIB_ID& libId : toDelete )
  630. {
  631. if( m_libMgr->IsSymbolModified( libId.GetLibItemName(), libId.GetLibNickname() )
  632. && !IsOK( this, wxString::Format( _( "The symbol '%s' has been modified.\n"
  633. "Do you want to remove it from the library?" ),
  634. libId.GetUniStringLibItemName() ) ) )
  635. {
  636. continue;
  637. }
  638. if( m_libMgr->HasDerivedSymbols( libId.GetLibItemName(), libId.GetLibNickname() ) )
  639. {
  640. wxString msg;
  641. msg.Printf(
  642. _( "The symbol %s is used to derive other symbols.\n"
  643. "Deleting this symbol will delete all of the symbols derived from it.\n\n"
  644. "Do you wish to delete this symbol and all of its derivatives?" ),
  645. libId.GetLibItemName().wx_str() );
  646. wxMessageDialog::ButtonLabel yesButtonLabel( _( "Delete Symbol" ) );
  647. wxMessageDialog::ButtonLabel noButtonLabel( _( "Keep Symbol" ) );
  648. wxMessageDialog dlg( this, msg, _( "Warning" ),
  649. wxYES_NO | wxYES_DEFAULT | wxICON_QUESTION | wxCENTER );
  650. dlg.SetYesNoLabels( yesButtonLabel, noButtonLabel );
  651. if( dlg.ShowModal() == wxID_NO )
  652. continue;
  653. }
  654. if( IsCurrentSymbol( libId ) )
  655. emptyScreen();
  656. m_libMgr->RemoveSymbol( libId.GetLibItemName(), libId.GetLibNickname() );
  657. }
  658. m_treePane->GetLibTree()->RefreshLibTree();
  659. }
  660. void SYMBOL_EDIT_FRAME::CopySymbolToClipboard()
  661. {
  662. std::vector<LIB_ID> symbols;
  663. if( GetTreeLIBIDs( symbols ) == 0 )
  664. return;
  665. STRING_FORMATTER formatter;
  666. for( LIB_ID& libId : symbols )
  667. {
  668. LIB_SYMBOL* symbol = m_libMgr->GetBufferedSymbol( libId.GetLibItemName(),
  669. libId.GetLibNickname() );
  670. if( !symbol )
  671. continue;
  672. std::unique_ptr<LIB_SYMBOL> tmp = symbol->Flatten();
  673. SCH_IO_KICAD_SEXPR::FormatLibSymbol( tmp.get(), formatter );
  674. }
  675. wxLogNull doNotLog; // disable logging of failed clipboard actions
  676. auto clipboard = wxTheClipboard;
  677. wxClipboardLocker clipboardLock( clipboard );
  678. if( !clipboardLock || !clipboard->IsOpened() )
  679. return;
  680. auto data = new wxTextDataObject( wxString( formatter.GetString().c_str(), wxConvUTF8 ) );
  681. clipboard->SetData( data );
  682. clipboard->Flush();
  683. }
  684. void SYMBOL_EDIT_FRAME::DuplicateSymbol( bool aFromClipboard )
  685. {
  686. LIB_ID libId = GetTargetLibId();
  687. wxString lib = libId.GetLibNickname();
  688. if( !m_libMgr->LibraryExists( lib ) )
  689. return;
  690. std::vector<LIB_SYMBOL*> newSymbols;
  691. if( aFromClipboard )
  692. {
  693. std::string clipboardData = m_toolManager->GetClipboardUTF8();
  694. try
  695. {
  696. newSymbols = SCH_IO_KICAD_SEXPR::ParseLibSymbols( clipboardData, "Clipboard" );
  697. }
  698. catch( IO_ERROR& e )
  699. {
  700. wxLogMessage( wxS( "Can not paste: %s" ), e.Problem() );
  701. }
  702. }
  703. else
  704. {
  705. LIB_SYMBOL* srcSymbol = m_libMgr->GetBufferedSymbol( libId.GetLibItemName(), lib );
  706. wxCHECK( srcSymbol, /* void */ );
  707. newSymbols.emplace_back( new LIB_SYMBOL( *srcSymbol ) );
  708. // Derive from same parent.
  709. if( srcSymbol->IsAlias() )
  710. {
  711. std::shared_ptr< LIB_SYMBOL > srcParent = srcSymbol->GetParent().lock();
  712. wxCHECK( srcParent, /* void */ );
  713. newSymbols.back()->SetParent( srcParent.get() );
  714. }
  715. }
  716. if( newSymbols.empty() )
  717. return;
  718. for( LIB_SYMBOL* symbol : newSymbols )
  719. {
  720. ensureUniqueName( symbol, lib );
  721. m_libMgr->UpdateSymbol( symbol, lib );
  722. LoadOneLibrarySymbolAux( symbol, lib, GetUnit(), GetConvert() );
  723. }
  724. SyncLibraries( false );
  725. m_treePane->GetLibTree()->SelectLibId( LIB_ID( lib, newSymbols[0]->GetName() ) );
  726. for( LIB_SYMBOL* symbol : newSymbols )
  727. delete symbol;
  728. }
  729. void SYMBOL_EDIT_FRAME::ensureUniqueName( LIB_SYMBOL* aSymbol, const wxString& aLibrary )
  730. {
  731. wxCHECK( aSymbol, /* void */ );
  732. int i = 1;
  733. wxString newName = aSymbol->GetName();
  734. // Append a number to the name until the name is unique in the library.
  735. while( m_libMgr->SymbolExists( newName, aLibrary ) )
  736. newName.Printf( "%s_%d", aSymbol->GetName(), i++ );
  737. aSymbol->SetName( newName );
  738. }
  739. void SYMBOL_EDIT_FRAME::Revert( bool aConfirm )
  740. {
  741. LIB_ID libId = GetTargetLibId();
  742. const wxString& libName = libId.GetLibNickname();
  743. // Empty if this is the library itself that is selected.
  744. const wxString& symbolName = libId.GetLibItemName();
  745. wxString msg = wxString::Format( _( "Revert '%s' to last version saved?" ),
  746. symbolName.IsEmpty() ? libName : symbolName );
  747. if( aConfirm && !ConfirmRevertDialog( this, msg ) )
  748. return;
  749. bool reload_currentSymbol = false;
  750. wxString curr_symbolName = symbolName;
  751. if( GetCurSymbol() )
  752. {
  753. // the library itself is reverted: the current symbol will be reloaded only if it is
  754. // owned by this library
  755. if( symbolName.IsEmpty() )
  756. {
  757. LIB_ID curr_libId = GetCurSymbol()->GetLibId();
  758. reload_currentSymbol = libName == curr_libId.GetLibNickname();
  759. if( reload_currentSymbol )
  760. curr_symbolName = curr_libId.GetUniStringLibItemName();
  761. }
  762. else
  763. {
  764. reload_currentSymbol = IsCurrentSymbol( libId );
  765. }
  766. }
  767. int unit = m_unit;
  768. if( reload_currentSymbol )
  769. emptyScreen();
  770. if( symbolName.IsEmpty() )
  771. {
  772. m_libMgr->RevertLibrary( libName );
  773. }
  774. else
  775. {
  776. libId = m_libMgr->RevertSymbol( libId.GetLibItemName(), libId.GetLibNickname() );
  777. m_treePane->GetLibTree()->SelectLibId( libId );
  778. m_libMgr->ClearSymbolModified( libId.GetLibItemName(), libId.GetLibNickname() );
  779. }
  780. if( reload_currentSymbol && m_libMgr->SymbolExists( curr_symbolName, libName ) )
  781. LoadSymbol( curr_symbolName, libName, unit );
  782. m_treePane->Refresh();
  783. }
  784. void SYMBOL_EDIT_FRAME::RevertAll()
  785. {
  786. wxCHECK_RET( m_libMgr, "Library manager object not created." );
  787. Revert( false );
  788. m_libMgr->RevertAll();
  789. }
  790. void SYMBOL_EDIT_FRAME::LoadSymbol( const wxString& aAlias, const wxString& aLibrary, int aUnit )
  791. {
  792. if( GetCurSymbol() && IsSymbolFromSchematic() && GetScreen()->IsContentModified() )
  793. {
  794. if( !HandleUnsavedChanges( this, _( "The current symbol has been modified. Save changes?" ),
  795. [&]() -> bool
  796. {
  797. return saveCurrentSymbol();
  798. } ) )
  799. {
  800. return;
  801. }
  802. }
  803. LIB_SYMBOL* symbol = m_libMgr->GetBufferedSymbol( aAlias, aLibrary );
  804. if( !symbol )
  805. {
  806. DisplayError( this, wxString::Format( _( "Symbol %s not found in library '%s'." ),
  807. aAlias,
  808. aLibrary ) );
  809. m_treePane->GetLibTree()->RefreshLibTree();
  810. return;
  811. }
  812. // Optimize default edit options for this symbol
  813. // Usually if units are locked, graphic items are specific to each unit
  814. // and if units are interchangeable, graphic items are common to units
  815. SYMBOL_EDITOR_DRAWING_TOOLS* tools = GetToolManager()->GetTool<SYMBOL_EDITOR_DRAWING_TOOLS>();
  816. tools->SetDrawSpecificUnit( symbol->UnitsLocked() );
  817. LoadOneLibrarySymbolAux( symbol, aLibrary, aUnit, 0 );
  818. }
  819. bool SYMBOL_EDIT_FRAME::saveLibrary( const wxString& aLibrary, bool aNewFile )
  820. {
  821. wxFileName fn;
  822. wxString msg;
  823. SYMBOL_SAVEAS_TYPE type = SYMBOL_SAVEAS_TYPE::NORMAL_SAVE_AS;
  824. SCH_IO_MGR::SCH_FILE_T fileType = SCH_IO_MGR::SCH_FILE_T::SCH_KICAD;
  825. PROJECT& prj = Prj();
  826. m_toolManager->RunAction( ACTIONS::cancelInteractive );
  827. if( !aNewFile && ( aLibrary.empty() || !PROJECT_SCH::SchSymbolLibTable( &prj )->HasLibrary( aLibrary ) ) )
  828. {
  829. ShowInfoBarError( _( "No library specified." ) );
  830. return false;
  831. }
  832. if( aNewFile )
  833. {
  834. SEARCH_STACK* search = PROJECT_SCH::SchSearchS( &prj );
  835. // Get a new name for the library
  836. wxString default_path = prj.GetRString( PROJECT::SCH_LIB_PATH );
  837. if( !default_path )
  838. default_path = search->LastVisitedPath();
  839. fn.SetName( aLibrary );
  840. fn.SetExt( FILEEXT::KiCadSymbolLibFileExtension );
  841. wxString wildcards = FILEEXT::KiCadSymbolLibFileWildcard();
  842. wxFileDialog dlg( this, wxString::Format( _( "Save Library '%s' As..." ), aLibrary ),
  843. default_path, fn.GetFullName(), wildcards,
  844. wxFD_SAVE | wxFD_OVERWRITE_PROMPT );
  845. SYMBOL_FILEDLG_SAVE_AS saveAsHook( type );
  846. dlg.SetCustomizeHook( saveAsHook );
  847. if( dlg.ShowModal() == wxID_CANCEL )
  848. return false;
  849. fn = dlg.GetPath();
  850. prj.SetRString( PROJECT::SCH_LIB_PATH, fn.GetPath() );
  851. if( fn.GetExt().IsEmpty() )
  852. fn.SetExt( FILEEXT::KiCadSymbolLibFileExtension );
  853. type = saveAsHook.GetOption();
  854. }
  855. else
  856. {
  857. fn = PROJECT_SCH::SchSymbolLibTable( &prj )->GetFullURI( aLibrary );
  858. fileType = SCH_IO_MGR::GuessPluginTypeFromLibPath( fn.GetFullPath() );
  859. if( fileType == SCH_IO_MGR::SCH_FILE_UNKNOWN )
  860. fileType = SCH_IO_MGR::SCH_KICAD;
  861. }
  862. // Verify the user has write privileges before attempting to save the library file.
  863. if( !aNewFile && m_libMgr->IsLibraryReadOnly( aLibrary ) )
  864. return false;
  865. ClearMsgPanel();
  866. // Copy .kicad_symb file to .bak.
  867. if( !backupFile( fn, "bak" ) )
  868. return false;
  869. if( !m_libMgr->SaveLibrary( aLibrary, fn.GetFullPath(), fileType ) )
  870. {
  871. msg.Printf( _( "Failed to save changes to symbol library file '%s'." ),
  872. fn.GetFullPath() );
  873. DisplayErrorMessage( this, _( "Error Saving Library" ), msg );
  874. return false;
  875. }
  876. if( !aNewFile )
  877. {
  878. m_libMgr->ClearLibraryModified( aLibrary );
  879. // Update the library modification time so that we don't reload based on the watcher
  880. if( aLibrary == getTargetLib() )
  881. SetSymModificationTime( fn.GetModificationTime() );
  882. }
  883. else
  884. {
  885. bool resyncLibTree = false;
  886. wxString originalLibNickname = getTargetLib();
  887. wxString forceRefresh;
  888. switch( type )
  889. {
  890. case SYMBOL_SAVEAS_TYPE::REPLACE_TABLE_ENTRY:
  891. resyncLibTree = replaceLibTableEntry( originalLibNickname, fn.GetFullPath() );
  892. forceRefresh = originalLibNickname;
  893. break;
  894. case SYMBOL_SAVEAS_TYPE::ADD_GLOBAL_TABLE_ENTRY:
  895. resyncLibTree = addLibTableEntry( fn.GetFullPath() );
  896. break;
  897. case SYMBOL_SAVEAS_TYPE::ADD_PROJECT_TABLE_ENTRY:
  898. resyncLibTree = addLibTableEntry( fn.GetFullPath(), PROJECT_LIB_TABLE );
  899. break;
  900. default:
  901. break;
  902. }
  903. if( resyncLibTree )
  904. {
  905. FreezeLibraryTree();
  906. SyncLibraries( true, false, forceRefresh );
  907. ThawLibraryTree();
  908. }
  909. }
  910. ClearMsgPanel();
  911. msg.Printf( _( "Symbol library file '%s' saved." ), fn.GetFullPath() );
  912. RebuildSymbolUnitsList();
  913. return true;
  914. }
  915. bool SYMBOL_EDIT_FRAME::saveAllLibraries( bool aRequireConfirmation )
  916. {
  917. wxString msg, msg2;
  918. bool doSave = true;
  919. int dirtyCount = 0;
  920. bool applyToAll = false;
  921. bool retv = true;
  922. for( const wxString& libNickname : m_libMgr->GetLibraryNames() )
  923. {
  924. if( m_libMgr->IsLibraryModified( libNickname ) )
  925. dirtyCount++;
  926. }
  927. for( const wxString& libNickname : m_libMgr->GetLibraryNames() )
  928. {
  929. if( m_libMgr->IsLibraryModified( libNickname ) )
  930. {
  931. if( aRequireConfirmation && !applyToAll )
  932. {
  933. msg.Printf( _( "Save changes to '%s' before closing?" ), libNickname );
  934. switch( UnsavedChangesDialog( this, msg, dirtyCount > 1 ? &applyToAll : nullptr ) )
  935. {
  936. case wxID_YES: doSave = true; break;
  937. case wxID_NO: doSave = false; break;
  938. default:
  939. case wxID_CANCEL: return false;
  940. }
  941. }
  942. if( doSave )
  943. {
  944. // If saving under existing name fails then do a Save As..., and if that
  945. // fails then cancel close action.
  946. if( m_libMgr->IsLibraryReadOnly( libNickname ) )
  947. {
  948. msg.Printf( _( "Symbol library '%s' is not writable." ), libNickname );
  949. msg2 = _( "You must save to a different location." );
  950. if( dirtyCount == 1 )
  951. {
  952. if( OKOrCancelDialog( this, _( "Warning" ), msg, msg2 ) != wxID_OK )
  953. {
  954. retv = false;
  955. continue;
  956. }
  957. }
  958. else
  959. {
  960. m_infoBar->Dismiss();
  961. m_infoBar->ShowMessageFor( msg + wxS( " " ) + msg2,
  962. 2000, wxICON_EXCLAMATION );
  963. while( m_infoBar->IsShownOnScreen() )
  964. wxSafeYield();
  965. retv = false;
  966. continue;
  967. }
  968. }
  969. else if( saveLibrary( libNickname, false ) )
  970. {
  971. continue;
  972. }
  973. if( !saveLibrary( libNickname, true ) )
  974. retv = false;
  975. }
  976. }
  977. }
  978. UpdateTitle();
  979. return retv;
  980. }
  981. void SYMBOL_EDIT_FRAME::UpdateSymbolMsgPanelInfo()
  982. {
  983. EDA_DRAW_FRAME::ClearMsgPanel();
  984. if( !m_symbol )
  985. return;
  986. wxString msg = m_symbol->GetName();
  987. AppendMsgPanel( _( "Name" ), UnescapeString( msg ), 8 );
  988. if( m_symbol->IsAlias() )
  989. {
  990. LIB_SYMBOL_SPTR parent = m_symbol->GetParent().lock();
  991. msg = parent ? parent->GetName() : _( "Undefined!" );
  992. AppendMsgPanel( _( "Parent" ), UnescapeString( msg ), 8 );
  993. }
  994. static wxChar UnitLetter[] = wxT( "?ABCDEFGHIJKLMNOPQRSTUVWXYZ" );
  995. msg = UnitLetter[m_unit];
  996. AppendMsgPanel( _( "Unit" ), msg, 8 );
  997. if( m_convert > 1 )
  998. msg = _( "Convert" );
  999. else
  1000. msg = _( "Normal" );
  1001. AppendMsgPanel( _( "Body" ), msg, 8 );
  1002. if( m_symbol->IsPower() )
  1003. msg = _( "Power Symbol" );
  1004. else
  1005. msg = _( "Symbol" );
  1006. AppendMsgPanel( _( "Type" ), msg, 8 );
  1007. AppendMsgPanel( _( "Description" ), m_symbol->GetDescription(), 8 );
  1008. AppendMsgPanel( _( "Keywords" ), m_symbol->GetKeyWords() );
  1009. AppendMsgPanel( _( "Datasheet" ), m_symbol->GetDatasheetField().GetText() );
  1010. }