window_management.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  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. var fnames = __localizeFilenames(
  378. __filterFilenamesByExtension(
  379. resp.split('\n'),
  380. args['extensions'] || ['.*'])
  381. ).sort(),
  382. maxFnameLength =
  383. utils.max(fnames,function(_) {return _.length;}),
  384. viewlinks = $('<div>'),
  385. a_listview = $('<a>'),
  386. a_filebview = $('<a>'),
  387. select =
  388. GUIUtils.getSelector(fnames,args['multipleChoice'],undefined,20),
  389. fileb =
  390. GUIUtils.getFileBrowser(fnames,false,args['manualInput'],__getRecentDir(args['startDir'])),
  391. input =
  392. GUIUtils.getStringInput('',undefined,maxFnameLength+'ex');
  393. // a_listview.attr("href", "#");
  394. // a_filebview.attr("href", '#');
  395. // a_listview.attr("class", 'enabled_link');
  396. // a_filebview.attr("class", 'enabled_link');
  397. var clickFunction = function(ev) {
  398. var toListView =
  399. (ev != undefined && ev.target == a_listview.get(0) ) ||
  400. this == a_listview;
  401. if( toListView )
  402. {
  403. a_listview.css("fontWeight", 'bold');
  404. a_filebview.css("fontWeight", 'normal');
  405. select.css("display", 'inline');
  406. input.css("display", 'inline');
  407. fileb['filebrowser'].css("display", 'none');
  408. }
  409. else
  410. {
  411. a_listview.css("fontWeight", 'normal');
  412. a_filebview.css("fontWeight", 'bold');
  413. select.css("display", 'none');
  414. input.css("display", 'none');
  415. fileb['filebrowser'].css("display", 'inline-block');
  416. }
  417. return false;
  418. };
  419. a_listview.html('list view')
  420. .attr("href", "#")
  421. .attr("class", 'enabled_link')
  422. .click( clickFunction );
  423. a_filebview.html('file browser view')
  424. .attr("href", '#')
  425. .attr("class", 'enabled_link')
  426. .click( clickFunction );
  427. // a_listview.click( clickFunction );
  428. // a_filebview.click( clickFunction );
  429. viewlinks.append(a_listview);
  430. viewlinks.append(GUIUtils.getTextSpan(' | '));
  431. viewlinks.append(a_filebview);
  432. a_filebview.click();
  433. select.get().onchange =
  434. function(event)
  435. {
  436. input.val( HttpUtils.getSelectorSelection(select) );
  437. };
  438. if( ! args['manualInput'] )
  439. input.attr("disabled", "true");
  440. GUIUtils.setupAndShowDialog(
  441. [fileb['filebrowser'],select,input,viewlinks],
  442. function()
  443. {
  444. var value =
  445. (fileb['filebrowser'].css("display") == 'none' ?
  446. (input.val() == HttpUtils.getSelectorSelection(select) ?
  447. HttpUtils.getSelectorSelection(select) : [input.val()]) :
  448. [fileb['getselection']()]);
  449. if (value.length > 0 && value[0] != "" && args['startDir']) {
  450. __setRecentDir(args['startDir'],value[0].substring(0, value[0].lastIndexOf('/') + 1));
  451. }
  452. return value;
  453. },
  454. __TWO_BUTTONS,
  455. args['title'],
  456. callback);
  457. });
  458. }
  459. else if( type == _LEGAL_CONNECTIONS )
  460. /* args: uri1, uri2, ctype, forceCallback */
  461. {
  462. var legalConnections = __legalConnections(args['uri1'],args['uri2'],args['ctype']);
  463. if( legalConnections.length == 0 )
  464. {
  465. var err = 'no valid connection between selected types';
  466. if( args['forceCallback'] )
  467. callback({'$err':err});
  468. else
  469. error(err);
  470. }
  471. else if( legalConnections.length == 1 )
  472. callback( legalConnections[0]+'Link.type' );
  473. else
  474. {
  475. var select = GUIUtils.getSelector(legalConnections);
  476. GUIUtils.setupAndShowDialog(
  477. [select],
  478. function() {return HttpUtils.getSelectorSelection(select)+'Link.type';},
  479. __TWO_BUTTONS,
  480. 'choose connection type',
  481. callback);
  482. }
  483. }
  484. else if( type == _LOADED_TOOLBARS )
  485. /* args: multipleChoice, type, title */
  486. {
  487. var choosableToolbars = [];
  488. for( var tb in __loadedToolbars )
  489. {
  490. if( (args['type'] == undefined &&
  491. (__isIconMetamodel(tb) || __isButtonModel(tb))) ||
  492. (args['type'] == 'metamodels' &&
  493. __isIconMetamodel(tb)) ||
  494. (args['type'] == 'buttons' &&
  495. __isButtonModel(tb)) )
  496. choosableToolbars.push(tb);
  497. }
  498. var select = GUIUtils.getSelector(choosableToolbars,args['multipleChoice']);
  499. GUIUtils.setupAndShowDialog(
  500. [select],
  501. function() {return HttpUtils.getSelectorSelection(select);},
  502. __TWO_BUTTONS,
  503. args['title'],
  504. callback);
  505. }
  506. else if( type == _DICTIONARY_EDITOR )
  507. /* args: data, ignoreKey, keepEverything, title */
  508. {
  509. var form = $('<form>'),
  510. table = $('<table>'),
  511. attrs2ii = {};
  512. form.onsubmit = function() {return false;};
  513. form.append(table);
  514. for( var attr in args['data'] )
  515. {
  516. if( args['ignoreKey'] != undefined &&
  517. args['ignoreKey'](attr,args['data'][attr]['value']) )
  518. continue;
  519. var tr = $('<tr>');
  520. var ii = GUIUtils.getInputField(
  521. args['data'][attr]['type'],
  522. args['data'][attr]['value']);
  523. // var tr = table.append( $('<tr>') ),
  524. // ii = GUIUtils.getInputField(
  525. // args['data'][attr]['type'],
  526. // args['data'][attr]['value']);
  527. tr.append( $('<td>').append( GUIUtils.getTextSpan(attr)) );
  528. tr.append( $('<td>').append(ii.input) );
  529. attrs2ii[attr] = ii;
  530. table.append( tr );
  531. }
  532. GUIUtils.setupAndShowDialog(
  533. [form],
  534. function()
  535. {
  536. var changes = {},
  537. keepAll = (args['keepEverything'] != undefined &&
  538. args['keepEverything']());
  539. for( var attr in attrs2ii )
  540. {
  541. var am = attrs2ii[attr];
  542. var newVal = am['getinput'](am['input']);
  543. if( keepAll ||
  544. utils.jsons(newVal) != utils.jsons(am['oldVal']) )
  545. changes[attr] = newVal;
  546. }
  547. return changes;
  548. },
  549. __TWO_BUTTONS,
  550. args['title'],
  551. callback);
  552. }
  553. else if( type == __SVG_TEXT_EDITOR )
  554. {
  555. if( args.tagName != 'tspan' )
  556. {
  557. console.warn('SVG text editing only works on "Text" VisualObjects');
  558. return;
  559. }
  560. var vobj = args.parentNode,
  561. vobjuri = vobj.getAttribute('__vobjuri'),
  562. iconuri = __vobj2uri(vobj),
  563. lines = [];
  564. for( var i=0; i < vobj.children.length; i++ )
  565. if( vobj.children[i].tagName == 'tspan' )
  566. lines.push(vobj.children[i].textContent);
  567. var input =
  568. GUIUtils.getTextInput(
  569. lines.join('\n'),
  570. undefined,
  571. Math.min(lines.length,__MAX_TEXTAREA_LINES) );
  572. GUIUtils.setupAndShowDialog(
  573. [input],
  574. function() {return input.value;},
  575. __TWO_BUTTONS,
  576. 'enter new text',
  577. function(newVal)
  578. {
  579. DataUtils.update(
  580. iconuri+'/'+vobjuri+'.vobject',{'textContent':newVal});
  581. });
  582. }
  583. };
  584. /* spawn a new instance of atompm... if a model is specified (as 'fname'), it is
  585. loaded into the new instance... if a callback url is specified, critical
  586. information about the new instance is POSTed to it
  587. NOTE:: window.open returns a reference to the created window... however, this
  588. reference is not always complete (e.g. body.onload has not necessarily
  589. run its course)... for this reason, before proceeding with handling
  590. 'fname' and 'callbackURL', we poll the reference to ensure its
  591. completion */
  592. this.spawnClient = function (fname,callbackURL)
  593. {
  594. var c = window.open(window.location.href, '_blank'),
  595. onspawn =
  596. function()
  597. {
  598. if( (fname || callbackURL) &&
  599. (c.__wid == undefined ||
  600. c.__aswid == undefined ||
  601. c._loadModel == undefined) )
  602. return window.setTimeout(onspawn,250);
  603. c.__user = __user;
  604. if( fname )
  605. c._loadModel(fname);
  606. if( callbackURL )
  607. _httpReq(
  608. 'POST',
  609. callbackURL,
  610. {'aswid':c.__aswid,
  611. 'cswid':c.__wid,
  612. 'fname':fname,
  613. 'host':window.location.host});
  614. };
  615. onspawn();
  616. };
  617. /* initialize a headless client, i.e. a client with a proper backend but whose
  618. socket-message handling code is user-defined
  619. 1. setup new backend csworker and subscribe to it
  620. 2. call 'onready'
  621. 3. from this point on, all incoming socket messages are dispatched to
  622. 'onchlog'
  623. NOTE:: this code and the above comments are simplified versions of what's in
  624. initClient() (TBI:: merge this function with initClient()??)
  625. NOTE:: the context object gets populated with the headless client's wids and
  626. with a pointer to a function that closes it (as 'close') */
  627. this.spawnHeadlessClient = function (context,onready,onchlog)
  628. {
  629. var socket = io.connect(
  630. window.location.hostname,
  631. {'port':8124,'reconnect':false,'force new connection':true});
  632. socket.on('message',
  633. function(msg)
  634. {
  635. console.debug(' >>> '+utils.jsons(msg));
  636. if( msg['statusCode'] != undefined )
  637. {
  638. if( msg['statusCode'] == 201 )
  639. {
  640. HttpUtils.httpReq(
  641. 'PUT',
  642. '/aswSubscription?wid='+context.__wid,
  643. undefined,
  644. function(statusCode,resp)
  645. {
  646. context.__aswid = utils.jsonp(resp)['data'];
  647. onready();
  648. });
  649. context.close = socket.socket.disconnect;
  650. }
  651. else
  652. console.error('headless client failed to connect to back-end');
  653. }
  654. else
  655. onchlog(
  656. msg['data']['changelog'],
  657. msg['data']['sequence#'],
  658. msg['data']['hitchhiker']);
  659. });
  660. socket.on('disconnect',
  661. function()
  662. {
  663. console.debug('headless client lost connection to back-end');
  664. });
  665. socket.on('connect',
  666. function()
  667. {
  668. HttpUtils.httpReq(
  669. 'POST',
  670. '/csworker',
  671. undefined,
  672. function(statusCode,resp)
  673. {
  674. console.debug("Connect!");
  675. console.debug(statusCode);
  676. console.debug(resp);
  677. context.__wid = resp;
  678. socket.emit(
  679. 'message',
  680. {'method':'POST','url':'/changeListener?wid='+context.__wid});
  681. });
  682. });
  683. };
  684. /**
  685. * Sets whether to update the window title or not
  686. * @param changed whether or not the title has changed
  687. */
  688. this.setWindowTitle = function(changed)
  689. {
  690. if( __saveas == undefined )
  691. document.title =
  692. __TITLE +' - '+
  693. (changed ? '+ ' :'')+
  694. '[Unnamed]';
  695. else
  696. document.title =
  697. __TITLE+' - '+
  698. (changed ? '+ ' :'')+
  699. __saveas.match(/(.*\/){0,1}(.*)\.model/)[2]+' - '+
  700. __saveas;
  701. };
  702. /**
  703. * Displays the modal dialog
  704. */
  705. this.showDialog = function()
  706. {
  707. var dialog = $('#div_dialog'),
  708. dim_bg = $('#div_dim_bg');
  709. dim_bg.css("display", 'inline');
  710. dialog.css("display", 'block');
  711. dialog.css("left", document.body.scrollLeft +
  712. window.innerWidth/2 -
  713. dialog.width()/2 + "px");
  714. dialog.css("top", document.body.scrollTop +
  715. window.innerHeight/2 -
  716. dialog.height()/2 + "px");
  717. __setCanvasScrolling(false);
  718. };
  719. /**
  720. * Closes the modal dialog if it is currently opened
  721. */
  722. this.closeDialog = function()
  723. {
  724. var dialog = $('#div_dialog');
  725. dialog.css("display", 'none');
  726. $('#div_dim_bg').css("display", 'none');
  727. HttpUtils.removeChildren(dialog);
  728. __setCanvasScrolling(true);
  729. BehaviorManager.setActiveBehaviourStatechart(__SC_CANVAS);
  730. };
  731. /**
  732. * Closes the modal dialog if it is currently opened (with arg js event)
  733. * Huseyin Ergin
  734. * HUSEYIN-ENTER
  735. */
  736. this.closeDialog = function(ev)
  737. {
  738. if(ev!=null && ev.keyCode==13) {
  739. $('#okbutton').click();
  740. }
  741. var dialog = $('#div_dialog');
  742. dialog.css("display", 'none');
  743. $('#div_dim_bg').css("display", 'none');
  744. HttpUtils.removeChildren(dialog);
  745. __setCanvasScrolling(true);
  746. BehaviorManager.setActiveBehaviourStatechart(__SC_CANVAS);
  747. };
  748. return this;
  749. }();