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.

446 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 The 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. #include <project.h>
  92. class APP_SETTINGS_BASE;
  93. class TOOL_INTERACTIVE;
  94. class EDA_BASE_FRAME;
  95. class LIB_TREE_MODEL_ADAPTER: public wxDataViewModel
  96. {
  97. public:
  98. /**
  99. * @return a unicode string to mark a node name like a pinned library name.
  100. * This is not an ASCII7 char, but a unicode char.
  101. */
  102. static const wxString GetPinningSymbol()
  103. {
  104. return wxString::FromUTF8( "" );
  105. }
  106. public:
  107. /**
  108. * Destructor. Do NOT delete this class manually; it is reference-counted
  109. * by wxObject.
  110. */
  111. ~LIB_TREE_MODEL_ADAPTER();
  112. /**
  113. * This enum defines the order of the default columns in the tree view
  114. */
  115. enum TREE_COLS
  116. {
  117. NAME_COL = 0, ///< Library or library item name column
  118. DESC_COL, ///< Library or library description column
  119. NUM_COLS ///< The number of default tree columns
  120. };
  121. enum SORT_MODE
  122. {
  123. BEST_MATCH = 0,
  124. ALPHABETIC
  125. };
  126. /**
  127. * Save the column widths to the config file. This requires the tree view to still be
  128. * valid.
  129. */
  130. void SaveSettings();
  131. /**
  132. * Set the symbol filter type. Must be set before adding libraries
  133. *
  134. * @param aFilter if SYM_FILTER_POWER, only power parts are loaded
  135. */
  136. void SetFilter( std::function<bool( LIB_TREE_NODE& aNode )>* aFilter ) { m_filter = aFilter; }
  137. /**
  138. * Return the active filter.
  139. */
  140. std::function<bool( LIB_TREE_NODE& aNode )>* GetFilter() const { return m_filter; }
  141. void SetSortMode( SORT_MODE aMode ) { m_sort_mode = aMode; }
  142. SORT_MODE GetSortMode() const { return m_sort_mode; }
  143. /**
  144. * Whether or not to show units. May be set at any time; updates at the next
  145. * UpdateSearchString()
  146. *
  147. * @param aShow if true, units are displayed
  148. */
  149. void ShowUnits( bool aShow );
  150. /**
  151. * Set the symbol name to be selected if there are no search results.
  152. * May be set at any time; updates at the next UpdateSearchString().
  153. *
  154. * @param aLibId symbol #LIB_ID to be selected
  155. * @param aUnit unit to be selected, if > 0 (0 selects the alias itself)
  156. */
  157. void SetPreselectNode( const LIB_ID& aLibId, int aUnit );
  158. /**
  159. * Add the given list of symbols by alias. To be called in the setup
  160. * phase.
  161. *
  162. * @param aNodeName the parent node the symbols will appear under
  163. * @param aDesc the description field of the parent node
  164. * @param aItemList list of symbols
  165. */
  166. void DoAddLibrary( const wxString& aNodeName, const wxString& aDesc,
  167. const std::vector<LIB_TREE_ITEM*>& aItemList,
  168. bool pinned, bool presorted );
  169. /**
  170. * Remove the library by name.
  171. *
  172. * @param aNodeName the name of the library to remove
  173. */
  174. void DoRemoveLibrary( const wxString& aNodeName );
  175. std::vector<wxString> GetAvailableColumns() const { return m_availableColumns; }
  176. std::vector<wxString> GetShownColumns() const { return m_shownColumns; }
  177. std::vector<wxString> GetOpenLibs() const;
  178. void OpenLibs( const std::vector<wxString>& aLibs );
  179. /**
  180. * Sets which columns are shown in the widget. Invalid column names are discarded.
  181. * @param aColumnNames is an ordered list of column names to show
  182. */
  183. void SetShownColumns( const std::vector<wxString>& aColumnNames );
  184. /**
  185. * Sort the tree and assign ranks after adding libraries.
  186. */
  187. void AssignIntrinsicRanks() { m_tree.AssignIntrinsicRanks(); }
  188. /**
  189. * Set the search string provided by the user.
  190. *
  191. * @param aSearch full, unprocessed search text
  192. * @param aState if true, we are keeping the state and so we shouldn't collapse the tree
  193. */
  194. void UpdateSearchString( const wxString& aSearch, bool aState );
  195. /**
  196. * Attach to a wxDataViewCtrl and initialize it. This will set up columns
  197. * and associate the model via the adapter.
  198. *
  199. * @param aDataViewCtrl the view symbol in the dialog
  200. */
  201. void AttachTo( wxDataViewCtrl* aDataViewCtrl );
  202. /**
  203. * A final-stage initialization to be called after the window hierarchy has been realized
  204. * and the window sizes set.
  205. */
  206. void FinishTreeInitialization();
  207. /**
  208. * Return the alias for the given item.
  209. *
  210. * @param aSelection item from the wxDataViewCtrl
  211. * (see wxDataViewCtrl::GetSelection())
  212. *
  213. * @return alias, or nullptr if none is selected
  214. */
  215. LIB_ID GetAliasFor( const wxDataViewItem& aSelection ) const;
  216. /**
  217. * Return the unit for the given item.
  218. *
  219. * @param aSelection item from the wxDataViewCtrl
  220. * (see wxDataViewCtrl::GetSelection())
  221. *
  222. * @return Unit, or zero if the alias itself is selected. Return valid is
  223. * invalid if GetAliasFor() returns nullptr.
  224. */
  225. int GetUnitFor( const wxDataViewItem& aSelection ) const;
  226. /**
  227. * Return node type for the given item.
  228. *
  229. * @param aSelection item from the wxDataViewCtrl
  230. * (see wxDataViewCtrl::GetSelection())
  231. *
  232. * @return Type of the selected node, might be INVALID.
  233. */
  234. LIB_TREE_NODE::TYPE GetTypeFor( const wxDataViewItem& aSelection ) const;
  235. LIB_TREE_NODE* GetTreeNodeFor( const wxDataViewItem& aSelection ) const;
  236. virtual wxString GenerateInfo( const LIB_ID& aLibId, int aUnit ) { return wxEmptyString; }
  237. virtual bool HasPreview( const wxDataViewItem& aItem ) { return false; }
  238. virtual void ShowPreview( wxWindow* aParent, const wxDataViewItem& aItem ) {}
  239. TOOL_DISPATCHER* GetToolDispatcher() const { return m_parent->GetToolDispatcher(); }
  240. /**
  241. * Return the number of symbols loaded in the tree.
  242. */
  243. int GetItemCount() const;
  244. /**
  245. * Return the number of libraries loaded in the tree.
  246. */
  247. virtual int GetLibrariesCount() const
  248. {
  249. return m_tree.m_Children.size();
  250. }
  251. /**
  252. * Returns tree item corresponding to part.
  253. *
  254. * @param aLibId specifies the part and library name to be searched for.
  255. * @return Tree data item representing the part. Might be invalid if nothings was found.
  256. */
  257. wxDataViewItem FindItem( const LIB_ID& aLibId );
  258. virtual wxDataViewItem GetCurrentDataViewItem();
  259. /**
  260. * Populate a list of all the children of an item
  261. *
  262. * @return number of children
  263. */
  264. unsigned int GetChildren( const wxDataViewItem& aItem,
  265. wxDataViewItemArray& aChildren ) const override;
  266. // Freezing/Thawing. Used when updating the table model so that we don't try and fetch
  267. // values during updating. Primarily a problem on OSX which doesn't pay attention to the
  268. // wxDataViewCtrl's freeze count when updating the keyWindow.
  269. void Freeze() { m_freeze++; }
  270. void Thaw() { m_freeze--; }
  271. bool IsFrozen() const { return m_freeze; }
  272. void RefreshTree();
  273. // Allows subclasses to nominate a context menu handler.
  274. virtual TOOL_INTERACTIVE* GetContextMenuTool() { return nullptr; }
  275. void PinLibrary( LIB_TREE_NODE* aTreeNode );
  276. void UnpinLibrary( LIB_TREE_NODE* aTreeNode );
  277. void ShowChangedLanguage()
  278. {
  279. recreateColumns();
  280. }
  281. protected:
  282. /**
  283. * Convert #SYM_TREE_NODE -> wxDataViewItem.
  284. */
  285. static wxDataViewItem ToItem( const LIB_TREE_NODE* aNode );
  286. /**
  287. * Convert wxDataViewItem -> #SYM_TREE_NODE.
  288. */
  289. static LIB_TREE_NODE* ToNode( wxDataViewItem aItem );
  290. /**
  291. * Create the adapter.
  292. *
  293. * @param aParent is the parent frame
  294. * @param aPinnedKey is the key to load the pinned libraries list from the project file
  295. * @param aCfg app settings for the specific editor
  296. */
  297. LIB_TREE_MODEL_ADAPTER( EDA_BASE_FRAME* aParent, const wxString& aPinnedKey,
  298. APP_SETTINGS_BASE* aCfg );
  299. LIB_TREE_NODE_LIBRARY& DoAddLibraryNode( const wxString& aNodeName, const wxString& aDesc,
  300. bool pinned );
  301. /**
  302. * Check whether a container has columns too
  303. */
  304. bool HasContainerColumns( const wxDataViewItem& aItem ) const override;
  305. /**
  306. * Check whether an item can have children.
  307. */
  308. bool IsContainer( const wxDataViewItem& aItem ) const override;
  309. /**
  310. * Get the parent of an item.
  311. *
  312. * @return parent of aItem, or an invalid wxDataViewItem if parent is root
  313. */
  314. wxDataViewItem GetParent( const wxDataViewItem& aItem ) const override;
  315. unsigned int GetColumnCount() const override { return m_columns.size(); }
  316. /**
  317. * Return the type of data stored in the column as indicated by wxVariant::GetType()
  318. */
  319. wxString GetColumnType( unsigned int aCol ) const override { return "string"; }
  320. /**
  321. * Get the value of an item.
  322. *
  323. * @param aVariant wxVariant to receive the data
  324. * @param aItem item whose data will be placed into aVariant
  325. * @param aCol column number of the data
  326. */
  327. void GetValue( wxVariant& aVariant,
  328. const wxDataViewItem& aItem,
  329. unsigned int aCol ) const override;
  330. /**
  331. * Set the value of an item. Does nothing - this model doesn't support
  332. * editing.
  333. */
  334. bool SetValue( const wxVariant& aVariant,
  335. const wxDataViewItem& aItem,
  336. unsigned int aCol ) override { return false; }
  337. /**
  338. * Get any formatting for an item.
  339. *
  340. * @param aItem item to get formatting for
  341. * @param aCol column number of interest
  342. * @param aAttr receiver for attributes
  343. * @return true if the item has non-default attributes
  344. */
  345. bool GetAttr( const wxDataViewItem& aItem,
  346. unsigned int aCol,
  347. wxDataViewItemAttr& aAttr ) const override;
  348. virtual PROJECT::LIB_TYPE_T getLibType() = 0;
  349. void resortTree();
  350. private:
  351. /**
  352. * Find and expand successful search results. Return the best match (if any).
  353. */
  354. const LIB_TREE_NODE* ShowResults();
  355. wxDataViewColumn* doAddColumn( const wxString& aHeader, bool aTranslate = true );
  356. protected:
  357. void addColumnIfNecessary( const wxString& aHeader );
  358. void recreateColumns();
  359. LIB_TREE_NODE_ROOT m_tree;
  360. std::map<unsigned, wxString> m_colIdxMap;
  361. std::vector<wxString> m_availableColumns;
  362. wxDataViewCtrl* m_widget;
  363. private:
  364. EDA_BASE_FRAME* m_parent;
  365. APP_SETTINGS_BASE* m_cfg;
  366. SORT_MODE m_sort_mode;
  367. bool m_show_units;
  368. LIB_ID m_preselect_lib_id;
  369. int m_preselect_unit;
  370. int m_freeze;
  371. std::function<bool( LIB_TREE_NODE& aNode )>* m_filter;
  372. std::vector<wxDataViewColumn*> m_columns;
  373. std::map<wxString, wxDataViewColumn*> m_colNameMap;
  374. std::map<wxString, int> m_colWidths;
  375. std::vector<wxString> m_shownColumns; // Stored in display order
  376. };
  377. #endif // LIB_TREE_MODEL_ADAPTER_H