summaryrefslogtreecommitdiffstats
path: root/b2g/components/FilePicker.js
blob: 803eef6818901bb11538edba2547314753f54af8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/*
 * No magic constructor behaviour, as is de rigeur for XPCOM.
 * If you must perform some initialization, and it could possibly fail (even
 * due to an out-of-memory condition), you should use an Init method, which
 * can convey failure appropriately (thrown exception in JS,
 * NS_FAILED(nsresult) return in C++).
 *
 * In JS, you can actually cheat, because a thrown exception will cause the
 * CreateInstance call to fail in turn, but not all languages are so lucky.
 * (Though ANSI C++ provides exceptions, they are verboten in Mozilla code
 * for portability reasons -- and even when you're building completely
 * platform-specific code, you can't throw across an XPCOM method boundary.)
 */

const { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;

// FIXME: improve this list of filters.
const IMAGE_FILTERS = ['image/gif', 'image/jpeg', 'image/pjpeg',
                       'image/png', 'image/svg+xml', 'image/tiff',
                       'image/vnd.microsoft.icon'];
const VIDEO_FILTERS = ['video/mpeg', 'video/mp4', 'video/ogg',
                       'video/quicktime', 'video/webm', 'video/x-matroska',
                       'video/x-ms-wmv', 'video/x-flv'];
const AUDIO_FILTERS = ['audio/basic', 'audio/L24', 'audio/mp4',
                       'audio/mpeg', 'audio/ogg', 'audio/vorbis',
                       'audio/vnd.rn-realaudio', 'audio/vnd.wave',
                       'audio/webm'];

Cu.import('resource://gre/modules/XPCOMUtils.jsm');
Cu.import("resource://gre/modules/osfile.jsm");

XPCOMUtils.defineLazyServiceGetter(this, 'cpmm',
                                   '@mozilla.org/childprocessmessagemanager;1',
                                   'nsIMessageSender');

function FilePicker() {
}

FilePicker.prototype = {
  classID: Components.ID('{436ff8f9-0acc-4b11-8ec7-e293efba3141}'),
  QueryInterface: XPCOMUtils.generateQI([Ci.nsIFilePicker]),

  /* members */

  mParent: undefined,
  mExtraProps: undefined,
  mFilterTypes: undefined,
  mFileEnumerator: undefined,
  mFilePickerShownCallback: undefined,

  /* methods */

  init: function(parent, title, mode) {
    this.mParent = parent;
    this.mExtraProps = {};
    this.mFilterTypes = [];
    this.mMode = mode;

    if (mode != Ci.nsIFilePicker.modeOpen &&
        mode != Ci.nsIFilePicker.modeOpenMultiple) {
      throw Cr.NS_ERROR_NOT_IMPLEMENTED;
    }
  },

  /* readonly attribute nsILocalFile file - not implemented; */
  /* readonly attribute nsISimpleEnumerator files - not implemented; */
  /* readonly attribute nsIURI fileURL - not implemented; */

  get domFileOrDirectoryEnumerator() {
    return this.mFilesEnumerator;
  },

  // We don't support directory selection yet.
  get domFileOrDirectory() {
    return this.mFilesEnumerator ? this.mFilesEnumerator.mFiles[0] : null;
  },

  get mode() {
    return this.mMode;
  },

  appendFilters: function(filterMask) {
    // Ci.nsIFilePicker.filterHTML is not supported
    // Ci.nsIFilePicker.filterText is not supported

    if (filterMask & Ci.nsIFilePicker.filterImages) {
      this.mFilterTypes = this.mFilterTypes.concat(IMAGE_FILTERS);
      // This property is needed for the gallery app pick activity.
      this.mExtraProps['nocrop'] = true;
    }

    // Ci.nsIFilePicker.filterXML is not supported
    // Ci.nsIFilePicker.filterXUL is not supported
    // Ci.nsIFilePicker.filterApps is not supported
    // Ci.nsIFilePicker.filterAllowURLs is not supported

    if (filterMask & Ci.nsIFilePicker.filterVideo) {
      this.mFilterTypes = this.mFilterTypes.concat(VIDEO_FILTERS);
    }

    if (filterMask & Ci.nsIFilePicker.filterAudio) {
      this.mFilterTypes = this.mFilterTypes.concat(AUDIO_FILTERS);
    }

    if (filterMask & Ci.nsIFilePicker.filterAll) {
      // This property is needed for the gallery app pick activity.
      this.mExtraProps['nocrop'] = true;
    }
  },

  appendFilter: function(title, extensions) {
    // pick activity doesn't support extensions
  },

  open: function(aFilePickerShownCallback) {
    this.mFilePickerShownCallback = aFilePickerShownCallback;

    cpmm.addMessageListener('file-picked', this);

    let detail = {};
    if (this.mFilterTypes) {
       detail.type = this.mFilterTypes;
    }

    for (let prop in this.mExtraProps) {
      if (!(prop in detail)) {
        detail[prop] = this.mExtraProps[prop];
      }
    }

    cpmm.sendAsyncMessage('file-picker', detail);
  },

  fireSuccess: function(file) {
    this.mFilesEnumerator = {
      QueryInterface: XPCOMUtils.generateQI([Ci.nsISimpleEnumerator]),

      mFiles: [file],
      mIndex: 0,

      hasMoreElements: function() {
        return (this.mIndex < this.mFiles.length);
      },

      getNext: function() {
        if (this.mIndex >= this.mFiles.length) {
          throw Components.results.NS_ERROR_FAILURE;
        }
        return this.mFiles[this.mIndex++];
      }
    };

    if (this.mFilePickerShownCallback) {
      this.mFilePickerShownCallback.done(Ci.nsIFilePicker.returnOK);
      this.mFilePickerShownCallback = null;
    }
  },

  fireError: function() {
    if (this.mFilePickerShownCallback) {
      this.mFilePickerShownCallback.done(Ci.nsIFilePicker.returnCancel);
      this.mFilePickerShownCallback = null;
    }
  },

  receiveMessage: function(message) {
    if (message.name !== 'file-picked') {
      return;
    }

    cpmm.removeMessageListener('file-picked', this);

    let data = message.data;
    if (!data.success || !data.result.blob) {
      this.fireError();
      return;
    }

    // The name to be shown can be part of the message, or can be taken from
    // the File (if the blob is a File).
    let name = data.result.name;
    if (!name &&
        (data.result.blob instanceof this.mParent.File) &&
        data.result.blob.name) {
      name = data.result.blob.name;
    }

    // Let's try to remove the full path and take just the filename.
    if (name) {
      let names = OS.Path.split(name);
      name = names.components[names.components.length - 1];
    }

    // the fallback is a filename composed by 'blob' + extension.
    if (!name) {
      name = 'blob';
      if (data.result.blob.type) {
        let mimeSvc = Cc["@mozilla.org/mime;1"].getService(Ci.nsIMIMEService);
        let mimeInfo = mimeSvc.getFromTypeAndExtension(data.result.blob.type, '');
        if (mimeInfo) {
          name += '.' + mimeInfo.primaryExtension;
        }
      }
    }

    let file = new this.mParent.File([data.result.blob],
                                     name,
                                     { type: data.result.blob.type });

    if (file) {
      this.fireSuccess(file);
    } else {
      this.fireError();
    }
  }
};

this.NSGetFactory = XPCOMUtils.generateNSGetFactory([FilePicker]);