You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

oc-dialogs.js 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  1. /**
  2. * ownCloud
  3. *
  4. * @author Bartek Przybylski, Christopher Schäpers, Thomas Tanghus
  5. * @copyright 2012 Bartek Przybylski bartek@alefzero.eu
  6. *
  7. * This library is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
  9. * License as published by the Free Software Foundation; either
  10. * version 3 of the License, or any later version.
  11. *
  12. * This library is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
  16. *
  17. * You should have received a copy of the GNU Affero General Public
  18. * License along with this library. If not, see <http://www.gnu.org/licenses/>.
  19. *
  20. */
  21. /* global alert */
  22. /**
  23. * this class to ease the usage of jquery dialogs
  24. * @lends OC.dialogs
  25. */
  26. var OCdialogs = {
  27. // dialog button types
  28. YES_NO_BUTTONS: 70,
  29. OK_BUTTONS: 71,
  30. // used to name each dialog
  31. dialogsCounter: 0,
  32. /**
  33. * displays alert dialog
  34. * @param text content of dialog
  35. * @param title dialog title
  36. * @param callback which will be triggered when user presses OK
  37. * @param modal make the dialog modal
  38. */
  39. alert:function(text, title, callback, modal) {
  40. this.message(
  41. text,
  42. title,
  43. 'alert',
  44. OCdialogs.OK_BUTTON,
  45. callback,
  46. modal
  47. );
  48. },
  49. /**
  50. * displays info dialog
  51. * @param text content of dialog
  52. * @param title dialog title
  53. * @param callback which will be triggered when user presses OK
  54. * @param modal make the dialog modal
  55. */
  56. info:function(text, title, callback, modal) {
  57. this.message(text, title, 'info', OCdialogs.OK_BUTTON, callback, modal);
  58. },
  59. /**
  60. * displays confirmation dialog
  61. * @param text content of dialog
  62. * @param title dialog title
  63. * @param callback which will be triggered when user presses YES or NO
  64. * (true or false would be passed to callback respectively)
  65. * @param modal make the dialog modal
  66. */
  67. confirm:function(text, title, callback, modal) {
  68. return this.message(
  69. text,
  70. title,
  71. 'notice',
  72. OCdialogs.YES_NO_BUTTONS,
  73. callback,
  74. modal
  75. );
  76. },
  77. /**
  78. * displays confirmation dialog
  79. * @param text content of dialog
  80. * @param title dialog title
  81. * @param callback which will be triggered when user presses YES or NO
  82. * (true or false would be passed to callback respectively)
  83. * @param modal make the dialog modal
  84. */
  85. confirmHtml:function(text, title, callback, modal) {
  86. return this.message(
  87. text,
  88. title,
  89. 'notice',
  90. OCdialogs.YES_NO_BUTTONS,
  91. callback,
  92. modal,
  93. true
  94. );
  95. },
  96. /**
  97. * displays prompt dialog
  98. * @param text content of dialog
  99. * @param title dialog title
  100. * @param callback which will be triggered when user presses YES or NO
  101. * (true or false would be passed to callback respectively)
  102. * @param modal make the dialog modal
  103. * @param name name of the input field
  104. * @param password whether the input should be a password input
  105. */
  106. prompt: function (text, title, callback, modal, name, password) {
  107. return $.when(this._getMessageTemplate()).then(function ($tmpl) {
  108. var dialogName = 'oc-dialog-' + OCdialogs.dialogsCounter + '-content';
  109. var dialogId = '#' + dialogName;
  110. var $dlg = $tmpl.octemplate({
  111. dialog_name: dialogName,
  112. title : title,
  113. message : text,
  114. type : 'notice'
  115. });
  116. var input = $('<input/>');
  117. input.attr('type', password ? 'password' : 'text').attr('id', dialogName + '-input');
  118. var label = $('<label/>').attr('for', dialogName + '-input').text(name + ': ');
  119. $dlg.append(label);
  120. $dlg.append(input);
  121. if (modal === undefined) {
  122. modal = false;
  123. }
  124. $('body').append($dlg);
  125. var buttonlist = [{
  126. text : t('core', 'No'),
  127. click: function () {
  128. if (callback !== undefined) {
  129. callback(false, input.val());
  130. }
  131. $(dialogId).ocdialog('close');
  132. }
  133. }, {
  134. text : t('core', 'Yes'),
  135. click : function () {
  136. if (callback !== undefined) {
  137. callback(true, input.val());
  138. }
  139. $(dialogId).ocdialog('close');
  140. },
  141. defaultButton: true
  142. }
  143. ];
  144. $(dialogId).ocdialog({
  145. closeOnEscape: true,
  146. modal : modal,
  147. buttons : buttonlist
  148. });
  149. OCdialogs.dialogsCounter++;
  150. });
  151. },
  152. /**
  153. * show a file picker to pick a file from
  154. * @param title dialog title
  155. * @param callback which will be triggered when user presses Choose
  156. * @param multiselect whether it should be possible to select multiple files
  157. * @param mimetypeFilter mimetype to filter by - directories will always be included
  158. * @param modal make the dialog modal
  159. */
  160. filepicker:function(title, callback, multiselect, mimetypeFilter, modal) {
  161. var self = this;
  162. // avoid opening the picker twice
  163. if (this.filepicker.loading) {
  164. return;
  165. }
  166. this.filepicker.loading = true;
  167. this.filepicker.filesClient = OC.Files.getClient();
  168. $.when(this._getFilePickerTemplate()).then(function($tmpl) {
  169. self.filepicker.loading = false;
  170. var dialogName = 'oc-dialog-filepicker-content';
  171. if(self.$filePicker) {
  172. self.$filePicker.ocdialog('close');
  173. }
  174. self.$filePicker = $tmpl.octemplate({
  175. dialog_name: dialogName,
  176. title: title,
  177. emptytext: t('core', 'No files in here')
  178. }).data('path', '').data('multiselect', multiselect).data('mimetype', mimetypeFilter);
  179. if (modal === undefined) {
  180. modal = false;
  181. }
  182. if (multiselect === undefined) {
  183. multiselect = false;
  184. }
  185. if (mimetypeFilter === undefined) {
  186. mimetypeFilter = '';
  187. }
  188. $('body').append(self.$filePicker);
  189. self.$filePicker.ready(function() {
  190. self.$filelist = self.$filePicker.find('.filelist tbody');
  191. self.$dirTree = self.$filePicker.find('.dirtree');
  192. self.$dirTree.on('click', 'div:not(:last-child)', self, self._handleTreeListSelect.bind(self));
  193. self.$filelist.on('click', 'tr', function(event) {
  194. self._handlePickerClick(event, $(this));
  195. });
  196. self._fillFilePicker('');
  197. });
  198. // build buttons
  199. var functionToCall = function() {
  200. if (callback !== undefined) {
  201. var datapath;
  202. if (multiselect === true) {
  203. datapath = [];
  204. self.$filelist.find('tr.filepicker_element_selected').each(function(index, element) {
  205. datapath.push(self.$filePicker.data('path') + '/' + $(element).data('entryname'));
  206. });
  207. } else {
  208. datapath = self.$filePicker.data('path');
  209. var selectedName = self.$filelist.find('tr.filepicker_element_selected').data('entryname');
  210. if (selectedName) {
  211. datapath += '/' + selectedName;
  212. }
  213. }
  214. callback(datapath);
  215. self.$filePicker.ocdialog('close');
  216. }
  217. };
  218. var buttonlist = [{
  219. text: t('core', 'Choose'),
  220. click: functionToCall,
  221. defaultButton: true
  222. }];
  223. self.$filePicker.ocdialog({
  224. closeOnEscape: true,
  225. // max-width of 600
  226. width: Math.min((4/5)*$(document).width(), 600),
  227. height: 420,
  228. modal: modal,
  229. buttons: buttonlist,
  230. close: function() {
  231. try {
  232. $(this).ocdialog('destroy').remove();
  233. } catch(e) {}
  234. self.$filePicker = null;
  235. }
  236. });
  237. // We can access primary class only from oc-dialog.
  238. // Hence this is one of the approach to get the choose button.
  239. var getOcDialog = self.$filePicker.closest('.oc-dialog');
  240. var buttonEnableDisable = getOcDialog.find('.primary');
  241. if (self.$filePicker.data('mimetype') === "httpd/unix-directory") {
  242. buttonEnableDisable.prop("disabled", false);
  243. } else {
  244. buttonEnableDisable.prop("disabled", true);
  245. }
  246. if (!OC.Util.hasSVGSupport()) {
  247. OC.Util.replaceSVG(self.$filePicker.parent());
  248. }
  249. })
  250. .fail(function(status, error) {
  251. // If the method is called while navigating away
  252. // from the page, it is probably not needed ;)
  253. self.filepicker.loading = false;
  254. if(status !== 0) {
  255. alert(t('core', 'Error loading file picker template: {error}', {error: error}));
  256. }
  257. });
  258. },
  259. /**
  260. * Displays raw dialog
  261. * You better use a wrapper instead ...
  262. */
  263. message:function(content, title, dialogType, buttons, callback, modal, allowHtml) {
  264. return $.when(this._getMessageTemplate()).then(function($tmpl) {
  265. var dialogName = 'oc-dialog-' + OCdialogs.dialogsCounter + '-content';
  266. var dialogId = '#' + dialogName;
  267. var $dlg = $tmpl.octemplate({
  268. dialog_name: dialogName,
  269. title: title,
  270. message: content,
  271. type: dialogType
  272. }, allowHtml ? {escapeFunction: ''} : {});
  273. if (modal === undefined) {
  274. modal = false;
  275. }
  276. $('body').append($dlg);
  277. var buttonlist = [];
  278. switch (buttons) {
  279. case OCdialogs.YES_NO_BUTTONS:
  280. buttonlist = [{
  281. text: t('core', 'No'),
  282. click: function(){
  283. if (callback !== undefined) {
  284. callback(false);
  285. }
  286. $(dialogId).ocdialog('close');
  287. }
  288. },
  289. {
  290. text: t('core', 'Yes'),
  291. click: function(){
  292. if (callback !== undefined) {
  293. callback(true);
  294. }
  295. $(dialogId).ocdialog('close');
  296. },
  297. defaultButton: true
  298. }];
  299. break;
  300. case OCdialogs.OK_BUTTON:
  301. var functionToCall = function() {
  302. $(dialogId).ocdialog('close');
  303. if(callback !== undefined) {
  304. callback();
  305. }
  306. };
  307. buttonlist[0] = {
  308. text: t('core', 'Ok'),
  309. click: functionToCall,
  310. defaultButton: true
  311. };
  312. break;
  313. }
  314. $(dialogId).ocdialog({
  315. closeOnEscape: true,
  316. modal: modal,
  317. buttons: buttonlist
  318. });
  319. OCdialogs.dialogsCounter++;
  320. })
  321. .fail(function(status, error) {
  322. // If the method is called while navigating away from
  323. // the page, we still want to deliver the message.
  324. if(status === 0) {
  325. alert(title + ': ' + content);
  326. } else {
  327. alert(t('core', 'Error loading message template: {error}', {error: error}));
  328. }
  329. });
  330. },
  331. _fileexistsshown: false,
  332. /**
  333. * Displays file exists dialog
  334. * @param {object} data upload object
  335. * @param {object} original file with name, size and mtime
  336. * @param {object} replacement file with name, size and mtime
  337. * @param {object} controller with onCancel, onSkip, onReplace and onRename methods
  338. * @return {Promise} jquery promise that resolves after the dialog template was loaded
  339. */
  340. fileexists:function(data, original, replacement, controller) {
  341. var self = this;
  342. var dialogDeferred = new $.Deferred();
  343. var getCroppedPreview = function(file) {
  344. var deferred = new $.Deferred();
  345. // Only process image files.
  346. var type = file.type && file.type.split('/').shift();
  347. if (window.FileReader && type === 'image') {
  348. var reader = new FileReader();
  349. reader.onload = function (e) {
  350. var blob = new Blob([e.target.result]);
  351. window.URL = window.URL || window.webkitURL;
  352. var originalUrl = window.URL.createObjectURL(blob);
  353. var image = new Image();
  354. image.src = originalUrl;
  355. image.onload = function () {
  356. var url = crop(image);
  357. deferred.resolve(url);
  358. };
  359. };
  360. reader.readAsArrayBuffer(file);
  361. } else {
  362. deferred.reject();
  363. }
  364. return deferred;
  365. };
  366. var crop = function(img) {
  367. var canvas = document.createElement('canvas'),
  368. targetSize = 96,
  369. width = img.width,
  370. height = img.height,
  371. x, y, size;
  372. // Calculate the width and height, constraining the proportions
  373. if (width > height) {
  374. y = 0;
  375. x = (width - height) / 2;
  376. } else {
  377. y = (height - width) / 2;
  378. x = 0;
  379. }
  380. size = Math.min(width, height);
  381. // Set canvas size to the cropped area
  382. canvas.width = size;
  383. canvas.height = size;
  384. var ctx = canvas.getContext("2d");
  385. ctx.drawImage(img, x, y, size, size, 0, 0, size, size);
  386. // Resize the canvas to match the destination (right size uses 96px)
  387. resampleHermite(canvas, size, size, targetSize, targetSize);
  388. return canvas.toDataURL("image/png", 0.7);
  389. };
  390. /**
  391. * Fast image resize/resample using Hermite filter with JavaScript.
  392. *
  393. * @author: ViliusL
  394. *
  395. * @param {*} canvas
  396. * @param {number} W
  397. * @param {number} H
  398. * @param {number} W2
  399. * @param {number} H2
  400. */
  401. var resampleHermite = function (canvas, W, H, W2, H2) {
  402. W2 = Math.round(W2);
  403. H2 = Math.round(H2);
  404. var img = canvas.getContext("2d").getImageData(0, 0, W, H);
  405. var img2 = canvas.getContext("2d").getImageData(0, 0, W2, H2);
  406. var data = img.data;
  407. var data2 = img2.data;
  408. var ratio_w = W / W2;
  409. var ratio_h = H / H2;
  410. var ratio_w_half = Math.ceil(ratio_w / 2);
  411. var ratio_h_half = Math.ceil(ratio_h / 2);
  412. for (var j = 0; j < H2; j++) {
  413. for (var i = 0; i < W2; i++) {
  414. var x2 = (i + j * W2) * 4;
  415. var weight = 0;
  416. var weights = 0;
  417. var weights_alpha = 0;
  418. var gx_r = 0;
  419. var gx_g = 0;
  420. var gx_b = 0;
  421. var gx_a = 0;
  422. var center_y = (j + 0.5) * ratio_h;
  423. for (var yy = Math.floor(j * ratio_h); yy < (j + 1) * ratio_h; yy++) {
  424. var dy = Math.abs(center_y - (yy + 0.5)) / ratio_h_half;
  425. var center_x = (i + 0.5) * ratio_w;
  426. var w0 = dy * dy; //pre-calc part of w
  427. for (var xx = Math.floor(i * ratio_w); xx < (i + 1) * ratio_w; xx++) {
  428. var dx = Math.abs(center_x - (xx + 0.5)) / ratio_w_half;
  429. var w = Math.sqrt(w0 + dx * dx);
  430. if (w >= -1 && w <= 1) {
  431. //hermite filter
  432. weight = 2 * w * w * w - 3 * w * w + 1;
  433. if (weight > 0) {
  434. dx = 4 * (xx + yy * W);
  435. //alpha
  436. gx_a += weight * data[dx + 3];
  437. weights_alpha += weight;
  438. //colors
  439. if (data[dx + 3] < 255)
  440. weight = weight * data[dx + 3] / 250;
  441. gx_r += weight * data[dx];
  442. gx_g += weight * data[dx + 1];
  443. gx_b += weight * data[dx + 2];
  444. weights += weight;
  445. }
  446. }
  447. }
  448. }
  449. data2[x2] = gx_r / weights;
  450. data2[x2 + 1] = gx_g / weights;
  451. data2[x2 + 2] = gx_b / weights;
  452. data2[x2 + 3] = gx_a / weights_alpha;
  453. }
  454. }
  455. canvas.getContext("2d").clearRect(0, 0, Math.max(W, W2), Math.max(H, H2));
  456. canvas.width = W2;
  457. canvas.height = H2;
  458. canvas.getContext("2d").putImageData(img2, 0, 0);
  459. };
  460. var addConflict = function($conflicts, original, replacement) {
  461. var $conflict = $conflicts.find('.template').clone().removeClass('template').addClass('conflict');
  462. var $originalDiv = $conflict.find('.original');
  463. var $replacementDiv = $conflict.find('.replacement');
  464. $conflict.data('data',data);
  465. $conflict.find('.filename').text(original.name);
  466. $originalDiv.find('.size').text(humanFileSize(original.size));
  467. $originalDiv.find('.mtime').text(formatDate(original.mtime));
  468. // ie sucks
  469. if (replacement.size && replacement.lastModifiedDate) {
  470. $replacementDiv.find('.size').text(humanFileSize(replacement.size));
  471. $replacementDiv.find('.mtime').text(formatDate(replacement.lastModifiedDate));
  472. }
  473. var path = original.directory + '/' +original.name;
  474. var urlSpec = {
  475. file: path,
  476. x: 96,
  477. y: 96,
  478. c: original.etag,
  479. forceIcon: 0
  480. };
  481. var previewpath = Files.generatePreviewUrl(urlSpec);
  482. // Escaping single quotes
  483. previewpath = previewpath.replace(/'/g, "%27");
  484. $originalDiv.find('.icon').css({"background-image": "url('" + previewpath + "')"});
  485. getCroppedPreview(replacement).then(
  486. function(path){
  487. $replacementDiv.find('.icon').css('background-image','url(' + path + ')');
  488. }, function(){
  489. path = OC.MimeType.getIconUrl(replacement.type);
  490. $replacementDiv.find('.icon').css('background-image','url(' + path + ')');
  491. }
  492. );
  493. // connect checkboxes with labels
  494. var checkboxId = $conflicts.find('.conflict').length;
  495. $originalDiv.find('input:checkbox').attr('id', 'checkbox_original_'+checkboxId);
  496. $replacementDiv.find('input:checkbox').attr('id', 'checkbox_replacement_'+checkboxId);
  497. $conflicts.append($conflict);
  498. //set more recent mtime bold
  499. // ie sucks
  500. if (replacement.lastModifiedDate && replacement.lastModifiedDate.getTime() > original.mtime) {
  501. $replacementDiv.find('.mtime').css('font-weight', 'bold');
  502. } else if (replacement.lastModifiedDate && replacement.lastModifiedDate.getTime() < original.mtime) {
  503. $originalDiv.find('.mtime').css('font-weight', 'bold');
  504. } else {
  505. //TODO add to same mtime collection?
  506. }
  507. // set bigger size bold
  508. if (replacement.size && replacement.size > original.size) {
  509. $replacementDiv.find('.size').css('font-weight', 'bold');
  510. } else if (replacement.size && replacement.size < original.size) {
  511. $originalDiv.find('.size').css('font-weight', 'bold');
  512. } else {
  513. //TODO add to same size collection?
  514. }
  515. //TODO show skip action for files with same size and mtime in bottom row
  516. // always keep readonly files
  517. if (original.status === 'readonly') {
  518. $originalDiv
  519. .addClass('readonly')
  520. .find('input[type="checkbox"]')
  521. .prop('checked', true)
  522. .prop('disabled', true);
  523. $originalDiv.find('.message')
  524. .text(t('core','read-only'))
  525. }
  526. };
  527. //var selection = controller.getSelection(data.originalFiles);
  528. //if (selection.defaultAction) {
  529. // controller[selection.defaultAction](data);
  530. //} else {
  531. var dialogName = 'oc-dialog-fileexists-content';
  532. var dialogId = '#' + dialogName;
  533. if (this._fileexistsshown) {
  534. // add conflict
  535. var $conflicts = $(dialogId+ ' .conflicts');
  536. addConflict($conflicts, original, replacement);
  537. var count = $(dialogId+ ' .conflict').length;
  538. var title = n('core',
  539. '{count} file conflict',
  540. '{count} file conflicts',
  541. count,
  542. {count:count}
  543. );
  544. $(dialogId).parent().children('.oc-dialog-title').text(title);
  545. //recalculate dimensions
  546. $(window).trigger('resize');
  547. dialogDeferred.resolve();
  548. } else {
  549. //create dialog
  550. this._fileexistsshown = true;
  551. $.when(this._getFileExistsTemplate()).then(function($tmpl) {
  552. var title = t('core','One file conflict');
  553. var $dlg = $tmpl.octemplate({
  554. dialog_name: dialogName,
  555. title: title,
  556. type: 'fileexists',
  557. allnewfiles: t('core','New Files'),
  558. allexistingfiles: t('core','Already existing files'),
  559. why: t('core','Which files do you want to keep?'),
  560. what: t('core','If you select both versions, the copied file will have a number added to its name.')
  561. });
  562. $('body').append($dlg);
  563. if (original && replacement) {
  564. var $conflicts = $dlg.find('.conflicts');
  565. addConflict($conflicts, original, replacement);
  566. }
  567. var buttonlist = [{
  568. text: t('core', 'Cancel'),
  569. classes: 'cancel',
  570. click: function(){
  571. if ( typeof controller.onCancel !== 'undefined') {
  572. controller.onCancel(data);
  573. }
  574. $(dialogId).ocdialog('close');
  575. }
  576. },
  577. {
  578. text: t('core', 'Continue'),
  579. classes: 'continue',
  580. click: function(){
  581. if ( typeof controller.onContinue !== 'undefined') {
  582. controller.onContinue($(dialogId + ' .conflict'));
  583. }
  584. $(dialogId).ocdialog('close');
  585. }
  586. }];
  587. $(dialogId).ocdialog({
  588. width: 500,
  589. closeOnEscape: true,
  590. modal: true,
  591. buttons: buttonlist,
  592. closeButton: null,
  593. close: function() {
  594. self._fileexistsshown = false;
  595. $(this).ocdialog('destroy').remove();
  596. }
  597. });
  598. $(dialogId).css('height','auto');
  599. var $primaryButton = $dlg.closest('.oc-dialog').find('button.continue');
  600. $primaryButton.prop('disabled', true);
  601. function updatePrimaryButton() {
  602. var checkedCount = $dlg.find('.conflicts .checkbox:checked').length;
  603. $primaryButton.prop('disabled', checkedCount === 0);
  604. }
  605. //add checkbox toggling actions
  606. $(dialogId).find('.allnewfiles').on('click', function() {
  607. var $checkboxes = $(dialogId).find('.conflict .replacement input[type="checkbox"]');
  608. $checkboxes.prop('checked', $(this).prop('checked'));
  609. });
  610. $(dialogId).find('.allexistingfiles').on('click', function() {
  611. var $checkboxes = $(dialogId).find('.conflict .original:not(.readonly) input[type="checkbox"]');
  612. $checkboxes.prop('checked', $(this).prop('checked'));
  613. });
  614. $(dialogId).find('.conflicts').on('click', '.replacement,.original:not(.readonly)', function() {
  615. var $checkbox = $(this).find('input[type="checkbox"]');
  616. $checkbox.prop('checked', !$checkbox.prop('checked'));
  617. });
  618. $(dialogId).find('.conflicts').on('click', '.replacement input[type="checkbox"],.original:not(.readonly) input[type="checkbox"]', function() {
  619. var $checkbox = $(this);
  620. $checkbox.prop('checked', !$checkbox.prop('checked'));
  621. });
  622. //update counters
  623. $(dialogId).on('click', '.replacement,.allnewfiles', function() {
  624. var count = $(dialogId).find('.conflict .replacement input[type="checkbox"]:checked').length;
  625. if (count === $(dialogId+ ' .conflict').length) {
  626. $(dialogId).find('.allnewfiles').prop('checked', true);
  627. $(dialogId).find('.allnewfiles + .count').text(t('core','(all selected)'));
  628. } else if (count > 0) {
  629. $(dialogId).find('.allnewfiles').prop('checked', false);
  630. $(dialogId).find('.allnewfiles + .count').text(t('core','({count} selected)',{count:count}));
  631. } else {
  632. $(dialogId).find('.allnewfiles').prop('checked', false);
  633. $(dialogId).find('.allnewfiles + .count').text('');
  634. }
  635. updatePrimaryButton();
  636. });
  637. $(dialogId).on('click', '.original,.allexistingfiles', function(){
  638. var count = $(dialogId).find('.conflict .original input[type="checkbox"]:checked').length;
  639. if (count === $(dialogId+ ' .conflict').length) {
  640. $(dialogId).find('.allexistingfiles').prop('checked', true);
  641. $(dialogId).find('.allexistingfiles + .count').text(t('core','(all selected)'));
  642. } else if (count > 0) {
  643. $(dialogId).find('.allexistingfiles').prop('checked', false);
  644. $(dialogId).find('.allexistingfiles + .count')
  645. .text(t('core','({count} selected)',{count:count}));
  646. } else {
  647. $(dialogId).find('.allexistingfiles').prop('checked', false);
  648. $(dialogId).find('.allexistingfiles + .count').text('');
  649. }
  650. updatePrimaryButton();
  651. });
  652. dialogDeferred.resolve();
  653. })
  654. .fail(function() {
  655. dialogDeferred.reject();
  656. alert(t('core', 'Error loading file exists template'));
  657. });
  658. }
  659. //}
  660. return dialogDeferred.promise();
  661. },
  662. _getFilePickerTemplate: function() {
  663. var defer = $.Deferred();
  664. if(!this.$filePickerTemplate) {
  665. var self = this;
  666. $.get(OC.filePath('core', 'templates', 'filepicker.html'), function(tmpl) {
  667. self.$filePickerTemplate = $(tmpl);
  668. self.$listTmpl = self.$filePickerTemplate.find('.filelist tr:first-child').detach();
  669. defer.resolve(self.$filePickerTemplate);
  670. })
  671. .fail(function(jqXHR, textStatus, errorThrown) {
  672. defer.reject(jqXHR.status, errorThrown);
  673. });
  674. } else {
  675. defer.resolve(this.$filePickerTemplate);
  676. }
  677. return defer.promise();
  678. },
  679. _getMessageTemplate: function() {
  680. var defer = $.Deferred();
  681. if(!this.$messageTemplate) {
  682. var self = this;
  683. $.get(OC.filePath('core', 'templates', 'message.html'), function(tmpl) {
  684. self.$messageTemplate = $(tmpl);
  685. defer.resolve(self.$messageTemplate);
  686. })
  687. .fail(function(jqXHR, textStatus, errorThrown) {
  688. defer.reject(jqXHR.status, errorThrown);
  689. });
  690. } else {
  691. defer.resolve(this.$messageTemplate);
  692. }
  693. return defer.promise();
  694. },
  695. _getFileExistsTemplate: function () {
  696. var defer = $.Deferred();
  697. if (!this.$fileexistsTemplate) {
  698. var self = this;
  699. $.get(OC.filePath('files', 'templates', 'fileexists.html'), function (tmpl) {
  700. self.$fileexistsTemplate = $(tmpl);
  701. defer.resolve(self.$fileexistsTemplate);
  702. })
  703. .fail(function () {
  704. defer.reject();
  705. });
  706. } else {
  707. defer.resolve(this.$fileexistsTemplate);
  708. }
  709. return defer.promise();
  710. },
  711. _getFileList: function(dir, mimeType) { //this is only used by the spreedme app atm
  712. if (typeof(mimeType) === "string") {
  713. mimeType = [mimeType];
  714. }
  715. return $.getJSON(
  716. OC.filePath('files', 'ajax', 'list.php'),
  717. {
  718. dir: dir,
  719. mimetypes: JSON.stringify(mimeType)
  720. }
  721. );
  722. },
  723. /**
  724. * fills the filepicker with files
  725. */
  726. _fillFilePicker:function(dir) {
  727. var self = this;
  728. this.$filelist.empty().addClass('icon-loading');
  729. this.$filePicker.data('path', dir);
  730. var filter = this.$filePicker.data('mimetype');
  731. if (typeof(filter) === "string") {
  732. filter = [filter];
  733. }
  734. self.filepicker.filesClient.getFolderContents(dir).then(function(status, files) {
  735. if (filter) {
  736. files = files.filter(function (file) {
  737. return filter == [] || file.type === 'dir' || filter.indexOf(file.mimetype) !== -1;
  738. });
  739. }
  740. files = files.sort(function(a, b) {
  741. if (a.type === 'dir' && b.type !== 'dir') {
  742. return -1;
  743. } else if(a.type !== 'dir' && b.type === 'dir') {
  744. return 1;
  745. } else {
  746. return 0;
  747. }
  748. });
  749. self._fillSlug();
  750. if (files.length === 0) {
  751. self.$filePicker.find('.emptycontent').show();
  752. } else {
  753. self.$filePicker.find('.emptycontent').hide();
  754. }
  755. $.each(files, function(idx, entry) {
  756. entry.icon = OC.MimeType.getIconUrl(entry.mimetype);
  757. if (typeof(entry.size) !== 'undefined' && entry.size >= 0) {
  758. var simpleSize = humanFileSize(parseInt(entry.size, 10), true);
  759. var sizeColor = Math.round(160 - Math.pow((entry.size / (1024 * 1024)), 2));
  760. } else {
  761. simpleSize = t('files', 'Pending');
  762. }
  763. var $row = self.$listTmpl.octemplate({
  764. type: entry.type,
  765. dir: dir,
  766. filename: entry.name,
  767. date: OC.Util.relativeModifiedDate(entry.mtime),
  768. size: simpleSize,
  769. sizeColor: sizeColor,
  770. icon: entry.icon
  771. });
  772. if (entry.type === 'file') {
  773. var urlSpec = {
  774. file: dir + '/' + entry.name,
  775. };
  776. var img = new Image();
  777. var previewUrl = OC.generateUrl('/core/preview.png?') + $.param(urlSpec);
  778. img.onload = function() {
  779. if (img.width > 5) {
  780. $row.find('td.filename').attr('style', 'background-image:url(' + previewUrl + ')');
  781. }
  782. };
  783. img.src = previewUrl;
  784. }
  785. self.$filelist.append($row);
  786. });
  787. self.$filelist.removeClass('icon-loading');
  788. if (!OC.Util.hasSVGSupport()) {
  789. OC.Util.replaceSVG(self.$filePicker.find('.dirtree'));
  790. }
  791. });
  792. },
  793. /**
  794. * fills the tree list with directories
  795. */
  796. _fillSlug: function() {
  797. this.$dirTree.empty();
  798. var self = this;
  799. var dir;
  800. var path = this.$filePicker.data('path');
  801. var $template = $('<div data-dir="{dir}"><a>{name}</a></div>').addClass('crumb');
  802. if(path) {
  803. var paths = path.split('/');
  804. $.each(paths, function(index, dir) {
  805. dir = paths.pop();
  806. if(dir === '') {
  807. return false;
  808. }
  809. self.$dirTree.prepend($template.octemplate({
  810. dir: paths.join('/') + '/' + dir,
  811. name: dir
  812. }));
  813. });
  814. }
  815. $template.octemplate({
  816. dir: '',
  817. name: '' // Ugly but works ;)
  818. }, {escapeFunction: null}).prependTo(this.$dirTree);
  819. },
  820. /**
  821. * handle selection made in the tree list
  822. */
  823. _handleTreeListSelect:function(event) {
  824. var self = event.data;
  825. var dir = $(event.target).parent().data('dir');
  826. self._fillFilePicker(dir);
  827. var getOcDialog = (event.target).closest('.oc-dialog');
  828. var buttonEnableDisable = $('.primary', getOcDialog);
  829. if (this.$filePicker.data('mimetype') === "httpd/unix-directory") {
  830. buttonEnableDisable.prop("disabled", false);
  831. } else {
  832. buttonEnableDisable.prop("disabled", true);
  833. }
  834. },
  835. /**
  836. * handle clicks made in the filepicker
  837. */
  838. _handlePickerClick:function(event, $element) {
  839. var getOcDialog = this.$filePicker.closest('.oc-dialog');
  840. var buttonEnableDisable = getOcDialog.find('.primary');
  841. if ($element.data('type') === 'file') {
  842. if (this.$filePicker.data('multiselect') !== true || !event.ctrlKey) {
  843. this.$filelist.find('.filepicker_element_selected').removeClass('filepicker_element_selected');
  844. }
  845. $element.toggleClass('filepicker_element_selected');
  846. buttonEnableDisable.prop("disabled", false);
  847. } else if ( $element.data('type') === 'dir' ) {
  848. this._fillFilePicker(this.$filePicker.data('path') + '/' + $element.data('entryname'));
  849. if (this.$filePicker.data('mimetype') === "httpd/unix-directory") {
  850. buttonEnableDisable.prop("disabled", false);
  851. } else {
  852. buttonEnableDisable.prop("disabled", true);
  853. }
  854. }
  855. }
  856. };