AddOn.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. /**
  2. * Copyright (c) 2011-2018 by Andrew Mustun. All rights reserved.
  3. *
  4. * This file is part of the QCAD project.
  5. *
  6. * QCAD is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * QCAD is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with QCAD.
  18. */
  19. //include("WidgetFactory.js");
  20. /**
  21. * \class AddOn
  22. * \brief Initializes and manages all add-ons. Every directory in the
  23. * script directory of QCAD is a add-on if it contains an ECMAScript
  24. * file with the same name as the directory and the extension ".js".
  25. * For example MyAddOn/MyAddOn.js.
  26. */
  27. function AddOn(addOnPath) {
  28. this.fileInfo = new QFileInfo(addOnPath);
  29. this.widget = undefined;
  30. AddOn.xslt = undefined;
  31. }
  32. /**
  33. * For debugging.
  34. */
  35. AddOn.prototype.toString = function() {
  36. var actionText = "";
  37. if (!isNull(this.getGuiAction())) {
  38. actionText = this.getGuiAction().text;
  39. }
  40. return "AddOn("
  41. + "actionText: '" + actionText + "'"
  42. + ", groupName: " + this.getGroupName()
  43. + ", filePath: " + this.getFilePath()
  44. + ")";
  45. };
  46. /**
  47. * Called once on startup to initialize the add-on, its preference page
  48. * and its documentation if applicable.
  49. */
  50. AddOn.prototype.init = function(splash, text) {
  51. this.initAddOn(splash, text);
  52. // slow:
  53. //this.initPreferencePage();
  54. };
  55. /**
  56. * Called once on startup to post-initialize the add-on.
  57. */
  58. AddOn.prototype.postInit = function(splash, text) {
  59. this.postInitAddOn(splash, text);
  60. };
  61. /**
  62. * Loads the add-on by including its main source file.
  63. *
  64. * \param initOnly True: only load the add-on if no file ClassNameInit.js
  65. * is present.
  66. */
  67. AddOn.prototype.load = function(initOnly) {
  68. if (isNull(initOnly)) {
  69. initOnly = false;
  70. }
  71. if (initOnly) {
  72. var initFilePath = this.getInitFilePath();
  73. if (new QFileInfo(initFilePath).exists()) {
  74. return;
  75. }
  76. }
  77. var fileName = this.getFilePath();
  78. if (!new QFileInfo(fileName).exists()) {
  79. qWarning("AddOn " + fileName + " not found and not loaded.");
  80. return;
  81. }
  82. include(fileName);
  83. };
  84. /**
  85. * \internal Called once on startup.
  86. */
  87. AddOn.prototype.initAddOn = function(splash, text) {
  88. var className = this.getClassName();
  89. var path = this.getPath();
  90. var bak = includeBasePath;
  91. includeBasePath = path;
  92. var initFilePath = this.getInitFilePath();
  93. if (new QFileInfo(initFilePath).exists()) {
  94. include(initFilePath, className, true);
  95. init(includeBasePath);
  96. }
  97. else {
  98. if (typeof(global[className])!=='undefined' && isFunction(global[className].init)) {
  99. global[className].init(includeBasePath, splash, text);
  100. }
  101. }
  102. includeBasePath = bak;
  103. // TODO: release add-on to free memory:
  104. //global[className] = undefined;
  105. };
  106. /**
  107. * \internal Called once in the end after startup.
  108. */
  109. AddOn.prototype.postInitAddOn = function(splash, text) {
  110. var className = this.getClassName();
  111. var path = this.getPath();
  112. var bak = includeBasePath;
  113. includeBasePath = path;
  114. var postInitFilePath = this.getPostInitFilePath();
  115. if (new QFileInfo(postInitFilePath).exists()) {
  116. include(postInitFilePath);
  117. postInit(includeBasePath);
  118. }
  119. else {
  120. if (!isNull(global[className]) && isFunction(global[className].postInit)) {
  121. global[className].postInit(includeBasePath, splash, text);
  122. }
  123. }
  124. includeBasePath = bak;
  125. };
  126. AddOn.prototype.uninit = function() {
  127. //var className = this.getClassName();
  128. //global[className] = undefined;
  129. var className = this.getClassName();
  130. var path = this.getPath();
  131. //var bak = includeBasePath;
  132. //includeBasePath = path;
  133. var uninitFilePath = this.getUninitFilePath();
  134. if (new QFileInfo(uninitFilePath).exists()) {
  135. include(uninitFilePath, className);
  136. uninit();
  137. }
  138. else {
  139. if (typeof(global[className])!=='undefined' && isFunction(global[className].uninit)) {
  140. global[className].uninit();
  141. }
  142. }
  143. //includeBasePath = bak;
  144. };
  145. /**
  146. * \internal Called once on startup.
  147. */
  148. /*
  149. AddOn.prototype.initPreferencePage = function() {
  150. var className = this.getClassName();
  151. var uiFileName = this.getPreferenceFile();
  152. // load preference page, if one exists
  153. if (new QFileInfo(uiFileName).exists()) {
  154. var settingsKey = "PreferencePageInitialized/" + className;
  155. var alreadyInitialized = RSettings.getBoolValue(settingsKey, false);
  156. // freak bug FS#406 with custom key codes / command configured:
  157. //isDeleted("");
  158. isNull();
  159. if (alreadyInitialized) {
  160. return;
  161. }
  162. var widget = WidgetFactory.createWidget("", uiFileName);
  163. try {
  164. eval("if( !isNull(" + className + ") && isFunction(" + className + ".initPreferences) ) {"
  165. + className + ".initPreferences(widget);"
  166. + "}");
  167. } catch (e) {
  168. qDebug("AddOn.js:", "AddOn has no method initPreferences(): " + e );
  169. }
  170. WidgetFactory.restoreState(widget);
  171. WidgetFactory.saveState(widget);
  172. WidgetFactory.requiresRestart = false;
  173. destr(widget);
  174. RSettings.setValue(settingsKey, true);
  175. }
  176. };
  177. */
  178. /**
  179. * \return Absolute path of the preference UI definition for this add-on.
  180. * The file name is PreferencesPage.ui and it must be located in the add-on
  181. * path to be found.
  182. */
  183. AddOn.prototype.getPreferenceFile = function() {
  184. var path = this.getPath();
  185. var uiFile = new QFileInfo("%1/PreferencesPage.ui".arg(path));
  186. return uiFile.absoluteFilePath();
  187. };
  188. /**
  189. * \return True if this add-on has a preferences UI file.
  190. */
  191. AddOn.prototype.preferenceFileExists = function() {
  192. var uiFileName = this.getPreferenceFile();
  193. var ret = (new QFileInfo(uiFileName).exists());
  194. if (!ret) {
  195. qWarning("AddOn.js: File does not exists: " + uiFileName);
  196. }
  197. return ret;
  198. };
  199. /**
  200. * \return True if shortcuts can be defined for this add-on (default) or
  201. * false if a add-on explicitly defines, that is does not support
  202. * shortcuts (ClassName.hasShortcuts()).
  203. */
  204. AddOn.prototype.hasShortcuts = function() {
  205. var className = this.getClassName();
  206. try {
  207. var ret = true;
  208. if (!isNull(global[className]) && isFunction(global[className].hasShortcuts)) {
  209. ret = global[className].hasShortcuts();
  210. }
  211. return ret;
  212. } catch (e) {
  213. debugger;
  214. }
  215. return undefined;
  216. };
  217. /**
  218. * \return True if this add-on has a GUI action (QAction) attached to it
  219. * which can be used to launch the action this add-on represents.
  220. */
  221. AddOn.prototype.hasGuiAction = function() {
  222. return this.getGuiAction() != null;
  223. };
  224. /**
  225. * \return The GUI action attached to this add-on.
  226. */
  227. AddOn.prototype.getGuiAction = function() {
  228. return RGuiAction.getByScriptFile(this.getFilePath());
  229. };
  230. AddOn.prototype.setPreferenceWidget = function(w) {
  231. this.widget = w;
  232. };
  233. AddOn.prototype.getPreferenceWidget = function() {
  234. return this.widget;
  235. };
  236. AddOn.prototype.getGroupName = function() {
  237. var dir = new QDir(this.fileInfo.path());
  238. dir.cdUp();
  239. return dir.dirName();
  240. };
  241. /**
  242. * \return Translated title of this add on (from GUI action or class info).
  243. */
  244. AddOn.prototype.getTitle = function() {
  245. var title;
  246. // try to get title from class (getTitle):
  247. var className = this.getClassName();
  248. title = AddOn.getClassTitle(className);
  249. if (isNull(title)) {
  250. // try to get title from gui action:
  251. var a = this.getGuiAction();
  252. if (!isNull(a)) {
  253. title = a.text;
  254. }
  255. }
  256. if (!isNull(title)) {
  257. title = title.replace("&", "");
  258. // remove everything after tab (shortcuts under windows):
  259. if (title.indexOf("\t")!==-1) {
  260. title = title.substring(0, title.indexOf("\t"));
  261. }
  262. }
  263. return title;
  264. };
  265. /**
  266. * \return The title of this add-on's parent add-on. E.g. for
  267. * scripts/Draw/Line/Line2P.js, that's the title returned by
  268. * Line.getTitle().
  269. */
  270. AddOn.prototype.getParentTitle = function() {
  271. var gn = this.getGroupName();
  272. return AddOn.getClassTitle(gn);
  273. };
  274. /**
  275. * \return Translated title for the given class name.
  276. */
  277. AddOn.getClassTitle = function(cn) {
  278. var title;
  279. try {
  280. if (!isNull(global[cn]) && isFunction(global[cn].getTitle)) {
  281. title = global[cn].getTitle();
  282. }
  283. } catch (e) {
  284. qWarning("AddOn.js:", "getClassTitle(): Exception:", e);
  285. }
  286. if (!isNull(title)) {
  287. title = title.replace("&", "");
  288. }
  289. return title;
  290. };
  291. /**
  292. * \return Hierarchy of titles for this add on (e.g. [Draw, Line, Line 2P]).
  293. */
  294. AddOn.prototype.getParentTitles = function() {
  295. var ret = [];
  296. var dir = new QDir(this.fileInfo.path());
  297. ret.unshift(this.getTitle());
  298. do {
  299. if (!dir.cdUp()) {
  300. break;
  301. }
  302. var dn = dir.dirName();
  303. var title = AddOn.getClassTitle(dn);
  304. if (isNull(title)) {
  305. break;
  306. }
  307. ret.unshift(title);
  308. } while (true);
  309. return ret;
  310. };
  311. /**
  312. * \return true If the add-on's parent is "scripts", the top level
  313. * directory that contains all script add-ons.
  314. */
  315. AddOn.prototype.isTopLevel = function() {
  316. return this.getGroupName() === "scripts";
  317. };
  318. AddOn.prototype.getClassName = function() {
  319. return this.fileInfo.completeBaseName();
  320. };
  321. AddOn.prototype.getPath = function() {
  322. return this.fileInfo.path();
  323. };
  324. /**
  325. * \return The ECMAScript file path of the add-on implementation.
  326. */
  327. AddOn.prototype.getFilePath = function() {
  328. return this.fileInfo.filePath();
  329. };
  330. /**
  331. * \return The ECMAScript file path of the add-on init function implementation.
  332. */
  333. AddOn.prototype.getInitFilePath = function() {
  334. return this.fileInfo.absolutePath() + QDir.separator + this.fileInfo.completeBaseName() + "Init.js";
  335. };
  336. /**
  337. * \return The ECMAScript file path of the add-on postInit function implementation.
  338. */
  339. AddOn.prototype.getPostInitFilePath = function() {
  340. return this.fileInfo.absolutePath() + QDir.separator + this.fileInfo.completeBaseName() + "PostInit.js";
  341. };
  342. AddOn.prototype.getUninitFilePath = function() {
  343. return this.fileInfo.absolutePath() + QDir.separator + this.fileInfo.completeBaseName() + "Uninit.js";
  344. };
  345. AddOn.prototype.getBaseName = function() {
  346. return this.fileInfo.completeBaseName();
  347. };
  348. AddOn.prototype.hasDoc = function() {
  349. return this.getDocPath().exists();
  350. };
  351. AddOn.prototype.getDocPath = function() {
  352. return new QFileInfo(this.getPath() + "/doc");
  353. };
  354. AddOn.prototype.getDocJsFile = function() {
  355. return new QFile(this.getDocPath().filePath() + "/" + this.getClassName()
  356. + "_doc.js");
  357. };
  358. AddOn.prototype.getDocHtmlUrl = function() {
  359. return QUrl.fromLocalFile(this.getDocPath().absoluteFilePath() + "/"
  360. + this.getClassName() + "_" + RSettings.getLocale()
  361. + ".html");
  362. };
  363. AddOn.findByGroupName = function(addOns, groupName) {
  364. for ( var i = 0; i < addOns.length; ++i) {
  365. var addOn = addOns[i];
  366. //qDebug("class name: ", addOn.getClassName(), " groupName: ", groupName);
  367. if (addOn.getClassName() === groupName) {
  368. return addOn;
  369. }
  370. }
  371. return undefined;
  372. };
  373. AddOn.getParentAddOn = function(addOns, addOn) {
  374. var ret = AddOn.findByGroupName(addOns, addOn.getGroupName());
  375. if (isNull(ret)) {
  376. qWarning("AddOn.getParentAddOn: no parent add-on found for group name: ", addOn.getGroupName());
  377. }
  378. return ret;
  379. };
  380. /**
  381. * \return Array of all AddOn objects found.
  382. *
  383. * \param dir Used internally for recursive calls
  384. */
  385. AddOn.getAddOns = function(dir) {
  386. var topCall = isNull(dir);
  387. if (topCall && !isNull(AddOn.addOns)) {
  388. // return cached list:
  389. return AddOn.addOns;
  390. }
  391. var fileMenuList, i, k;
  392. var addOns = [];
  393. var dirFilter = makeQDirFilters(QDir.NoDotAndDotDot, QDir.Readable, QDir.Dirs);
  394. var sortFlags = makeQDirSortFlags(QDir.NoSort);
  395. // first call without recursion:
  396. if (topCall) {
  397. var args = RSettings.getOriginalArguments();
  398. // ignore all scripts in ./scripts directory
  399. // and only load scripts from plugins
  400. // used mainly for testing / development
  401. if (args.contains("-ignore-script-files")) {
  402. dir = undefined;
  403. }
  404. else {
  405. dir = "scripts";
  406. }
  407. // fixed set of directories that will be scanned for add-ons first to
  408. // ensure fixed order of menus and tool bars:
  409. fileMenuList = [
  410. // scripts compiled as resources in plugins:
  411. new QFileInfo(":scripts"),
  412. // local scripts:
  413. new QFileInfo(RSettings.getDataLocation() + "/scripts"),
  414. ];
  415. // local scripts from installed add-ons:
  416. var localAddOns = AddOn.getLocalAddOns();
  417. for (i=0; i<localAddOns.length; i++) {
  418. var localAddOnDir = RSettings.getDataLocation() + "/" + localAddOns[i] + "/scripts";
  419. var fi = new QFileInfo(localAddOnDir);
  420. if (fi.exists()) {
  421. qDebug("adding scripts dir of add-on: ", localAddOnDir);
  422. fileMenuList.push(fi);
  423. }
  424. }
  425. // append directories not in the list above:
  426. if (!isNull(dir)) {
  427. var menuList = new QDir(dir).entryInfoList(dirFilter, sortFlags);
  428. for (i=0; i<menuList.length; ++i) {
  429. if (!fileMenuList.contains(menuList[i], function(a,b) { return a.absoluteFilePath()===b.absoluteFilePath(); })) {
  430. fileMenuList.push(menuList[i]);
  431. }
  432. }
  433. }
  434. } else {
  435. fileMenuList = new QDir(dir).entryInfoList(dirFilter, sortFlags);
  436. }
  437. for (i=0; i<fileMenuList.length; ++i) {
  438. var dirInfo = fileMenuList[i];
  439. if (!dirInfo.exists()) {
  440. continue;
  441. }
  442. if (AddOn.isIgnored(dirInfo.filePath())) {
  443. continue;
  444. }
  445. // don't dive into translation, doc or Tests folders:
  446. if (dirInfo.fileName() === "ts" || dirInfo.fileName() === "doc" || dirInfo.fileName() === "Tests") {
  447. continue;
  448. }
  449. var fileInfo = new QFileInfo(dirInfo.filePath() + "/" + dirInfo.fileName() + ".js");
  450. if (dirInfo.fileName().startsWith("AutoLoad")) {
  451. if (typeof(RAutoLoadEcma)!=="undefined") {
  452. RAutoLoadEcma.addAutoLoadFile(fileInfo.filePath());
  453. }
  454. if (typeof(RAutoLoadJs)!=="undefined") {
  455. RAutoLoadJs.addAutoLoadFile(fileInfo.filePath());
  456. }
  457. }
  458. else {
  459. if (fileInfo.exists() && !AddOn.isIgnored(fileInfo.absoluteFilePath())) {
  460. // if (addOns.contains(fileInfo.filePath(), function(a,b) { qDebug(a.getPath(), b); return a.getPath()===b; })) {
  461. // qDebug("already loaded: ", fileInfo.filePath());
  462. // }
  463. if (!addOns.contains(fileInfo.filePath(), function(a,b) { return a.getPath()===b; })) {
  464. addOns.push(new AddOn(fileInfo.filePath()));
  465. }
  466. }
  467. }
  468. addOns = addOns.concat(AddOn.getAddOns(dirInfo.filePath()));
  469. }
  470. if (topCall) {
  471. // sort add ons by menu order:
  472. var menuNames = {
  473. //"Reset":10,
  474. "File":20,// "Data": 30, "Interaction": 40, "Optimize": 50
  475. // , "View":40, "Select":50,
  476. "Layer":1500,
  477. "Window":1600, "Widgets":1700//, "Local":170
  478. };
  479. // var menuNames = {
  480. // "Reset":10, "File":20, "Edit":30, "View":40, "Select":50, "Draw":60, "Dimension":70,
  481. // "Modify":80, "Snap":90, "Information":100, "Layer":110, "Block":120, "Developer":130,
  482. // "Window":140, "Widgets":150, "Misc":160, "Local":170, "Help":100000
  483. // };
  484. var rx1 = new RegExp(":?\/?scripts\/");
  485. var rx2 = new RegExp("\/.*");
  486. var gotRegularFile = false;
  487. addOns.sort(function(a,b) {
  488. var aPath = a.getPath();
  489. var bPath = b.getPath();
  490. if (!gotRegularFile && (aPath[0]!==":" || bPath[0]!==":")) {
  491. gotRegularFile = true;
  492. }
  493. // get top dir name after scripts (e.g. 'File', 'Layer', ...):
  494. var da = aPath.replace(rx1, "").replace(rx2, "");
  495. var db = bPath.replace(rx1, "").replace(rx2, "");
  496. // first priority:
  497. // sort by predefined menu order:
  498. // get sort order from menuNames map:
  499. var oa = menuNames[da];
  500. var ob = menuNames[db];
  501. // menu not in list:
  502. // insert between Local and Help:
  503. if (isNull(oa)) {
  504. oa = 1000;
  505. }
  506. if (isNull(ob)) {
  507. ob = 1000;
  508. }
  509. if (oa!==ob) {
  510. return oa-ob;
  511. }
  512. // secondary priority:
  513. // sort alphabetically:
  514. var aPathNoColon = aPath;
  515. var bPathNoColon = bPath;
  516. if (aPathNoColon[0]===":") {
  517. aPathNoColon = aPathNoColon.substring(1);
  518. }
  519. if (bPathNoColon[0]===":") {
  520. bPathNoColon = bPathNoColon.substring(1);
  521. }
  522. if (aPathNoColon!==bPathNoColon) {
  523. return (aPathNoColon>bPathNoColon) ? 1 : -1;
  524. }
  525. // prioritize 'scripts' paths (QCAD) over ':scripts' (plugin):
  526. if (!aPath.startsWith(":") && bPath.startsWith(":")) {
  527. return -1;
  528. }
  529. else if (aPath.startsWith(":") && !bPath.startsWith(":")) {
  530. return 1;
  531. }
  532. else {
  533. return 0;
  534. }
  535. });
  536. // for (var i=0; i<addOns.length; i++) {
  537. // qDebug("addOn: ", addOns[i].getPath());
  538. // }
  539. if (gotRegularFile) {
  540. // filter out duplicate paths from plugins:
  541. // files take priority over resources:
  542. var addOnsFiltered = [];
  543. var prevPathNoColon = undefined;
  544. for (var i=0; i<addOns.length; i++) {
  545. var addOn = addOns[i];
  546. var pathNoColon = addOn.fileInfo.filePath();
  547. if (pathNoColon[0]===":") {
  548. pathNoColon = pathNoColon.substring(1);
  549. }
  550. if (!isNull(prevPathNoColon) && prevPathNoColon===pathNoColon) {
  551. continue;
  552. }
  553. addOnsFiltered.push(addOn);
  554. prevPathNoColon = pathNoColon;
  555. }
  556. addOns = addOnsFiltered;
  557. }
  558. // cache:
  559. AddOn.addOns = addOns;
  560. }
  561. return addOns;
  562. };
  563. AddOn.getLocalAddOns = function() {
  564. var dataDir = new QDir(RSettings.getDataLocation());
  565. var fs = makeQDirFilters(QDir.NoDotAndDotDot, QDir.Readable, QDir.Dirs, QDir.Executable);
  566. var sf = makeQDirSortFlags(QDir.Name);
  567. return dataDir.entryList([], fs, sf);
  568. };
  569. AddOn.isIgnored = function(path) {
  570. if (isNull(AddOn.ignores)) {
  571. var args = RSettings.getOriginalArguments();
  572. AddOn.ignores = [];
  573. for (var i=1; i < args.length; ++i) {
  574. if (args[i] === "-ignore") {
  575. ++i;
  576. if (isNull(args[i])) {
  577. break;
  578. }
  579. AddOn.ignores.push(args[i]);
  580. }
  581. }
  582. }
  583. for (var k=0; k<AddOn.ignores.length; ++k) {
  584. if (path.contains(AddOn.ignores[k])) {
  585. return true;
  586. }
  587. }
  588. return false;
  589. };
  590. AddOn.getAddOnPath = function(name) {
  591. var addOns = AddOn.getAddOns();
  592. for (var i = 0; i < addOns.length; ++i) {
  593. var addOn = addOns[i];
  594. if (addOn.getClassName()===name) {
  595. return addOn.getPath();
  596. }
  597. }
  598. };