window_management.js 34 KB

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