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.

434 lines
15 KiB

2 years ago
  1. /*
  2. * This program source code file is part of KiCad, a free EDA CAD application.
  3. *
  4. * Copyright (C) 2017 Chris Pavlina <pavlina.chris@gmail.com>
  5. * Copyright (C) 2014 Henner Zeller <h.zeller@acm.org>
  6. * Copyright (C) 2023 CERN
  7. * Copyright (C) 2014-2024 KiCad Developers, see AUTHORS.txt for contributors.
  8. *
  9. * This program is free software: you can redistribute it and/or modify it
  10. * under the terms of the GNU General Public License as published by the
  11. * Free Software Foundation, either version 3 of the License, or (at your
  12. * option) any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful, but
  15. * WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  17. * General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public License along
  20. * with this program. If not, see <http://www.gnu.org/licenses/>.
  21. */
  22. #ifndef LIB_TREE_MODEL_ADAPTER_H
  23. #define LIB_TREE_MODEL_ADAPTER_H
  24. #include <eda_base_frame.h>
  25. #include <lib_id.h>
  26. #include <lib_tree_model.h>
  27. #include <wx/hashmap.h>
  28. #include <wx/dataview.h>
  29. #include <wx/headerctrl.h>
  30. #include <vector>
  31. #include <functional>
  32. #include <set>
  33. #include <map>
  34. /**
  35. * Adapter class in the symbol selector Model-View-Adapter (mediated MVC)
  36. * architecture. The other pieces are in:
  37. *
  38. * - Model: SYM_TREE_NODE and descendants in eeschema/cmp_tree_model.h
  39. * - View:
  40. * - DIALOG_CHOOSE_COMPONENT in eeschema/dialogs/dialog_choose_component.h
  41. * - wxDataViewCtrl
  42. *
  43. * This adapter presents the interface specified by wxDataViewModel to the
  44. * wxDataViewCtrl:
  45. *
  46. * +---+ +------------------+
  47. * +---+ Generates | A | | VIEW |
  48. * | M | from libs | D | wxDataViewModel |------------------|
  49. * | O | <---------- | A | <------------------> | wxDataViewCtrl |
  50. * | D | | P | |------------------|
  51. * | E | <---------> | T | <------------------- | wxTextCtrl |
  52. * | L | UpdateScore | E | UpdateSearchString() |------------------|
  53. * +---+ | R | | |
  54. * +---+ +------------------+
  55. *
  56. * Because this adapter is a wxDataViewModel, it is reference-counted by
  57. * wxObject. To ensure this interface is used correctly, the constructor
  58. * is private; LIB_TREE_MODEL_ADAPTER should be created by the static
  59. * factory method LIB_TREE_MODEL_ADAPTER::Create().
  60. *
  61. * Quick summary of methods used to drive this class:
  62. *
  63. * - `SetFilter()` - set whether the view is restricted to power parts
  64. * - `ShowUnits()` - set whether units are displayed
  65. * - `SetPreselectNode()` - set a node to highlight when not searching
  66. * - `AddLibrary()` - populate the model with all aliases in a library
  67. * - `AddAliasList()` - populate the model with a specific list of aliases
  68. *
  69. * Quick summary of methods used by the View:
  70. *
  71. * - `UpdateSearchString()` - pass in the user's search text
  72. * - `AttachTo()` - pass in the wxDataViewCtrl
  73. * - `GetAliasFor()` - get the LIB_ALIAS* for a selected item
  74. * - `GetUnitFor()` - get the unit for a selected item
  75. * - `GetComponentsCount()` - count the aliases loaded
  76. *
  77. * Methods implemented as part of wxDataViewModel:
  78. *
  79. * - `HasContainerColumns()` - whether a parent item has more than one column
  80. * - `IsContainer()` - whether an item is a parent
  81. * - `GetParent()` - return the parent of an item, or invalid if root
  82. * - `GetChildren()` - get the children of an item
  83. * - `GetColumnCount()` - get the number of columns in the view
  84. * - `GetColumnType()` - get the data type shown in each column
  85. * - `GetValue()` - get the data shown in a cell
  86. * - `SetValue()` - edit the data in a cell (does nothing)
  87. * - `GetAttr()` - get any per-item formatting
  88. * - `Compare()` - compare two rows, for sorting
  89. * - `HasDefaultCompare()` - whether sorted by default
  90. */
  91. class APP_SETTINGS_BASE;
  92. class TOOL_INTERACTIVE;
  93. class EDA_BASE_FRAME;
  94. class LIB_TREE_MODEL_ADAPTER: public wxDataViewModel
  95. {
  96. public:
  97. /**
  98. * @return a unicode string to mark a node name like a pinned library name.
  99. * This is not an ASCII7 char, but a unicode char.
  100. */
  101. static const wxString GetPinningSymbol()
  102. {
  103. return wxString::FromUTF8( "" );
  104. }
  105. public:
  106. /**
  107. * Destructor. Do NOT delete this class manually; it is reference-counted
  108. * by wxObject.
  109. */
  110. ~LIB_TREE_MODEL_ADAPTER();
  111. /**
  112. * This enum defines the order of the default columns in the tree view
  113. */
  114. enum TREE_COLS
  115. {
  116. NAME_COL = 0, ///< Library or library item name column
  117. DESC_COL, ///< Library or library description column
  118. NUM_COLS ///< The number of default tree columns
  119. };
  120. enum SORT_MODE
  121. {
  122. BEST_MATCH = 0,
  123. ALPHABETIC
  124. };
  125. /**
  126. * Save the column widths to the config file. This requires the tree view to still be
  127. * valid.
  128. */
  129. void SaveSettings();
  130. /**
  131. * Set the symbol filter type. Must be set before adding libraries
  132. *
  133. * @param aFilter if SYM_FILTER_POWER, only power parts are loaded
  134. */
  135. void SetFilter( std::function<bool( LIB_TREE_NODE& aNode )>* aFilter ) { m_filter = aFilter; }
  136. /**
  137. * Return the active filter.
  138. */
  139. std::function<bool( LIB_TREE_NODE& aNode )>* GetFilter() const { return m_filter; }
  140. void SetSortMode( SORT_MODE aMode ) { m_sort_mode = aMode; }
  141. SORT_MODE GetSortMode() const { return m_sort_mode; }
  142. /**
  143. * Whether or not to show units. May be set at any time; updates at the next
  144. * UpdateSearchString()
  145. *
  146. * @param aShow if true, units are displayed
  147. */
  148. void ShowUnits( bool aShow );
  149. /**
  150. * Set the symbol name to be selected if there are no search results.
  151. * May be set at any time; updates at the next UpdateSearchString().
  152. *
  153. * @param aLibId symbol #LIB_ID to be selected
  154. * @param aUnit unit to be selected, if > 0 (0 selects the alias itself)
  155. */
  156. void SetPreselectNode( const LIB_ID& aLibId, int aUnit );
  157. /**
  158. * Add the given list of symbols by alias. To be called in the setup
  159. * phase.
  160. *
  161. * @param aNodeName the parent node the symbols will appear under
  162. * @param aDesc the description field of the parent node
  163. * @param aItemList list of symbols
  164. */
  165. void DoAddLibrary( const wxString& aNodeName, const wxString& aDesc,
  166. const std::vector<LIB_TREE_ITEM*>& aItemList,
  167. bool pinned, bool presorted );
  168. std::vector<wxString> GetAvailableColumns() const { return m_availableColumns; }
  169. std::vector<wxString> GetShownColumns() const { return m_shownColumns; }
  170. std::vector<wxString> GetOpenLibs() const;
  171. void OpenLibs( const std::vector<wxString>& aLibs );
  172. /**
  173. * Sets which columns are shown in the widget. Invalid column names are discarded.
  174. * @param aColumnNames is an ordered list of column names to show
  175. */
  176. void SetShownColumns( const std::vector<wxString>& aColumnNames );
  177. /**
  178. * Sort the tree and assign ranks after adding libraries.
  179. */
  180. void AssignIntrinsicRanks() { m_tree.AssignIntrinsicRanks(); }
  181. /**
  182. * Set the search string provided by the user.
  183. *
  184. * @param aSearch full, unprocessed search text
  185. * @param aState if true, we are keeping the state and so we shouldn't collapse the tree
  186. */
  187. void UpdateSearchString( const wxString& aSearch, bool aState );
  188. /**
  189. * Attach to a wxDataViewCtrl and initialize it. This will set up columns
  190. * and associate the model via the adapter.
  191. *
  192. * @param aDataViewCtrl the view symbol in the dialog
  193. */
  194. void AttachTo( wxDataViewCtrl* aDataViewCtrl );
  195. /**
  196. * A final-stage initialization to be called after the window hierarchy has been realized
  197. * and the window sizes set.
  198. */
  199. void FinishTreeInitialization();
  200. /**
  201. * Return the alias for the given item.
  202. *
  203. * @param aSelection item from the wxDataViewCtrl
  204. * (see wxDataViewCtrl::GetSelection())
  205. *
  206. * @return alias, or nullptr if none is selected
  207. */
  208. LIB_ID GetAliasFor( const wxDataViewItem& aSelection ) const;
  209. /**
  210. * Return the unit for the given item.
  211. *
  212. * @param aSelection item from the wxDataViewCtrl
  213. * (see wxDataViewCtrl::GetSelection())
  214. *
  215. * @return Unit, or zero if the alias itself is selected. Return valid is
  216. * invalid if GetAliasFor() returns nullptr.
  217. */
  218. int GetUnitFor( const wxDataViewItem& aSelection ) const;
  219. /**
  220. * Return node type for the given item.
  221. *
  222. * @param aSelection item from the wxDataViewCtrl
  223. * (see wxDataViewCtrl::GetSelection())
  224. *
  225. * @return Type of the selected node, might be INVALID.
  226. */
  227. LIB_TREE_NODE::TYPE GetTypeFor( const wxDataViewItem& aSelection ) const;
  228. LIB_TREE_NODE* GetTreeNodeFor( const wxDataViewItem& aSelection ) const;
  229. virtual wxString GenerateInfo( const LIB_ID& aLibId, int aUnit ) { return wxEmptyString; }
  230. virtual bool HasPreview( const wxDataViewItem& aItem ) { return false; }
  231. virtual void ShowPreview( wxWindow* aParent, const wxDataViewItem& aItem ) {}
  232. TOOL_DISPATCHER* GetToolDispatcher() const { return m_parent->GetToolDispatcher(); }
  233. /**
  234. * Return the number of symbols loaded in the tree.
  235. */
  236. int GetItemCount() const;
  237. /**
  238. * Return the number of libraries loaded in the tree.
  239. */
  240. virtual int GetLibrariesCount() const
  241. {
  242. return m_tree.m_Children.size();
  243. }
  244. /**
  245. * Returns tree item corresponding to part.
  246. *
  247. * @param aLibId specifies the part and library name to be searched for.
  248. * @return Tree data item representing the part. Might be invalid if nothings was found.
  249. */
  250. wxDataViewItem FindItem( const LIB_ID& aLibId );
  251. virtual wxDataViewItem GetCurrentDataViewItem();
  252. /**
  253. * Populate a list of all the children of an item
  254. *
  255. * @return number of children
  256. */
  257. unsigned int GetChildren( const wxDataViewItem& aItem,
  258. wxDataViewItemArray& aChildren ) const override;
  259. // Freezing/Thawing. Used when updating the table model so that we don't try and fetch
  260. // values during updating. Primarily a problem on OSX which doesn't pay attention to the
  261. // wxDataViewCtrl's freeze count when updating the keyWindow.
  262. void Freeze() { m_freeze++; }
  263. void Thaw() { m_freeze--; }
  264. bool IsFrozen() const { return m_freeze; }
  265. void RefreshTree();
  266. // Allows subclasses to nominate a context menu handler.
  267. virtual TOOL_INTERACTIVE* GetContextMenuTool() { return nullptr; }
  268. void PinLibrary( LIB_TREE_NODE* aTreeNode );
  269. void UnpinLibrary( LIB_TREE_NODE* aTreeNode );
  270. void ShowChangedLanguage()
  271. {
  272. recreateColumns();
  273. }
  274. protected:
  275. /**
  276. * Convert #SYM_TREE_NODE -> wxDataViewItem.
  277. */
  278. static wxDataViewItem ToItem( const LIB_TREE_NODE* aNode );
  279. /**
  280. * Convert wxDataViewItem -> #SYM_TREE_NODE.
  281. */
  282. static LIB_TREE_NODE* ToNode( wxDataViewItem aItem );
  283. /**
  284. * Create the adapter.
  285. *
  286. * @param aParent is the parent frame
  287. * @param aPinnedKey is the key to load the pinned libraries list from the project file
  288. */
  289. LIB_TREE_MODEL_ADAPTER( EDA_BASE_FRAME* aParent, const wxString& aPinnedKey );
  290. LIB_TREE_NODE_LIBRARY& DoAddLibraryNode( const wxString& aNodeName, const wxString& aDesc,
  291. bool pinned );
  292. /**
  293. * Check whether a container has columns too
  294. */
  295. bool HasContainerColumns( const wxDataViewItem& aItem ) const override;
  296. /**
  297. * Check whether an item can have children.
  298. */
  299. bool IsContainer( const wxDataViewItem& aItem ) const override;
  300. /**
  301. * Get the parent of an item.
  302. *
  303. * @return parent of aItem, or an invalid wxDataViewItem if parent is root
  304. */
  305. wxDataViewItem GetParent( const wxDataViewItem& aItem ) const override;
  306. unsigned int GetColumnCount() const override { return m_columns.size(); }
  307. /**
  308. * Return the type of data stored in the column as indicated by wxVariant::GetType()
  309. */
  310. wxString GetColumnType( unsigned int aCol ) const override { return "string"; }
  311. /**
  312. * Get the value of an item.
  313. *
  314. * @param aVariant wxVariant to receive the data
  315. * @param aItem item whose data will be placed into aVariant
  316. * @param aCol column number of the data
  317. */
  318. void GetValue( wxVariant& aVariant,
  319. const wxDataViewItem& aItem,
  320. unsigned int aCol ) const override;
  321. /**
  322. * Set the value of an item. Does nothing - this model doesn't support
  323. * editing.
  324. */
  325. bool SetValue( const wxVariant& aVariant,
  326. const wxDataViewItem& aItem,
  327. unsigned int aCol ) override { return false; }
  328. /**
  329. * Get any formatting for an item.
  330. *
  331. * @param aItem item to get formatting for
  332. * @param aCol column number of interest
  333. * @param aAttr receiver for attributes
  334. * @return true if the item has non-default attributes
  335. */
  336. bool GetAttr( const wxDataViewItem& aItem,
  337. unsigned int aCol,
  338. wxDataViewItemAttr& aAttr ) const override;
  339. virtual bool isSymbolModel() = 0;
  340. void resortTree();
  341. private:
  342. /**
  343. * Find and expand successful search results. Return the best match (if any).
  344. */
  345. const LIB_TREE_NODE* ShowResults();
  346. wxDataViewColumn* doAddColumn( const wxString& aHeader, bool aTranslate = true );
  347. protected:
  348. void addColumnIfNecessary( const wxString& aHeader );
  349. void recreateColumns();
  350. LIB_TREE_NODE_ROOT m_tree;
  351. std::map<unsigned, wxString> m_colIdxMap;
  352. std::vector<wxString> m_availableColumns;
  353. wxDataViewCtrl* m_widget;
  354. private:
  355. EDA_BASE_FRAME* m_parent;
  356. SORT_MODE m_sort_mode;
  357. bool m_show_units;
  358. LIB_ID m_preselect_lib_id;
  359. int m_preselect_unit;
  360. int m_freeze;
  361. std::function<bool( LIB_TREE_NODE& aNode )>* m_filter;
  362. std::vector<wxDataViewColumn*> m_columns;
  363. std::map<wxString, wxDataViewColumn*> m_colNameMap;
  364. std::map<wxString, int> m_colWidths;
  365. std::vector<wxString> m_shownColumns; // Stored in display order
  366. };
  367. #endif // LIB_TREE_MODEL_ADAPTER_H