window_management.js 34 KB

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