oc-dialogs.js 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094
  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. FILEPICKER_TYPE_CHOOSE: 1,
  31. FILEPICKER_TYPE_MOVE: 2,
  32. FILEPICKER_TYPE_COPY: 3,
  33. FILEPICKER_TYPE_COPY_MOVE: 4,
  34. // used to name each dialog
  35. dialogsCounter: 0,
  36. /**
  37. * displays alert dialog
  38. * @param text content of dialog
  39. * @param title dialog title
  40. * @param callback which will be triggered when user presses OK
  41. * @param modal make the dialog modal
  42. */
  43. alert:function(text, title, callback, modal) {
  44. this.message(
  45. text,
  46. title,
  47. 'alert',
  48. OCdialogs.OK_BUTTON,
  49. callback,
  50. modal
  51. );
  52. },
  53. /**
  54. * displays info dialog
  55. * @param text content of dialog
  56. * @param title dialog title
  57. * @param callback which will be triggered when user presses OK
  58. * @param modal make the dialog modal
  59. */
  60. info:function(text, title, callback, modal) {
  61. this.message(text, title, 'info', OCdialogs.OK_BUTTON, callback, modal);
  62. },
  63. /**
  64. * displays confirmation dialog
  65. * @param text content of dialog
  66. * @param title dialog title
  67. * @param callback which will be triggered when user presses YES or NO
  68. * (true or false would be passed to callback respectively)
  69. * @param modal make the dialog modal
  70. */
  71. confirm:function(text, title, callback, modal) {
  72. return this.message(
  73. text,
  74. title,
  75. 'notice',
  76. OCdialogs.YES_NO_BUTTONS,
  77. callback,
  78. modal
  79. );
  80. },
  81. /**
  82. * displays confirmation dialog
  83. * @param text content of dialog
  84. * @param title dialog title
  85. * @param callback which will be triggered when user presses YES or NO
  86. * (true or false would be passed to callback respectively)
  87. * @param modal make the dialog modal
  88. */
  89. confirmHtml:function(text, title, callback, modal) {
  90. return this.message(
  91. text,
  92. title,
  93. 'notice',
  94. OCdialogs.YES_NO_BUTTONS,
  95. callback,
  96. modal,
  97. true
  98. );
  99. },
  100. /**
  101. * displays prompt dialog
  102. * @param text content of dialog
  103. * @param title dialog title
  104. * @param callback which will be triggered when user presses YES or NO
  105. * (true or false would be passed to callback respectively)
  106. * @param modal make the dialog modal
  107. * @param name name of the input field
  108. * @param password whether the input should be a password input
  109. */
  110. prompt: function (text, title, callback, modal, name, password) {
  111. return $.when(this._getMessageTemplate()).then(function ($tmpl) {
  112. var dialogName = 'oc-dialog-' + OCdialogs.dialogsCounter + '-content';
  113. var dialogId = '#' + dialogName;
  114. var $dlg = $tmpl.octemplate({
  115. dialog_name: dialogName,
  116. title : title,
  117. message : text,
  118. type : 'notice'
  119. });
  120. var input = $('<input/>');
  121. input.attr('type', password ? 'password' : 'text').attr('id', dialogName + '-input').attr('placeholder', name);
  122. var label = $('<label/>').attr('for', dialogName + '-input').text(name + ': ');
  123. $dlg.append(label);
  124. $dlg.append(input);
  125. if (modal === undefined) {
  126. modal = false;
  127. }
  128. $('body').append($dlg);
  129. // wrap callback in _.once():
  130. // only call callback once and not twice (button handler and close
  131. // event) but call it for the close event, if ESC or the x is hit
  132. if (callback !== undefined) {
  133. callback = _.once(callback);
  134. }
  135. var buttonlist = [{
  136. text : t('core', 'No'),
  137. click: function () {
  138. if (callback !== undefined) {
  139. callback(false, input.val());
  140. }
  141. $(dialogId).ocdialog('close');
  142. }
  143. }, {
  144. text : t('core', 'Yes'),
  145. click : function () {
  146. if (callback !== undefined) {
  147. callback(true, input.val());
  148. }
  149. $(dialogId).ocdialog('close');
  150. },
  151. defaultButton: true
  152. }
  153. ];
  154. $(dialogId).ocdialog({
  155. closeOnEscape: true,
  156. modal : modal,
  157. buttons : buttonlist,
  158. close : function() {
  159. // callback is already fired if Yes/No is clicked directly
  160. if (callback !== undefined) {
  161. callback(false, input.val());
  162. }
  163. }
  164. });
  165. input.focus();
  166. OCdialogs.dialogsCounter++;
  167. });
  168. },
  169. /**
  170. * show a file picker to pick a file from
  171. *
  172. * In order to pick several types of mime types they need to be passed as an
  173. * array of strings.
  174. *
  175. * When no mime type filter is given only files can be selected. In order to
  176. * be able to select both files and folders "['*', 'httpd/unix-directory']"
  177. * should be used instead.
  178. *
  179. * @param title dialog title
  180. * @param callback which will be triggered when user presses Choose
  181. * @param multiselect whether it should be possible to select multiple files
  182. * @param mimetypeFilter mimetype to filter by - directories will always be included
  183. * @param modal make the dialog modal
  184. * @param type Type of file picker : Choose, copy, move, copy and move
  185. */
  186. filepicker:function(title, callback, multiselect, mimetypeFilter, modal, type) {
  187. var self = this;
  188. this.filepicker.sortField = 'name';
  189. this.filepicker.sortOrder = 'asc';
  190. // avoid opening the picker twice
  191. if (this.filepicker.loading) {
  192. return;
  193. }
  194. if (type === undefined) {
  195. type = this.FILEPICKER_TYPE_CHOOSE;
  196. }
  197. var emptyText = t('core', 'No files in here');
  198. if (type === this.FILEPICKER_TYPE_COPY || type === this.FILEPICKER_TYPE_MOVE || type === this.FILEPICKER_TYPE_COPY_MOVE) {
  199. emptyText = t('core', 'No more subfolders in here');
  200. }
  201. this.filepicker.loading = true;
  202. this.filepicker.filesClient = (OCA.Sharing && OCA.Sharing.PublicApp && OCA.Sharing.PublicApp.fileList)? OCA.Sharing.PublicApp.fileList.filesClient: OC.Files.getClient();
  203. $.when(this._getFilePickerTemplate()).then(function($tmpl) {
  204. self.filepicker.loading = false;
  205. var dialogName = 'oc-dialog-filepicker-content';
  206. if(self.$filePicker) {
  207. self.$filePicker.ocdialog('close');
  208. }
  209. if (mimetypeFilter === undefined || mimetypeFilter === null) {
  210. mimetypeFilter = [];
  211. }
  212. if (typeof(mimetypeFilter) === "string") {
  213. mimetypeFilter = [mimetypeFilter];
  214. }
  215. self.$filePicker = $tmpl.octemplate({
  216. dialog_name: dialogName,
  217. title: title,
  218. emptytext: emptyText
  219. }).data('path', '').data('multiselect', multiselect).data('mimetype', mimetypeFilter);
  220. if (modal === undefined) {
  221. modal = false;
  222. }
  223. if (multiselect === undefined) {
  224. multiselect = false;
  225. }
  226. // No grid for IE!
  227. if (OC.Util.isIE()) {
  228. self.$filePicker.find('#picker-view-toggle').remove();
  229. self.$filePicker.find('#picker-filestable').removeClass('view-grid');
  230. }
  231. $('body').append(self.$filePicker);
  232. self.$showGridView = $('input#picker-showgridview');
  233. self.$showGridView.on('change', _.bind(self._onGridviewChange, self));
  234. if (!OC.Util.isIE()) {
  235. self._getGridSettings();
  236. }
  237. self.$filePicker.ready(function() {
  238. self.$fileListHeader = self.$filePicker.find('.filelist thead tr');
  239. self.$filelist = self.$filePicker.find('.filelist tbody');
  240. self.$filelistContainer = self.$filePicker.find('.filelist-container');
  241. self.$dirTree = self.$filePicker.find('.dirtree');
  242. self.$dirTree.on('click', 'div:not(:last-child)', self, function (event) {
  243. self._handleTreeListSelect(event, type);
  244. });
  245. self.$filelist.on('click', 'tr', function(event) {
  246. self._handlePickerClick(event, $(this), type);
  247. });
  248. self.$fileListHeader.on('click', 'a', function(event) {
  249. var dir = self.$filePicker.data('path');
  250. self.filepicker.sortField = $(event.currentTarget).data('sort');
  251. self.filepicker.sortOrder = self.filepicker.sortOrder === 'asc' ? 'desc' : 'asc';
  252. self._fillFilePicker(dir);
  253. });
  254. self._fillFilePicker('');
  255. });
  256. // build buttons
  257. var functionToCall = function(returnType) {
  258. if (callback !== undefined) {
  259. var datapath;
  260. if (multiselect === true) {
  261. datapath = [];
  262. self.$filelist.find('tr.filepicker_element_selected').each(function(index, element) {
  263. datapath.push(self.$filePicker.data('path') + '/' + $(element).data('entryname'));
  264. });
  265. } else {
  266. datapath = self.$filePicker.data('path');
  267. var selectedName = self.$filelist.find('tr.filepicker_element_selected').data('entryname');
  268. if (selectedName) {
  269. datapath += '/' + selectedName;
  270. }
  271. }
  272. callback(datapath, returnType);
  273. self.$filePicker.ocdialog('close');
  274. }
  275. };
  276. var chooseCallback = function () {
  277. functionToCall(OCdialogs.FILEPICKER_TYPE_CHOOSE);
  278. };
  279. var copyCallback = function () {
  280. functionToCall(OCdialogs.FILEPICKER_TYPE_COPY);
  281. };
  282. var moveCallback = function () {
  283. functionToCall(OCdialogs.FILEPICKER_TYPE_MOVE);
  284. };
  285. var buttonlist = [];
  286. if (type === OCdialogs.FILEPICKER_TYPE_CHOOSE) {
  287. buttonlist.push({
  288. text: t('core', 'Choose'),
  289. click: chooseCallback,
  290. defaultButton: true
  291. });
  292. } else {
  293. if (type === OCdialogs.FILEPICKER_TYPE_COPY || type === OCdialogs.FILEPICKER_TYPE_COPY_MOVE) {
  294. buttonlist.push({
  295. text: t('core', 'Copy'),
  296. click: copyCallback,
  297. defaultButton: false
  298. });
  299. }
  300. if (type === OCdialogs.FILEPICKER_TYPE_MOVE || type === OCdialogs.FILEPICKER_TYPE_COPY_MOVE) {
  301. buttonlist.push({
  302. text: t('core', 'Move'),
  303. click: moveCallback,
  304. defaultButton: true
  305. });
  306. }
  307. }
  308. self.$filePicker.ocdialog({
  309. closeOnEscape: true,
  310. // max-width of 600
  311. width: 600,
  312. height: 500,
  313. modal: modal,
  314. buttons: buttonlist,
  315. style: {
  316. buttons: 'aside',
  317. },
  318. close: function() {
  319. try {
  320. $(this).ocdialog('destroy').remove();
  321. } catch(e) {}
  322. self.$filePicker = null;
  323. }
  324. });
  325. // We can access primary class only from oc-dialog.
  326. // Hence this is one of the approach to get the choose button.
  327. var getOcDialog = self.$filePicker.closest('.oc-dialog');
  328. var buttonEnableDisable = getOcDialog.find('.primary');
  329. if (self.$filePicker.data('mimetype').indexOf("httpd/unix-directory") !== -1) {
  330. buttonEnableDisable.prop("disabled", false);
  331. } else {
  332. buttonEnableDisable.prop("disabled", true);
  333. }
  334. })
  335. .fail(function(status, error) {
  336. // If the method is called while navigating away
  337. // from the page, it is probably not needed ;)
  338. self.filepicker.loading = false;
  339. if(status !== 0) {
  340. alert(t('core', 'Error loading file picker template: {error}', {error: error}));
  341. }
  342. });
  343. },
  344. /**
  345. * Displays raw dialog
  346. * You better use a wrapper instead ...
  347. */
  348. message:function(content, title, dialogType, buttons, callback, modal, allowHtml) {
  349. return $.when(this._getMessageTemplate()).then(function($tmpl) {
  350. var dialogName = 'oc-dialog-' + OCdialogs.dialogsCounter + '-content';
  351. var dialogId = '#' + dialogName;
  352. var $dlg = $tmpl.octemplate({
  353. dialog_name: dialogName,
  354. title: title,
  355. message: content,
  356. type: dialogType
  357. }, allowHtml ? {escapeFunction: ''} : {});
  358. if (modal === undefined) {
  359. modal = false;
  360. }
  361. $('body').append($dlg);
  362. var buttonlist = [];
  363. switch (buttons) {
  364. case OCdialogs.YES_NO_BUTTONS:
  365. buttonlist = [{
  366. text: t('core', 'No'),
  367. click: function(){
  368. if (callback !== undefined) {
  369. callback(false);
  370. }
  371. $(dialogId).ocdialog('close');
  372. }
  373. },
  374. {
  375. text: t('core', 'Yes'),
  376. click: function(){
  377. if (callback !== undefined) {
  378. callback(true);
  379. }
  380. $(dialogId).ocdialog('close');
  381. },
  382. defaultButton: true
  383. }];
  384. break;
  385. case OCdialogs.OK_BUTTON:
  386. var functionToCall = function() {
  387. $(dialogId).ocdialog('close');
  388. if(callback !== undefined) {
  389. callback();
  390. }
  391. };
  392. buttonlist[0] = {
  393. text: t('core', 'OK'),
  394. click: functionToCall,
  395. defaultButton: true
  396. };
  397. break;
  398. }
  399. $(dialogId).ocdialog({
  400. closeOnEscape: true,
  401. modal: modal,
  402. buttons: buttonlist
  403. });
  404. OCdialogs.dialogsCounter++;
  405. })
  406. .fail(function(status, error) {
  407. // If the method is called while navigating away from
  408. // the page, we still want to deliver the message.
  409. if(status === 0) {
  410. alert(title + ': ' + content);
  411. } else {
  412. alert(t('core', 'Error loading message template: {error}', {error: error}));
  413. }
  414. });
  415. },
  416. _fileexistsshown: false,
  417. /**
  418. * Displays file exists dialog
  419. * @param {object} data upload object
  420. * @param {object} original file with name, size and mtime
  421. * @param {object} replacement file with name, size and mtime
  422. * @param {object} controller with onCancel, onSkip, onReplace and onRename methods
  423. * @return {Promise} jquery promise that resolves after the dialog template was loaded
  424. */
  425. fileexists:function(data, original, replacement, controller) {
  426. var self = this;
  427. var dialogDeferred = new $.Deferred();
  428. var getCroppedPreview = function(file) {
  429. var deferred = new $.Deferred();
  430. // Only process image files.
  431. var type = file.type && file.type.split('/').shift();
  432. if (window.FileReader && type === 'image') {
  433. var reader = new FileReader();
  434. reader.onload = function (e) {
  435. var blob = new Blob([e.target.result]);
  436. window.URL = window.URL || window.webkitURL;
  437. var originalUrl = window.URL.createObjectURL(blob);
  438. var image = new Image();
  439. image.src = originalUrl;
  440. image.onload = function () {
  441. var url = crop(image);
  442. deferred.resolve(url);
  443. };
  444. };
  445. reader.readAsArrayBuffer(file);
  446. } else {
  447. deferred.reject();
  448. }
  449. return deferred;
  450. };
  451. var crop = function(img) {
  452. var canvas = document.createElement('canvas'),
  453. targetSize = 96,
  454. width = img.width,
  455. height = img.height,
  456. x, y, size;
  457. // Calculate the width and height, constraining the proportions
  458. if (width > height) {
  459. y = 0;
  460. x = (width - height) / 2;
  461. } else {
  462. y = (height - width) / 2;
  463. x = 0;
  464. }
  465. size = Math.min(width, height);
  466. // Set canvas size to the cropped area
  467. canvas.width = size;
  468. canvas.height = size;
  469. var ctx = canvas.getContext("2d");
  470. ctx.drawImage(img, x, y, size, size, 0, 0, size, size);
  471. // Resize the canvas to match the destination (right size uses 96px)
  472. resampleHermite(canvas, size, size, targetSize, targetSize);
  473. return canvas.toDataURL("image/png", 0.7);
  474. };
  475. /**
  476. * Fast image resize/resample using Hermite filter with JavaScript.
  477. *
  478. * @author: ViliusL
  479. *
  480. * @param {*} canvas
  481. * @param {number} W
  482. * @param {number} H
  483. * @param {number} W2
  484. * @param {number} H2
  485. */
  486. var resampleHermite = function (canvas, W, H, W2, H2) {
  487. W2 = Math.round(W2);
  488. H2 = Math.round(H2);
  489. var img = canvas.getContext("2d").getImageData(0, 0, W, H);
  490. var img2 = canvas.getContext("2d").getImageData(0, 0, W2, H2);
  491. var data = img.data;
  492. var data2 = img2.data;
  493. var ratio_w = W / W2;
  494. var ratio_h = H / H2;
  495. var ratio_w_half = Math.ceil(ratio_w / 2);
  496. var ratio_h_half = Math.ceil(ratio_h / 2);
  497. for (var j = 0; j < H2; j++) {
  498. for (var i = 0; i < W2; i++) {
  499. var x2 = (i + j * W2) * 4;
  500. var weight = 0;
  501. var weights = 0;
  502. var weights_alpha = 0;
  503. var gx_r = 0;
  504. var gx_g = 0;
  505. var gx_b = 0;
  506. var gx_a = 0;
  507. var center_y = (j + 0.5) * ratio_h;
  508. for (var yy = Math.floor(j * ratio_h); yy < (j + 1) * ratio_h; yy++) {
  509. var dy = Math.abs(center_y - (yy + 0.5)) / ratio_h_half;
  510. var center_x = (i + 0.5) * ratio_w;
  511. var w0 = dy * dy; //pre-calc part of w
  512. for (var xx = Math.floor(i * ratio_w); xx < (i + 1) * ratio_w; xx++) {
  513. var dx = Math.abs(center_x - (xx + 0.5)) / ratio_w_half;
  514. var w = Math.sqrt(w0 + dx * dx);
  515. if (w >= -1 && w <= 1) {
  516. //hermite filter
  517. weight = 2 * w * w * w - 3 * w * w + 1;
  518. if (weight > 0) {
  519. dx = 4 * (xx + yy * W);
  520. //alpha
  521. gx_a += weight * data[dx + 3];
  522. weights_alpha += weight;
  523. //colors
  524. if (data[dx + 3] < 255)
  525. weight = weight * data[dx + 3] / 250;
  526. gx_r += weight * data[dx];
  527. gx_g += weight * data[dx + 1];
  528. gx_b += weight * data[dx + 2];
  529. weights += weight;
  530. }
  531. }
  532. }
  533. }
  534. data2[x2] = gx_r / weights;
  535. data2[x2 + 1] = gx_g / weights;
  536. data2[x2 + 2] = gx_b / weights;
  537. data2[x2 + 3] = gx_a / weights_alpha;
  538. }
  539. }
  540. canvas.getContext("2d").clearRect(0, 0, Math.max(W, W2), Math.max(H, H2));
  541. canvas.width = W2;
  542. canvas.height = H2;
  543. canvas.getContext("2d").putImageData(img2, 0, 0);
  544. };
  545. var addConflict = function($conflicts, original, replacement) {
  546. var $conflict = $conflicts.find('.template').clone().removeClass('template').addClass('conflict');
  547. var $originalDiv = $conflict.find('.original');
  548. var $replacementDiv = $conflict.find('.replacement');
  549. $conflict.data('data',data);
  550. $conflict.find('.filename').text(original.name);
  551. $originalDiv.find('.size').text(humanFileSize(original.size));
  552. $originalDiv.find('.mtime').text(formatDate(original.mtime));
  553. // ie sucks
  554. if (replacement.size && replacement.lastModifiedDate) {
  555. $replacementDiv.find('.size').text(humanFileSize(replacement.size));
  556. $replacementDiv.find('.mtime').text(formatDate(replacement.lastModifiedDate));
  557. }
  558. var path = original.directory + '/' +original.name;
  559. var urlSpec = {
  560. file: path,
  561. x: 96,
  562. y: 96,
  563. c: original.etag,
  564. forceIcon: 0
  565. };
  566. var previewpath = Files.generatePreviewUrl(urlSpec);
  567. // Escaping single quotes
  568. previewpath = previewpath.replace(/'/g, "%27");
  569. $originalDiv.find('.icon').css({"background-image": "url('" + previewpath + "')"});
  570. getCroppedPreview(replacement).then(
  571. function(path){
  572. $replacementDiv.find('.icon').css('background-image','url(' + path + ')');
  573. }, function(){
  574. path = OC.MimeType.getIconUrl(replacement.type);
  575. $replacementDiv.find('.icon').css('background-image','url(' + path + ')');
  576. }
  577. );
  578. // connect checkboxes with labels
  579. var checkboxId = $conflicts.find('.conflict').length;
  580. $originalDiv.find('input:checkbox').attr('id', 'checkbox_original_'+checkboxId);
  581. $replacementDiv.find('input:checkbox').attr('id', 'checkbox_replacement_'+checkboxId);
  582. $conflicts.append($conflict);
  583. //set more recent mtime bold
  584. // ie sucks
  585. if (replacement.lastModifiedDate && replacement.lastModifiedDate.getTime() > original.mtime) {
  586. $replacementDiv.find('.mtime').css('font-weight', 'bold');
  587. } else if (replacement.lastModifiedDate && replacement.lastModifiedDate.getTime() < original.mtime) {
  588. $originalDiv.find('.mtime').css('font-weight', 'bold');
  589. } else {
  590. //TODO add to same mtime collection?
  591. }
  592. // set bigger size bold
  593. if (replacement.size && replacement.size > original.size) {
  594. $replacementDiv.find('.size').css('font-weight', 'bold');
  595. } else if (replacement.size && replacement.size < original.size) {
  596. $originalDiv.find('.size').css('font-weight', 'bold');
  597. } else {
  598. //TODO add to same size collection?
  599. }
  600. //TODO show skip action for files with same size and mtime in bottom row
  601. // always keep readonly files
  602. if (original.status === 'readonly') {
  603. $originalDiv
  604. .addClass('readonly')
  605. .find('input[type="checkbox"]')
  606. .prop('checked', true)
  607. .prop('disabled', true);
  608. $originalDiv.find('.message')
  609. .text(t('core','read-only'));
  610. }
  611. };
  612. //var selection = controller.getSelection(data.originalFiles);
  613. //if (selection.defaultAction) {
  614. // controller[selection.defaultAction](data);
  615. //} else {
  616. var dialogName = 'oc-dialog-fileexists-content';
  617. var dialogId = '#' + dialogName;
  618. if (this._fileexistsshown) {
  619. // add conflict
  620. var $conflicts = $(dialogId+ ' .conflicts');
  621. addConflict($conflicts, original, replacement);
  622. var count = $(dialogId+ ' .conflict').length;
  623. var title = n('core',
  624. '{count} file conflict',
  625. '{count} file conflicts',
  626. count,
  627. {count:count}
  628. );
  629. $(dialogId).parent().children('.oc-dialog-title').text(title);
  630. //recalculate dimensions
  631. $(window).trigger('resize');
  632. dialogDeferred.resolve();
  633. } else {
  634. //create dialog
  635. this._fileexistsshown = true;
  636. $.when(this._getFileExistsTemplate()).then(function($tmpl) {
  637. var title = t('core','One file conflict');
  638. var $dlg = $tmpl.octemplate({
  639. dialog_name: dialogName,
  640. title: title,
  641. type: 'fileexists',
  642. allnewfiles: t('core','New Files'),
  643. allexistingfiles: t('core','Already existing files'),
  644. why: t('core','Which files do you want to keep?'),
  645. what: t('core','If you select both versions, the copied file will have a number added to its name.')
  646. });
  647. $('body').append($dlg);
  648. if (original && replacement) {
  649. var $conflicts = $dlg.find('.conflicts');
  650. addConflict($conflicts, original, replacement);
  651. }
  652. var buttonlist = [{
  653. text: t('core', 'Cancel'),
  654. classes: 'cancel',
  655. click: function(){
  656. if ( typeof controller.onCancel !== 'undefined') {
  657. controller.onCancel(data);
  658. }
  659. $(dialogId).ocdialog('close');
  660. }
  661. },
  662. {
  663. text: t('core', 'Continue'),
  664. classes: 'continue',
  665. click: function(){
  666. if ( typeof controller.onContinue !== 'undefined') {
  667. controller.onContinue($(dialogId + ' .conflict'));
  668. }
  669. $(dialogId).ocdialog('close');
  670. }
  671. }];
  672. $(dialogId).ocdialog({
  673. width: 500,
  674. closeOnEscape: true,
  675. modal: true,
  676. buttons: buttonlist,
  677. closeButton: null,
  678. close: function() {
  679. self._fileexistsshown = false;
  680. $(this).ocdialog('destroy').remove();
  681. }
  682. });
  683. $(dialogId).css('height','auto');
  684. var $primaryButton = $dlg.closest('.oc-dialog').find('button.continue');
  685. $primaryButton.prop('disabled', true);
  686. function updatePrimaryButton() {
  687. var checkedCount = $dlg.find('.conflicts .checkbox:checked').length;
  688. $primaryButton.prop('disabled', checkedCount === 0);
  689. }
  690. //add checkbox toggling actions
  691. $(dialogId).find('.allnewfiles').on('click', function() {
  692. var $checkboxes = $(dialogId).find('.conflict .replacement input[type="checkbox"]');
  693. $checkboxes.prop('checked', $(this).prop('checked'));
  694. });
  695. $(dialogId).find('.allexistingfiles').on('click', function() {
  696. var $checkboxes = $(dialogId).find('.conflict .original:not(.readonly) input[type="checkbox"]');
  697. $checkboxes.prop('checked', $(this).prop('checked'));
  698. });
  699. $(dialogId).find('.conflicts').on('click', '.replacement,.original:not(.readonly)', function() {
  700. var $checkbox = $(this).find('input[type="checkbox"]');
  701. $checkbox.prop('checked', !$checkbox.prop('checked'));
  702. });
  703. $(dialogId).find('.conflicts').on('click', '.replacement input[type="checkbox"],.original:not(.readonly) input[type="checkbox"]', function() {
  704. var $checkbox = $(this);
  705. $checkbox.prop('checked', !$checkbox.prop('checked'));
  706. });
  707. //update counters
  708. $(dialogId).on('click', '.replacement,.allnewfiles', function() {
  709. var count = $(dialogId).find('.conflict .replacement input[type="checkbox"]:checked').length;
  710. if (count === $(dialogId+ ' .conflict').length) {
  711. $(dialogId).find('.allnewfiles').prop('checked', true);
  712. $(dialogId).find('.allnewfiles + .count').text(t('core','(all selected)'));
  713. } else if (count > 0) {
  714. $(dialogId).find('.allnewfiles').prop('checked', false);
  715. $(dialogId).find('.allnewfiles + .count').text(t('core','({count} selected)',{count:count}));
  716. } else {
  717. $(dialogId).find('.allnewfiles').prop('checked', false);
  718. $(dialogId).find('.allnewfiles + .count').text('');
  719. }
  720. updatePrimaryButton();
  721. });
  722. $(dialogId).on('click', '.original,.allexistingfiles', function(){
  723. var count = $(dialogId).find('.conflict .original input[type="checkbox"]:checked').length;
  724. if (count === $(dialogId+ ' .conflict').length) {
  725. $(dialogId).find('.allexistingfiles').prop('checked', true);
  726. $(dialogId).find('.allexistingfiles + .count').text(t('core','(all selected)'));
  727. } else if (count > 0) {
  728. $(dialogId).find('.allexistingfiles').prop('checked', false);
  729. $(dialogId).find('.allexistingfiles + .count')
  730. .text(t('core','({count} selected)',{count:count}));
  731. } else {
  732. $(dialogId).find('.allexistingfiles').prop('checked', false);
  733. $(dialogId).find('.allexistingfiles + .count').text('');
  734. }
  735. updatePrimaryButton();
  736. });
  737. dialogDeferred.resolve();
  738. })
  739. .fail(function() {
  740. dialogDeferred.reject();
  741. alert(t('core', 'Error loading file exists template'));
  742. });
  743. }
  744. //}
  745. return dialogDeferred.promise();
  746. },
  747. // get the gridview setting and set the input accordingly
  748. _getGridSettings: function() {
  749. var self = this;
  750. $.get(OC.generateUrl('/apps/files/api/v1/showgridview'), function(response) {
  751. self.$showGridView.get(0).checked = response.gridview;
  752. self.$showGridView.next('#picker-view-toggle')
  753. .removeClass('icon-toggle-filelist icon-toggle-pictures')
  754. .addClass(response.gridview ? 'icon-toggle-filelist' : 'icon-toggle-pictures')
  755. $('.list-container').toggleClass('view-grid', response.gridview);
  756. });
  757. },
  758. _onGridviewChange: function() {
  759. var show = this.$showGridView.is(':checked');
  760. // only save state if user is logged in
  761. if (OC.currentUser) {
  762. $.post(OC.generateUrl('/apps/files/api/v1/showgridview'), {
  763. show: show
  764. });
  765. }
  766. this.$showGridView.next('#picker-view-toggle')
  767. .removeClass('icon-toggle-filelist icon-toggle-pictures')
  768. .addClass(show ? 'icon-toggle-filelist' : 'icon-toggle-pictures')
  769. $('.list-container').toggleClass('view-grid', show);
  770. },
  771. _getFilePickerTemplate: function() {
  772. var defer = $.Deferred();
  773. if(!this.$filePickerTemplate) {
  774. var self = this;
  775. $.get(OC.filePath('core', 'templates', 'filepicker.html'), function(tmpl) {
  776. self.$filePickerTemplate = $(tmpl);
  777. self.$listTmpl = self.$filePickerTemplate.find('.filelist tbody tr:first-child').detach();
  778. defer.resolve(self.$filePickerTemplate);
  779. })
  780. .fail(function(jqXHR, textStatus, errorThrown) {
  781. defer.reject(jqXHR.status, errorThrown);
  782. });
  783. } else {
  784. defer.resolve(this.$filePickerTemplate);
  785. }
  786. return defer.promise();
  787. },
  788. _getMessageTemplate: function() {
  789. var defer = $.Deferred();
  790. if(!this.$messageTemplate) {
  791. var self = this;
  792. $.get(OC.filePath('core', 'templates', 'message.html'), function(tmpl) {
  793. self.$messageTemplate = $(tmpl);
  794. defer.resolve(self.$messageTemplate);
  795. })
  796. .fail(function(jqXHR, textStatus, errorThrown) {
  797. defer.reject(jqXHR.status, errorThrown);
  798. });
  799. } else {
  800. defer.resolve(this.$messageTemplate);
  801. }
  802. return defer.promise();
  803. },
  804. _getFileExistsTemplate: function () {
  805. var defer = $.Deferred();
  806. if (!this.$fileexistsTemplate) {
  807. var self = this;
  808. $.get(OC.filePath('files', 'templates', 'fileexists.html'), function (tmpl) {
  809. self.$fileexistsTemplate = $(tmpl);
  810. defer.resolve(self.$fileexistsTemplate);
  811. })
  812. .fail(function () {
  813. defer.reject();
  814. });
  815. } else {
  816. defer.resolve(this.$fileexistsTemplate);
  817. }
  818. return defer.promise();
  819. },
  820. _getFileList: function(dir, mimeType) { //this is only used by the spreedme app atm
  821. if (typeof(mimeType) === "string") {
  822. mimeType = [mimeType];
  823. }
  824. return $.getJSON(
  825. OC.filePath('files', 'ajax', 'list.php'),
  826. {
  827. dir: dir,
  828. mimetypes: JSON.stringify(mimeType)
  829. }
  830. );
  831. },
  832. /**
  833. * fills the filepicker with files
  834. */
  835. _fillFilePicker:function(dir) {
  836. var self = this;
  837. this.$filelist.empty();
  838. this.$filePicker.find('.emptycontent').hide();
  839. this.$filelistContainer.addClass('icon-loading');
  840. this.$filePicker.data('path', dir);
  841. var filter = this.$filePicker.data('mimetype');
  842. if (typeof(filter) === "string") {
  843. filter = [filter];
  844. }
  845. self.$fileListHeader.find('.sort-indicator').addClass('hidden').removeClass('icon-triangle-n').removeClass('icon-triangle-s');
  846. self.$fileListHeader.find('[data-sort=' + self.filepicker.sortField + '] .sort-indicator').removeClass('hidden');
  847. if (self.filepicker.sortOrder === 'asc') {
  848. self.$fileListHeader.find('[data-sort=' + self.filepicker.sortField + '] .sort-indicator').addClass('icon-triangle-n');
  849. } else {
  850. self.$fileListHeader.find('[data-sort=' + self.filepicker.sortField + '] .sort-indicator').addClass('icon-triangle-s');
  851. }
  852. self.filepicker.filesClient.getFolderContents(dir).then(function(status, files) {
  853. if (filter && filter.length > 0 && filter.indexOf('*') === -1) {
  854. files = files.filter(function (file) {
  855. return file.type === 'dir' || filter.indexOf(file.mimetype) !== -1;
  856. });
  857. }
  858. var Comparators = {
  859. name: function(fileInfo1, fileInfo2) {
  860. if (fileInfo1.type === 'dir' && fileInfo2.type !== 'dir') {
  861. return -1;
  862. }
  863. if (fileInfo1.type !== 'dir' && fileInfo2.type === 'dir') {
  864. return 1;
  865. }
  866. return OC.Util.naturalSortCompare(fileInfo1.name, fileInfo2.name);
  867. },
  868. size: function(fileInfo1, fileInfo2) {
  869. return fileInfo1.size - fileInfo2.size;
  870. },
  871. mtime: function(fileInfo1, fileInfo2) {
  872. return fileInfo1.mtime - fileInfo2.mtime;
  873. }
  874. };
  875. var comparator = Comparators[self.filepicker.sortField] || Comparators.name;
  876. files = files.sort(function(file1, file2) {
  877. var isFavorite = function(fileInfo) {
  878. return fileInfo.tags && fileInfo.tags.indexOf(OC.TAG_FAVORITE) >= 0;
  879. };
  880. if (isFavorite(file1) && !isFavorite(file2)) {
  881. return -1;
  882. } else if (!isFavorite(file1) && isFavorite(file2)) {
  883. return 1;
  884. }
  885. return self.filepicker.sortOrder === 'asc' ? comparator(file1, file2) : -comparator(file1, file2);
  886. });
  887. self._fillSlug();
  888. if (files.length === 0) {
  889. self.$filePicker.find('.emptycontent').show();
  890. self.$fileListHeader.hide();
  891. } else {
  892. self.$filePicker.find('.emptycontent').hide();
  893. self.$fileListHeader.show();
  894. }
  895. $.each(files, function(idx, entry) {
  896. entry.icon = OC.MimeType.getIconUrl(entry.mimetype);
  897. var simpleSize, sizeColor;
  898. if (typeof(entry.size) !== 'undefined' && entry.size >= 0) {
  899. simpleSize = humanFileSize(parseInt(entry.size, 10), true);
  900. sizeColor = Math.round(160 - Math.pow((entry.size / (1024 * 1024)), 2));
  901. } else {
  902. simpleSize = t('files', 'Pending');
  903. sizeColor = 80;
  904. }
  905. var $row = self.$listTmpl.octemplate({
  906. type: entry.type,
  907. dir: dir,
  908. filename: entry.name,
  909. date: OC.Util.relativeModifiedDate(entry.mtime),
  910. size: simpleSize,
  911. sizeColor: sizeColor,
  912. icon: entry.icon
  913. });
  914. if (entry.type === 'file') {
  915. var urlSpec = {
  916. file: dir + '/' + entry.name,
  917. x: 100,
  918. y: 100
  919. };
  920. var img = new Image();
  921. var previewUrl = OC.generateUrl('/core/preview.png?') + $.param(urlSpec);
  922. img.onload = function() {
  923. if (img.width > 5) {
  924. $row.find('td.filename').attr('style', 'background-image:url(' + previewUrl + ')');
  925. }
  926. };
  927. img.src = previewUrl;
  928. }
  929. self.$filelist.append($row);
  930. });
  931. self.$filelistContainer.removeClass('icon-loading');
  932. });
  933. },
  934. /**
  935. * fills the tree list with directories
  936. */
  937. _fillSlug: function() {
  938. this.$dirTree.empty();
  939. var self = this;
  940. var dir;
  941. var path = this.$filePicker.data('path');
  942. var $template = $('<div data-dir="{dir}"><a>{name}</a></div>').addClass('crumb');
  943. if(path) {
  944. var paths = path.split('/');
  945. $.each(paths, function(index, dir) {
  946. dir = paths.pop();
  947. if(dir === '') {
  948. return false;
  949. }
  950. self.$dirTree.prepend($template.octemplate({
  951. dir: paths.join('/') + '/' + dir,
  952. name: dir
  953. }));
  954. });
  955. }
  956. $template.octemplate({
  957. dir: '',
  958. name: '' // Ugly but works ;)
  959. }, {escapeFunction: null}).prependTo(this.$dirTree);
  960. },
  961. /**
  962. * handle selection made in the tree list
  963. */
  964. _handleTreeListSelect:function(event, type) {
  965. var self = event.data;
  966. var dir = $(event.target).closest('.crumb').data('dir');
  967. self._fillFilePicker(dir);
  968. var getOcDialog = (event.target).closest('.oc-dialog');
  969. var buttonEnableDisable = $('.primary', getOcDialog);
  970. this._changeButtonsText(type, dir.split(/[/]+/).pop());
  971. if (this.$filePicker.data('mimetype').indexOf("httpd/unix-directory") !== -1) {
  972. buttonEnableDisable.prop("disabled", false);
  973. } else {
  974. buttonEnableDisable.prop("disabled", true);
  975. }
  976. },
  977. /**
  978. * handle clicks made in the filepicker
  979. */
  980. _handlePickerClick:function(event, $element, type) {
  981. var getOcDialog = this.$filePicker.closest('.oc-dialog');
  982. var buttonEnableDisable = getOcDialog.find('.primary');
  983. if ($element.data('type') === 'file') {
  984. if (this.$filePicker.data('multiselect') !== true || !event.ctrlKey) {
  985. this.$filelist.find('.filepicker_element_selected').removeClass('filepicker_element_selected');
  986. }
  987. $element.toggleClass('filepicker_element_selected');
  988. buttonEnableDisable.prop("disabled", false);
  989. } else if ( $element.data('type') === 'dir' ) {
  990. this._fillFilePicker(this.$filePicker.data('path') + '/' + $element.data('entryname'));
  991. this._changeButtonsText(type, $element.data('entryname'));
  992. if (this.$filePicker.data('mimetype').indexOf("httpd/unix-directory") !== -1) {
  993. buttonEnableDisable.prop("disabled", false);
  994. } else {
  995. buttonEnableDisable.prop("disabled", true);
  996. }
  997. }
  998. },
  999. /**
  1000. * Handle
  1001. * @param type of action
  1002. * @param dir on which to change buttons text
  1003. * @private
  1004. */
  1005. _changeButtonsText: function(type, dir) {
  1006. var copyText = dir === '' ? t('core', 'Copy') : t('core', 'Copy to {folder}', {folder: dir});
  1007. var moveText = dir === '' ? t('core', 'Move') : t('core', 'Move to {folder}', {folder: dir});
  1008. var buttons = $('.oc-dialog-buttonrow button');
  1009. switch (type) {
  1010. case this.FILEPICKER_TYPE_CHOOSE:
  1011. break;
  1012. case this.FILEPICKER_TYPE_COPY:
  1013. buttons.text(copyText);
  1014. break;
  1015. case this.FILEPICKER_TYPE_MOVE:
  1016. buttons.text(moveText);
  1017. break;
  1018. case this.FILEPICKER_TYPE_COPY_MOVE:
  1019. buttons.eq(0).text(copyText);
  1020. buttons.eq(1).text(moveText);
  1021. break;
  1022. }
  1023. }
  1024. };