window_management.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  1. /*******************************************************************************
  2. AToMPM - A Tool for Multi-Paradigm Modelling
  3. Copyright (c) 2011 Raphael Mannadiar (raphael.mannadiar@mail.mcgill.ca)
  4. Modified by Conner Hansen (chansen@crimson.ua.edu)
  5. This file is part of AToMPM.
  6. AToMPM is free software: you can redistribute it and/or modify it under the
  7. terms of the GNU Lesser General Public License as published by the Free Software
  8. Foundation, either version 3 of the License, or (at your option) any later
  9. version.
  10. AToMPM is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
  12. PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
  13. You should have received a copy of the GNU Lesser General Public License along
  14. with AToMPM. If not, see <http://www.gnu.org/licenses/>.
  15. *******************************************************************************/
  16. ///////////////////////////////////////////////////////////////////////////////
  17. // DEPRECATED FUNCTIONS
  18. ///////////////////////////////////////////////////////////////////////////////
  19. function _openDialog(type, args, callback){
  20. AtomPMClient.alertDeprecatedFunctionCall("_openDialog");
  21. WindowManagement.openDialog(type, args, callback);
  22. }
  23. function _spawnClient(fname,callbackURL){
  24. AtomPMClient.alertDeprecatedFunctionCall("_spawnClient");
  25. WindowManagement.spawnClient(fname, callbackURL);
  26. }
  27. function _spawnHeadlessClient(context,onready,onchlog){
  28. AtomPMClient.alertDeprecatedFunctionCall("_spawnHeadlessClient");
  29. WindowManagement.spawnHeadlessClient(context, onready, onchlog);
  30. }
  31. function __showDialog(){
  32. alert(AtomPMClient);
  33. AtomPMClient.alertDeprecatedFunctionCall("__showDialog");
  34. WindowManagement.showDialog();
  35. }
  36. function __closeDialog(){
  37. AtomPMClient.alertDeprecatedFunctionCall("__closeDialog");
  38. WindowManagement.closeDialog();
  39. }
  40. ///////////////////////////////////////////////////////////////////////////////
  41. //DEPRECATED FUNCTIONS
  42. ///////////////////////////////////////////////////////////////////////////////
  43. WindowManagement = function(){
  44. /**
  45. * Hides the login screen
  46. */
  47. this.hideLoginScreen = function()
  48. {
  49. //$('#div_login').style.display = 'none';
  50. $('#div_login').css('display', 'none');
  51. __setCanvasScrolling(true);
  52. };
  53. /**
  54. * Shows the login screen
  55. */
  56. this.showLoginScreen = function()
  57. {
  58. //$('#div_login').style.display = 'inline';
  59. $('#div_login').css('display', 'inline');
  60. __setCanvasScrolling(false);
  61. };
  62. //Todo: Shred this function into smaller functions, as this should
  63. // really just amount to a switch statement
  64. //TBI: complete comments about each dialog (copy from user's manual)
  65. /**
  66. * Opens a general dialog window
  67. */
  68. this.openDialog = function(type,args,callback)
  69. {
  70. args = args || {};
  71. function error(err,fatal)
  72. {
  73. console.error("Error! " + err);
  74. GUIUtils.setupAndShowDialog(
  75. [GUIUtils.getTextSpan(
  76. err,
  77. 'error')],
  78. undefined,
  79. (fatal ? __NO_BUTTONS : __ONE_BUTTON),
  80. (fatal ? 'FATAL ERROR (restart required)' : 'ERROR'));
  81. //console.error(err,args);
  82. }
  83. // TODO: Fix this, convert to JQuery
  84. if( type == _CLOUD_DATA_MANAGER )
  85. /* args: extensions,readonly,title */
  86. {
  87. HttpUtils.httpReq(
  88. 'GET',
  89. HttpUtils.url('/filelist',__NO_WID),
  90. undefined,
  91. function(statusCode,resp){
  92. var fnames = __localizeFilenames(
  93. __filterFilenamesByExtension(
  94. resp.split('\n'),
  95. args['extensions'] || ['.*'])).sort(),
  96. maxFnameLength =
  97. utils.max(fnames, function(_) {
  98. return _.length;
  99. }),
  100. fileb = GUIUtils.getFileBrowser(fnames,true),
  101. feedbackarea = $('<div>'),
  102. feedback = GUIUtils.getTextSpan(''),
  103. progressbar = $('<div>'),
  104. progressfill = $('<div>'),
  105. download = $('<div>'),
  106. trash = $('<div>'),
  107. div_dldel = $('<div>'),
  108. hldropzone =
  109. /* highlight or unhighlight the dropzone */
  110. function(zone)
  111. {
  112. if( zone == undefined )
  113. {
  114. fileb['filepane']().attr('class', 'fileb_pane');
  115. download.attr('class', 'dropzone');
  116. trash.attr('class', 'dropzone');
  117. }
  118. else if( zone == 'upload' )
  119. {
  120. var filepane = fileb['filepane']();
  121. filepane.attr('class', 'fileb_pane droppable');
  122. filepane.get(0).ondrop = onfilepanedrop;
  123. }
  124. else if( zone == 'dl/del' )
  125. {
  126. download.attr('class', 'dropzone droppable');
  127. trash.attr('class', 'dropzone droppable');
  128. }
  129. },
  130. cancelevt =
  131. /* prevent event bubbling */
  132. function(event)
  133. {
  134. event.stopPropagation();
  135. event.preventDefault();
  136. return false;
  137. },
  138. ondownloaddrop =
  139. function(event)
  140. {
  141. cancelevt(event);
  142. hldropzone();
  143. window.location.assign(event.dataTransfer.getData('uri'));
  144. },
  145. ontrashdrop =
  146. function(event)
  147. {
  148. cancelevt(event);
  149. hldropzone();
  150. var uri = event.dataTransfer.getData('uri');
  151. DataUtils.deleteFromCloud(uri,
  152. function(statusCode,resp)
  153. {
  154. if( ! utils.isHttpSuccessCode(statusCode) )
  155. return error(resp);
  156. feedback.html('deleted '+uri.match(/.*\/(.+)\.file/)[1]);
  157. });
  158. },
  159. onfilepanedrop =
  160. /* react to file drop from desktop
  161. 1. exit with error if non-zip files
  162. 2. move to handleFiles() otherwise */
  163. function(event)
  164. {
  165. cancelevt(event);
  166. hldropzone();
  167. var files = event.dataTransfer.files;
  168. for( var i=0; i<files.length; i++ )
  169. if( files[i].type != 'application/zip' )
  170. return error('uploaded files must zip archives');
  171. handleFiles(event.dataTransfer.files,0);
  172. },
  173. handleFiles =
  174. /* handle each dropped file from desktop
  175. 1. retrieve next file to handle
  176. 2. update feedback message and show progress bar
  177. 3. init file reader event handlers
  178. . onprogress updates progress bar
  179. . onload reacts to upload completion by adjusting
  180. feedback message, hiding progress bar and sending
  181. file to backend
  182. 4. start upload */
  183. function(files,i)
  184. {
  185. if( i >= files.length)
  186. return;
  187. var file = files[i];
  188. feedback.html('uploading '+file.name);
  189. progressbar.css("display", 'inline-block');
  190. var reader = new FileReader();
  191. reader.onprogress =
  192. function(event)
  193. {
  194. if( event.lengthComputable )
  195. progressfill.css("width",
  196. (100*event.loaded/event.total)+'%');
  197. };
  198. reader.onload =
  199. function(event)
  200. {
  201. progressfill.css("width", '100%');
  202. feedback.html('processing '+file.name+' ...');
  203. progressbar.css("display", 'none');
  204. DataUtils.uploadToCloud(
  205. fileb['getcurrfolder'](),
  206. event.target.result,
  207. function(statusCode,resp)
  208. {
  209. if( ! utils.isHttpSuccessCode(statusCode) )
  210. return error(resp);
  211. feedback.html('successfully processed '+file.name);
  212. handleFiles(files,++i);
  213. });
  214. };
  215. reader.readAsBinaryString(file);
  216. },
  217. cloudmgrClosed =
  218. function()
  219. {
  220. return fileb['filebrowser'].parent() == null;
  221. };
  222. document.body.ondragenter =
  223. /* show dropzone when file drag from desktop enters window */
  224. function(event)
  225. {
  226. if(cloudmgrClosed()) return true;
  227. cancelevt(event);
  228. hldropzone(
  229. (event.dataTransfer.effectAllowed == 'copyMove' ? 'dl/del' : 'upload'));
  230. return false;
  231. };
  232. document.body.ondragleave =
  233. /* hide dropzone when file drag from desktop leaves window (which
  234. causes event.pageX == 0) */
  235. function(event)
  236. {
  237. if(cloudmgrClosed()) return true;
  238. cancelevt(event);
  239. if( event.pageX == 0 )
  240. hldropzone();
  241. return false;
  242. };
  243. document.body.ondrop =
  244. function(event)
  245. {
  246. if(cloudmgrClosed()) return true;
  247. cancelevt(event);
  248. hldropzone();
  249. console.warn('non-dropzone drops are ignored');
  250. return false;
  251. };
  252. fileb['filebrowser'].attr('title',
  253. 'drag\'n\'drop files to file pane to upload\n'+
  254. '(close and re-open dialog to observe effects)');
  255. download.attr('title', 'drag\'n\'drop files from file pane to download');
  256. trash.attr('title', 'drag\'n\'drop files from file pane to delete\n'+
  257. '(close and re-open dialog to observe effects)');
  258. progressfill.attr('class', 'progress_fill');
  259. progressfill.html('&nbsp;');
  260. progressbar.attr('class', 'progress_bar');
  261. progressbar.append(progressfill);
  262. progressbar.css("display", 'none');
  263. feedbackarea.append(feedback);
  264. feedbackarea.append(progressbar);
  265. download.css("backgroundImage", 'url(client/media/download.png)');
  266. trash.css("backgroundImage", 'url(client/media/trash.png)');
  267. download.attr('class', 'dropzone');
  268. trash.attr('class', 'dropzone');
  269. download.css("cssFloat", 'left');
  270. trash.css("cssFloat", 'right');
  271. download.get(0).ondragover = cancelevt;
  272. trash.get(0).ondragover = cancelevt;
  273. download.get(0).ondrop = ondownloaddrop;
  274. trash.get(0).ondrop = ontrashdrop;
  275. div_dldel.append(download);
  276. div_dldel.append(trash);
  277. if( args['readonly'] )
  278. trash.css("display", 'none');
  279. GUIUtils.setupAndShowDialog(
  280. [fileb['filebrowser'],div_dldel,feedbackarea],
  281. undefined,
  282. __ONE_BUTTON,
  283. args['title'] ||
  284. 'manage your cloud data\n(note:: you must close and re-open '+
  285. 'dialog to view upload and deletion effects)');
  286. });
  287. }
  288. else if( type == _CUSTOM )
  289. /* args: widgets, title
  290. 'widgets' must be a list where each entry is either
  291. ['id':___,'type':'input','label':___,'default':___], or
  292. ['id':___,'type':'select','choices':___,'multipleChoice':___] */
  293. {
  294. var elements = [],
  295. getinputs = [];
  296. args['widgets'].forEach(
  297. function(w)
  298. {
  299. if( w['type'] == 'select' )
  300. {
  301. var select = GUIUtils.getSelector(w['choices'],w['multipleChoice']);
  302. getinputs.push(function(_)
  303. {
  304. _[w['id']] = HttpUtils.getSelectorSelection(select);
  305. });
  306. elements.push(select);
  307. }
  308. else if( w['type'] == 'input' )
  309. {
  310. var label = GUIUtils.getTextSpan(w['label'] || ''),
  311. input = GUIUtils.getStringInput(w['default'] || '');
  312. getinputs.push(function(_)
  313. {
  314. _[w['id']] = input[0].value;
  315. });
  316. elements.push(label,input);
  317. }
  318. });
  319. GUIUtils.setupAndShowDialog(
  320. elements,
  321. function()
  322. {
  323. var values = {};
  324. getinputs.forEach( function(gi) {gi(values);} );
  325. return values;
  326. },
  327. __TWO_BUTTONS,
  328. args['title'],
  329. callback);
  330. }
  331. else if( type == _ENTITY_EDITOR )
  332. /* args: uri */
  333. {
  334. var uri = (args['uri'] || __selection['items'][0]),
  335. matches = uri.match(/.*\/(.*)Icon\/(.*)\.instance/) ||
  336. uri.match(/.*\/(.*)Link\/(.*)\.instance/),
  337. type = matches[1],
  338. id = matches[2];
  339. HttpUtils.httpReq(
  340. 'GET',
  341. HttpUtils.url(uri),
  342. undefined,
  343. function(statusCode,resp)
  344. {
  345. if( ! utils.isHttpSuccessCode(statusCode) )
  346. return error(resp);
  347. return openDialog(
  348. _DICTIONARY_EDITOR,
  349. {'data': utils.jsonp( utils.jsonp(resp)['data'] ),
  350. 'ignoreKey':
  351. function(attr,val)
  352. {
  353. return attr.charAt(0) == '$' || val == undefined;
  354. },
  355. 'keepEverything':
  356. function()
  357. {
  358. return __changed(uri);
  359. },
  360. 'title':'edit '+type+' #'+id},
  361. callback || function(changes) {DataUtils.update(uri,changes);});
  362. });
  363. }
  364. else if( type == _ERROR )
  365. error(args);
  366. else if( type == __FATAL_ERROR )
  367. error(args,true);
  368. else if( type == _FILE_BROWSER )
  369. /* args: extensions,multipleChoice,manualInput,title,startDir */
  370. {
  371. HttpUtils.httpReq(
  372. 'GET',
  373. HttpUtils.url('/filelist',__NO_WID),
  374. undefined,
  375. function(statusCode,resp)
  376. {
  377. args['extensions'].push('/');
  378. var fnames = __localizeFilenames(
  379. __filterFilenamesByExtension(
  380. resp.split('\n'),
  381. args['extensions'] || ['.*'])
  382. ).sort(),
  383. maxFnameLength =
  384. utils.max(fnames,function(_) {return _.length;}),
  385. folder_buttons = $('<div>'),
  386. new_folder_b = $('<button>'),
  387. rename_folder_b = $('<button>'),
  388. delete_folder_b = $('<button>'),
  389. move_folder_b = $('<button>'),
  390. file_buttons = $('<div>'),
  391. rename_file_b = $('<button>'),
  392. delete_file_b = $('<button>'),
  393. move_file_b = $('<button>'),
  394. feedbackarea = $('<div>'),
  395. feedback = GUIUtils.getTextSpan('',"feedback"),
  396. fileb =
  397. GUIUtils.getFileBrowser(fnames,false,args['manualInput'],__getRecentDir(args['startDir']));
  398. new_folder_b.html('new folder')
  399. .click(function(ev) {
  400. var folder_name = prompt("please fill in a name for the folder");
  401. if (folder_name != null) {
  402. folder_name = folder_name.replace(/^\s+|\s+$/g, ''); // trim
  403. if (!folder_name.match(/^[a-zA-Z0-9_\s]+$/i)) {
  404. feedback.html("invalid folder name: " + folder_name);
  405. } else {
  406. console.log("/" + window.localStorage.getItem('user') + fileb['getcurrfolder']() + folder_name + '.folder');
  407. DataUtils.createFolder("/" + window.localStorage.getItem('user') + fileb['getcurrfolder']() + folder_name + '.folder', function(statusCode, resp) {
  408. if( ! utils.isHttpSuccessCode(statusCode) ) {
  409. feedback.html(resp)
  410. } else {
  411. feedback.html('created ' + folder_name);
  412. fnames.push(fileb['getcurrfolder']() + folder_name + "/")
  413. fileb['refresh'](fnames);
  414. }
  415. });
  416. }
  417. }
  418. });
  419. folder_buttons.append(new_folder_b);
  420. rename_folder_b.html('rename folder')
  421. .click(function(ev) {
  422. var value = fileb['getcurrfolder']();
  423. var folder_name = prompt("please fill in a new name for folder " + value);
  424. if (folder_name != null) {
  425. folder_name = folder_name.replace(/^\s+|\s+$/g, ''); // trim
  426. if (!folder_name.match(/^[a-zA-Z0-9_\s]+$/i)) {
  427. feedback.html("invalid folder name: " + folder_name);
  428. } else {
  429. DataUtils.renameInCloud("/" + window.localStorage.getItem('user') + value.slice(0, -1) + ".folder", folder_name, function(statusCode,resp)
  430. {
  431. if( ! utils.isHttpSuccessCode(statusCode) ) {
  432. feedback.html(resp);
  433. } else {
  434. var matches = value.match(/^\/(.*\/)?(.*)\/$/),
  435. newvalue = "/" + (matches[1] || "") + folder_name + "/";
  436. for (var idx in fnames) {
  437. fnames[idx] = fnames[idx].replace(new RegExp("^("+value+")(.*)"), newvalue+"$2");
  438. }
  439. fileb['refresh'](fnames, newvalue);
  440. feedback.html('renamed ' + value + ' to ' + newvalue);
  441. }
  442. });
  443. }
  444. }
  445. });
  446. folder_buttons.append(rename_folder_b);
  447. delete_folder_b.html('delete folder')
  448. .click(function(ev) {
  449. var value = fileb['getcurrfolder']();
  450. if (confirm("are you sure you want to delete " + value + "?")) {
  451. DataUtils.deleteFromCloud("/" + window.localStorage.getItem('user') + value.slice(0, -1) + ".folder", function(statusCode,resp)
  452. {
  453. if( ! utils.isHttpSuccessCode(statusCode) ) {
  454. feedback.html(resp);
  455. } else {
  456. var matches = value.match(/^\/(.*\/)?(.*)\/$/),
  457. newvalue = "/_Trash_" + value;
  458. for (var idx in fnames) {
  459. fnames[idx] = fnames[idx].replace(new RegExp("^("+value+")(.*)"), newvalue+"$2");
  460. }
  461. fileb['refresh'](fnames);
  462. feedback.html('deleted ' + value);
  463. }
  464. });
  465. }
  466. });
  467. folder_buttons.append(delete_folder_b);
  468. move_folder_b.html('move folder')
  469. .click(function(ev) {
  470. var value = fileb['getcurrfolder']();
  471. var folder_loc = prompt("please fill in a new parent folder for folder " + value);
  472. if (folder_loc != null) {
  473. folder_loc = folder_loc.replace(/^\s+|\s+$/g, ''); // trim
  474. if (!folder_loc.match(/^\/([a-zA-Z0-9_\s]+\/)*$/i)) {
  475. feedback.html("invalid parent location: " + folder_loc);
  476. } else {
  477. DataUtils.moveInCloud("/" + window.localStorage.getItem('user') + value.slice(0, -1) + ".folder", folder_loc, function(statusCode,resp)
  478. {
  479. if( ! utils.isHttpSuccessCode(statusCode) ) {
  480. feedback.html(resp);
  481. } else {
  482. var matches = value.match(/^\/(.*\/)?(.*)\/$/),
  483. newvalue = folder_loc + matches[2] + "/";
  484. for (var idx in fnames) {
  485. fnames[idx] = fnames[idx].replace(new RegExp("^("+value+")(.*)"), newvalue+"$2");
  486. }
  487. fileb['refresh'](fnames, newvalue);
  488. feedback.html('moved ' + value + ' to ' + folder_loc);
  489. }
  490. });
  491. }
  492. }
  493. });
  494. folder_buttons.append(move_folder_b);
  495. rename_file_b.html('rename file')
  496. .click(function(ev) {
  497. var value = fileb['getselection']();
  498. var file_name = prompt("please fill in a new name for file " + value);
  499. if (file_name != null) {
  500. file_name = file_name.replace(/^\s+|\s+$/g, ''); // trim
  501. if (!file_name.match(/^[a-zA-Z0-9_\s\.]+$/i)) {
  502. feedback.html("invalid folder name: " + file_name);
  503. } else {
  504. DataUtils.renameInCloud("/" + window.localStorage.getItem('user') + value.slice(0, -1) + ".file", file_name, function(statusCode,resp)
  505. {
  506. if( ! utils.isHttpSuccessCode(statusCode) ) {
  507. feedback.html(resp);
  508. } else {
  509. var matches = value.match(/^\/(.*\/)?(.*)\/$/),
  510. newvalue = "/" + (matches[1] || "") + file_name;
  511. var idx = fnames.indexOf(value);
  512. if (idx >= 0) {
  513. fnames[idx] = newvalue;
  514. }
  515. fileb['refresh'](fnames);
  516. feedback.html('renamed ' + value + ' to ' + newvalue);
  517. }
  518. });
  519. }
  520. }
  521. });
  522. file_buttons.append(rename_file_b);
  523. delete_file_b.html('delete file')
  524. .click(function(ev) {
  525. var value = fileb['getselection']();
  526. if (confirm("are you sure you want to delete " + value + "?")) {
  527. DataUtils.deleteFromCloud("/" + window.localStorage.getItem('user') + value + ".file", function(statusCode,resp)
  528. {
  529. if( ! utils.isHttpSuccessCode(statusCode) ) {
  530. feedback.html(resp);
  531. } else {
  532. feedback.html('deleted ' + value);
  533. var idx = fnames.indexOf(value);
  534. if (idx >= 0) {
  535. fnames.splice(idx, 1);
  536. }
  537. fileb['refresh'](fnames);
  538. }
  539. });
  540. }
  541. });
  542. file_buttons.append(delete_file_b);
  543. move_file_b.html('move file')
  544. .click(function(ev) {
  545. var value = fileb['getselection']();
  546. var folder_loc = prompt("please fill in a new parent folder for file " + value);
  547. if (folder_loc != null) {
  548. folder_loc = folder_loc.replace(/^\s+|\s+$/g, ''); // trim
  549. if (!folder_loc.match(/^\/([a-zA-Z0-9_\s]+\/)*$/i)) {
  550. feedback.html("invalid parent location: " + folder_loc);
  551. } else {
  552. DataUtils.moveInCloud("/" + window.localStorage.getItem('user') + value + ".file", folder_loc, function(statusCode,resp)
  553. {
  554. if( ! utils.isHttpSuccessCode(statusCode) ) {
  555. feedback.html(resp);
  556. } else {
  557. var matches = value.match(/^\/(.*\/)?(.*)$/),
  558. newvalue = folder_loc + matches[2];
  559. feedback.html('moved ' + value + ' to ' + folder_loc);
  560. var idx = fnames.indexOf(value);
  561. if (idx >= 0) {
  562. fnames[idx] = newvalue;
  563. }
  564. fileb['refresh'](fnames);
  565. }
  566. });
  567. }
  568. }
  569. });
  570. file_buttons.append(move_file_b);
  571. GUIUtils.setupAndShowDialog(
  572. [fileb['filebrowser'],folder_buttons,file_buttons,feedback],
  573. function()
  574. {
  575. var value = [fileb['getselection']()];
  576. if (value.length > 0 && value[0] != "" && args['startDir']) {
  577. __setRecentDir(args['startDir'],value[0].substring(0, value[0].lastIndexOf('/') + 1));
  578. }
  579. return value;
  580. },
  581. __TWO_BUTTONS,
  582. args['title'],
  583. callback);
  584. });
  585. }
  586. else if( type == _LEGAL_CONNECTIONS )
  587. /* args: uri1, uri2, ctype, forceCallback */
  588. {
  589. var legalConnections = __legalConnections(args['uri1'],args['uri2'],args['ctype']);
  590. if( legalConnections.length == 0 )
  591. {
  592. var err = 'no valid connection between selected types';
  593. if( args['forceCallback'] )
  594. callback({'$err':err});
  595. else
  596. error(err);
  597. }
  598. else if( legalConnections.length == 1 )
  599. callback( legalConnections[0]+'Link.type' );
  600. else
  601. {
  602. var select = GUIUtils.getSelector(legalConnections);
  603. GUIUtils.setupAndShowDialog(
  604. [select],
  605. function() {return HttpUtils.getSelectorSelection(select)+'Link.type';},
  606. __TWO_BUTTONS,
  607. 'choose connection type',
  608. callback);
  609. }
  610. }
  611. else if( type == _LOADED_TOOLBARS )
  612. /* args: multipleChoice, type, title */
  613. {
  614. var choosableToolbars = [];
  615. for( var tb in __loadedToolbars )
  616. {
  617. if( (args['type'] == undefined &&
  618. (__isIconMetamodel(tb) || __isButtonModel(tb))) ||
  619. (args['type'] == 'metamodels' &&
  620. __isIconMetamodel(tb)) ||
  621. (args['type'] == 'buttons' &&
  622. __isButtonModel(tb)) )
  623. choosableToolbars.push(tb);
  624. }
  625. var select = GUIUtils.getSelector(choosableToolbars,args['multipleChoice']);
  626. GUIUtils.setupAndShowDialog(
  627. [select],
  628. function() {return HttpUtils.getSelectorSelection(select);},
  629. __TWO_BUTTONS,
  630. args['title'],
  631. callback);
  632. }
  633. else if( type == _DICTIONARY_EDITOR )
  634. /* args: data, ignoreKey, keepEverything, title */
  635. {
  636. var form = $('<form>'),
  637. table = $('<table>'),
  638. attrs2ii = {};
  639. form.onsubmit = function() {return false;};
  640. form.append(table);
  641. for( var attr in args['data'] )
  642. {
  643. if( args['ignoreKey'] != undefined &&
  644. args['ignoreKey'](attr,args['data'][attr]['value']) )
  645. continue;
  646. var tr = $('<tr>');
  647. var ii = GUIUtils.getInputField(
  648. args['data'][attr]['type'],
  649. args['data'][attr]['value']);
  650. // var tr = table.append( $('<tr>') ),
  651. // ii = GUIUtils.getInputField(
  652. // args['data'][attr]['type'],
  653. // args['data'][attr]['value']);
  654. tr.append( $('<td>').append( GUIUtils.getTextSpan(attr)) );
  655. tr.append( $('<td>').append(ii.input) );
  656. attrs2ii[attr] = ii;
  657. table.append( tr );
  658. }
  659. GUIUtils.setupAndShowDialog(
  660. [form],
  661. function()
  662. {
  663. var changes = {},
  664. keepAll = (args['keepEverything'] != undefined &&
  665. args['keepEverything']());
  666. for( var attr in attrs2ii )
  667. {
  668. var am = attrs2ii[attr];
  669. var newVal = am['getinput'](am['input']);
  670. if( keepAll ||
  671. utils.jsons(newVal) != utils.jsons(am['oldVal']) )
  672. changes[attr] = newVal;
  673. }
  674. return changes;
  675. },
  676. __TWO_BUTTONS,
  677. args['title'],
  678. callback);
  679. }
  680. else if( type == __SVG_TEXT_EDITOR )
  681. {
  682. if( args.tagName != 'tspan' )
  683. {
  684. console.warn('SVG text editing only works on "Text" VisualObjects');
  685. return;
  686. }
  687. var vobj = args.parentNode,
  688. vobjuri = vobj.getAttribute('__vobjuri'),
  689. iconuri = __vobj2uri(vobj),
  690. lines = [];
  691. for( var i=0; i < vobj.children.length; i++ )
  692. if( vobj.children[i].tagName == 'tspan' )
  693. lines.push(vobj.children[i].textContent);
  694. var input =
  695. GUIUtils.getTextInput(
  696. lines.join('\n'),
  697. undefined,
  698. Math.min(lines.length,__MAX_TEXTAREA_LINES) );
  699. GUIUtils.setupAndShowDialog(
  700. [input],
  701. function() {return input.value;},
  702. __TWO_BUTTONS,
  703. 'enter new text',
  704. function(newVal)
  705. {
  706. DataUtils.update(
  707. iconuri+'/'+vobjuri+'.vobject',{'textContent':newVal});
  708. });
  709. }
  710. };
  711. /* spawn a new instance of atompm... if a model is specified (as 'fname'), it is
  712. loaded into the new instance... if a callback url is specified, critical
  713. information about the new instance is POSTed to it
  714. NOTE:: window.open returns a reference to the created window... however, this
  715. reference is not always complete (e.g. body.onload has not necessarily
  716. run its course)... for this reason, before proceeding with handling
  717. 'fname' and 'callbackURL', we poll the reference to ensure its
  718. completion */
  719. this.spawnClient = function (fname,callbackURL)
  720. {
  721. var c = window.open(window.location.href, '_blank'),
  722. onspawn =
  723. function()
  724. {
  725. if( (fname || callbackURL) &&
  726. (c.__wid == undefined ||
  727. c.__aswid == undefined ||
  728. c._loadModel == undefined) )
  729. return window.setTimeout(onspawn,250);
  730. c.__user = __user;
  731. if( fname )
  732. c._loadModel(fname);
  733. if( callbackURL )
  734. _httpReq(
  735. 'POST',
  736. callbackURL,
  737. {'aswid':c.__aswid,
  738. 'cswid':c.__wid,
  739. 'fname':fname,
  740. 'host':window.location.host});
  741. };
  742. onspawn();
  743. };
  744. /* initialize a headless client, i.e. a client with a proper backend but whose
  745. socket-message handling code is user-defined
  746. 1. setup new backend csworker and subscribe to it
  747. 2. call 'onready'
  748. 3. from this point on, all incoming socket messages are dispatched to
  749. 'onchlog'
  750. NOTE:: this code and the above comments are simplified versions of what's in
  751. initClient() (TBI:: merge this function with initClient()??)
  752. NOTE:: the context object gets populated with the headless client's wids and
  753. with a pointer to a function that closes it (as 'close') */
  754. this.spawnHeadlessClient = function (context,onready,onchlog)
  755. {
  756. var socket = io.connect(
  757. window.location.hostname,
  758. {'port':8124,'reconnect':false,'force new connection':true});
  759. socket.on('message',
  760. function(msg)
  761. {
  762. console.debug(' >>> '+utils.jsons(msg));
  763. if( msg['statusCode'] != undefined )
  764. {
  765. if( msg['statusCode'] == 201 )
  766. {
  767. HttpUtils.httpReq(
  768. 'PUT',
  769. '/aswSubscription?wid='+context.__wid,
  770. undefined,
  771. function(statusCode,resp)
  772. {
  773. context.__aswid = utils.jsonp(resp)['data'];
  774. onready();
  775. });
  776. context.close = socket.socket.disconnect;
  777. }
  778. else
  779. console.error('headless client failed to connect to back-end');
  780. }
  781. else
  782. onchlog(
  783. msg['data']['changelog'],
  784. msg['data']['sequence#'],
  785. msg['data']['hitchhiker']);
  786. });
  787. socket.on('disconnect',
  788. function()
  789. {
  790. console.debug('headless client lost connection to back-end');
  791. });
  792. socket.on('connect',
  793. function()
  794. {
  795. HttpUtils.httpReq(
  796. 'POST',
  797. '/csworker',
  798. undefined,
  799. function(statusCode,resp)
  800. {
  801. console.debug("Connect!");
  802. console.debug(statusCode);
  803. console.debug(resp);
  804. context.__wid = resp;
  805. socket.emit(
  806. 'message',
  807. {'method':'POST','url':'/changeListener?wid='+context.__wid});
  808. });
  809. });
  810. };
  811. /**
  812. * Sets whether to update the window title or not
  813. * @param changed whether or not the title has changed
  814. */
  815. this.setWindowTitle = function(changed)
  816. {
  817. if( __saveas == undefined )
  818. document.title =
  819. __TITLE +' - '+
  820. (changed ? '+ ' :'')+
  821. '[Unnamed]';
  822. else
  823. document.title =
  824. __TITLE+' - '+
  825. (changed ? '+ ' :'')+
  826. __saveas.match(/(.*\/){0,1}(.*)\.model/)[2]+' - '+
  827. __saveas;
  828. };
  829. /**
  830. * Displays the modal dialog
  831. */
  832. this.showDialog = function()
  833. {
  834. var dialog = $('#div_dialog'),
  835. dim_bg = $('#div_dim_bg');
  836. dim_bg.css("display", 'inline');
  837. dialog.css("display", 'block');
  838. dialog.css("left", document.body.scrollLeft +
  839. window.innerWidth/2 -
  840. dialog.width()/2 + "px");
  841. dialog.css("top", document.body.scrollTop +
  842. window.innerHeight/2 -
  843. dialog.height()/2 + "px");
  844. __setCanvasScrolling(false);
  845. };
  846. /**
  847. * Closes the modal dialog if it is currently opened
  848. */
  849. this.closeDialog = function()
  850. {
  851. var dialog = $('#div_dialog');
  852. dialog.css("display", 'none');
  853. $('#div_dim_bg').css("display", 'none');
  854. HttpUtils.removeChildren(dialog);
  855. __setCanvasScrolling(true);
  856. BehaviorManager.setActiveBehaviourStatechart(__SC_CANVAS);
  857. };
  858. /**
  859. * Closes the modal dialog if it is currently opened (with arg js event)
  860. * Huseyin Ergin
  861. * HUSEYIN-ENTER
  862. */
  863. this.closeDialog = function(ev)
  864. {
  865. if(ev!=null && ev.keyCode==13) {
  866. $('#okbutton').click();
  867. }
  868. var dialog = $('#div_dialog');
  869. dialog.css("display", 'none');
  870. $('#div_dim_bg').css("display", 'none');
  871. HttpUtils.removeChildren(dialog);
  872. __setCanvasScrolling(true);
  873. BehaviorManager.setActiveBehaviourStatechart(__SC_CANVAS);
  874. };
  875. return this;
  876. }();