DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (31ec81b5d7bb)

VCS Links

Line Code
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 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 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/. */

#include "nsMetroFilePicker.h"
#include "nsComponentManagerUtils.h"
#include "nsNetUtil.h"
#include "nsAutoPtr.h"
#include "MetroUtils.h"

#include <windows.ui.viewmanagement.h>
#include <windows.storage.search.h>

using namespace ABI::Windows::Foundation;
using namespace ABI::Windows::Foundation::Collections;
using namespace ABI::Windows::Storage;
using namespace ABI::Windows::Storage::Pickers;
using namespace ABI::Windows::Storage::Streams;
using namespace ABI::Windows::UI;
using namespace ABI::Windows::UI::ViewManagement;
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;
using namespace mozilla::widget::winrt;

///////////////////////////////////////////////////////////////////////////////
// nsIFilePicker

nsMetroFilePicker::nsMetroFilePicker()
{
}

nsMetroFilePicker::~nsMetroFilePicker()
{
}

NS_IMPL_ISUPPORTS1(nsMetroFilePicker, nsIFilePicker)

NS_IMETHODIMP
nsMetroFilePicker::Init(nsIDOMWindow *parent, const nsAString& title, int16_t mode)
{
  mMode = mode;
  HRESULT hr;
  switch(mMode) {
  case nsIFilePicker::modeOpen:
  case nsIFilePicker::modeOpenMultiple:
    hr = ActivateGenericInstance(RuntimeClass_Windows_Storage_Pickers_FileOpenPicker, mFileOpenPicker);
    AssertRetHRESULT(hr, NS_ERROR_UNEXPECTED);
    return NS_OK;
  case nsIFilePicker::modeSave:
    hr = ActivateGenericInstance(RuntimeClass_Windows_Storage_Pickers_FileSavePicker, mFileSavePicker);
    AssertRetHRESULT(hr, NS_ERROR_UNEXPECTED);
    return NS_OK;
  default:
    return NS_ERROR_NOT_IMPLEMENTED;
  }
}

NS_IMETHODIMP
nsMetroFilePicker::Show(int16_t *aReturnVal)
{
  // Metro file picker only offers an async variant which calls back to the 
  // UI thread, which is the main thread.  We therefore can't call it
  // synchronously from the main thread.
  return NS_ERROR_NOT_IMPLEMENTED;
}

HRESULT nsMetroFilePicker::OnPickSingleFile(IAsyncOperation<StorageFile*>* aFile,
                                            AsyncStatus aStatus)
{
  if (aStatus != ABI::Windows::Foundation::AsyncStatus::Completed) {
    if (mCallback)
      mCallback->Done(nsIFilePicker::returnCancel);
    return S_OK;
  }

  HRESULT hr;
  ComPtr<IStorageFile> file;
  hr = aFile->GetResults(file.GetAddressOf());
  // When the user cancels hr == S_OK and file is NULL
  if (FAILED(hr) || !file) {
    if (mCallback)
      mCallback->Done(nsIFilePicker::returnCancel);
    return S_OK;
  }
  ComPtr<IStorageItem> storageItem;
  hr = file.As(&storageItem);
  if (FAILED(hr)) {
    if (mCallback)
      mCallback->Done(nsIFilePicker::returnCancel);
    return S_OK;
  }
  
  HSTRING path;
  if (FAILED(storageItem->get_Path(&path))) {
    if (mCallback)
      mCallback->Done(nsIFilePicker::returnCancel);
    return S_OK;
  }
  WindowsDuplicateString(path, mFilePath.GetAddressOf());
  WindowsDeleteString(path);

  if (mCallback) {
    mCallback->Done(nsIFilePicker::returnOK);
  }
  return S_OK;
}

HRESULT nsMetroFilePicker::OnPickMultipleFiles(IAsyncOperation<IVectorView<StorageFile*>*>* aFileList,
                                               AsyncStatus aStatus)
{
  if (aStatus != ABI::Windows::Foundation::AsyncStatus::Completed) {
    if (mCallback)
      mCallback->Done(nsIFilePicker::returnCancel);
    return S_OK;
  }

  HRESULT hr;
  ComPtr<IVectorView<StorageFile*>> view;
  hr = aFileList->GetResults(view.GetAddressOf());
  if (FAILED(hr)) {
    if (mCallback)
      mCallback->Done(nsIFilePicker::returnCancel);
    return S_OK;
  }

  unsigned int length;
  view->get_Size(&length);
  for (unsigned int idx = 0; idx < length; idx++) {
    ComPtr<IStorageFile> file;
    hr = view->GetAt(idx, file.GetAddressOf());
    if (FAILED(hr)) {
      continue;
    }

    ComPtr<IStorageItem> storageItem;
    hr = file.As(&storageItem);
    if (FAILED(hr)) {
      continue;
    }

    HSTRING path;
    if (SUCCEEDED(storageItem->get_Path(&path))) {
      nsCOMPtr<nsILocalFile> file = 
        do_CreateInstance("@mozilla.org/file/local;1");
      unsigned int tmp;
      if (NS_SUCCEEDED(file->InitWithPath(
          nsAutoString(WindowsGetStringRawBuffer(path, &tmp))))) {
        mFiles.AppendObject(file);
      }
    }
    WindowsDeleteString(path);
  }

  if (mCallback) {
    mCallback->Done(nsIFilePicker::returnOK);
  }
  return S_OK;
}

NS_IMETHODIMP
nsMetroFilePicker::Open(nsIFilePickerShownCallback *aCallback)
{
  HRESULT hr;
  // Capture a reference to the callback which we'll also pass into the
  // closure to ensure it's not freed.
  mCallback = aCallback;

  // The filepicker cannot open when in snapped view, try to unsnapp
  // before showing the filepicker.
  ApplicationViewState viewState;
  MetroUtils::GetViewState(viewState);
  if (viewState == ApplicationViewState::ApplicationViewState_Snapped) {
    bool unsnapped = SUCCEEDED(MetroUtils::TryUnsnap());
    NS_ENSURE_TRUE(unsnapped, NS_ERROR_FAILURE);
  }

  switch(mMode) {
  case nsIFilePicker::modeOpen: {
    NS_ENSURE_ARG_POINTER(mFileOpenPicker);

    // Initiate the file picker operation
    ComPtr<IAsyncOperation<StorageFile*>> asyncOperation;
    hr = mFileOpenPicker->PickSingleFileAsync(asyncOperation.GetAddressOf());
    AssertRetHRESULT(hr, NS_ERROR_FAILURE);

    // Subscribe to the completed event
    ComPtr<IAsyncOperationCompletedHandler<StorageFile*>>
      completedHandler(Callback<IAsyncOperationCompletedHandler<StorageFile*>>(
        this, &nsMetroFilePicker::OnPickSingleFile));
    hr = asyncOperation->put_Completed(completedHandler.Get());
    AssertRetHRESULT(hr, NS_ERROR_UNEXPECTED);
    break;
  }

  case nsIFilePicker::modeOpenMultiple: {
    NS_ENSURE_ARG_POINTER(mFileOpenPicker);

    typedef IVectorView<StorageFile*> StorageTemplate;
    typedef IAsyncOperation<StorageTemplate*> AsyncCallbackTemplate;
    typedef IAsyncOperationCompletedHandler<StorageTemplate*> HandlerTemplate;

    // Initiate the file picker operation
    ComPtr<AsyncCallbackTemplate> asyncOperation;
    hr = mFileOpenPicker->PickMultipleFilesAsync(asyncOperation.GetAddressOf());
    AssertRetHRESULT(hr, NS_ERROR_FAILURE);

    // Subscribe to the completed event
    ComPtr<HandlerTemplate> completedHandler(Callback<HandlerTemplate>(
      this, &nsMetroFilePicker::OnPickMultipleFiles));
    hr = asyncOperation->put_Completed(completedHandler.Get());
    AssertRetHRESULT(hr, NS_ERROR_UNEXPECTED);
    break;
  }

  case nsIFilePicker::modeSave: {
    NS_ENSURE_ARG_POINTER(mFileSavePicker);

    // Set the default file name
    mFileSavePicker->put_SuggestedFileName(HStringReference(mDefaultFilename.BeginReading()).Get());

    // Set the default file extension
    if (mDefaultExtension.Length() > 0) {
      nsAutoString defaultFileExtension(mDefaultExtension);

      // Touch up the extansion format platform hands us.
      if (defaultFileExtension[0] == L'*') {
        defaultFileExtension.Cut(0, 1);
      } else if (defaultFileExtension[0] != L'.') {
        defaultFileExtension.Insert(L".", 0);
      }

      // Sometimes the default file extension is not passed in correctly,
      // so we purposfully ignore failures here.
      HString ext;
      ext.Set(defaultFileExtension.BeginReading());
      hr = mFileSavePicker->put_DefaultFileExtension(ext.Get());
      NS_ASSERTION(SUCCEEDED(hr), "put_DefaultFileExtension failed, bad format for extension?");

      // Due to a bug in the WinRT file picker, the first file extension in the
      // list is always used when saving a file. So we explicitly make sure the
      // default extension is the first one in the list here.
      if (mFirstTitle.Get()) {
        ComPtr<IMap<HSTRING, IVector<HSTRING>*>> map;
        mFileSavePicker->get_FileTypeChoices(map.GetAddressOf());
        if (map) {
          boolean found = false;
          unsigned int index;
          map->HasKey(mFirstTitle.Get(), &found);
          if (found) {
            ComPtr<IVector<HSTRING>> list;
            if (SUCCEEDED(map->Lookup(mFirstTitle.Get(), list.GetAddressOf()))) {
              HString ext;
              ext.Set(defaultFileExtension.get());
              found = false;
              list->IndexOf(HStringReference(defaultFileExtension.get()).Get(), &index, &found);
              if (found) {
                list->RemoveAt(index);
                list->InsertAt(0, HStringReference(defaultFileExtension.get()).Get());
              }
            }
          }
        }
      }
    }

    // Dispatch the async show operation
    ComPtr<IAsyncOperation<StorageFile*>> asyncOperation;
    hr = mFileSavePicker->PickSaveFileAsync(asyncOperation.GetAddressOf());
    AssertRetHRESULT(hr, NS_ERROR_FAILURE);

    // Subscribe to the completed event
    ComPtr<IAsyncOperationCompletedHandler<StorageFile*>>
      completedHandler(Callback<IAsyncOperationCompletedHandler<StorageFile*>>(
        this, &nsMetroFilePicker::OnPickSingleFile));
    hr = asyncOperation->put_Completed(completedHandler.Get());
    AssertRetHRESULT(hr, NS_ERROR_UNEXPECTED);
    break;
  }

  case modeGetFolder:
    return NS_ERROR_NOT_IMPLEMENTED;

  default:
    return NS_ERROR_NOT_IMPLEMENTED;
  }
  return NS_OK;
}

NS_IMETHODIMP
nsMetroFilePicker::GetFile(nsIFile **aFile)
{
  NS_ENSURE_ARG_POINTER(aFile);
  *aFile = nullptr;

  if (WindowsIsStringEmpty(mFilePath.Get()))
    return NS_OK;

  nsCOMPtr<nsILocalFile> file(do_CreateInstance("@mozilla.org/file/local;1"));
  NS_ENSURE_TRUE(file, NS_ERROR_FAILURE);
  unsigned int length;
  file->InitWithPath(nsAutoString(mFilePath.GetRawBuffer(&length)));
  NS_ADDREF(*aFile = file);
  return NS_OK;
}

NS_IMETHODIMP
nsMetroFilePicker::GetFileURL(nsIURI **aFileURL)
{
  *aFileURL = nullptr;
  nsCOMPtr<nsIFile> file;
  nsresult rv = GetFile(getter_AddRefs(file));
  if (!file)
    return rv;

  return NS_NewFileURI(aFileURL, file);
}

NS_IMETHODIMP
nsMetroFilePicker::GetFiles(nsISimpleEnumerator **aFiles)
{
  NS_ENSURE_ARG_POINTER(aFiles);
  return NS_NewArrayEnumerator(aFiles, mFiles);
}

// Set the filter index
NS_IMETHODIMP
nsMetroFilePicker::GetFilterIndex(int32_t *aFilterIndex)
{
  // No associated concept with a Metro file picker
  return NS_ERROR_NOT_IMPLEMENTED;
}

NS_IMETHODIMP
nsMetroFilePicker::SetFilterIndex(int32_t aFilterIndex)
{
  // No associated concept with a Metro file picker
  return NS_ERROR_NOT_IMPLEMENTED;
}

// AFACT, it's up to use to supply the implementation of a vector list.
class MozHStringVector : public RuntimeClass<IVector<HSTRING>> {
  InspectableClass(L"MozHStringVector", TrustLevel::BaseTrust)
  ~MozHStringVector() {
    Clear();
  }

  // See IVector_impl in windows.foundation.collections.h
public:
  STDMETHOD(GetAt)(unsigned aIndex, HSTRING* aString) {
    if (aIndex >= mList.Length()) {
      return E_INVALIDARG;
    }
    return WindowsDuplicateString(mList[aIndex], aString);
  }

  STDMETHOD(get_Size)(unsigned int* aLength) {
    if (!aLength) {
      return E_INVALIDARG;
    }
    *aLength = mList.Length();
    return S_OK;
  }

  STDMETHOD(Append)(HSTRING aString) {
    HSTRING str;
    if (FAILED(WindowsDuplicateString(aString, &str))) {
      return E_INVALIDARG;
    }
    mList.AppendElement(str);
    return S_OK;
  }

  STDMETHOD(Clear)() {
    int length = mList.Length();
    for (int idx = 0; idx < length; idx++)
      WindowsDeleteString(mList[idx]);
    mList.Clear();
    return S_OK;
  }

  // interfaces picker code doesn't seem to need
  STDMETHOD(GetView)(IVectorView<HSTRING> **aView) { return E_NOTIMPL; }
  STDMETHOD(IndexOf)(HSTRING aValue, unsigned *aIndex, boolean *found) { return E_NOTIMPL; }
  STDMETHOD(SetAt)(unsigned aIndex, HSTRING aString) { return E_NOTIMPL; }
  STDMETHOD(InsertAt)(unsigned aIndex, HSTRING aString) { return E_NOTIMPL; }
  STDMETHOD(RemoveAt)(unsigned aIndex) { return E_NOTIMPL; }
  STDMETHOD(RemoveAtEnd)() { return E_NOTIMPL; }

private:
  nsTArray<HSTRING> mList;
};

nsresult
nsMetroFilePicker::ParseFiltersIntoVector(ComPtr<IVector<HSTRING>>& aVector,
                                          const nsAString& aFilter,
                                          bool aAllowAll)
{
  const PRUnichar *beg = aFilter.BeginReading();
  const PRUnichar *end = aFilter.EndReading();
  for (const PRUnichar *cur = beg, *fileTypeStart = beg; cur <= end; ++cur) {
    // Start of a a filetype, example: *.png
    if (cur == end || PRUnichar(' ') == *cur) {
      int32_t startPos = fileTypeStart - beg;
      int32_t endPos = cur - fileTypeStart - (cur == end ? 0 : 1);
      const nsAString& fileType = Substring(aFilter,
                                            startPos,
                                            endPos);
      // There is no way to say show all files in Metro save file picker, so
      // just use .data if * or *.* is specified.
      if (fileType.IsEmpty() ||
          fileType.Equals(L"*") ||
          fileType.Equals(L"*.*")) {
        HString str;
        if (aAllowAll) {
          str.Set(L"*");
          aVector->Append(str.Get());
        } else {
          str.Set(L".data");
          aVector->Append(str.Get());
        }
      } else {
        nsAutoString filter(fileType);
        if (filter[0] == L'*') {
          filter.Cut(0, 1);
        } else if (filter[0] != L'.') {
          filter.Insert(L".", 0);
        }
        HString str;
        str.Set(filter.BeginReading());
        aVector->Append(str.Get());
      }

      fileTypeStart = cur + 1;
    }
  }
  return NS_OK;
}

NS_IMETHODIMP
nsMetroFilePicker::AppendFilter(const nsAString& aTitle, 
                                const nsAString& aFilter)
{
  HRESULT hr;
  switch(mMode) {
  case nsIFilePicker::modeOpen:
  case nsIFilePicker::modeOpenMultiple: {
    NS_ENSURE_ARG_POINTER(mFileOpenPicker);
    ComPtr<IVector<HSTRING>> list;
    mFileOpenPicker->get_FileTypeFilter(list.GetAddressOf());
    nsresult rv = ParseFiltersIntoVector(list, aFilter, true);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  case nsIFilePicker::modeSave: {
    NS_ENSURE_ARG_POINTER(mFileSavePicker);

    ComPtr<IMap<HSTRING,IVector<HSTRING>*>> map;
    hr = mFileSavePicker->get_FileTypeChoices(map.GetAddressOf());
    AssertRetHRESULT(hr, NS_ERROR_FAILURE);

    HString key;
    key.Set(aTitle.BeginReading());

    ComPtr<IVector<HSTRING>> saveTypes;
    saveTypes = Make<MozHStringVector>();
    nsresult rv = ParseFiltersIntoVector(saveTypes, aFilter, false);
    NS_ENSURE_SUCCESS(rv, rv);

    if (WindowsIsStringEmpty(mFirstTitle.Get())) {
      mFirstTitle.Set(key.Get());
    }

    boolean replaced;
    map->Insert(key.Get(), saveTypes.Get(), &replaced);
  }
  break;

  default:
    return NS_ERROR_FAILURE;
  }
  return NS_OK;
}