What's new? | Help | Directory | Sign in
Google
gears
Improving Your Web Browser
  
  
  
    
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
// Copyright 2008, Google Inc.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. Neither the name of Google Inc. nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#if defined(WIN32)

#include "gears/desktop/file_dialog_win32.h"
#include "gears/base/common/string_utils.h"

namespace {

// TODO(bpm): Localize and unify with other copies of these strings for other
// platforms.
const char16* kDefaultFilterLabel = STRING16(L"All Readable Documents");
const char16* kAllDocumentsLabel = STRING16(L"All Documents");

const char16 *kSelectionCompleteTopic = STRING16(L"selection complete");

// Maximum number of characters for the selected path and all filenames,
// combined.
const size_t kFilenameBufferSize = 32768;

// Utility class for passing StringList between threads.
class FileDialogData : public NotificationData {
public:
FileDialogData() {}
virtual ~FileDialogData() {}

FileDialog::StringList selected_files;

private:
// NotificationData implementation. These methods are not required.
virtual SerializableClassId GetSerializableClassId() const {
assert(false);
return SERIALIZABLE_NULL;
}
virtual bool Serialize(Serializer *out) const {
assert(false);
return false;
}
virtual bool Deserialize(Deserializer *in) {
assert(false);
return false;
}

DISALLOW_EVIL_CONSTRUCTORS(FileDialogData);
};

void ExitDialog(HWND dlg) {
::PostMessage(dlg, WM_COMMAND, MAKEWPARAM(IDCANCEL, 0), NULL);
}

} // anonymous namespace

FileDialogWin32::FileDialogWin32(const ModuleImplBaseClass* module, HWND parent)
: FileDialog(module), parent_(parent), should_exit_(false), wnd_(NULL) {
static unsigned long id = 0;
topic_.assign(kSelectionCompleteTopic);
topic_.append(IntegerToString16(++id));

// Set up the thread message queue.
if (!ThreadMessageQueue::GetInstance()->InitThreadMessageQueue()) {
LOG(("Failed to set up thread message queue.\n"));
assert(false);
return;
}

MessageService::GetInstance()->AddObserver(this, topic_.c_str());
}

FileDialogWin32::~FileDialogWin32() {
MessageService::GetInstance()->RemoveObserver(this, topic_.c_str());
}

bool FileDialogWin32::BeginSelection(const FileDialog::Options& options,
std::string16* error) {
InitDialog(options);

std::string16 filter_buffer;
if (!SetFilter(options.filter, error))
return false;

if (0 == Start()) {
*error = STRING16(L"Thread creation failed.");
return false;
}
return true;
}

void FileDialogWin32::CancelSelection() {
MutexLock lock(&mutex_);
if (wnd_) {
ExitDialog(wnd_);
} else {
should_exit_ = true;
}
}

void FileDialogWin32::Run() {
scoped_ptr<FileDialogData> data(new FileDialogData);
std::string16 error;
if (!Display(&data->selected_files, &error)) {
HandleError(error);
}
MessageService::GetInstance()->NotifyObservers(topic_.c_str(),
data.release());
}

void FileDialogWin32::OnNotify(MessageService *service,
const char16 *topic,
const NotificationData *data) {
assert(topic_ == topic);
Join(); // The worker thread has completed.
const FileDialogData* dialog_data = static_cast<const FileDialogData*>(data);
CompleteSelection(dialog_data->selected_files);
}

// Initialize an open file dialog to open multiple files.
void FileDialogWin32::InitDialog(const FileDialog::Options& options) {
filename_buffer_.resize(kFilenameBufferSize);

// Initialize OPENFILENAME
memset(&ofn_, 0, sizeof(ofn_));
ofn_.lStructSize = sizeof(ofn_);
ofn_.hwndOwner = parent_;
ofn_.lpstrFile = &filename_buffer_[0];
ofn_.lpstrFile[0] = '\0';
ofn_.nMaxFile = kFilenameBufferSize;
ofn_.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER
| OFN_HIDEREADONLY;
if (MULTIPLE_FILES == options.mode) {
#ifdef WINCE
// The native WinCE file picker does not support multi-select.
#else
ofn_.Flags |= OFN_ALLOWMULTISELECT;
#endif
}
}

bool FileDialogWin32::SetFilter(const StringList& filter,
std::string16* error) {
MediaMap media_map;
GetMediaTypeMap(&media_map);

std::string16 default_filter;
for (StringList::const_iterator it = filter.begin(); it != filter.end();
++it) {
// Handle extensions of the form ".foo".
if (L'.' == (*it)[0]) {
if (!default_filter.empty()) {
default_filter.push_back(L';');
}
default_filter.push_back(L'*');
default_filter.append(*it);
continue;
}

// Handle media types of the form "application/foo".
MediaMap::const_iterator entry = media_map.find(*it);
if (entry != media_map.end()) {
if (!default_filter.empty()) {
default_filter.push_back(L';');
}
default_filter.append(entry->second);
}

// TODO(bpm): Handle wildcard media types.
}
if (!default_filter.empty()) {
filter_.append(kDefaultFilterLabel);
filter_.push_back('\0');
filter_.append(default_filter);
filter_.push_back('\0');
}

// An unrestricted filter is always available. On Win32, *.* matches
// everything, even files with no extension.
filter_.append(kAllDocumentsLabel);
filter_.push_back('\0');
filter_.append(STRING16(L"*.*"));
filter_.push_back('\0');

// Terminate the filter with an extra null.
filter_.push_back('\0');

ofn_.lpstrFilter = filter_.c_str();
ofn_.nFilterIndex = 1;
return true;
}

bool FileDialogWin32::GetMediaTypeMap(MediaMap* map) {
map->clear();

for (DWORD index = 0; true; ++index) {
TCHAR name[32]; // Ignore any extensions larger than 30 chars.
DWORD len = ARRAYSIZE(name);
LONG result = RegEnumKeyEx(HKEY_CLASSES_ROOT, index, name, &len, NULL, NULL,
NULL, NULL);
if (ERROR_NO_MORE_ITEMS == result)
break;
if (ERROR_SUCCESS != result)
continue;
if (name[0] != L'.')
continue;
HKEY key;
result = RegOpenKeyEx(HKEY_CLASSES_ROOT, name, 0, KEY_QUERY_VALUE, &key);
if (ERROR_SUCCESS != result)
continue;
DWORD regtype;
TCHAR content_type[128]; // Ignore content types larger than 127 chars.
// Note: content_type length is expressed in bytes, not char16s, and may not
// be null-terminated.
len = sizeof(content_type) - 2;
result = RegQueryValueEx(key, L"Content Type", NULL, &regtype,
reinterpret_cast<BYTE*>(content_type), &len);
if ((ERROR_SUCCESS == result) && (REG_SZ == regtype)) {
content_type[len / 2] = L'\0'; // Ensure null-termination. (len in bytes)
std::string16& extensions = (*map)[content_type];
if (!extensions.empty()) {
extensions.push_back(L';');
}
extensions.push_back(L'*');
extensions.append(name);
}
RegCloseKey(key);
}

return true;
}

bool FileDialogWin32::Display(StringList* selected_files,
std::string16* error) {
if (FAILED(CoInitializeEx(NULL, GEARS_COINIT_THREAD_MODEL))) {
*error = STRING16("Failed to initialize new thread.");
return false;
}
ofn_.lpfnHook = &FileDialogWin32::HookProc;
ofn_.lCustData = reinterpret_cast<LPARAM>(this);
bool success = (FALSE != ::GetOpenFileName(&ofn_));
if (success) {
success = ProcessSelection(selected_files, error);
}
::CoUninitialize();
return success;
}

UINT_PTR FileDialogWin32::HookProc(HWND hdlg, UINT uiMsg, WPARAM wParam,
LPARAM lParam) {
if (WM_INITDIALOG == uiMsg) {
OPENFILENAME* ofn = reinterpret_cast<OPENFILENAME*>(lParam);
FileDialogWin32* dialog =
reinterpret_cast<FileDialogWin32*>(ofn->lCustData);
MutexLock lock(&dialog->mutex_);
if (dialog->should_exit_) {
ExitDialog(::GetParent(hdlg));
} else {
dialog->wnd_ = ::GetParent(hdlg);
}
} else if (WM_NOTIFY == uiMsg) {
NMHDR* nmhdr = reinterpret_cast<NMHDR*>(lParam);
if (CDN_INITDONE == nmhdr->code) {
#if 0
// TODO(bpm): Determine if we want this.
// This code sets a customized icon for the dialog, and centers it on the
// screen.
HWND dialog_handle = ::GetParent(hdlg);
if (HICON icon = ::LoadIcon(::GetModuleHandle(NULL), L"IDI_ICON")) {
::SendMessage(dialog_handle, WM_SETICON, ICON_BIG,
reinterpret_cast<LPARAM>(icon));
}
RECT desktop_area, dialog_area;
::GetWindowRect(::GetDesktopWindow(), &desktop_area);
desktop_area.right -= desktop_area.left;
desktop_area.bottom -= desktop_area.top;
::GetWindowRect(dialog_handle, &dialog_area);
dialog_area.right -= dialog_area.left;
dialog_area.bottom -= dialog_area.top;
desktop_area.left += (desktop_area.right - dialog_area.right) / 2;
desktop_area.top += (desktop_area.bottom - dialog_area.bottom) / 2;
::SetWindowPos(dialog_handle, NULL,
desktop_area.left, desktop_area.top,
0, 0, SWP_NOSIZE | SWP_NOZORDER);
#endif
}
}
return 0;
}

bool FileDialogWin32::ProcessSelection(StringList* selected_files,
std::string16* error) {
StringList files;
const TCHAR* selection = ofn_.lpstrFile;
while (*selection) { // Empty string indicates end of list.
files.push_back(selection);
// Skip over filename and null-terminator.
selection += files.back().length() + 1;
}
if (files.empty()) {
*error = STRING16(L"Selection contained no files. A minimum of one was "
L"expected.");
return false;
}
if (files.size() == 1) {
// When there is one file, it contains the path and filename.
selected_files->swap(files);
} else {
// Otherwise, the first string is the path, and the remainder are filenames.
StringList::iterator path = files.begin();
for (StringList::iterator file = path + 1; file != files.end(); ++file) {
selected_files->push_back(*path + L'\\' + *file);
}
}
return true;
}

#endif // WIN32
Show details Hide details

Change log

r2409 by gears.daemon on Jul 17, 2008   Diff
[Author: bpm]

Change getLocalFiles into new openFiles
API, except for async behavior, mime-
wildcards, and finalization of filter
strings, to be done in a follow-on CL.
Includes the following changes:
     - Merge FileDialog functions from
file_dialog_utils.* to file_dialog.*.
     - Change openFiles to take object-
based optional parameters, and return
files via callback.
...
Go to: 
Project members, sign in to write a code review

Older revisions

r2106 by gears.daemon on Jun 25, 2008   Diff
[Author: bpm]

Add single-file option to
desktop.getLocalFiles().

...
r1936 by gears.daemon on Jun 11, 2008   Diff
[Author: fry]

make blob support official!

PRESUBMIT=passed
...
r1125 by gears.daemon on Mar 06, 2008   Diff
[Author: steveblock]

Adss file picker for WinCE.
Also updates cab_updater to use new
BrowserHelperObject::GetBrowserWindow
...
All revisions of this file

File info

Size: 11390 bytes, 337 lines