Esempio n. 1
0
static void AddNewLineString(UString &s, const UString &m)
{
  s += m;
  s.Add_LF();
}
Esempio n. 2
0
  bool InitName(const UString &name, bool newStyle)
  {
    _first = true;
    _newStyle = newStyle;
    int dotPos = name.ReverseFind('.');
    UString basePart = name;
    if (dotPos >= 0)
    {
      UString ext = name.Mid(dotPos + 1);
      if (ext.CompareNoCase(L"rar") == 0)
      {
        _afterPart = name.Mid(dotPos);
        basePart = name.Left(dotPos);
      }
      else if (ext.CompareNoCase(L"exe") == 0)
      {
        _afterPart = L".rar";
        basePart = name.Left(dotPos);
      }
      else if (!_newStyle)
      {
        if (ext.CompareNoCase(L"000") == 0 ||
            ext.CompareNoCase(L"001") == 0 ||
            ext.CompareNoCase(L"r00") == 0 ||
            ext.CompareNoCase(L"r01") == 0)
        {
          _afterPart.Empty();
          _first = false;
          _changedPart = ext;
          _unchangedPart = name.Left(dotPos + 1);
          return true;
        }
      }
    }

    if (!_newStyle)
    {
      _afterPart.Empty();
      _unchangedPart = basePart + UString(L".");
      _changedPart = L"r00";
      return true;
    }

    int numLetters = 1;
    if (basePart.Right(numLetters) == L"1" || basePart.Right(numLetters) == L"0")
    {
      while (numLetters < basePart.Length())
      {
        if (basePart[basePart.Length() - numLetters - 1] != '0')
          break;
        numLetters++;
      }
    }
    else
      return false;
    _unchangedPart = basePart.Left(basePart.Length() - numLetters);
    _changedPart = basePart.Right(numLetters);
    return true;
  }
Esempio n. 3
0
CtrlGeneric *TopWindow::findHitControl( int xPos, int yPos )
{
    if( m_pActiveLayout == NULL )
    {
        return NULL;
    }

    // Get the controls in the active layout
    const list<LayeredControl> &ctrlList = m_pActiveLayout->getControlList();
    list<LayeredControl>::const_reverse_iterator iter;

    // New control hit by the mouse
    CtrlGeneric *pNewHitControl = NULL;

    // Loop on the control list to find the uppest hit control
    for( iter = ctrlList.rbegin(); iter != ctrlList.rend(); ++iter )
    {
        // Get the position of the control in the layout
        const Position *pos = (*iter).m_pControl->getPosition();
        if( pos != NULL )
        {
            // Compute the coordinates of the mouse relative to the control
            int xRel = xPos - pos->getLeft();
            int yRel = yPos - pos->getTop();

            CtrlGeneric *pCtrl = (*iter).m_pControl;
            // Control hit ?
            if( pCtrl->isVisible() && pCtrl->mouseOver( xRel, yRel ) )
            {
                pNewHitControl = (*iter).m_pControl;
                break;
            }
        }
        else
        {
            msg_Dbg( getIntf(), "control at NULL position" );
        }
    }

    // If the hit control has just been entered, send it an enter event
    if( pNewHitControl && (pNewHitControl != m_pLastHitControl) )
    {
        // Don't send the event if another control captured the mouse
        if( !m_pCapturingControl || (m_pCapturingControl == pNewHitControl ) )
        {
            EvtEnter evt( getIntf() );
            pNewHitControl->handleEvent( evt );

            if( !m_pCapturingControl )
            {
                // Show the tooltip
                m_rWindowManager.hideTooltip();
                UString tipText = pNewHitControl->getTooltipText();
                if( tipText.length() > 0 )
                {
                    // Set the tooltip text variable
                    VarManager *pVarManager = VarManager::instance( getIntf() );
                    pVarManager->getTooltipText().set( tipText );
                    m_rWindowManager.showTooltip();
                }
            }
        }
    }

    return pNewHitControl;
}
Esempio n. 4
0
bool FilePath::isDirectory(const UString &p) {
	return (exists(p.c_str()) && is_directory(p.c_str()));
}
Esempio n. 5
0
UString FilePath::getExtension(const UString &p) {
	path file(p.c_str());

	return file.extension();
}
Esempio n. 6
0
bool CMenuPage::OnInit()
{
  _initMode = true;

  Clear_MenuChanged();
  
  LangSetDlgItems(*this, kLangIDs, ARRAY_SIZE(kLangIDs));

  #ifdef UNDER_CE

  HideItem(IDX_SYSTEM_INTEGRATE_TO_MENU);
  HideItem(IDX_SYSTEM_INTEGRATE_TO_MENU_2);

  #else

  {
    UString s;
    {
      CWindow window(GetItem(IDX_SYSTEM_INTEGRATE_TO_MENU));
      window.GetText(s);
    }
    UString bit64 = LangString(IDS_PROP_BIT64);
    if (bit64.IsEmpty())
      bit64.SetFromAscii("64-bit");
    #ifdef _WIN64
      bit64.Replace(L"64", L"32");
    #endif
    s.Add_Space();
    s += L'(';
    s += bit64;
    s += L')';
    SetItemText(IDX_SYSTEM_INTEGRATE_TO_MENU_2, s);
  }

  const FString prefix = NDLL::GetModuleDirPrefix();
  
  _dlls[0].ctrl = IDX_SYSTEM_INTEGRATE_TO_MENU;
  _dlls[1].ctrl = IDX_SYSTEM_INTEGRATE_TO_MENU_2;
  
  _dlls[0].wow = 0;
  _dlls[1].wow =
      #ifdef _WIN64
        KEY_WOW64_32KEY
      #else
        KEY_WOW64_64KEY
      #endif
      ;

  for (unsigned d = 0; d < 2; d++)
  {
    CShellDll &dll = _dlls[d];

    dll.wasChanged = false;

    #ifndef _WIN64
    if (d != 0 && !g_Is_Wow64)
    {
      HideItem(dll.ctrl);
      continue;
    }
    #endif

    FString &path = dll.Path;
    path = prefix;
    path.AddAscii(d == 0 ? "7-zip.dll" :
        #ifdef _WIN64
          "7-zip32.dll"
        #else
          "7-zip64.dll"
        #endif
        );


    if (!NFile::NFind::DoesFileExist(path))
    {
      path.Empty();
      EnableItem(dll.ctrl, false);
    }
    else
    {
      dll.prevValue = CheckContextMenuHandler(fs2us(path), dll.wow);
      CheckButton(dll.ctrl, dll.prevValue);
    }
  }

  #endif


  CContextMenuInfo ci;
  ci.Load();

  CheckButton(IDX_SYSTEM_CASCADED_MENU, ci.Cascaded.Val);
  CheckButton(IDX_SYSTEM_ICON_IN_MENU, ci.MenuIcons.Val);
  CheckButton(IDX_EXTRACT_ELIM_DUP, ci.ElimDup.Val);

  _listView.Attach(GetItem(IDL_SYSTEM_OPTIONS));

  const UInt32 newFlags = LVS_EX_CHECKBOXES | LVS_EX_FULLROWSELECT;
  _listView.SetExtendedListViewStyle(newFlags, newFlags);

  _listView.InsertColumn(0, L"", 200);

  for (unsigned i = 0; i < ARRAY_SIZE(kMenuItems); i++)
  {
    const CContextMenuItem &menuItem = kMenuItems[i];

    UString s = LangString(menuItem.ControlID);
    if (menuItem.Flag == kCRC)
      s.SetFromAscii("CRC SHA");
    if (menuItem.Flag == kOpenAs ||
        menuItem.Flag == kCRC)
      s.AddAscii(" >");

    switch (menuItem.ControlID)
    {
      case IDS_CONTEXT_EXTRACT_TO:
      {
        s = MyFormatNew(s, LangString(IDS_CONTEXT_FOLDER));
        break;
      }
      case IDS_CONTEXT_COMPRESS_TO:
      case IDS_CONTEXT_COMPRESS_TO_EMAIL:
      {
        UString s2 = LangString(IDS_CONTEXT_ARCHIVE);
        switch (menuItem.Flag)
        {
          case kCompressTo7z:
          case kCompressTo7zEmail:
            s2.AddAscii(".7z");
            break;
          case kCompressToZip:
          case kCompressToZipEmail:
            s2.AddAscii(".zip");
            break;
        }
        s = MyFormatNew(s, s2);
        break;
      }
    }

    int itemIndex = _listView.InsertItem(i, s);
    _listView.SetCheckState(itemIndex, ((ci.Flags & menuItem.Flag) != 0));
  }

  _listView.SetColumnWidthAuto(0);
  _initMode = false;

  return CPropertyPage::OnInit();
}
Esempio n. 7
0
UString FilePath::escapeStringLiteral(const UString &str) {
	const boost::regex esc("[\\^\\.\\$\\|\\(\\)\\[\\]\\*\\+\\?\\/\\\\]");
	const std::string  rep("\\\\\\1&");

	return boost::regex_replace(std::string(str.c_str()), esc, rep, boost::match_default | boost::format_sed);
}
Esempio n. 8
0
HRESULT CPanel::CopyTo(CCopyToOptions &options, const CRecordVector<UInt32> &indices,
    UStringVector *messages,
    bool &usePassword, UString &password)
{
  CMyComPtr<IFolderOperations> folderOperations;
  if (_folder.QueryInterface(IID_IFolderOperations, &folderOperations) != S_OK)
  {
    UString errorMessage = LangString(IDS_OPERATION_IS_NOT_SUPPORTED);
    if (options.showErrorMessages)
      MessageBox(errorMessage);
    else if (messages != 0)
      messages->Add(errorMessage);
    return E_FAIL;
  }

  HRESULT res;
  {
  CPanelCopyThread extracter;

  extracter.ExtractCallbackSpec = new CExtractCallbackImp;
  extracter.ExtractCallback = extracter.ExtractCallbackSpec;

  extracter.options = &options;
  extracter.ExtractCallbackSpec->ProgressDialog = &extracter.ProgressDialog;
  extracter.ProgressDialog.CompressingMode = false;

  extracter.ExtractCallbackSpec->StreamMode = options.streamMode;

  #ifdef EXTERNAL_CODECS
  CExternalCodecs __externalCodecs;
  #else
  CMyComPtr<IUnknown> compressCodecsInfo;
  #endif

  if (indices.Size() == 1)
    extracter.FirstFilePath = GetItemRelPath(indices[0]);

  if (options.VirtFileSystem)
  {
    extracter.ExtractCallbackSpec->VirtFileSystem = options.VirtFileSystem;
    extracter.ExtractCallbackSpec->VirtFileSystemSpec = options.VirtFileSystemSpec;
  }
  extracter.ExtractCallbackSpec->ProcessAltStreams = options.includeAltStreams;

  if (!options.hashMethods.IsEmpty())
  {
    {
      CCodecs *codecs = new CCodecs;
      ThrowException_if_Error(codecs->Load());
      #ifdef EXTERNAL_CODECS
      __externalCodecs.GetCodecs = codecs;
      __externalCodecs.GetHashers = codecs;
      ThrowException_if_Error(__externalCodecs.LoadCodecs());
      #else
      compressCodecsInfo = codecs;
      #endif
    }

    extracter.Hash.SetMethods(EXTERNAL_CODECS_VARS options.hashMethods);
    extracter.ExtractCallbackSpec->SetHashMethods(&extracter.Hash);
  }
  else if (options.testMode)
  {
    extracter.ExtractCallbackSpec->SetHashCalc(&extracter.Hash);
  }

  extracter.Hash.Init();

  
  UString title;
  {
    UInt32 titleID = IDS_COPYING;
    if (options.moveMode)
      titleID = IDS_MOVING;
    else if (!options.hashMethods.IsEmpty() && options.streamMode)
    {
      titleID = IDS_CHECKSUM_CALCULATING;
      if (options.hashMethods.Size() == 1)
      {
        const UString &s = options.hashMethods[0];
        if (s != L"*")
          title = s;
      }
    }
    else if (options.testMode)
      titleID = IDS_PROGRESS_TESTING;

    if (title.IsEmpty())
      title = LangString(titleID);
  }

  UString progressWindowTitle = L"7-Zip"; // LangString(IDS_APP_TITLE);
  
  extracter.ProgressDialog.MainWindow = GetParent();
  extracter.ProgressDialog.MainTitle = progressWindowTitle;
  extracter.ProgressDialog.MainAddTitle = title + L' ';
    
  extracter.ExtractCallbackSpec->OverwriteMode = NExtract::NOverwriteMode::kAsk;
  extracter.ExtractCallbackSpec->Init();
  extracter.Indices = indices;
  extracter.FolderOperations = folderOperations;

  extracter.ExtractCallbackSpec->PasswordIsDefined = usePassword;
  extracter.ExtractCallbackSpec->Password = password;
  
  RINOK(extracter.Create(title, GetParent()));
  
  if (messages != 0)
    *messages = extracter.ProgressDialog.Sync.Messages;
  res = extracter.Result;

  if (res == S_OK && extracter.ExtractCallbackSpec->IsOK())
  {
    usePassword = extracter.ExtractCallbackSpec->PasswordIsDefined;
    password = extracter.ExtractCallbackSpec->Password;
  }
  }
  
  RefreshTitleAlways();
  return res;
}
Esempio n. 9
0
//------------------------------------------------------------------------
void AGainSimple::setDefaultMessageText (String128 text)
{
	UString str (defaultMessageText, 128);
	str.assign (text, -1);
}
Esempio n. 10
0
	UString HawkSqlite::AmendString(const UString& sValue)
	{
		AString sRet = AmendString((Char*)sValue.c_str());
		return (Utf8*)sRet.c_str();
	}
Esempio n. 11
0
OtpAuthToken::OtpAuthToken(CryptEngine* eng_, const UString& buf)
{
   U_TRACE_REGISTER_OBJECT(5, OtpAuthToken, "%p,%.*S", eng_,  U_STRING_TO_TRACE(buf))

   eng = eng_;

   U_STR_RESERVE(buffer, 1000);

   long pos;
   unsigned char ptr[1000];

#ifdef U_PROXY_UNIT
   Base64engine eng1;
   pos = eng1.decode((unsigned char*)buf.data(), (long)buf.size(), ptr);
   pos = eng->decrypt(ptr, pos, (unsigned char*)buffer.data());
#else
   pos = u_base64_decode(U_STRING_TO_PARAM(buf), ptr);
#  ifdef USE_LIBSSL
   pos = u_des3_decode(ptr, pos, (unsigned char*)buffer.data());
#  endif
#endif

   U_STR_SIZE_ADJUST_FORCE(buffer, pos);

   migrate   = false;
   valid     = (memcmp(buffer.data(), U_CONSTANT_TO_PARAM("TID=")) == 0);
   timestamp = 0;

   if (valid)
      {
      unsigned n = U_VEC_SPLIT(vec, buffer, "=; \r\n"), i = 10;

      if (n < i)
         {
         valid = false;

         return;
         }

      U_INTERNAL_ASSERT(vec[0] == U_STRING_FROM_CONSTANT("TID"))
      tid = vec[1];
      U_INTERNAL_ASSERT(vec[2] == U_STRING_FROM_CONSTANT("UID"))
      uid = vec[3];
      U_INTERNAL_ASSERT(vec[4] == U_STRING_FROM_CONSTANT("SID"))
      sid = vec[5];
      U_INTERNAL_ASSERT(vec[6] == U_STRING_FROM_CONSTANT("TS"))
      ts = vec[7];
      U_INTERNAL_ASSERT(vec[8] == U_STRING_FROM_CONSTANT("CF"))
      cf = vec[9];

      while (i < n)
         {
         if (vec[i] == U_STRING_FROM_CONSTANT("MIGRATE"))
            {
            migrate = true;

            ++i;
            }
         else
            {
            hp.push_back(vec[i]);

            ++i;

            if (i >= n)
               {
               valid = false;

               return;
               }

            hp.push_back(vec[i]);

            ++i;
            }
         }

#  ifdef U_STD_STRING
      char* _ptr = (char*) ts.c_str();
#  else
      char* _ptr = ts.data();
#  endif

      static struct tm tm;

      (void) strptime(_ptr, "%Y%m%d%H%M%S", &tm);

      timestamp = mktime(&tm);
      }
}
Esempio n. 12
0
static void UnicodeStringToMultiByte2(AString &dest, const UString &src, UINT codePage, char defaultChar, bool &defaultCharWasUsed)
{
  dest.Empty();
  defaultCharWasUsed = false;
  if (src.IsEmpty())
    return;
  {
    /*
    unsigned numRequiredBytes = src.Len() * 2;
    char *d = dest.GetBuf(numRequiredBytes);
    const wchar_t *s = (const wchar_t *)src;
    unsigned i;
    
    for (i = 0;;)
    {
      wchar_t c = s[i];
      if (c >= 0x80 || c == 0)
        break;
      d[i++] = (char)c;
    }
    
    if (i != src.Len())
    {
      BOOL defUsed = FALSE;
      defaultChar = defaultChar;

      bool isUtf = (codePage == CP_UTF8 || codePage == CP_UTF7);
      unsigned len = WideCharToMultiByte(codePage, 0, s + i, src.Len() - i,
          d + i, numRequiredBytes + 1 - i,
          (isUtf ? NULL : &defaultChar),
          (isUtf ? NULL : &defUsed));
      defaultCharWasUsed = (defUsed != FALSE);
      if (len == 0)
        throw 282229;
      i += len;
    }

    d[i] = 0;
    dest.ReleaseBuf_SetLen(i);
    */

    /*
    if (codePage != CP_UTF7)
    {
      const wchar_t *s = (const wchar_t *)src;
      unsigned i;
      for (i = 0;; i++)
      {
        wchar_t c = s[i];
        if (c >= 0x80 || c == 0)
          break;
      }
      
      if (s[i] == 0)
      {
        char *d = dest.GetBuf(src.Len());
        for (i = 0;;)
        {
          wchar_t c = s[i];
          if (c == 0)
            break;
          d[i++] = (char)c;
        }
        d[i] = 0;
        dest.ReleaseBuf_SetLen(i);
        return;
      }
    }
    */

    unsigned len = WideCharToMultiByte(codePage, 0, src, src.Len(), NULL, 0, NULL, NULL);
    if (len == 0)
    {
      if (GetLastError() != 0)
        throw 282228;
    }
    else
    {
      BOOL defUsed = FALSE;
      bool isUtf = (codePage == CP_UTF8 || codePage == CP_UTF7);
      // defaultChar = defaultChar;
      len = WideCharToMultiByte(codePage, 0, src, src.Len(),
          dest.GetBuf(len), len,
          (isUtf ? NULL : &defaultChar),
          (isUtf ? NULL : &defUsed)
          );
      if (!isUtf)
        defaultCharWasUsed = (defUsed != FALSE);
      if (len == 0)
        throw 282228;
      dest.ReleaseBuf_SetEnd(len);
    }
  }
}
String::String(const UString& str)
{
    if (str.isNull())
        return;
    m_impl = StringImpl::create(str);
}
Esempio n. 14
0
HRESULT CPanel::RefreshListCtrl(const UString &focusedName, int focusedPos, bool selectFocused,
    const UStringVector &selectedNames)
{
  _dontShowMode = false;
  LoadFullPathAndShow();
  // OutputDebugStringA("=======\n");
  // OutputDebugStringA("s1 \n");
  CDisableTimerProcessing timerProcessing(*this);
  CDisableNotify disableNotify(*this);

  if (focusedPos < 0)
    focusedPos = 0;

  _listView.SetRedraw(false);
  // m_RedrawEnabled = false;

  LVITEMW item;
  ZeroMemory(&item, sizeof(item));
  
  // DWORD tickCount0 = GetTickCount();
  _enableItemChangeNotify = false;
  _listView.DeleteAllItems();
  _enableItemChangeNotify = true;


  int listViewItemCount = 0;

  _selectedStatusVector.Clear();
  // _realIndices.Clear();
  _startGroupSelect = 0;

  _selectionIsDefined = false;
  
  // m_Files.Clear();

  if (!_folder)
  {
    // throw 1;
    SetToRootFolder();
  }
  
  _headerToolBar.EnableButton(kParentFolderID, !IsRootFolder());

  {
    CMyComPtr<IFolderSetFlatMode> folderSetFlatMode;
    _folder.QueryInterface(IID_IFolderSetFlatMode, &folderSetFlatMode);
    if (folderSetFlatMode)
      folderSetFlatMode->SetFlatMode(BoolToInt(_flatMode));
  }

  /*
  {
    CMyComPtr<IFolderSetShowNtfsStreamsMode> setShow;
    _folder.QueryInterface(IID_IFolderSetShowNtfsStreamsMode, &setShow);
    if (setShow)
      setShow->SetShowNtfsStreamsMode(BoolToInt(_showNtfsStrems_Mode));
  }
  */

  // DWORD tickCount1 = GetTickCount();
  RINOK(_folder->LoadItems());
  // DWORD tickCount2 = GetTickCount();
  RINOK(InitColumns());

  // OutputDebugString(TEXT("Start Dir\n"));
  UInt32 numItems;
  _folder->GetNumberOfItems(&numItems);

  bool showDots = _showDots && !IsRootFolder();

  _listView.SetItemCount(numItems + (showDots ? 1 : 0));

  _selectedStatusVector.ClearAndReserve(numItems);
  int cursorIndex = -1;

  CMyComPtr<IFolderGetSystemIconIndex> folderGetSystemIconIndex;
  if (!Is_Slow_Icon_Folder() || _showRealFileIcons)
    _folder.QueryInterface(IID_IFolderGetSystemIconIndex, &folderGetSystemIconIndex);

  if (!IsFSFolder())
  {
    CMyComPtr<IGetFolderArcProps> getFolderArcProps;
    _folder.QueryInterface(IID_IGetFolderArcProps, &getFolderArcProps);
    _thereAreDeletedItems = false;
    if (getFolderArcProps)
    {
      CMyComPtr<IFolderArcProps> arcProps;
      getFolderArcProps->GetFolderArcProps(&arcProps);
      if (arcProps)
      {
        UInt32 numLevels;
        if (arcProps->GetArcNumLevels(&numLevels) != S_OK)
          numLevels = 0;
        NCOM::CPropVariant prop;
        if (arcProps->GetArcProp(numLevels - 1, kpidIsDeleted, &prop) == S_OK)
          if (prop.vt == VT_BOOL && VARIANT_BOOLToBool(prop.boolVal))
            _thereAreDeletedItems = true;
      }
    }
  }

  if (showDots)
  {
    UString itemName = L"..";
    item.iItem = listViewItemCount;
    if (itemName == focusedName)
      cursorIndex = item.iItem;
    item.mask = LVIF_TEXT | LVIF_PARAM | LVIF_IMAGE;
    int subItem = 0;
    item.iSubItem = subItem++;
    item.lParam = kParentIndex;
    // item.pszText = const_cast<wchar_t *>((const wchar_t *)itemName);
    item.pszText = LPSTR_TEXTCALLBACKW;
    UInt32 attrib = FILE_ATTRIBUTE_DIRECTORY;
    item.iImage = _extToIconMap.GetIconIndex(attrib, itemName);
    if (item.iImage < 0)
      item.iImage = 0;
    if (_listView.InsertItem(&item) == -1)
      return E_FAIL;
    listViewItemCount++;
  }
  
  // OutputDebugStringA("S1\n");

  UString correctedName;
  UString itemName;
  UString relPath;
  
  for (UInt32 i = 0; i < numItems; i++)
  {
    const wchar_t *name = NULL;
    unsigned nameLen = 0;
    
    if (_folderGetItemName)
      _folderGetItemName->GetItemName(i, &name, &nameLen);
    if (!name)
    {
      GetItemName(i, itemName);
      name = itemName;
      nameLen = itemName.Len();
    }
  
    bool selected = false;
    
    if (!focusedName.IsEmpty() || !selectedNames.IsEmpty())
    {
      relPath.Empty();

      // relPath += GetItemPrefix(i);
      // change it (_flatMode)
      if (i != kParentIndex && _flatMode)
      {
        const wchar_t *prefix = NULL;
        if (_folderGetItemName)
        {
          unsigned prefixLen = 0;
          _folderGetItemName->GetItemPrefix(i, &prefix, &prefixLen);
          if (prefix)
            relPath += prefix;
        }
        if (!prefix)
        {
          NCOM::CPropVariant prop;
          if (_folder->GetProperty(i, kpidPrefix, &prop) != S_OK)
            throw 2723400;
          if (prop.vt == VT_BSTR)
            relPath += prop.bstrVal;
        }
      }
      relPath += name;
      if (relPath == focusedName)
        cursorIndex = listViewItemCount;
      if (selectedNames.FindInSorted(relPath) >= 0)
        selected = true;
    }
    
    _selectedStatusVector.AddInReserved(selected);

    item.mask = LVIF_TEXT | LVIF_PARAM | LVIF_IMAGE;

    if (!_mySelectMode)
      if (selected)
      {
        item.mask |= LVIF_STATE;
        item.state = LVIS_SELECTED;
      }
  
    int subItem = 0;
    item.iItem = listViewItemCount;
    
    item.iSubItem = subItem++;
    item.lParam = i;
    
    /*
    int finish = nameLen - 4;
    int j;
    for (j = 0; j < finish; j++)
    {
      if (name[j    ] == ' ' &&
          name[j + 1] == ' ' &&
          name[j + 2] == ' ' &&
          name[j + 3] == ' ' &&
          name[j + 4] == ' ')
        break;
    }
    if (j < finish)
    {
      correctedName.Empty();
      correctedName = L"virus";
      int pos = 0;
      for (;;)
      {
        int posNew = itemName.Find(L"     ", pos);
        if (posNew < 0)
        {
          correctedName += itemName.Ptr(pos);
          break;
        }
        correctedName += itemName.Mid(pos, posNew - pos);
        correctedName += L" ... ";
        pos = posNew;
        while (itemName[++pos] == ' ');
      }
      item.pszText = const_cast<wchar_t *>((const wchar_t *)correctedName);
    }
    else
    */
    {
      // item.pszText = const_cast<wchar_t *>((const wchar_t *)name);
      item.pszText = LPSTR_TEXTCALLBACKW;
      /* LPSTR_TEXTCALLBACKW works, but in some cases there are problems,
      since we block notify handler. */
    }

    UInt32 attrib = 0;
    // for (int yyy = 0; yyy < 6000000; yyy++) {
    NCOM::CPropVariant prop;
    RINOK(_folder->GetProperty(i, kpidAttrib, &prop));
    if (prop.vt == VT_UI4)
    {
      // char s[256]; sprintf(s, "attrib = %7x", attrib); OutputDebugStringA(s);
      attrib = prop.ulVal;
    }
    else if (IsItem_Folder(i))
      attrib |= FILE_ATTRIBUTE_DIRECTORY;
    // }

    bool defined = false;
  
    if (folderGetSystemIconIndex)
    {
      folderGetSystemIconIndex->GetSystemIconIndex(i, &item.iImage);
      defined = (item.iImage > 0);
    }
    if (!defined)
    {
      if (_currentFolderPrefix.IsEmpty())
      {
        int iconIndexTemp;
        GetRealIconIndex(us2fs((UString)name) + FCHAR_PATH_SEPARATOR, attrib, iconIndexTemp);
        item.iImage = iconIndexTemp;
      }
      else
      {
        item.iImage = _extToIconMap.GetIconIndex(attrib, name);
      }
    }
    
    if (item.iImage < 0)
      item.iImage = 0;

    if (_listView.InsertItem(&item) == -1)
      return E_FAIL;
    listViewItemCount++;
  }
  
  // OutputDebugStringA("End2\n");

  if (_listView.GetItemCount() > 0 && cursorIndex >= 0)
    SetFocusedSelectedItem(cursorIndex, selectFocused);
  // DWORD tickCount3 = GetTickCount();
  SetSortRawStatus();
  _listView.SortItems(CompareItems, (LPARAM)this);
  // DWORD tickCount4 = GetTickCount();
  if (cursorIndex < 0 && _listView.GetItemCount() > 0)
  {
    if (focusedPos >= _listView.GetItemCount())
      focusedPos = _listView.GetItemCount() - 1;
    // we select item only in showDots mode.
    SetFocusedSelectedItem(focusedPos, showDots);
  }
  // m_RedrawEnabled = true;
  // DWORD tickCount5 = GetTickCount();
  _listView.EnsureVisible(_listView.GetFocusedItem(), false);
  // DWORD tickCount6 = GetTickCount();

  disableNotify.SetMemMode_Enable();
  disableNotify.Restore();
  _listView.SetRedraw(true);
  // DWORD tickCount7 = GetTickCount();
  _listView.InvalidateRect(NULL, true);
  // DWORD tickCount8 = GetTickCount();
  // OutputDebugStringA("End1\n");
  /*
  _listView.UpdateWindow();
  */
  Refresh_StatusBar();
  // DWORD tickCount9 = GetTickCount();
  /*
  char s[256];
  sprintf(s,
      // "attribMap = %5d, extMap = %5d, "
      "delete = %5d, load = %5d, list = %5d, sort = %5d, end = %5d",
      // _extToIconMap._attribMap.Size(),
      // _extToIconMap._extMap.Size(),
      tickCount1 - tickCount0,
      tickCount2 - tickCount1,
      tickCount3 - tickCount2,
      tickCount4 - tickCount3,
      tickCount5 - tickCount4
      );
  sprintf(s,
      "5 = %5d, 6 = %5d, 7 = %5d, 8 = %5d, 9 = %5d",
      tickCount5 - tickCount4,
      tickCount6 - tickCount5,
      tickCount7 - tickCount6,
      tickCount8 - tickCount7,
      tickCount9 - tickCount8
      );
  OutputDebugStringA(s);
  */
  return S_OK;
}
Esempio n. 15
0
void CApp::OnCopy(bool move, bool copyToSame, int srcPanelIndex)
{
  int destPanelIndex = (NumPanels <= 1) ? srcPanelIndex : (1 - srcPanelIndex);
  CPanel &srcPanel = Panels[srcPanelIndex];
  CPanel &destPanel = Panels[destPanelIndex];

  CPanel::CDisableTimerProcessing disableTimerProcessing1(destPanel);
  CPanel::CDisableTimerProcessing disableTimerProcessing2(srcPanel);

  if (!srcPanel.DoesItSupportOperations())
  {
    srcPanel.MessageBox(LangString(IDS_OPERATION_IS_NOT_SUPPORTED, 0x03020208));
    return;
  }

  CRecordVector<UInt32> indices;
  UString destPath;
  bool useDestPanel = false;

  {
    if (copyToSame)
    {
      int focusedItem = srcPanel._listView.GetFocusedItem();
      if (focusedItem < 0)
        return;
      int realIndex = srcPanel.GetRealItemIndex(focusedItem);
      if (realIndex == kParentIndex)
        return;
      indices.Add(realIndex);
      destPath = srcPanel.GetItemName(realIndex);
    }
    else
    {
      srcPanel.GetOperatedItemIndices(indices);
      if (indices.Size() == 0)
        return;
      destPath = destPanel._currentFolderPrefix;
      if (NumPanels == 1)
        ReducePathToRealFileSystemPath(destPath);
    }

    CCopyDialog copyDialog;
    UStringVector copyFolders;
    ReadCopyHistory(copyFolders);

    copyDialog.Strings = copyFolders;
    copyDialog.Value = destPath;
    
    copyDialog.Title = move ? 
        LangString(IDS_MOVE, 0x03020202):
        LangString(IDS_COPY, 0x03020201);
    copyDialog.Static = move ? 
        LangString(IDS_MOVE_TO, 0x03020204):
        LangString(IDS_COPY_TO, 0x03020203);

    if (copyDialog.Create(srcPanel.GetParent()) == IDCANCEL)
      return;

    destPath = copyDialog.Value;

    if (!IsPathAbsolute(destPath))
    {
      if (!srcPanel.IsFSFolder())
      {
        srcPanel.MessageBox(LangString(IDS_OPERATION_IS_NOT_SUPPORTED, 0x03020208));
        return;
      }
      destPath = srcPanel._currentFolderPrefix + destPath;
    }

    if (indices.Size() > 1 || (destPath.Length() > 0 && destPath.ReverseFind('\\') == destPath.Length() - 1) || 
        IsThereFolderOfPath(destPath))
    {
      NDirectory::CreateComplexDirectory(destPath);
      NName::NormalizeDirPathPrefix(destPath);
      if (!CheckFolderPath(destPath))
      {
        if (NumPanels < 2 || destPath != destPanel._currentFolderPrefix || !destPanel.DoesItSupportOperations())
        {
          srcPanel.MessageBox(LangString(IDS_OPERATION_IS_NOT_SUPPORTED, 0x03020208));
          return;
        }
        useDestPanel = true;
      }
    }
    else
    {
      int pos = destPath.ReverseFind('\\');
      if (pos >= 0)
      {
        UString prefix = destPath.Left(pos + 1);
        NDirectory::CreateComplexDirectory(prefix);
        if (!CheckFolderPath(prefix))
        {
          srcPanel.MessageBox(LangString(IDS_OPERATION_IS_NOT_SUPPORTED, 0x03020208));
          return;
        }
      }
    }

    AddUniqueStringToHeadOfList(copyFolders, destPath);
    while (copyFolders.Size() > 20)
      copyFolders.DeleteBack();
    SaveCopyHistory(copyFolders);
  }

  bool useSrcPanel = (!useDestPanel || !srcPanel.IsFSFolder() || destPanel.IsFSFolder());
  bool useTemp = useSrcPanel && useDestPanel;
  NFile::NDirectory::CTempDirectoryW tempDirectory;
  UString tempDirPrefix;
  if (useTemp)
  {
    tempDirectory.Create(kTempDirPrefix);
    tempDirPrefix = tempDirectory.GetPath();
    NFile::NName::NormalizeDirPathPrefix(tempDirPrefix);
  }

  CSelectedState srcSelState;
  CSelectedState destSelState;
  srcPanel.SaveSelectedState(srcSelState);
  destPanel.SaveSelectedState(destSelState);

  HRESULT result;
  if (useSrcPanel)
  {
    UString folder = useTemp ? tempDirPrefix : destPath;
    result = srcPanel.CopyTo(indices, folder, move, true, 0);
    if (result != S_OK)
    {
      disableTimerProcessing1.Restore();
      disableTimerProcessing2.Restore();
      // For Password:
      srcPanel.SetFocusToList();
      if (result != E_ABORT)
        srcPanel.MessageBoxError(result, L"Error");
      return;
    }
  }
  
  if (useDestPanel)
  {
    UStringVector filePaths;
    UString folderPrefix;
    if (useTemp)
      folderPrefix = tempDirPrefix;
    else
      folderPrefix = srcPanel._currentFolderPrefix;
    filePaths.Reserve(indices.Size());
    for(int i = 0; i < indices.Size(); i++)
      filePaths.Add(srcPanel.GetItemRelPath(indices[i]));

    result = destPanel.CopyFrom(folderPrefix, filePaths, true, 0);

    if (result != S_OK)
    {
      disableTimerProcessing1.Restore();
      disableTimerProcessing2.Restore();
      // For Password:
      srcPanel.SetFocusToList();
      if (result != E_ABORT)
        srcPanel.MessageBoxError(result, L"Error");
      return;
    }
  }

  RefreshTitleAlways();
  if (copyToSame || move)
  {
    srcPanel.RefreshListCtrl(srcSelState);
  }
  if (!copyToSame)
  {
    destPanel.RefreshListCtrl(destSelState);
    srcPanel.KillSelection();
  }
  disableTimerProcessing1.Restore();
  disableTimerProcessing2.Restore();
  srcPanel.SetFocusToList();
}
Esempio n. 16
0
	void TextView::update(const UString& _text, IFont* _font, int _height, Align _align, VertexColourType _format, int _maxWidth)
	{
		mFontHeight = _height;

		// массив для быстрой конвертации цветов
		static const char convert_colour[64] =
		{
			0,  1,  2,  3,  4,  5,  6, 7, 8, 9, 0, 0, 0, 0, 0, 0,
			0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0
		};

		mViewSize.clear();

		RollBackPoint roll_back;
		IntSize result;
		float width = 0.0f;
		size_t count = 0;
		mLength = 0;
		mLineInfo.clear();
		LineInfo line_info;
		int font_height = _font->getDefaultHeight();

		UString::const_iterator end = _text.end();
		UString::const_iterator index = _text.begin();

		/*if (index == end)
			return;*/

		result.height += _height;

		for (; index != end; ++index)
		{
			Char character = *index;

			// новая строка
			if (character == FontCodeType::CR
				|| character == FontCodeType::NEL
				|| character == FontCodeType::LF)
			{
				if (character == FontCodeType::CR)
				{
					UString::const_iterator peeki = index;
					++peeki;
					if ((peeki != end) && (*peeki == FontCodeType::LF))
						index = peeki; // skip both as one newline
				}

				line_info.width = (int)ceil(width);
				line_info.count = count;
				mLength += line_info.count + 1;

				result.height += _height;
				setMax(result.width, line_info.width);
				width = 0;
				count = 0;

				mLineInfo.push_back(line_info);
				line_info.clear();

				// отменяем откат
				roll_back.clear();

				continue;
			}
			// тег
			else if (character == L'#')
			{
				// берем следующий символ
				++ index;
				if (index == end)
				{
					--index;    // это защита
					continue;
				}

				character = *index;
				// если два подряд, то рисуем один шарп, если нет то меняем цвет
				if (character != L'#')
				{
					// парсим первый символ
					uint32 colour = convert_colour[(character - 48) & 0x3F];

					// и еще пять символов после шарпа
					for (char i = 0; i < 5; i++)
					{
						++ index;
						if (index == end)
						{
							--index;    // это защита
							continue;
						}
						colour <<= 4;
						colour += convert_colour[ ((*index) - 48) & 0x3F ];
					}

					// если нужно, то меняем красный и синий компоненты
					texture_utility::convertColour(colour, _format);

					line_info.simbols.push_back( CharInfo(colour) );

					continue;
				}
			}

			GlyphInfo* info = _font->getGlyphInfo(character);

			if (info == nullptr)
				continue;

			if (FontCodeType::Space == character)
			{
				roll_back.set(line_info.simbols.size(), index, count, width);
			}
			else if (FontCodeType::Tab == character)
			{
				roll_back.set(line_info.simbols.size(), index, count, width);
			}

			float char_width = info->width;
			float char_height = info->height;
			float char_advance = info->advance;
			float char_bearingX = info->bearingX;
			float char_bearingY = info->bearingY;

			if (_height != font_height)
			{
				float scale = (float)_height / font_height;

				char_width *= scale;
				char_height *= scale;
				char_advance *= scale;
				char_bearingX *= scale;
				char_bearingY *= scale;
			}

			float char_fullAdvance = char_bearingX + char_advance;

			// перенос слов
			if (_maxWidth != -1
				&& (width + char_fullAdvance) > _maxWidth
				&& !roll_back.empty())
			{
				// откатываем до последнего пробела
				width = roll_back.getWidth();
				count = roll_back.getCount();
				index = roll_back.getTextIter();
				line_info.simbols.erase(line_info.simbols.begin() + roll_back.getPosition(), line_info.simbols.end());

				// запоминаем место отката, как полную строку
				line_info.width = (int)ceil(width);
				line_info.count = count;
				mLength += line_info.count + 1;

				result.height += _height;
				setMax(result.width, line_info.width);
				width = 0;
				count = 0;

				mLineInfo.push_back(line_info);
				line_info.clear();

				// отменяем откат
				roll_back.clear();

				continue;
			}

			line_info.simbols.push_back(CharInfo(info->uvRect, char_width, char_height, char_advance, char_bearingX, char_bearingY));
			width += char_fullAdvance;
			count ++;
		}

		line_info.width = (int)ceil(width);
		line_info.count = count;
		mLength += line_info.count;

		mLineInfo.push_back(line_info);

		setMax(result.width, line_info.width);

		// теперь выравниванием строки
		for (VectorLineInfo::iterator line = mLineInfo.begin(); line != mLineInfo.end(); ++line)
		{
			if (_align.isRight())
				line->offset = result.width - line->width;
			else if (_align.isHCenter())
				line->offset = (result.width - line->width) / 2;
		}

		mViewSize = result;
	}
Esempio n. 17
0
PassRefPtr<OpaqueJSString> OpaqueJSString::create(const UString& ustring)
{
    if (!ustring.isNull())
        return adoptRef(new OpaqueJSString(ustring.data(), ustring.size()));
    return 0;
}
Esempio n. 18
0
ULog::ULog(const UString& path, uint32_t _size, const char* dir_log_gz) : UFile(path, 0)
{
   U_TRACE_REGISTER_OBJECT(0, ULog, "%V,%u,%S", path.rep, _size, dir_log_gz)

   lock         = 0;
   ptr_log_data = 0;
   log_file_sz  =
   log_gzip_sz  = 0;

   U_Log_start_stop_msg(this) = false;

#ifdef USE_LIBZ
     buf_path_compress = 0;
   index_path_compress = 0;
#endif

   if (UFile::getPath().equal(U_CONSTANT_TO_PARAM("syslog")))
      {
      U_Log_syslog(this) = true;

#  ifndef _MSWINDOWS_
      openlog(u_progname, LOG_PID, LOG_LOCAL0);
#  endif

      return;
      }

   if (UFile::creat(O_RDWR | O_APPEND, 0664) == false)
      {
#  ifndef U_COVERITY_FALSE_POSITIVE
      U_ERROR("cannot creat log file %.*S", U_FILE_TO_TRACE(*this));
#  endif

      return;
      }

   /**
    * typedef struct log_data {
    *  uint32_t file_ptr;
    *  uint32_t file_page;
    *  uint32_t gzip_len;
    *  sem_t lock_shared;
    *  char spinlock_shared[1];
    *  // --------------> maybe unnamed array of char for gzip compression...
    * } log_data;
    */

   ptr_log_data = U_MALLOC_TYPE(log_data);

   ptr_log_data->file_ptr = 0;

   if (_size)
      {
      uint32_t file_size = UFile::size();

      bool bsize = (file_size != _size);

      if ((bsize && UFile::ftruncate(_size) == false) ||
          UFile::memmap(PROT_READ | PROT_WRITE) == false)
         {
         U_ERROR("cannot init log file %.*S", U_FILE_TO_TRACE(*this));

         return;
         }

      if (bsize) ptr_log_data->file_ptr = file_size; // append mode
      else
         {
         // NB: we can have a previous crash without resizing the file or we are an other process (apache like log)...

         char* ptr = (char*) u_find(UFile::map, file_size, U_CONSTANT_TO_PARAM(U_MARK_END));

         if (ptr)
            {
            ptr_log_data->file_ptr = ptr - UFile::map;

            // NB: we can be an other process that manage this file (apache like log)...

            u_put_unalignedp64(ptr,    U_MULTICHAR_CONSTANT64('\n','\n','\n','\n','\n','\n','\n','\n'));
            u_put_unalignedp64(ptr+8,  U_MULTICHAR_CONSTANT64('\n','\n','\n','\n','\n','\n','\n','\n'));
            u_put_unalignedp64(ptr+16, U_MULTICHAR_CONSTANT64('\n','\n','\n','\n','\n','\n','\n','\n'));

            UFile::msync(ptr + U_CONSTANT_SIZE(U_MARK_END), UFile::map, MS_SYNC);
            }

         U_INTERNAL_ASSERT_MINOR(ptr_log_data->file_ptr, UFile::st_size)
         }

      log_file_sz = UFile::st_size;
      }

   U_INTERNAL_ASSERT(ptr_log_data->file_ptr <= UFile::st_size)

   lock                    = U_NEW(ULock);
   U_Log_syslog(this)      = false;
   ptr_log_data->gzip_len  = 0;
   ptr_log_data->file_page = ptr_log_data->file_ptr;

#ifdef USE_LIBZ
   char suffix[32];
   uint32_t len_suffix = u__snprintf(suffix, sizeof(suffix), ".%4D.gz");

   buf_path_compress = U_NEW(UString(MAX_FILENAME_LEN));

   char* ptr = buf_path_compress->data();

   if (dir_log_gz == 0)
      {
#  ifndef U_COVERITY_FALSE_POSITIVE // Uninitialized pointer read (UNINIT)
      (void) UFile::setPathFromFile(*this, ptr, suffix, len_suffix);
#  endif

      buf_path_compress->size_adjust();

      index_path_compress = (buf_path_compress->size() - len_suffix + 1);
      }
   else
      {
      UString name = UFile::getName();
      uint32_t len = u__strlen(dir_log_gz, __PRETTY_FUNCTION__), sz = name.size();

      (void) memcpy(ptr, dir_log_gz, len);

       ptr  += len;
      *ptr++ = '/';

      buf_path_compress->size_adjust(len + 1 + sz + len_suffix);

      (void) memcpy(ptr, name.data(), sz);
                    ptr            += sz;
      (void) memcpy(ptr, suffix, len_suffix);

      index_path_compress = buf_path_compress->distance(ptr) + 1;
      }
#endif
}
Esempio n. 19
0
HRESULT CArc::OpenStream(
    CCodecs *codecs,
    int formatIndex,
    IInStream *stream,
    ISequentialInStream *seqStream,
    IArchiveOpenCallback *callback)
{
  Archive.Release();
  ErrorMessage.Empty();
  const UString fileName = ExtractFileNameFromPath(Path);
  UString extension;
  {
    int dotPos = fileName.ReverseFind(L'.');
    if (dotPos >= 0)
      extension = fileName.Mid(dotPos + 1);
  }
  CIntVector orderIndices;
  if (formatIndex >= 0)
    orderIndices.Add(formatIndex);
  else
  {

  int i;
  int numFinded = 0;
  for (i = 0; i < codecs->Formats.Size(); i++)
    if (codecs->Formats[i].FindExtension(extension) >= 0)
      orderIndices.Insert(numFinded++, i);
    else
      orderIndices.Add(i);
  
  if (!stream)
  {
    if (numFinded != 1)
      return E_NOTIMPL;
    orderIndices.DeleteFrom(1);
  }

  #ifndef _SFX
  if (orderIndices.Size() >= 2 && (numFinded == 0 || extension.CompareNoCase(L"exe") == 0))
  {
    CIntVector orderIndices2;
    CByteBuffer byteBuffer;
    const size_t kBufferSize = (1 << 21);
    byteBuffer.SetCapacity(kBufferSize);
    RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL));
    size_t processedSize = kBufferSize;
    RINOK(ReadStream(stream, byteBuffer, &processedSize));
    if (processedSize == 0)
      return S_FALSE;

    const Byte *buf = byteBuffer;
    CByteBuffer hashBuffer;
    const UInt32 kNumVals = 1 << (kNumHashBytes * 8);
    hashBuffer.SetCapacity(kNumVals);
    Byte *hash = hashBuffer;
    memset(hash, 0xFF, kNumVals);
    Byte prevs[256];
    if (orderIndices.Size() >= 256)
      return S_FALSE;
    int i;
    for (i = 0; i < orderIndices.Size(); i++)
    {
      const CArcInfoEx &ai = codecs->Formats[orderIndices[i]];
      const CByteBuffer &sig = ai.StartSignature;
      if (sig.GetCapacity() < kNumHashBytes)
        continue;
      UInt32 v = HASH_VAL(sig, 0);
      prevs[i] = hash[v];
      hash[v] = (Byte)i;
    }

    processedSize -= (kNumHashBytes - 1);
    for (UInt32 pos = 0; pos < processedSize; pos++)
    {
      for (; pos < processedSize && hash[HASH_VAL(buf, pos)] == 0xFF; pos++);
      if (pos == processedSize)
        break;
      UInt32 v = HASH_VAL(buf, pos);
      Byte *ptr = &hash[v];
      int i = *ptr;
      do
      {
        int index = orderIndices[i];
        const CArcInfoEx &ai = codecs->Formats[index];
        const CByteBuffer &sig = ai.StartSignature;
        if (sig.GetCapacity() != 0 && pos + sig.GetCapacity() <= processedSize + (kNumHashBytes - 1) &&
            TestSignature(buf + pos, sig, sig.GetCapacity()))
        {
          orderIndices2.Add(index);
          orderIndices[i] = 0xFF;
          *ptr = prevs[i];
        }
        else
          ptr = &prevs[i];
        i = *ptr;
      }
      while (i != 0xFF);
    }
    
    for (i = 0; i < orderIndices.Size(); i++)
    {
      int val = orderIndices[i];
      if (val != 0xFF)
        orderIndices2.Add(val);
    }
    orderIndices = orderIndices2;
  }
  else if (extension == L"000" || extension == L"001")
  {
    CByteBuffer byteBuffer;
    const size_t kBufferSize = (1 << 10);
    byteBuffer.SetCapacity(kBufferSize);
    Byte *buffer = byteBuffer;
    RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL));
    size_t processedSize = kBufferSize;
    RINOK(ReadStream(stream, buffer, &processedSize));
    if (processedSize >= 16)
    {
      Byte kRarHeader[] = {0x52 , 0x61, 0x72, 0x21, 0x1a, 0x07, 0x00};
      if (TestSignature(buffer, kRarHeader, 7) && buffer[9] == 0x73 && (buffer[10] & 1) != 0)
      {
        for (int i = 0; i < orderIndices.Size(); i++)
        {
          int index = orderIndices[i];
          const CArcInfoEx &ai = codecs->Formats[index];
          if (ai.Name.CompareNoCase(L"rar") != 0)
            continue;
          orderIndices.Delete(i--);
          orderIndices.Insert(0, index);
          break;
        }
      }
    }
  }
  if (orderIndices.Size() >= 2)
  {
    int isoIndex = codecs->FindFormatForArchiveType(L"iso");
    int udfIndex = codecs->FindFormatForArchiveType(L"udf");
    int iIso = -1;
    int iUdf = -1;
    for (int i = 0; i < orderIndices.Size(); i++)
    {
      if (orderIndices[i] == isoIndex) iIso = i;
      if (orderIndices[i] == udfIndex) iUdf = i;
    }
    if (iUdf > iIso && iIso >= 0)
    {
      orderIndices[iUdf] = isoIndex;
      orderIndices[iIso] = udfIndex;
    }
  }

  #endif
  }

  for (int i = 0; i < orderIndices.Size(); i++)
  {
    if (stream)
    {
      RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL));
    }
    CMyComPtr<IInArchive> archive;

    FormatIndex = orderIndices[i];
    RINOK(codecs->CreateInArchive(FormatIndex, archive));
    if (!archive)
      continue;

    #ifdef EXTERNAL_CODECS
    {
      CMyComPtr<ISetCompressCodecsInfo> setCompressCodecsInfo;
      archive.QueryInterface(IID_ISetCompressCodecsInfo, (void **)&setCompressCodecsInfo);
      if (setCompressCodecsInfo)
      {
        RINOK(setCompressCodecsInfo->SetCompressCodecsInfo(codecs));
      }
    }
    #endif

    // OutputDebugStringW(codecs->Formats[FormatIndex].Name);

    HRESULT result;
    if (stream)
      result = archive->Open(stream, &kMaxCheckStartPosition, callback);
    else
    {
      CMyComPtr<IArchiveOpenSeq> openSeq;
      archive.QueryInterface(IID_IArchiveOpenSeq, (void **)&openSeq);
      if (!openSeq)
        return E_NOTIMPL;
      result = openSeq->OpenSeq(seqStream);
    }

    if (result == S_FALSE)
      continue;
    RINOK(result);

    {
      NCOM::CPropVariant prop;
      archive->GetArchiveProperty(kpidError, &prop);
      if (prop.vt != VT_EMPTY)
        ErrorMessage = (prop.vt == VT_BSTR) ? prop.bstrVal : L"Unknown error";
    }
    
    Archive = archive;
    const CArcInfoEx &format = codecs->Formats[FormatIndex];
    if (format.Exts.Size() == 0)
      DefaultName = GetDefaultName2(fileName, L"", L"");
    else
    {
      int subExtIndex = format.FindExtension(extension);
      if (subExtIndex < 0)
        subExtIndex = 0;
      const CArcExtInfo &extInfo = format.Exts[subExtIndex];
      DefaultName = GetDefaultName2(fileName, extInfo.Ext, extInfo.AddExt);
    }
    return S_OK;
  }
  return S_FALSE;
}
Esempio n. 20
0
static inline void documentWrite(ExecState* exec, HTMLDocument* document, NewlineRequirement addNewline)
{
    // DOM only specifies single string argument, but browsers allow multiple or no arguments.

    size_t size = exec->argumentCount();

    UString firstString = exec->argument(0).toString(exec);
#if defined(JSC_TAINTED)
    unsigned int tainted = 0;
    if (firstString.isTainted()) {
	TaintedStructure trace_struct;
        trace_struct.taintedno = firstString.isTainted();
        trace_struct.internalfunc = "documentWrite";
        trace_struct.jsfunc = "document.write/writeln";
        trace_struct.action = "sink";
        trace_struct.value = TaintedUtils::UString2string(firstString);

        TaintedTrace* trace = TaintedTrace::getInstance();
        trace->addTaintedTrace(trace_struct);
	tainted = firstString.isTainted();
    }
#endif
    SegmentedString segmentedString = ustringToString(firstString);
    if (size != 1) {
        if (!size)
            segmentedString.clear();
        else {
            for (size_t i = 1; i < size; ++i) {
                UString subsequentString = exec->argument(i).toString(exec);
#if defined(JSC_TAINTED)
	        unsigned int c_tainted = 0;
    		if (subsequentString.isTainted()) {
		    c_tainted = subsequentString.isTainted();
		}
		if (c_tainted) {
		    TaintedStructure trace_struct;
		    trace_struct.taintedno = c_tainted;
		    trace_struct.internalfunc = "documentWrite";
		    trace_struct.jsfunc = "document.write/writeln";
		    trace_struct.action = "sink";
		    trace_struct.value = TaintedUtils::UString2string(subsequentString);

		    TaintedTrace* trace = TaintedTrace::getInstance();
		    trace->addTaintedTrace(trace_struct);
		    tainted = c_tainted;
    		}
#endif
                segmentedString.append(SegmentedString(ustringToString(subsequentString)));
            }
        }
    }

    if (addNewline)
        segmentedString.append(SegmentedString(String(&newlineCharacter, 1)));

    Document* activeDocument = asJSDOMWindow(exec->lexicalGlobalObject())->impl()->document();
    document->write(segmentedString, activeDocument);
#if defined(JSC_TAINTED)
    if (tainted) {
	activeDocument->setTainted(tainted);
    }
#endif
}
Esempio n. 21
0
bool FilePath::isRegularFile(const UString &p) {
	return (exists(p.c_str()) && is_regular_file(p.c_str()));
}
Esempio n. 22
0
STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID,  PROPVARIANT *value)
{
  COM_TRY_BEGIN
  NWindows::NCOM::CPropVariant propVariant;
  const CItemEx &item = _items[index];
  switch(propID)
  {
    case kpidPath:
    {
      UString s = NItemName::WinNameToOSName(MultiByteToUnicodeString(item.GetName(), CP_OEMCP));
      if (!s.IsEmpty())
      {
        if (s[s.Length() - 1] == WCHAR_PATH_SEPARATOR)
           s.Delete(s.Length() - 1);
        propVariant = s;
      }
      break;
    }
    case kpidIsFolder:
      propVariant = item.IsDirectory();
      break;
    case kpidSize:
      propVariant = item.Size;
      break;
    case kpidPackedSize:
      propVariant = item.PackSize;
      break;
    case kpidLastWriteTime:
    {
      FILETIME utcFileTime;
      UInt32 unixTime;
      if (item.GetUnixTime(unixTime))
      {
        NTime::UnixTimeToFileTime(unixTime, utcFileTime);
      }
      else
      {
        FILETIME localFileTime;
        if (DosTimeToFileTime(item.ModifiedTime, localFileTime))
        {
          if (!LocalFileTimeToFileTime(&localFileTime, &utcFileTime))
            utcFileTime.dwHighDateTime = utcFileTime.dwLowDateTime = 0;
        }
        else
          utcFileTime.dwHighDateTime = utcFileTime.dwLowDateTime = 0;
      }
      propVariant = utcFileTime;
      break;
    }
    /*
    case kpidAttributes:
      propVariant = (UInt32)item.Attributes;
      break;
    case kpidCommented:
      propVariant = item.IsCommented();
      break;
    */
    case kpidCRC:
      propVariant = (UInt32)item.CRC;
      break;
    case kpidMethod:
    {
      wchar_t method2[kMethodIdSize + 1];
      method2[kMethodIdSize] = 0;
      for (int i = 0; i < kMethodIdSize; i++)
        method2[i] = item.Method[i];
      propVariant = method2;
      break;
    }
    case kpidHostOS:
      propVariant = GetOS(item.OsId);
      break;
  }
  propVariant.Detach(value);
  return S_OK;
  COM_TRY_END
}
Esempio n. 23
0
UString FilePath::getStem(const UString &p) {
	path file(p.c_str());

	return file.stem();
}
Esempio n. 24
0
UString MakeLegalName(const UString &name)
{
  UString zipName = name;
  zipName.Replace(kOSDirDelimiter, kDirDelimiter);
  return zipName;
}
Esempio n. 25
0
// if string contains switch then function updates switch structures
// out: (string is a switch)
bool CParser::ParseString(const UString &s, const CSwitchForm *switchForms)
{
  int len = s.Length();
  if (len == 0)
    return false;
  int pos = 0;
  if (!IsItSwitchChar(s[pos]))
    return false;
  while (pos < len)
  {
    if (IsItSwitchChar(s[pos]))
      pos++;
    const int kNoLen = -1;
    int matchedSwitchIndex = 0; // GCC Warning
    int maxLen = kNoLen;
    for (int switchIndex = 0; switchIndex < _numSwitches; switchIndex++)
    {
      int switchLen = MyStringLen(switchForms[switchIndex].IDString);
      if (switchLen <= maxLen || pos + switchLen > len)
        continue;

      UString temp = s + pos;
      temp = temp.Left(switchLen);
      if (temp.CompareNoCase(switchForms[switchIndex].IDString) == 0)
      // if (_strnicmp(switchForms[switchIndex].IDString, LPCSTR(s) + pos, switchLen) == 0)
      {
        matchedSwitchIndex = switchIndex;
        maxLen = switchLen;
      }
    }
    if (maxLen == kNoLen)
      throw "maxLen == kNoLen";
    CSwitchResult &matchedSwitch = _switches[matchedSwitchIndex];
    const CSwitchForm &switchForm = switchForms[matchedSwitchIndex];
    if ((!switchForm.Multi) && matchedSwitch.ThereIs)
      throw "switch must be single";
    matchedSwitch.ThereIs = true;
    pos += maxLen;
    int tailSize = len - pos;
    NSwitchType::EEnum type = switchForm.Type;
    switch(type)
    {
      case NSwitchType::kPostMinus:
        {
          if (tailSize == 0)
            matchedSwitch.WithMinus = false;
          else
          {
            matchedSwitch.WithMinus = (s[pos] == kSwitchMinus);
            if (matchedSwitch.WithMinus)
              pos++;
          }
          break;
        }
      case NSwitchType::kPostChar:
        {
          if (tailSize < switchForm.MinLen)
            throw "switch is not full";
          UString set = switchForm.PostCharSet;
          const int kEmptyCharValue = -1;
          if (tailSize == 0)
            matchedSwitch.PostCharIndex = kEmptyCharValue;
          else
          {
            int index = set.Find(s[pos]);
            if (index < 0)
              matchedSwitch.PostCharIndex =  kEmptyCharValue;
            else
            {
              matchedSwitch.PostCharIndex = index;
              pos++;
            }
          }
          break;
        }
      case NSwitchType::kLimitedPostString:
      case NSwitchType::kUnLimitedPostString:
        {
          int minLen = switchForm.MinLen;
          if (tailSize < minLen)
            throw "switch is not full";
          if (type == NSwitchType::kUnLimitedPostString)
          {
            matchedSwitch.PostStrings.Add(s.Mid(pos));
            return true;
          }
          int maxLen = switchForm.MaxLen;
          UString stringSwitch = s.Mid(pos, minLen);
          pos += minLen;
          for (int i = minLen; i < maxLen && pos < len; i++, pos++)
          {
            wchar_t c = s[pos];
            if (IsItSwitchChar(c))
              break;
            stringSwitch += c;
          }
          matchedSwitch.PostStrings.Add(stringSwitch);
          break;
        }
      case NSwitchType::kSimple:
          break;
    }
  }
  return true;
}
Esempio n. 26
0
UString GetOSName(const UString &name)
{
  UString newName = name;
  newName.Replace(kDirDelimiter, kOSDirDelimiter);
  return newName;
}
Esempio n. 27
0
File: user.cpp Progetto: aox/aox
void User::createHelper()
{
    Address * a = address();

    if ( !d->q ) {
        if ( !a->id() ) {
            AddressCreator * ac = new AddressCreator( a, d->t );
            ac->execute();
        }

        d->q = new Query( "select name from namespaces where id="
                          "(select max(id) from namespaces)", this );
        d->t->enqueue( d->q );
        d->t->execute();
    }

    if ( d->q->done() && a->id() && !d->inbox ) {
        Row *r = d->q->nextRow();
        if ( !r ) {
            d->t->commit();
            return;
        }

        UString m = r->getUString( "name" );
        m.append( '/' );
        m.append( d->login );
        m.append( "/INBOX" );
        d->inbox = Mailbox::obtain( m, true );
        d->inbox->create( d->t, 0 );

        Query * q1
            = new Query( "insert into aliases (address, mailbox) values "
                         "($1, (select id from mailboxes where name=$2))", 0 );
        q1->bind( 1, a->id() );
        q1->bind( 2, m );
        d->t->enqueue( q1 );

        Query * q2
            = new Query( "insert into users "
                         "(alias,parentspace,login,secret,quota) values "
                         "((select id from aliases where address=$1), "
                         "(select max(id) from namespaces), $2, $3, "
                         "coalesce((select quota from users group by quota"
                         " order by count(*) desc limit 1), 2147483647))", 0 );
        q2->bind( 1, a->id() );
        q2->bind( 2, d->login );
        q2->bind( 3, d->secret );
        d->t->enqueue( q2 );

        Query *q3 =
            new Query( "update mailboxes set "
                       "owner=(select id from users where login=$1) "
                       "where name=$2 or name like $2||'/%'", 0 );
        q3->bind( 1, d->login );
        q3->bind( 2, m );
        d->t->enqueue( q3 );

        d->t->commit();
    }

    if ( !d->t->done() )
        return;

    if ( d->t->failed() ) {
        d->state = Nonexistent;
        d->result->setError( d->t->error() );
    }
    else {
        d->state = Refreshed;
        d->result->setState( Query::Completed );
    }

    d->result->notify();
}
Esempio n. 28
0
UString WinNameToOSName(const UString &name)
{
  UString newName = name;
  newName.Replace(L'\\', kOSDirDelimiter);
  return newName;
}
Esempio n. 29
0
JSValue jsOwnedStringOrNull(ExecState* exec, const UString& s)
{
    if (s.isNull())
        return jsNull();
    return jsOwnedString(exec, s);
}
Esempio n. 30
0
void SetExtractErrorMessage(Int32 opRes, Int32 encrypted, const wchar_t *fileName, UString &s)
{
  s.Empty();

  if (opRes == NArchive::NExtract::NOperationResult::kOK)
    return;

  UINT messageID = 0;
  UINT id = 0;

  switch (opRes)
  {
    case NArchive::NExtract::NOperationResult::kUnsupportedMethod:
      messageID = IDS_EXTRACT_MESSAGE_UNSUPPORTED_METHOD;
      id = IDS_EXTRACT_MSG_UNSUPPORTED_METHOD;
      break;
    case NArchive::NExtract::NOperationResult::kDataError:
      messageID = encrypted ?
          IDS_EXTRACT_MESSAGE_DATA_ERROR_ENCRYPTED:
          IDS_EXTRACT_MESSAGE_DATA_ERROR;
      id = IDS_EXTRACT_MSG_DATA_ERROR;
      break;
    case NArchive::NExtract::NOperationResult::kCRCError:
      messageID = encrypted ?
          IDS_EXTRACT_MESSAGE_CRC_ERROR_ENCRYPTED:
          IDS_EXTRACT_MESSAGE_CRC_ERROR;
      id = IDS_EXTRACT_MSG_CRC_ERROR;
      break;
    case NArchive::NExtract::NOperationResult::kUnavailable:
      id = IDS_EXTRACT_MSG_UNAVAILABLE_DATA;
      break;
    case NArchive::NExtract::NOperationResult::kUnexpectedEnd:
      id = IDS_EXTRACT_MSG_UEXPECTED_END;
      break;
    case NArchive::NExtract::NOperationResult::kDataAfterEnd:
      id = IDS_EXTRACT_MSG_DATA_AFTER_END;
      break;
    case NArchive::NExtract::NOperationResult::kIsNotArc:
      id = IDS_EXTRACT_MSG_IS_NOT_ARC;
      break;
    case NArchive::NExtract::NOperationResult::kHeadersError:
      id = IDS_EXTRACT_MSG_HEADERS_ERROR;
      break;
    case NArchive::NExtract::NOperationResult::kWrongPassword:
      id = IDS_EXTRACT_MSG_WRONG_PSW_CLAIM;
      break;
    /*
    default:
      messageID = IDS_EXTRACT_MESSAGE_UNKNOWN_ERROR;
      break;
    */
  }

  UString msg;
  UString msgOld;

  #ifndef _SFX
  if (id != 0)
    LangString_OnlyFromLangFile(id, msg);
  if (messageID != 0 && msg.IsEmpty())
    LangString_OnlyFromLangFile(messageID, msgOld);
  #endif

  if (msg.IsEmpty() && !msgOld.IsEmpty())
    s = MyFormatNew(msgOld, fileName);
  else
  {
    if (msg.IsEmpty() && id != 0)
      LangString(id, msg);
    if (!msg.IsEmpty())
      s += msg;
    else
    {
      char temp[16];
      ConvertUInt32ToString(opRes, temp);
      s.AddAscii("Error #");
      s.AddAscii(temp);
    }

    if (encrypted && opRes != NArchive::NExtract::NOperationResult::kWrongPassword)
    {
      // s.AddAscii(" : ");
      // AddLangString(s, IDS_EXTRACT_MSG_ENCRYPTED);
      s.AddAscii(" : ");
      AddLangString(s, IDS_EXTRACT_MSG_WRONG_PSW_GUESS);
    }
    s.AddAscii(" : ");
    s += fileName;
  }
}