void ExcelDOMStripper::RemoveOLELinks(IDispatchPtr spDispatch) { if (spDispatch == 0) throw Workshare::ArgumentNullException(_T("spDispatch"), _T("The Worksheet that we want to remove the excel links from is invalid.")); Excel::_WorksheetPtr spWorksheet = spDispatch; if (spWorksheet == 0) throw Workshare::Com::ComException(_T("The dispatch instance passed does not implement the Excel::_Worksheet interface"), E_NOINTERFACE); try { _variant_t vtLinkSources(m_spWorkbook->LinkSources((long)Excel::xlLinkTypeOLELinks)); if (VT_EMPTY == vtLinkSources.vt) return; SAFEARRAY *psa = V_ARRAY(&vtLinkSources); LONG iLBound, iUBound; ::SafeArrayGetLBound(psa, 1, &iLBound); ::SafeArrayGetUBound(psa, 1, &iUBound); if (0 < (iUBound - iLBound + 1)) { CComSafeArray <VARIANT> safeArray(psa); for (ULONG i = 1; i <= safeArray.GetCount(); i++) { _variant_t name(safeArray.GetAt(i)); VARIANT result; VariantInit(&result); HRESULT hr = DispatchWrapper(DISPATCH_METHOD, &result, m_spWorkbook, L"BreakLink", 2, _variant_t(Excel::xlLinkTypeOLELinks), name); if (DISP_E_UNKNOWNNAME != hr) { if (0 != result.boolVal) throw Workshare::Com::ComException(_T("Failed to break the link on the Excel document"), E_FAIL); } } } Excel::OLEObjectsPtr spOLEObjects = spWorksheet->OLEObjects(); long lObjectCount = spOLEObjects->Count; for (long lObjectIndex = lObjectCount; 0 < lObjectIndex; lObjectIndex--) { Excel::_OLEObjectPtr spOLEObject = spOLEObjects->Item(lObjectIndex); _variant_t vtOLEType = spOLEObject->OLEType; if (Excel::xlOLELink == vtOLEType.intVal || Excel::xlOLEEmbed == vtOLEType.intVal) { if(m_spWorkbook->MultiUserEditing) throw Workshare::Com::ComException(_T("An embedded OLE link has been detected, but cannot be cleaned when Workbook Sharing (Track Changes) is enabled. To clean the link, click No and then resend while selecting to accept and switch off Track Changes."), E_FAIL); Excel::RangePtr spRangePtr = spOLEObject->TopLeftCell; /*spOLEObject->Copy(); spWorksheet->Paste(_variant_t(spRangePtr), vtMissing); spOLEObject->Delete();*/ spOLEObject->Copy(); //spOLEObject->Activate(); spOLEObject->Delete(); m_linksCount++; spRangePtr->Select(); spWorksheet->PasteSpecial(_T("Picture (PNG)"), VARIANT_FALSE, VARIANT_FALSE); } else { } } Excel::ShapesPtr spShapes = spWorksheet->Shapes; long lShapeCount = spShapes->Count; for (long lShapeIndex = lShapeCount; 0 < lShapeIndex; lShapeIndex--) { Excel::ShapePtr spShape = spShapes->Item(lShapeIndex); _variant_t vtShapeType = spShape->Type; if (msoffice::msoLinkedOLEObject == vtShapeType.intVal) { spShape->Copy(); spShape->TopLeftCell->Activate(); spShape->Delete(); m_linksCount++; spWorksheet->PasteSpecial(_T("Picture (PNG)"), VARIANT_FALSE, VARIANT_FALSE); } } } catch(Workshare::Exception const&) { throw; } catch(...) { unexpected(); } }
///////// // // primec(): // fetch the current character from the input stream // set inchar to the character or zero on EOF // void primec(void) { switch (fetchtype) { case SCRIPT_RAM: inchar = *(char *) fetchptr; break; case SCRIPT_PROGMEM: inchar = pgm_read_byte(fetchptr); break; case SCRIPT_EEPROM: inchar = eeread((int) fetchptr); break; #if defined(SDFILE) || defined(UNIX_BUILD) case SCRIPT_FILE: inchar = scriptread(); break; #endif default: unexpected(M_oops); } #ifdef PARSER_TRACE if (trace) { spb('<'); if (inchar >= 0x20) spb(inchar); else { spb('\\'); printInteger(inchar, 0, ' '); } spb('>'); } #endif }
void ExcelDOMStripper::RemoveMacros() throw(Workshare::Exception) { try { VBIDE::_VBProjectPtr vbProj=m_spWorkbook->VBProject; for(int i=vbProj->VBComponents->Count;i>=1;i--) { VBIDE::_VBComponentPtr vbComponent=vbProj->VBComponents->Item(i); try { vbProj->VBComponents->Remove(vbComponent); } catch(Workshare::ArgumentException)//some internal macros cannot be removed { } } for(int i=vbProj->VBComponents->Count;i>=1;i--) { VBIDE::_VBComponentPtr vbComponent=vbProj->VBComponents->Item(i); vbComponent->CodeModule->DeleteLines(1,vbComponent->CodeModule->CountOfLines); } } catch(Workshare::Exception const& ex) { if(ex.ErrorCode==E_VBA_ACCESS_NOT_TRUSTED) { throw Workshare::Com::ComException(_T("Unable to clean macros. Please enable 'Trust access to the VBA project object model' option in Excel's Trust Center."),ex.ErrorCode); } throw; } catch(...) { unexpected(); } }
int pushtexturetype(lua_State *L, unsigned int value) { switch(value) { #define CASE(CODE,str) case CODE: lua_pushstring(L, str); break CASE(aiTextureType_NONE, "none"); CASE(aiTextureType_DIFFUSE, "diffuse"); CASE(aiTextureType_SPECULAR, "specular"); CASE(aiTextureType_AMBIENT, "ambient"); CASE(aiTextureType_EMISSIVE, "emissive"); CASE(aiTextureType_HEIGHT, "height"); CASE(aiTextureType_NORMALS, "normals"); CASE(aiTextureType_SHININESS, "shininess"); CASE(aiTextureType_OPACITY, "opacity"); CASE(aiTextureType_DISPLACEMENT, "displacement"); CASE(aiTextureType_LIGHTMAP, "lightmap"); CASE(aiTextureType_REFLECTION, "reflection"); CASE(aiTextureType_UNKNOWN, "unknown"); #undef CASE default: return unexpected(L); } return 1; }
void SetPdfRestrictionLevel(const CStdString& sPdfFile, const CStdString& restrictionLevel) { LOG_WS_FUNCTION_SCOPE(); if (c_sNoRestriction != restrictionLevel && c_sFullRestriction != restrictionLevel && c_sInternalOnly != restrictionLevel) throw Workshare::ArgumentException(_T("restrictionLevel"), _T("Invalid value passed as restriction level")); try { PDFDocumentTagger pdfTagger(sPdfFile); if (0 == restrictionLevel.compare(c_sInternalOnly)) pdfTagger.SetInternalOnly(); if (0 == restrictionLevel.compare(c_sFullRestriction)) pdfTagger.SetFullyRestricted(); pdfTagger.CloseDocument(); } catch(const Workshare::Exception&) { throw; } catch(...) { unexpected(); } }
void ExcelControllerImpl08::WaitForWorkbookOpened(const CStdString& sFilePathName) { CStdString sWorkbookName = sFilePathName; int iPos = sWorkbookName.ReverseFind('\\'); if (-1 != iPos) sWorkbookName = sWorkbookName.Right((int)sWorkbookName.length() - iPos - 1); else { iPos = sWorkbookName.ReverseFind(_T('/')); if (-1 != iPos) sWorkbookName = sWorkbookName.Right((int)sWorkbookName.length() - iPos - 1); } int iTryCount = 0; while (200 >= iTryCount) // about 20 seconds { try { Excel::_ApplicationPtr spApplication = GetApplication(); Excel::_WorkbookPtr spWorkbook = spApplication->Workbooks->Item[sWorkbookName.c_str()]; return; } catch(const Workshare::Exception&) { //ignore } catch(...) { unexpected(); } ::Sleep(100); iTryCount++; } throw Workshare::Com::ComException(_T("Failed to open workbook [") + sFilePathName + _T("], wait time expired"), E_FAIL); }
static void In1_nrfdhi(int tr) { if (!parallel_atn) unexpected(tr); }
static void In1_ndaclo(int tr) { if (!parallel_atn) unexpected(tr); }
void chkpin(char pin) { // TODO: fix this warning re: comparison if ((pin >= NUMPINS) || (pin < 0)) unexpected(M_number); }
void SetPermissionHelper(const CStdString& sSourceFile, CStdString& sUsersPassword, VARIANT_BOOL bDisablePrinting, VARIANT_BOOL bDisableModification, VARIANT_BOOL bDisableCopy, VARIANT_BOOL bDisableNotesModification) { LOG_WS_FUNCTION_SCOPE(); std::tstring sTempFileName; //138.18: Temp file will be used instead of real file name during permissions processing. //CDIntfEx::IDIDocument is failing to open files if the filename contains non-latin characters //so use a temporary ANSI name and rename file back to the original after completing all processing. //This is a workaround. Amyuni have confirmed that IDIDocument.Open only supports ANSI chars in filenames. try { if (bDisablePrinting != VARIANT_TRUE && bDisableModification != VARIANT_TRUE && bDisableCopy != VARIANT_TRUE && bDisableNotesModification != VARIANT_TRUE && sUsersPassword.IsEmpty()) { return; } sTempFileName = CGeneral::GetTemporaryFileName(); if (!CGeneral::DeleteFile(sTempFileName.c_str(), _T(__FUNCTION__))) { throw Workshare::System::SystemException(_T("SetPermissionHelper() Failed to create working temporary copy of PDF (temp file creation).")); } ::CopyFile(sSourceFile, sTempFileName.c_str(), TRUE); if (!CGeneral::FileExists(sTempFileName.c_str())) { throw Workshare::System::SystemException( _T("SetPermissionHelper() Failed to create working temporary copy of PDF (copying original file to temp copy).")); } CDIntfEx::IDIDocumentPtr spDocument; HRESULT hr = spDocument.CreateInstance(__uuidof(CDIntfEx::Document)); if (S_OK != hr) { throw Workshare::Com::ComException(_T("Unable to create instance of PDF Document"), hr); } VARIANT_BOOL bOpen = spDocument->Open(sTempFileName.c_str()); if (VARIANT_FALSE == bOpen) { CStdString sError = _T("Failed to open PDF document ") + sSourceFile; throw Workshare::System::SystemException(sError); } VARIANT_BOOL bValid = spDocument->SetLicenseKey(c_sCompany, PDFPrinterLicenseChecker::getAppropPDFPrinterLicenseCode()); if (VARIANT_FALSE == bValid) { throw Workshare::System::SystemException(_T("Invalid PDF Publisher License key")); } DWORD dwPermissions = CalculatePermissions(bDisablePrinting, bDisableModification, bDisableCopy, bDisableNotesModification); CStdString entropy = _T("?|2^&(*$:@!!*"); CStdString sDefaultOwnerPassword = Workshare::OptionApi::GetEncrypted(L"PDFDefaultOwnerPassword", entropy); if( sDefaultOwnerPassword.IsEmpty() ) { CStdString sError = _T("Owner password cannot be blank when applying security ") + sSourceFile; throw Workshare::System::SystemException(sError); } VARIANT_BOOL bEncrypt = VARIANT_FALSE; if (DoesPdfPasswordApplyToOwner()) { _bstr_t bsPassword = (sUsersPassword.IsEmpty() ? sDefaultOwnerPassword : sUsersPassword); bEncrypt = spDocument->Encrypt128(bsPassword, _T(""), dwPermissions); } else { _bstr_t bsOwnerPassword = sDefaultOwnerPassword; _bstr_t bsUserPassword = sUsersPassword; // OwnerPassword should not equal to UserPassword if( bsOwnerPassword == bsUserPassword ) { CStdString sError = _T("Failed to validate User Password, cannot be same as Owner password ") + sSourceFile; throw Workshare::System::SystemException(sError); } bEncrypt = spDocument->Encrypt128(bsOwnerPassword, bsUserPassword, dwPermissions); } if (VARIANT_FALSE == bEncrypt) { CStdString sError = _T("Failed to encrypt PDF document ") + sSourceFile; throw Workshare::System::SystemException(sError); } VARIANT_BOOL bSave = spDocument->Save(sTempFileName.c_str()); if (VARIANT_FALSE == bSave) { CStdString sError = _T("Failed to save PDF document ") + sSourceFile; throw Workshare::System::SystemException(sError); } if (!CGeneral::DeleteFile(sSourceFile, _T(__FUNCTION__))) { throw Workshare::System::SystemException(_T("SetPermissionHelper() Failed to remove original copy of PDF")); } ::MoveFile(sTempFileName.c_str(), sSourceFile); if (!CGeneral::FileExists(sSourceFile)) { throw Workshare::System::SystemException(_T("SetPermissionHelper() Failed to move working temporary copy of PDF to the output file path.")); } CGeneral::DeleteTemporaryFile(sTempFileName); // to remove dir if empty } catch(const Workshare::Exception&) { CGeneral::DeleteTemporaryFile(sTempFileName); throw; } catch(...) { CGeneral::DeleteTemporaryFile(sTempFileName); unexpected(); } }
// Get a statement numvar getstatement(void) { numvar retval = 0; //char *fetchmark; numvar fetchmark; chkbreak(); if (sym == s_while) { // at this point sym is pointing at s_while, before the conditional expression // save fetchptr so we can restart parsing from here as the while iterates //fetchmark = fetchptr; fetchmark = markparsepoint(); for (;;) { //fetchptr = fetchmark; // restore to mark //primec(); // set up for mr. getsym() returntoparsepoint(fetchmark, 0); getsym(); // fetch the start of the conditional if (getnum()) { retval = getstatement(); if (sym == s_returning) break; // exit if we caught a return } else { skipstatement(); break; } } } else if (sym == s_if) { getsym(); // eat "if" if (getnum()) { retval = getstatement(); if (sym == s_else) { getsym(); // eat "else" skipstatement(); } } else { skipstatement(); if (sym == s_else) { getsym(); // eat "else" retval = getstatement(); } } } else if (sym == s_lcurly) { getsym(); // eat "{" while ((sym != s_eof) && (sym != s_returning) && (sym != s_rcurly)) retval = getstatement(); if (sym == s_rcurly) getsym(); // eat "}" } else if (sym == s_return) { getsym(); // eat "return" if ((sym != s_eof) && (sym != s_semi)) retval = getnum(); sym = s_returning; // signal we're returning up the line } else if (sym == s_switch) retval = getswitchstatement(); else if (sym == s_function) cmd_function(); else if (sym == s_run) { // run macroname getsym(); if ((sym != s_script_eeprom) && (sym != s_script_progmem) && (sym != s_script_file)) unexpected(M_id); // address of macroid is in symval via parseid // check for [,snoozeintervalms] getsym(); // eat macroid to check for comma; symval untouched if (sym == s_comma) { vpush(symval); getsym(); // eat the comma getnum(); // get a number or else startTask(vpop(), expval); } else startTask(symval, 0); } else if (sym == s_stop) { getsym(); if (sym == s_mul) { // stop * stops all tasks initTaskList(); getsym(); } else if ((sym == s_semi) || (sym == s_eof)) { if (background) stopTask(curtask); // stop with no args stops the current task IF we're in back else initTaskList(); // in foreground, stop all } else stopTask(getnum()); } else if (sym == s_boot) reboot(); else if (sym == s_rm) { // rm "sym" or rm * getsym(); if (sym == s_script_eeprom) { eraseentry(idbuf); } else if (sym == s_mul) nukeeeprom(); else if (sym != s_undef) expected(M_id); getsym(); } else if (sym == s_ps) { getsym(); showTaskList(); } else if (sym == s_peep) { getsym(); cmd_peep(); } else if (sym == s_ls) { getsym(); cmd_ls(); } else if (sym == s_help) { getsym(); cmd_help(); } else if (sym == s_print) { getsym(); cmd_print(); } else if (sym == s_semi) { ; } // ;) #ifdef HEX_UPLOAD // a line beginning with a colon is treated as a hex record // containing data to upload to eeprom // // TODO: verify checksum // else if (sym == s_colon) { // fetchptr points at the byte count byte byteCount = gethex(2); // 2 bytes byte count int addr = gethex(4); // 4 bytes address byte recordType = gethex(2); // 2 bytes record type; now fetchptr -> data if (recordType == 1) reboot(); // reboot on EOF record (01) if (recordType != 0) return; // we only handle the data record (00) if (addr == 0) nukeeeprom(); // auto-clear eeprom on write to 0000 while (byteCount--) eewrite(addr++, gethex(2)); // update the eeprom gethex(2); // discard the checksum getsym(); // and re-prime the parser } #endif else getexpression(); if (sym == s_semi) getsym(); // eat trailing ';' return retval; }
static sl_node_base_t* primary_expression(sl_parse_state_t* ps) { sl_token_t* tok; sl_node_base_t* node; switch(peek_token(ps)->type) { case SL_TOK_INTEGER: tok = next_token(ps); return sl_make_immediate_node(ps, sl_integer_parse(ps->vm, tok->as.str.buff, tok->as.str.len)); case SL_TOK_FLOAT: return sl_make_immediate_node(ps, sl_make_float(ps->vm, next_token(ps)->as.dbl)); case SL_TOK_STRING: tok = next_token(ps); return sl_make_immediate_node(ps, sl_make_string(ps->vm, tok->as.str.buff, tok->as.str.len)); case SL_TOK_REGEXP: return regexp_expression(ps); case SL_TOK_CONSTANT: tok = next_token(ps); return sl_make_const_node(ps, NULL, sl_intern2(ps->vm, sl_make_string(ps->vm, tok->as.str.buff, tok->as.str.len))); case SL_TOK_IDENTIFIER: tok = next_token(ps); return sl_make_var_node(ps, SL_NODE_VAR, sl_make_string(ps->vm, tok->as.str.buff, tok->as.str.len)); case SL_TOK_TRUE: next_token(ps); return sl_make_immediate_node(ps, ps->vm->lib._true); case SL_TOK_FALSE: next_token(ps); return sl_make_immediate_node(ps, ps->vm->lib._false); case SL_TOK_NIL: next_token(ps); return sl_make_immediate_node(ps, ps->vm->lib.nil); case SL_TOK_SELF: next_token(ps); return sl_make_self_node(ps); case SL_TOK_IVAR: tok = next_token(ps); node = sl_make_var_node(ps, SL_NODE_IVAR, sl_make_string(ps->vm, tok->as.str.buff, tok->as.str.len)); return node; case SL_TOK_CVAR: tok = next_token(ps); node = sl_make_var_node(ps, SL_NODE_CVAR, sl_make_string(ps->vm, tok->as.str.buff, tok->as.str.len)); return node; case SL_TOK_IF: case SL_TOK_UNLESS: return if_expression(ps); case SL_TOK_WHILE: case SL_TOK_UNTIL: return while_expression(ps); case SL_TOK_FOR: return for_expression(ps); case SL_TOK_CLASS: return class_expression(ps); case SL_TOK_DEF: return def_expression(ps); case SL_TOK_LAMBDA: return lambda_expression(ps); case SL_TOK_TRY: return try_expression(ps); case SL_TOK_OPEN_BRACKET: return array_expression(ps); case SL_TOK_OPEN_PAREN: return bracketed_expression(ps); case SL_TOK_OPEN_BRACE: return dict_expression(ps); case SL_TOK_NEXT: tok = next_token(ps); if(!(ps->scope->flags & SL_PF_CAN_NEXT_LAST)) { error(ps, sl_make_cstring(ps->vm, "next invalid outside loop"), tok); } return sl_make_singleton_node(ps, SL_NODE_NEXT); case SL_TOK_LAST: tok = next_token(ps); if(!(ps->scope->flags & SL_PF_CAN_NEXT_LAST)) { error(ps, sl_make_cstring(ps->vm, "last invalid outside loop"), tok); } return sl_make_singleton_node(ps, SL_NODE_LAST); case SL_TOK_RANGE_EX: next_token(ps); return sl_make_singleton_node(ps, SL_NODE_YADA_YADA); default: unexpected(ps, peek_token(ps)); return NULL; } }
// Handle unexpected character void badsym(void) { unexpected(M_char); #if !defined(TINY85) printHex(inchar);speol(); #endif }
void ExcelDOMStripper::RemoveLinks() throw(Workshare::Exception) { if (m_pExcelDOMStripperStrategy != NULL) { __raise m_pExcelDOMStripperStrategy->OnLinksBegin(); } try { m_mapNames.clear(); Excel::NamesPtr spNames = m_spWorkbook->Names; long count = spNames->Count; for (long nIndex = 1; nIndex <= count; ++nIndex) { Excel::NamePtr spName = spNames->Item(nIndex); m_mapNames.insert(std::map<CStdString, int>::value_type(spName->GetName(), 0)); } Excel::SheetsPtr pWorksheets = m_spWorkbook->Worksheets; count = pWorksheets->Count; for (long nWorkSheetIndex = 1; nWorkSheetIndex <= count; ++nWorkSheetIndex) { Excel::_WorksheetPtr spWorksheet = pWorksheets->Item[nWorkSheetIndex]; RemoveExcelLinks(spWorksheet); RemoveOLELinks(spWorksheet); } bool linksDeleted = false; std::map<CStdString, int> :: iterator mapName; for (long nIndex = spNames->Count; nIndex > 0; --nIndex) { Excel::NamePtr spName = spNames->Item(nIndex); mapName = m_mapNames.find(spName->GetName()); if (mapName != m_mapNames.end() && mapName->second == 1) { spName->Delete(); linksDeleted = true; } } if (m_pExcelDOMStripperStrategy != NULL) { _bstr_t bsEvent = (!linksDeleted && m_linksCount == 0 ? EVENTTEXT_NOT_PRESENT : EVENTTEXT_REMOVED); __raise m_pExcelDOMStripperStrategy->OnLink(bsEvent, bsEvent); __raise m_pExcelDOMStripperStrategy->OnLinksEnd(); } m_spWorkbook->PutSaved(0, VARIANT_FALSE); } catch (Workshare::Exception const&) { if (m_pExcelDOMStripperStrategy != NULL) { __raise m_pExcelDOMStripperStrategy->OnLinksEnd(); } try { m_spWorkbook->Application->Undo(); } catch(...) { //If the undo fails, we want to preserve the original exception } throw; } catch(...) { unexpected(); } }
void ExcelDOMStripper::RemoveCustomProperties() throw(Workshare::Exception) { if (m_pExcelDOMStripperStrategy != NULL) { __raise m_pExcelDOMStripperStrategy->OnCustomPropertiesBegin(); } try { IDispatchPtr spDispPropertyCollection = m_spWorkbook->CustomDocumentProperties; long lNumProperties = CCOMDispatchHelper::GetCollectionCount(spDispPropertyCollection); if (lNumProperties == 0) { if (m_pExcelDOMStripperStrategy != NULL) { _bstr_t bsEvent = EVENTTEXT_NOT_PRESENT; __raise m_pExcelDOMStripperStrategy->OnCustomProperty(bsEvent, bsEvent); __raise m_pExcelDOMStripperStrategy->OnCustomPropertiesEnd(); } return; } IDispatchPtr spProperty = NULL; _bstr_t bstrPropValue = _T(""); _bstr_t bstrPropName = _T(""); CStdString exclusions; if (m_excludedElements.size() == 0) exclusions = CMetawallGatewaySettings::GetCustomPropertiesExclusions(); else exclusions = CNewMetawallGatewaySettings::GetCustomPropertiesExclusions(m_excludedElements); for (long lPropertyIndex = lNumProperties; lPropertyIndex > 0; lPropertyIndex--) { HRESULT hr = CCOMDispatchHelper::GetPropertyItemValues(spDispPropertyCollection, lPropertyIndex, bstrPropName, bstrPropValue); if(FAILED(hr)) throw Workshare::Com::ComException(_T("Failing to get the value of an property while removing custom properties"), hr, spDispPropertyCollection); if(bstrPropName.length() > 0 && !ShouldExcludeCustomProperty(exclusions, static_cast<const TCHAR*>(bstrPropName))) { hr = CCOMDispatchHelper::GetCollectionItem(spDispPropertyCollection, lPropertyIndex, spProperty); if(FAILED(hr)) throw Workshare::Com::ComException(_T("Failing to get an item from a collection while removing custom properties"), hr, spDispPropertyCollection); hr = CCOMDispatchHelper::AutoWrap(DISPATCH_METHOD, NULL, spProperty, L"Delete", 0); if(FAILED(hr)) throw Workshare::Com::ComException(_T("Failing to delete an item from a collection while removing custom properties"), hr, spDispPropertyCollection); } } if (m_pExcelDOMStripperStrategy != NULL) { _bstr_t bsEvent = EVENTTEXT_REMOVED; __raise m_pExcelDOMStripperStrategy->OnCustomProperty(bsEvent, bsEvent); __raise m_pExcelDOMStripperStrategy->OnCustomPropertiesEnd(); } m_spWorkbook->PutSaved(0, VARIANT_FALSE); } catch(Workshare::Exception const&) { if (m_pExcelDOMStripperStrategy != NULL) { __raise m_pExcelDOMStripperStrategy->OnCustomPropertiesEnd(); } throw; } catch(...) { unexpected(); } }
void ExcelDOMStripper::RemoveBuiltInProperties() throw(Workshare::Exception) { if (m_pExcelDOMStripperStrategy != NULL) { __raise m_pExcelDOMStripperStrategy->OnBuiltInPropertiesBegin(); } try { IDispatchPtr spDispPropertyCollection = m_spWorkbook->BuiltinDocumentProperties; Excel::xlBuiltInProperty xlPropertyIndex[] = {Excel::xlPropertyTitle, Excel::xlPropertySubject, Excel::xlPropertyAuthor, Excel::xlPropertyKeywords, Excel::xlPropertyComments, Excel::xlPropertyCategory, Excel::xlPropertyManager, Excel::xlPropertyCompany, Excel::xlPropertyHyperlinkBase }; variant_t vtNoValue(_TEXT("")); HRESULT hr = S_OK; IDispatchPtr spProperty = NULL; _bstr_t bstrName = ""; _bstr_t bstrValue = ""; long lCount = sizeof(xlPropertyIndex)/sizeof(Excel::xlBuiltInProperty); for (long lIndex = 0; lIndex < lCount; lIndex++) { hr = CCOMDispatchHelper::GetCollectionItem(spDispPropertyCollection, xlPropertyIndex[lIndex], spProperty); if(FAILED(hr)) throw Workshare::Com::ComException(_T("Failed to obtain a collection item whilst removing builtin properies"), hr); bstrValue = ""; hr = CCOMDispatchHelper::GetPropertyItemValues(spDispPropertyCollection, xlPropertyIndex[lIndex], bstrName, bstrValue); if (bstrValue.length() != 0) { hr = CCOMDispatchHelper::AutoWrap(DISPATCH_PROPERTYPUT|DISPATCH_METHOD, NULL, spProperty, L"Value", 1, vtNoValue); if(FAILED(hr)) throw Workshare::Com::ComException(_T("Failed to set the Hyperlink Base Builtin Property value."),hr); } } if (m_pExcelDOMStripperStrategy != NULL) { _bstr_t bsEvent = EVENTTEXT_REMOVED; __raise m_pExcelDOMStripperStrategy->OnBuiltInProperty(bsEvent, bsEvent); __raise m_pExcelDOMStripperStrategy->OnBuiltInPropertiesEnd(); } m_spWorkbook->PutSaved(0, VARIANT_FALSE); } catch(Workshare::Exception const&) { if (m_pExcelDOMStripperStrategy != NULL) { __raise m_pExcelDOMStripperStrategy->OnBuiltInPropertiesEnd(); } throw; } catch(...) { unexpected(); } }
LRESULT CPasswordEnter::OnClickedOK(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { TCHAR szPassword[_MAX_PATH] = {0}; GetDlgItemText(IDC_PASSWORD_OPEN, szPassword, _MAX_PATH); CStdString sEnteredPassword(szPassword); TCHAR szModifyPassword[_MAX_PATH] = {0}; GetDlgItemText(IDC_PASSWORD_MODIFY, szModifyPassword, _MAX_PATH); m_ModifyPassword = szModifyPassword; TCHAR szRestrictionPassword[_MAX_PATH] = {0}; GetDlgItemText(IDC_PASSWORD_RESTRICT, szRestrictionPassword, _MAX_PATH); m_RestrictionPassword = szRestrictionPassword; if(m_enabledOpenPassword && sEnteredPassword.empty()) { ShowMessage(NULL, _T("Please enter the open password to continue"), WsOK, WsProtect, WsErrorIcon, L"", d2h_password_verify, LOG_LOCATION); return 0; } if(m_enabledModifyPassword && m_ModifyPassword.empty()) { ShowMessage(NULL, _T("Please enter the modify password to continue"), WsOK, WsProtect, WsErrorIcon, L"", d2h_password_verify, LOG_LOCATION); return 0; } if(m_enabledRestrictionPassword && m_RestrictionPassword.empty()) { ShowMessage(NULL, _T("Please enter the restriction password to continue"), WsOK, WsProtect, WsErrorIcon, L"", d2h_password_verify, LOG_LOCATION); return 0; } if(m_bVerifyUsingMD4) { try { WSCRYPTLib::IWSPwdEncrypterPtr crypt; HRESULT hr = crypt.CreateInstance(_PROGID_WSCrypto_WProf); if(FAILED(hr)) throw Workshare::ClassNotFoundException(_T(_PROGID_WSCrypto_WProf), _T("Failed to create an instance of the Workshare Encryption library. Please run the configuration assistant")); _bstr_t bstrPassword = sEnteredPassword.c_str(); crypt->MD4Encrypt(&bstrPassword.GetBSTR()); sEnteredPassword = bstrPassword; } catch (const Workshare::Exception&) { TCHAR szBuffer[80]; ::LoadString(_AtlBaseModule.m_hInstResource, MSG_ENCRYPT_FAILED, szBuffer, 80); ShowMessage(NULL, szBuffer, WsOK, WsProtect, WsErrorIcon, L"", d2h_password_verify, LOG_LOCATION); } catch(...) { TCHAR szBuffer[80]; ::LoadString(_AtlBaseModule.m_hInstResource, MSG_ENCRYPT_FAILED, szBuffer, 80); ShowMessage(NULL, szBuffer, WsOK, WsProtect, WsErrorIcon, L"", d2h_password_verify, LOG_LOCATION); unexpected(); } } if(m_verifyCurrent && (sEnteredPassword != m_OpenPassword)) { TCHAR szBuffer[80]; ::LoadString(_AtlBaseModule.m_hInstResource, MSG_PASSWORD_INCORRECT, szBuffer, 80); ShowMessage(NULL, szBuffer, WsOK, WsProtect, WsErrorIcon, L"", d2h_password_verify, LOG_LOCATION); } else { m_OpenPassword = szPassword; EndDialog(wID); } return 0; }
void ExcelDOMStripper::RemoveComments() throw(Workshare::Exception) { if (m_pExcelDOMStripperStrategy != NULL) { __raise m_pExcelDOMStripperStrategy->OnCommentsBegin(0); } if (m_commentsCount == 0) { if (m_pExcelDOMStripperStrategy != NULL) { _bstr_t bsEvent = EVENTTEXT_NOT_PRESENT; __raise m_pExcelDOMStripperStrategy->OnComment(bsEvent, bsEvent); __raise m_pExcelDOMStripperStrategy->OnCommentsEnd(); } return; } try { Excel::SheetsPtr spSheets = m_spWorkbook->Sheets; long lWorksheetCommentCount = 0; for (long lIndex = 1; lIndex <= spSheets->Count; lIndex++) { Excel::_WorksheetPtr spWorksheet = spSheets->Item[lIndex]; // Excel version 10 has five types of worksheets: worksheet, Excel 4 macro sheet, // international macro sheet, chart sheet and dialog sheet. // If the sheet at a particular index is a chart sheet or a dialog sheet, null is returned: if (spWorksheet != 0) { Excel::CommentsPtr spComments = spWorksheet->Comments; lWorksheetCommentCount = spComments->Count; for (long lCommentIndex = lWorksheetCommentCount; lCommentIndex > 0; lCommentIndex--) { Excel::CommentPtr spComment = spComments->Item(lCommentIndex); HRESULT hr = spComment->Delete(); if (FAILED(hr)) throw Workshare::Com::ComException(_T("Failed to remove a comment."), hr); } Excel::ShapesPtr spShapes = spWorksheet->Shapes; long shapeCount = spShapes->Count; for (long shapeIndex = shapeCount; shapeIndex > 0; shapeIndex--) { Excel::ShapePtr spShape = spShapes->Item(shapeIndex); int shapeType = spShape->Type; switch(shapeType) { case 6: { if (ContainsInkComments(spShape)) RemoveGroupedComments(spShape); break; } // Ink Annotations is an Office 2003 feature consisting out of Ink [msoffice::msoInk = 22] // and Ink Comments [msoffice::msoInkComment = 23] and both are considered to be Comments. // In Offce XP/2000 Ink Annotaions are classified as Freeform Shapes [msoffice::msoFreeform = 5]. // Protect will not remove Ink Annotations from Office 2003 documents if the client is using // Office XP/2000 as this might lead to the removal of other Freeform Shapes. [Story 136.38] case 22: case 23: { HRESULT hr = spShape->Delete(); if (FAILED(hr)) throw Workshare::Com::ComException(_T("Failed to remove an Ink Annotation"), hr); break; } default: continue; } } } } if (m_pExcelDOMStripperStrategy != NULL) { _bstr_t bsEVent = EVENTTEXT_REMOVED; __raise m_pExcelDOMStripperStrategy->OnComment(bsEVent, bsEVent); __raise m_pExcelDOMStripperStrategy->OnCommentsEnd(); } m_spWorkbook->PutSaved(0, VARIANT_FALSE); } catch(Workshare::Exception const&) { if (m_pExcelDOMStripperStrategy != NULL) { __raise m_pExcelDOMStripperStrategy->OnCommentsEnd(); } throw; } catch(...) { unexpected(); } }
void run() { #if ! BEAST_NO_STD_FUNCTION_CONSTRUCTIBLE static_assert (! std::is_constructible < std::function <void(void)>, int&&>::value, "Cannot construct std::function from int&&"); static_assert (! std::is_constructible < std::function <void(void)>, int>::value, "Cannot construct std::function from int"); static_assert (! std::is_constructible < asio::shared_handler <void(void)>, int>::value, "Cannot construct shared_handler from int"); #endif static_assert (std::is_constructible < asio::shared_handler <void(int)>, asio::shared_handler <void(int)>>::value, "Should construct <void(int)> from <void(int)>"); static_assert (! std::is_constructible < asio::shared_handler <void(int)>, asio::shared_handler <void(void)>>::value, "Can't construct <void(int)> from <void(void)>"); // Hooks called when using the raw handler { test_results r; test_handler h (r); async_op (h); expect (r.call); expect (r.alloc); expect (r.dealloc); expect (r.cont); test_invokable f; boost_asio_handler_invoke_helpers::invoke (std::ref (f), h); expect (r.invoke); expect (f.call); } // Use of std::function shows the hooks not getting called { test_results r; std::function <void(void)> fh ((test_handler) (r)); async_op (fh); expect (r.call); unexpected (r.alloc); unexpected (r.dealloc); unexpected (r.cont); test_invokable f; boost_asio_handler_invoke_helpers::invoke (std::ref (f), fh); unexpected (r.invoke); expect (f.call); } // Make sure shared_handler calls the hooks { test_results r; asio::shared_handler <void(void)> sh ((test_handler)(r)); async_op (sh); expect (r.call); expect (r.alloc); expect (r.dealloc); expect (r.cont); test_invokable f; boost_asio_handler_invoke_helpers::invoke (std::ref (f), sh); expect (r.invoke); expect (f.call); } // Make sure shared_handler via implicit conversion calls hooks { test_results r; test_handler h (r); virtual_async_op ((test_handler) (r)); expect (r.call); expect (r.alloc); expect (r.dealloc); expect (r.cont); } }
static void In2_ndachi(int tr) { if (!parallel_atn) unexpected(tr); }
inline void unexpected(const std::string& what, const char* file, int line, const char* function) { unexpected(what.c_str(), file, line, function); }
void ExcelDOMStripper::RemoveExcelLinks(IDispatchPtr spDispatch) { if (spDispatch == 0) throw Workshare::ArgumentNullException(_T("spDispatch"), _T("The Worksheet that we want to remove the excel links from is invalid.")); Excel::_WorksheetPtr spWorksheet = spDispatch; if (spWorksheet == 0) throw Workshare::Com::ComException(_T("The dispatch instance passed does not implement the Excel::_Worksheet interface"), E_NOINTERFACE); try { _variant_t vtLinkSources(m_spWorkbook->LinkSources((long)Excel::xlLinkTypeExcelLinks)); if (VT_EMPTY == vtLinkSources.vt) return; SAFEARRAY *psa = V_ARRAY(&vtLinkSources); LONG iLBound, iUBound; ::SafeArrayGetLBound(psa, 1, &iLBound); ::SafeArrayGetUBound(psa, 1, &iUBound); if (0 == (iUBound - iLBound + 1)) return; Excel::NamesPtr spNames = m_spWorkbook->Names; Excel::NamePtr spName = NULL; _variant_t vtCellFormula; CStdString sCellFormula, sFirstAddress; std::map<CStdString, int> :: iterator mapName; int nAddressCount = 0; Excel::RangePtr spUsedRange = spWorksheet->UsedRange; _variant_t vtWhat(_T("=")); Excel::RangePtr spCellRange = spUsedRange->Find(vtWhat, vtMissing, (long)Excel::xlFormulas, vtMissing, vtMissing, Excel::xlNext); while (spCellRange != 0) { if (0 == nAddressCount) sFirstAddress = spCellRange->GetAddress(vtMissing, vtMissing, Excel::xlA1); nAddressCount++; vtCellFormula = spCellRange->Formula; sCellFormula = vtCellFormula.bstrVal; if (_T('=') == sCellFormula[0]) { if (-1 != sCellFormula.Find(_T('['))) { spCellRange->Formula = spCellRange->Value; if (1 == nAddressCount) nAddressCount = 0; m_linksCount++; } else if (0 < m_mapNames.size()) { sCellFormula.Delete(0, 1); mapName = m_mapNames.find(sCellFormula); if (mapName != m_mapNames.end()) { try { spName = spNames->Item(sCellFormula.c_str()); } catch(...) { // Should not come here. Because the name is in the map it should also be in the Names collection. spName = 0; } if (spName != 0) { CStdString sValue = spName->Value; if (-1 != sValue.Find(_T('['))) { spCellRange->Formula = spCellRange->Value; mapName->second = 1; if (1 == nAddressCount) nAddressCount = 0; } } } } } _variant_t vtCellRange((IDispatch*)spCellRange); spCellRange = spUsedRange->FindNext(vtCellRange); if (spCellRange == 0) break; if (sFirstAddress == spCellRange->GetAddress(vtMissing, vtMissing, Excel::xlA1)) break; } //Links have been updated, now remove them CComSafeArray <VARIANT> safeArray(psa); for (ULONG i = 1; i <= safeArray.GetCount(); i++) { _variant_t name(safeArray.GetAt(i)); VARIANT result; VariantInit(&result); HRESULT hr = DispatchWrapper(DISPATCH_METHOD, &result, m_spWorkbook, L"BreakLink", 2, _variant_t(Excel::xlLinkTypeExcelLinks), name); if (DISP_E_UNKNOWNNAME != hr) { if (0 != result.boolVal) throw Workshare::Com::ComException(_T("Failed to break the link on the Excel document"), E_FAIL); } } } catch(Workshare::Exception const&) { throw; } catch(...) { unexpected(); } }
// // Recursive descent parser, old-school style. // void getfactor(void) { numvar thesymval = symval; byte thesym = sym; getsym(); // eat the sym we just saved switch (thesym) { case s_nval: vpush(thesymval); break; case s_nvar: if (sym == s_equals) { // assignment, push is after the break; getsym(); assignVar(thesymval, getnum()); } else if (sym == s_incr) { // postincrement nvar++ vpush(getVar(thesymval)); assignVar(thesymval, getVar(thesymval) + 1); getsym(); break; } else if (sym == s_decr) { // postdecrement nvar-- vpush(getVar(thesymval)); assignVar(thesymval, getVar(thesymval) - 1); getsym(); break; } vpush(getVar(thesymval)); // both assignment and reference get pushed here break; case s_nfunct: dofunctioncall(thesymval); // get its value onto the stack break; // Script-function-returning-value used as a factor case s_script_eeprom: // macro returning value callscriptfunction(SCRIPT_EEPROM, findend(thesymval)); break; case s_script_progmem: callscriptfunction(SCRIPT_PROGMEM, thesymval); break; case s_script_file: callscriptfunction(SCRIPT_FILE, (numvar) 0); // name implicitly in idbuf! break; case s_apin: // analog pin reference like a0 if (sym == s_equals) { // digitalWrite or analogWrite getsym(); analogWrite(thesymval, getnum()); vpush(expval); } else vpush(analogRead(thesymval)); break; case s_dpin: // digital pin reference like d1 if (sym == s_equals) { // digitalWrite or analogWrite getsym(); digitalWrite(thesymval, getnum()); vpush(expval); } else vpush(digitalRead(thesymval)); break; case s_incr: if (sym != s_nvar) expected(M_var); assignVar(symval, getVar(symval) + 1); vpush(getVar(symval)); getsym(); break; case s_decr: // pre decrement if (sym != s_nvar) expected(M_var); assignVar(symval, getVar(symval) - 1); vpush(getVar(symval)); getsym(); break; case s_arg: // arg(n) - argument value if (sym != s_lparen) expectedchar(s_lparen); getsym(); // eat '(' vpush(getarg(getnum())); if (sym != s_rparen) expectedchar(s_rparen); getsym(); // eat ')' break; case s_lparen: // expression in parens getexpression(); if (exptype != s_nval) expected(M_number); if (sym != s_rparen) missing(M_rparen); vpush(expval); getsym(); // eat the ) break; // // The Family of Unary Operators, which Bind Most Closely to their Factor // case s_add: // unary plus (like +3) is kind of a no-op getfactor(); // scan a factor and leave its result on the stack break; // done case s_sub: // unary minus (like -3) getfactor(); vpush(-vpop()); // similar to above but we adjust the stack value break; case s_bitnot: getfactor(); vpush(~vpop()); break; case s_logicalnot: getfactor(); vpush(!vpop()); break; case s_bitand: // &var gives address-of-var; ¯o gives eeprom address of macro if (sym == s_nvar) vpush((numvar) &vars[symval]); else if (sym == s_script_eeprom) vpush(symval); else expected(M_var); getsym(); // eat the var reference break; case s_mul: // *foo is contents-of-address-foo; *foo=bar is byte poke assignment /***** // what is really acceptable for an lvalue here? ;) // *y = 5 is failing now by assigning 5 to y before the * is dereferenced // due to calling getfactor // everything else works :( *****/ getfactor(); #if 0 if (sym == s_equals) { getsym(); // eat '=' getexpression(); * (volatile byte *) vpop() = (byte) expval; vpush((numvar) (byte) expval); } else #endif vpush((numvar) (* (volatile byte *) vpop())); break; default: unexpected(M_number); } }
void run () { testcase ("add/traverse"); beast::Journal const j; // debug journal tests::TestFamily f(j); // h3 and h4 differ only in the leaf, same terminal node (level 19) uint256 h1, h2, h3, h4, h5; h1.SetHex ("092891fe4ef6cee585fdc6fda0e09eb4d386363158ec3321b8123e5a772c6ca7"); h2.SetHex ("436ccbac3347baa1f1e53baeef1f43334da88f1f6d70d963b833afd6dfa289fe"); h3.SetHex ("b92891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8"); h4.SetHex ("b92891fe4ef6cee585fdc6fda2e09eb4d386363158ec3321b8123e5a772c6ca8"); h5.SetHex ("a92891fe4ef6cee585fdc6fda0e09eb4d386363158ec3321b8123e5a772c6ca7"); SHAMap sMap (SHAMapType::FREE, f); SHAMapItem i1 (h1, IntToVUC (1)), i2 (h2, IntToVUC (2)), i3 (h3, IntToVUC (3)), i4 (h4, IntToVUC (4)), i5 (h5, IntToVUC (5)); unexpected (!sMap.addItem (i2, true, false), "no add"); unexpected (!sMap.addItem (i1, true, false), "no add"); auto i = sMap.begin(); auto e = sMap.end(); unexpected (i == e || (*i != i1), "bad traverse"); ++i; unexpected (i == e || (*i != i2), "bad traverse"); ++i; unexpected (i != e, "bad traverse"); sMap.addItem (i4, true, false); sMap.delItem (i2.key()); sMap.addItem (i3, true, false); i = sMap.begin(); e = sMap.end(); unexpected (i == e || (*i != i1), "bad traverse"); ++i; unexpected (i == e || (*i != i3), "bad traverse"); ++i; unexpected (i == e || (*i != i4), "bad traverse"); ++i; unexpected (i != e, "bad traverse"); testcase ("snapshot"); SHAMapHash mapHash = sMap.getHash (); std::shared_ptr<SHAMap> map2 = sMap.snapShot (false); unexpected (sMap.getHash () != mapHash, "bad snapshot"); unexpected (map2->getHash () != mapHash, "bad snapshot"); unexpected (!sMap.delItem (sMap.begin()->key()), "bad mod"); unexpected (sMap.getHash () == mapHash, "bad snapshot"); unexpected (map2->getHash () != mapHash, "bad snapshot"); testcase ("build/tear"); { std::vector<uint256> keys(8); keys[0].SetHex ("b92891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8"); keys[1].SetHex ("b92881fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8"); keys[2].SetHex ("b92691fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8"); keys[3].SetHex ("b92791fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8"); keys[4].SetHex ("b91891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8"); keys[5].SetHex ("b99891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8"); keys[6].SetHex ("f22891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8"); keys[7].SetHex ("292891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8"); std::vector<uint256> hashes(8); hashes[0].SetHex ("B7387CFEA0465759ADC718E8C42B52D2309D179B326E239EB5075C64B6281F7F"); hashes[1].SetHex ("FBC195A9592A54AB44010274163CB6BA95F497EC5BA0A8831845467FB2ECE266"); hashes[2].SetHex ("4E7D2684B65DFD48937FFB775E20175C43AF0C94066F7D5679F51AE756795B75"); hashes[3].SetHex ("7A2F312EB203695FFD164E038E281839EEF06A1B99BFC263F3CECC6C74F93E07"); hashes[4].SetHex ("395A6691A372387A703FB0F2C6D2C405DAF307D0817F8F0E207596462B0E3A3E"); hashes[5].SetHex ("D044C0A696DE3169CC70AE216A1564D69DE96582865796142CE7D98A84D9DDE4"); hashes[6].SetHex ("76DCC77C4027309B5A91AD164083264D70B77B5E43E08AEDA5EBF94361143615"); hashes[7].SetHex ("DF4220E93ADC6F5569063A01B4DC79F8DB9553B6A3222ADE23DEA02BBE7230E5"); SHAMap map (SHAMapType::FREE, f); expect (map.getHash() == zero, "bad initial empty map hash"); for (int i = 0; i < keys.size(); ++i) { SHAMapItem item (keys[i], IntToVUC (i)); map.addItem (item, true, false); expect (map.getHash().as_uint256() == hashes[i], "bad buildup map hash"); } for (int i = keys.size() - 1; i >= 0; --i) { expect (map.getHash().as_uint256() == hashes[i], "bad teardown hash"); map.delItem (keys[i]); } expect (map.getHash() == zero, "bad final empty map hash"); } }
TokenType getNextToken(const util::FastInsertVector<string_view>& lines, size_t* line, size_t* offset, const string_view& whole, Location& pos, Token* out, bool crlf) { bool flag = true; if(*line == lines.size()) { out->loc = pos; out->type = TokenType::EndOfFile; return TokenType::EndOfFile; } string_view stream = lines[*line].substr(*offset); if(stream.empty()) { out->loc = pos; out->type = TokenType::EndOfFile; return TokenType::EndOfFile; } size_t read = 0; size_t unicodeLength = 0; // first eat all whitespace skipWhitespace(stream, pos, offset); Token& tok = *out; tok.loc = pos; tok.type = TokenType::Invalid; // check compound symbols first. if(hasPrefix(stream, "//")) { tok.type = TokenType::Comment; // stream = stream.substr(0, 0); (*line)++; pos.line++; pos.col = 0; (*offset) = 0; // don't assign lines[line] = stream, since over here we've changed 'line' to be the next one. flag = false; tok.text = ""; } else if(hasPrefix(stream, "==")) { tok.type = TokenType::EqualsTo; tok.text = "=="; read = 2; } else if(hasPrefix(stream, ">=")) { tok.type = TokenType::GreaterEquals; tok.text = ">="; read = 2; } else if(hasPrefix(stream, "<=")) { tok.type = TokenType::LessThanEquals; tok.text = "<="; read = 2; } else if(hasPrefix(stream, "!=")) { tok.type = TokenType::NotEquals; tok.text = "!="; read = 2; } else if(hasPrefix(stream, "||")) { tok.type = TokenType::LogicalOr; tok.text = "||"; read = 2; } else if(hasPrefix(stream, "&&")) { tok.type = TokenType::LogicalAnd; tok.text = "&&"; read = 2; } else if(hasPrefix(stream, "<-")) { tok.type = TokenType::LeftArrow; tok.text = "<-"; read = 2; } else if(hasPrefix(stream, "->")) { tok.type = TokenType::RightArrow; tok.text = "->"; read = 2; } else if(hasPrefix(stream, "<=")) { tok.type = TokenType::FatLeftArrow; tok.text = "<="; read = 2; } else if(hasPrefix(stream, "=>")) { tok.type = TokenType::FatRightArrow; tok.text = "=>"; read = 2; } else if(hasPrefix(stream, "++")) { tok.type = TokenType::DoublePlus; tok.text = "++"; read = 2; } else if(hasPrefix(stream, "--")) { tok.type = TokenType::DoubleMinus; tok.text = "--"; read = 2; } else if(hasPrefix(stream, "+=")) { tok.type = TokenType::PlusEq; tok.text = "+="; read = 2; } else if(hasPrefix(stream, "-=")) { tok.type = TokenType::MinusEq; tok.text = "-="; read = 2; } else if(hasPrefix(stream, "*=")) { tok.type = TokenType::MultiplyEq; tok.text = "*="; read = 2; } else if(hasPrefix(stream, "/=")) { tok.type = TokenType::DivideEq; tok.text = "/="; read = 2; } else if(hasPrefix(stream, "%=")) { tok.type = TokenType::ModEq; tok.text = "%="; read = 2; } else if(hasPrefix(stream, "&=")) { tok.type = TokenType::AmpersandEq; tok.text = "&="; read = 2; } else if(hasPrefix(stream, "|=")) { tok.type = TokenType::PipeEq; tok.text = "|="; read = 2; } else if(hasPrefix(stream, "^=")) { tok.type = TokenType::CaretEq; tok.text = "^="; read = 2; } else if(hasPrefix(stream, "::")) { tok.type = TokenType::DoubleColon; tok.text = "::"; read = 2; } else if(hasPrefix(stream, "...")) { tok.type = TokenType::Ellipsis; tok.text = "..."; read = 3; } else if(hasPrefix(stream, "..<")) { tok.type = TokenType::HalfOpenEllipsis; tok.text = "..<"; read = 3; } else if(hasPrefix(stream, "/*")) { int currentNest = 1; // support nested, so basically we have to loop until we find either a /* or a */ stream.remove_prefix(2); (*offset) += 2; pos.col += 2; Location opening = pos; Location curpos = pos; size_t k = 0; while(currentNest > 0) { // we can do this, because we know the closing token (*/) is 2 chars long // so if we have 1 char left, gg. if(k + 1 == stream.size() || stream[k] == '\n') { if(*line + 1 == lines.size()) error(opening, "expected closing */ (reached EOF), for block comment started here:"); // else, get the next line. // also note: if we're in this loop, we're inside a block comment. // since the ending token cannot be split across lines, we know that this last char // must also be part of the comment. hence, just skip over it. k = 0; curpos.line++; curpos.col = 0; (*offset) = 0; (*line)++; stream = lines[*line]; continue; } if(stream[k] == '/' && stream[k + 1] == '*') currentNest++, k++, curpos.col++, opening = curpos; else if(stream[k] == '*' && stream[k + 1] == '/') currentNest--, k++, curpos.col++; k++; curpos.col++; } if(currentNest != 0) error(opening, "expected closing */ (reached EOF), for block comment started here:"); pos = curpos; // don't actually store the text, because it's pointless and memory-wasting // tok.text = "/* I used to be a comment like you, until I took a memory-leak to the knee. */"; tok.type = TokenType::Comment; tok.text = ""; read = k; } else if(hasPrefix(stream, "*/")) { unexpected(tok.loc, "'*/'"); } // attrs else if(hasPrefix(stream, "@nomangle")) { tok.type = TokenType::Attr_NoMangle; tok.text = "@nomangle"; read = 9; } else if(hasPrefix(stream, "@entry")) { tok.type = TokenType::Attr_EntryFn; tok.text = "@entry"; read = 6; } else if(hasPrefix(stream, "@raw")) { tok.type = TokenType::Attr_Raw; tok.text = "@raw"; read = 4; } else if(hasPrefix(stream, "@operator")) { tok.type = TokenType::Attr_Operator; tok.text = "@operator"; read = 9; } // unicode stuff else if(hasPrefix(stream, "ƒ")) { tok.type = TokenType::Func; read = std::string("ƒ").length(); tok.text = "ƒ"; unicodeLength = 1; } else if(hasPrefix(stream, "fi")) { tok.type = TokenType::ForeignFunc; read = std::string("fi").length(); tok.text = "fi"; unicodeLength = 1; } else if(hasPrefix(stream, "÷")) { tok.type = TokenType::Divide; read = std::string("÷").length(); tok.text = "÷"; unicodeLength = 1; } else if(hasPrefix(stream, "≠")) { tok.type = TokenType::NotEquals; read = std::string("≠").length(); tok.text = "≠"; unicodeLength = 1; } else if(hasPrefix(stream, "≤")) { tok.type = TokenType::LessThanEquals; read = std::string("≤").length(); tok.text = "≤"; unicodeLength = 1; } else if(hasPrefix(stream, "≥")) { tok.type = TokenType::GreaterEquals; read = std::string("≥").length(); tok.text = "≥"; unicodeLength = 1; } // note some special-casing is needed to differentiate between unary +/- and binary +/- // cases where we want binary: // ...) + 3 // ...] + 3 // ident + 3 // number + 3 // string + 3 // so in every other case we want unary +/-. // note: this dumb '<=255' thing is because windows likes to assert useless things. else if((!stream.empty() && ((stream[0] >= 1 && (int) stream[0] <= 255 && isdigit(stream[0])) || shouldConsiderUnaryLiteral(stream, pos))) /* handle cases like '+ 3' or '- 14' (ie. space between sign and number) */ && ((isdigit(stream[0]) ? true : false) || (stream.size() > 1 && isdigit(stream[1])))) { // copy it. auto tmp = stream; if(tmp.find('-') == 0 || tmp.find('+') == 0) tmp.remove_prefix(1); int base = 10; if(tmp.find("0x") == 0 || tmp.find("0X") == 0) base = 16, tmp.remove_prefix(2); else if(tmp.find("0b") == 0 || tmp.find("0B") == 0) base = 2, tmp.remove_prefix(2); // find that shit auto end = std::find_if_not(tmp.begin(), tmp.end(), [base](const char& c) -> bool { if(base == 10) return isdigit(c); if(base == 16) return isdigit(c) || (toupper(c) >= 'A' && toupper(c) <= 'F'); else return (c == '0' || c == '1'); }); tmp.remove_prefix((end - tmp.begin())); // check if we have 'e' or 'E' bool hadExp = false; if(tmp.size() > 0 && (tmp[0] == 'e' || tmp[0] == 'E')) { if(base != 10) error("exponential form is supported with neither hexadecimal nor binary literals"); // find that shit auto next = std::find_if_not(tmp.begin() + 1, tmp.end(), isdigit); // this does the 'e' as well. tmp.remove_prefix(next - tmp.begin()); hadExp = true; } size_t didRead = stream.size() - tmp.size(); auto post = stream.substr(didRead); if(!post.empty() && post[0] == '.') { if(base != 10) error("invalid floating point literal; only valid in base 10"); else if(hadExp) error("invalid floating point literal; decimal point cannot occur after the exponent ('e' or 'E')."); // if the previous token was a '.' as well, then we're doing some tuple access // eg. x.0.1 (we would be at '0', having a period both ahead and behind us) // if the next token is not a number, then same thing, eg. // x.0.z, where the first tuple element of 'x' is a struct or something. // so -- lex a floating point *iff* the previous token was not '.', and the next token is a digit. if(prevType != TokenType::Period && post.size() > 1 && isdigit(post[1])) { // yes, parse a floating point post.remove_prefix(1), didRead++; while(post.size() > 0 && isdigit(post.front())) post.remove_prefix(1), didRead++; // ok. } else { // no, just return the integer token. // (which we do below, so just do nothing here) } } tok.text = stream.substr(0, didRead); tok.type = TokenType::Number; tok.loc.len = didRead; read = didRead; } else if(!stream.empty() && (stream[0] == '_' || utf8iscategory(stream.data(), stream.size(), UTF8_CATEGORY_LETTER) > 0)) { // get as many letters as possible first size_t identLength = utf8iscategory(stream.data(), stream.size(), UTF8_CATEGORY_LETTER | UTF8_CATEGORY_PUNCTUATION_CONNECTOR | UTF8_CATEGORY_NUMBER); read = identLength; tok.text = stream.substr(0, identLength); initKeywordMap(); if(auto it = keywordMap.find(tok.text); it != keywordMap.end()) tok.type = it->second; else
void PublishExcelToPDFWithWorkBook(Excel::_WorkbookPtr spWorkbook, const CStdString& sOutputFile, int from, int to) { LOG_WS_FUNCTION_SCOPE(); CStdString restrictionLevel = c_sNoRestriction; CStdString classification = c_sNoClassification; try { _variant_t vSaved = spWorkbook->Saved; restrictionLevel = GetRestrictionLevel(spWorkbook); classification = GetClassification(spWorkbook); // TODO: Switch off Excel's attempt to match the printer's paper size // by temporarily setting spWorkbook->Application->MapPaperSize = VARIANT_FALSE. // But that option isn't available in the Excel 2000 API that we're using. bool bIsNotExcel97 = (atof(spWorkbook->Application->Version) > 8.0); if( !PDFConverterController::UseExcelPrintArea() ) { for (int iIndex = 1; iIndex <= spWorkbook->Worksheets->Count; iIndex++) { Excel::_WorksheetPtr spWorksheet = spWorkbook->Worksheets->Item[ iIndex ]; spWorksheet->PageSetup->PrintArea = _T(""); } } PDFConverterController pdfConverter; pdfConverter.InitialisePDFConverterUseFileName(sOutputFile, VARIANT_TRUE); _variant_t vtPrintToFile(false); _variant_t vtActivePrinter(c_sPDFDriverName); _variant_t vtOutputFile(sOutputFile); _variant_t vtFrom(vtMissing); _variant_t vtTo(vtMissing); if (from != 0 || to != 0) { vtFrom = from; vtTo = to; } if(bIsNotExcel97) { //60.18: This msg loop is to prevent the 'known' issue with Workshare events from crashing. DoEvents(); spWorkbook->PrintOut(&vtFrom, &vtTo, &vtMissing, &vtMissing, &vtActivePrinter, &vtPrintToFile, &vtMissing, &vtOutputFile); } else { if (::PathFileExists(sOutputFile) && !::DeleteFile(sOutputFile)) { CStdString sMsg; sMsg.Format(_T("Failed to overwrite file %s"), sOutputFile.c_str()); throw Workshare::System::IO::IOException(sMsg); } DismissPrintDialog(sOutputFile); _variant_t vtResult; IDispatchPtr spDispDocument = spWorkbook; HRESULT hr = CCOMDispatchHelper::AutoWrap(DISPATCH_METHOD, &vtResult, spDispDocument, L"PrintOut", 7, vtMissing, vtPrintToFile, vtActivePrinter, vtMissing, vtMissing, vtMissing, vtMissing); if (FAILED(hr)) throw Workshare::Com::ComException(_T("Failed to invoke PrintOut method"), hr, spDispDocument); } pdfConverter.UnInitialisePDFConverter(); // Setting the following property fixes an issue in the Office - iManage integration, // in which iManage appears to query the Saved flag on Close and pops up a dialog, // even though we have specified to Close with no Save: LCID lCid = LocaleHelper::GetLocaleIDForInstalledExcel(spWorkbook); spWorkbook->put_Saved(lCid, vSaved); if(c_sNoRestriction != restrictionLevel) SetPdfRestrictionLevel(sOutputFile, restrictionLevel); if (c_sNoClassification != classification) SetPdfClassification(sOutputFile, classification); } catch(const Workshare::Exception&) { throw; } catch(...) { unexpected(); } }
void testParseUrl () { testcase ("parseUrl"); std::string strScheme; std::string strDomain; int iPort; std::string strPath; unexpected (!parseUrl ("lower://domain", strScheme, strDomain, iPort, strPath), "parseUrl: lower://domain failed"); unexpected (strScheme != "lower", "parseUrl: lower://domain : scheme failed"); unexpected (strDomain != "domain", "parseUrl: lower://domain : domain failed"); unexpected (iPort != -1, "parseUrl: lower://domain : port failed"); unexpected (strPath != "", "parseUrl: lower://domain : path failed"); unexpected (!parseUrl ("UPPER://domain:234/", strScheme, strDomain, iPort, strPath), "parseUrl: UPPER://domain:234/ failed"); unexpected (strScheme != "upper", "parseUrl: UPPER://domain:234/ : scheme failed"); unexpected (iPort != 234, boost::str (boost::format ("parseUrl: UPPER://domain:234/ : port failed: %d") % iPort)); unexpected (strPath != "/", "parseUrl: UPPER://domain:234/ : path failed"); unexpected (!parseUrl ("Mixed://domain/path", strScheme, strDomain, iPort, strPath), "parseUrl: Mixed://domain/path failed"); unexpected (strScheme != "mixed", "parseUrl: Mixed://domain/path tolower failed"); unexpected (strPath != "/path", "parseUrl: Mixed://domain/path path failed"); }
void run () { testcase ("add/traverse"); beast::manual_clock <std::chrono::steady_clock> clock; // manual advance clock beast::journal const j; // debug journal fullbelowcache fullbelowcache ("test.full_below", clock); treenodecache treenodecache ("test.tree_node_cache", 65536, 60, clock, j); nodestore::dummyscheduler scheduler; auto db = nodestore::manager::instance().make_database ( "test", scheduler, j, 0, parsedelimitedkeyvaluestring("type=memory|path=shamap_test")); // h3 and h4 differ only in the leaf, same terminal node (level 19) uint256 h1, h2, h3, h4, h5; h1.sethex ("092891fe4ef6cee585fdc6fda0e09eb4d386363158ec3321b8123e5a772c6ca7"); h2.sethex ("436ccbac3347baa1f1e53baeef1f43334da88f1f6d70d963b833afd6dfa289fe"); h3.sethex ("b92891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8"); h4.sethex ("b92891fe4ef6cee585fdc6fda2e09eb4d386363158ec3321b8123e5a772c6ca8"); h5.sethex ("a92891fe4ef6cee585fdc6fda0e09eb4d386363158ec3321b8123e5a772c6ca7"); shamap smap (smtfree, fullbelowcache, treenodecache, *db, handler(), beast::journal()); shamapitem i1 (h1, inttovuc (1)), i2 (h2, inttovuc (2)), i3 (h3, inttovuc (3)), i4 (h4, inttovuc (4)), i5 (h5, inttovuc (5)); unexpected (!smap.additem (i2, true, false), "no add"); unexpected (!smap.additem (i1, true, false), "no add"); shamapitem::pointer i; i = smap.peekfirstitem (); unexpected (!i || (*i != i1), "bad traverse"); i = smap.peeknextitem (i->gettag ()); unexpected (!i || (*i != i2), "bad traverse"); i = smap.peeknextitem (i->gettag ()); unexpected (i, "bad traverse"); smap.additem (i4, true, false); smap.delitem (i2.gettag ()); smap.additem (i3, true, false); i = smap.peekfirstitem (); unexpected (!i || (*i != i1), "bad traverse"); i = smap.peeknextitem (i->gettag ()); unexpected (!i || (*i != i3), "bad traverse"); i = smap.peeknextitem (i->gettag ()); unexpected (!i || (*i != i4), "bad traverse"); i = smap.peeknextitem (i->gettag ()); unexpected (i, "bad traverse"); testcase ("snapshot"); uint256 maphash = smap.gethash (); shamap::pointer map2 = smap.snapshot (false); unexpected (smap.gethash () != maphash, "bad snapshot"); unexpected (map2->gethash () != maphash, "bad snapshot"); unexpected (!smap.delitem (smap.peekfirstitem ()->gettag ()), "bad mod"); unexpected (smap.gethash () == maphash, "bad snapshot"); unexpected (map2->gethash () != maphash, "bad snapshot"); }
// Get a statement void getstatement(void) { #if !defined(TINY85) chkbreak(); #endif if (sym == s_while) { // at this point sym is pointing at s_while, before the conditional expression // save fetchptr so we can restart parsing from here as the while iterates char *fetchmark = fetchptr; for (;;) { fetchptr = fetchmark; // restore to mark primec(); // set up for mr. getsym() getsym(); // fetch the start of the conditional if (!getnum()) { //longjmp(env, X_EXIT); // get the conditional; exit on false sym = s_eof; // we're finished here. move along. return; } if (sym != s_colon) expectedchar(':'); getsym(); // eat : getstatementlist(); } } else if (sym == s_if) { getsym(); // fetch the start of the conditional if (!getnum()) { //longjmp(env, X_EXIT); // get the conditional; exit on false sym = s_eof; return; } if (sym != s_colon) expectedchar(':'); getsym(); // eat : getstatementlist(); } #if SKETCH // The switch statement: call one of N macros based on a selector value // switch <numval>: macroid1, macroid2,.., macroidN // numval < 0: numval = 0 // numval > N: numval = N else if (sym == s_switch) { getsym(); // eat "switch" numvar selector = getnum(); // evaluate the switch value if (selector < 0) selector = 0; if (sym != s_colon) expectedchar(':'); // we sit before the first macroid // scan and discard the <selector>'s worth of macro ids // that sit before the one we want for (;;) { getsym(); // get an id, sets symval to its eeprom addr as a side effect if (sym != s_macro) expected (6); // TODO: define M_macro instead of 6 getsym(); // eat id, get separator; assume symval is untouched if ((sym == s_semi) || (sym == s_eof)) break; // last case is default so we exit always if (sym != s_comma) expectedchar(','); if (!selector) break; // ok, this is the one we want to execute selector--; // one down... } // call the macro whose addr is squirreled in symval all this time // on return, the parser is ready to pick up where we left off doMacroCall(symval); // scan past the rest of the unused switch options, if any // TODO: syntax checking for non-chosen options could be made much tighter at the cost of some space while ((sym != s_semi) && (sym != s_eof)) getsym(); // scan to end of statement without executing } #endif else if ((sym == s_macro) || (sym == s_undef)) { // macro def or ref getsym(); // scan past macro name to next symbol: ; or := if (sym == s_define) { // macro definition: macroid := strvalue // to define the macro, we need to copy the id somewhere on the stack // to avoid having this local buffer in every getstatement stack frame, // we break out defineMacro here to a separate function that only eats that // stack in the case that a macro is being defined #ifdef TINY85 unexpected(M_defmacro); #else defineMacro(); #endif } else if ((sym == s_semi) || (sym == s_eof)) { // valid macro reference: let's call it #if SKETCH doMacroCall(symval); // parseid stashes the macro address in symval #else char op = sym; // save sym for restore expval = findKey(idbuf); // assumes id in idbuf isn't clobbered since getsym() above if (expval >= 0) { char *fetchmark = fetchptr; // save the current parse pointer // call the macro calleeprommacro(findend(expval)); // register the macro into the parser stream getsym(); getstatementlist(); // parse and execute the macro code here if (sym != s_eof) expected(M_eof); // restore parsing context so we can resume cleanly fetchptr = fetchmark; // restore pointer primec(); // and inchar sym = op; // restore saved sym: s_semi or s_eof } else unexpected(M_id); #endif } else expectedchar(';'); //else getexpression(); // assume it was macro1+32+macro2... } else if (sym == s_run) { // run macroname getsym(); if (sym != s_macro) unexpected(M_id); #if 0 // address of macroid is in symval via parseid startTask(kludge(symval)); getsym(); #else // address of macroid is in symval via parseid // check for [,snoozeintervalms] getsym(); // eat macroid to check for comma; symval untouched if (sym == s_comma) { vpush(symval); getsym(); // eat the comma getnum(); // get a number or else startTask(kludge(vpop()), expval); } else startTask(kludge(symval), 0); #endif } else if (sym == s_stop) { getsym(); if (sym == s_mul) { // stop * stops all tasks initTaskList(); getsym(); } else if ((sym == s_semi) || (sym == s_eof)) { if (background) stopTask(curtask); // stop with no args stops the current task IF we're in back else initTaskList(); // in foreground, stop all } else stopTask(getnum()); } else if (sym == s_boot) reboot(); #if !defined(TINY85) else if (sym == s_rm) { // rm "sym" or rm * getsym(); if (sym == s_macro) { eraseentry(idbuf); } else if (sym == s_mul) nukeeeprom(); else expected(M_id); getsym(); } else if (sym == s_ps) showTaskList(); else if (sym == s_peep) { getsym(); cmd_peep(); } else if (sym == s_ls) { getsym(); cmd_ls(); } else if (sym == s_help) { getsym(); cmd_help(); } else if (sym == s_print) { getsym(); cmd_print(); } #endif #ifdef HEX_UPLOAD // a line beginning with a colon is treated as a hex record // containing data to upload to eeprom // // TODO: verify checksum // else if (sym == s_colon) { // fetchptr points at the byte count byte byteCount = gethex(2); // 2 bytes byte count int addr = gethex(4); // 4 bytes address byte recordType = gethex(2); // 2 bytes record type; now fetchptr -> data if (recordType == 1) reboot(); // reboot on EOF record (01) if (recordType != 0) return; // we only handle the data record (00) if (addr == 0) nukeeeprom(); // auto-clear eeprom on write to 0000 while (byteCount--) eewrite(addr++, gethex(2)); // update the eeprom gethex(2); // discard the checksum getsym(); // and re-prime the parser } #endif else { getexpression(); } }
void TestPeerLogicSyncClient::on_connect () { { // pre-handshake hook is optional on_pre_handshake (); if (failure (error ())) return ; } if (socket ().requires_handshake ()) { if (failure (socket ().handshake (to_handshake_type (get_role ()), error ()))) return; } { std::size_t const amount = boost::asio::write ( socket (), boost::asio::buffer ("hello", 5), error ()); if (failure (error ())) return; if (unexpected (amount == 5, error ())) return; } { char data [7]; size_t const amount = boost::asio::read ( socket (), boost::asio::buffer (data, 7), error ()); if (failure (error ())) return; if (unexpected (amount == 7, error ())) return; if (unexpected (memcmp (&data, "goodbye", 7) == 0, error ())) return; } // Wait for 1 byte which should never come. Instead, // the server should close its end and we will get eof { char data [1]; boost::asio::read (socket (), boost::asio::buffer (data, 1), error ()); if (error () == boost::asio::error::eof) { error () = error_code (); } else if (unexpected (failure (error ()), error ())) { return; } } if (socket ().requires_handshake ()) { if (failure (socket ().shutdown (error ()), true)) return; } if (failure (socket ().shutdown (Socket::shutdown_both, error ()))) return; if (failure (socket ().close (error ()))) return; }