diff
stringlengths 41
2.03M
| msg
stringlengths 1
1.5k
⌀ | repo
stringlengths 5
40
| sha
stringlengths 40
40
| time
stringlengths 20
20
|
---|---|---|---|---|
mmm a / src / base / rss / rssdownloadrule . cpp <nl> ppp b / src / base / rss / rssdownloadrule . cpp <nl> bool DownloadRule : : matches ( const QString & articleTitle ) const <nl> pos = reg . indexIn ( articleTitle ) ; <nl> if ( pos ! = - 1 ) { <nl> int epTheirs = reg . cap ( 1 ) . toInt ( ) ; <nl> - if ( epOursFirst < = epTheirs & & epOursLast > = epTheirs ) <nl> + if ( ( epOursFirst < = epTheirs ) & & ( epOursLast > = epTheirs ) ) <nl> return true ; <nl> } <nl> } <nl> QStringList DownloadRule : : findMatchingArticles ( const FeedPtr & feed ) const <nl> <nl> ArticleHash : : ConstIterator artIt = feedArticles . begin ( ) ; <nl> ArticleHash : : ConstIterator artItend = feedArticles . end ( ) ; <nl> - for ( ; artIt ! = artItend ; + + artIt ) { <nl> + for ( ; artIt ! = artItend ; + + artIt ) { <nl> const QString title = artIt . value ( ) - > title ( ) ; <nl> if ( matches ( title ) ) <nl> ret < < title ; <nl> mmm a / src / base / rss / rssfeed . cpp <nl> ppp b / src / base / rss / rssfeed . cpp <nl> Feed : : Feed ( const QString & url , Manager * manager ) <nl> <nl> / / Download the RSS Feed icon <nl> Net : : DownloadHandler * handler = Net : : DownloadManager : : instance ( ) - > downloadUrl ( iconUrl ( ) , true ) ; <nl> - connect ( handler , SIGNAL ( downloadFinished ( QString , QString ) ) , this , SLOT ( handleIconDownloadFinished ( QString , QString ) ) ) ; <nl> + connect ( handler , SIGNAL ( downloadFinished ( QString , QString ) ) , this , SLOT ( handleIconDownloadFinished ( QString , QString ) ) ) ; <nl> <nl> / / Load old RSS articles <nl> loadItemsFromDisk ( ) ; <nl> void Feed : : saveItemsToDisk ( ) <nl> <nl> ArticleHash : : ConstIterator it = m_articles . begin ( ) ; <nl> ArticleHash : : ConstIterator itend = m_articles . end ( ) ; <nl> - for ( ; it ! = itend ; + + it ) { <nl> + for ( ; it ! = itend ; + + it ) <nl> oldItems < < it . value ( ) - > toHash ( ) ; <nl> - } <nl> qDebug ( " Saving % d old items for feed % s " , oldItems . size ( ) , qPrintable ( displayName ( ) ) ) ; <nl> QHash < QString , QVariant > allOldItems = qBTRSS . value ( " old_items " , QHash < QString , QVariant > ( ) ) . toHash ( ) ; <nl> allOldItems [ m_url ] = oldItems ; <nl> void Feed : : addArticle ( const ArticlePtr & article ) <nl> } <nl> <nl> / / Check if article was inserted at the end of the list and will break max_articles limit <nl> - if ( Preferences : : instance ( ) - > isRssDownloadingEnabled ( ) ) { <nl> + if ( Preferences : : instance ( ) - > isRssDownloadingEnabled ( ) ) <nl> if ( ( lbIndex < maxArticles ) & & ! article - > isRead ( ) ) <nl> downloadArticleTorrentIfMatching ( article ) ; <nl> - } <nl> } <nl> else { <nl> / / m_articles . contains ( article - > guid ( ) ) <nl> / / Try to download skipped articles <nl> if ( Preferences : : instance ( ) - > isRssDownloadingEnabled ( ) ) { <nl> ArticlePtr skipped = m_articles . value ( article - > guid ( ) , ArticlePtr ( ) ) ; <nl> - if ( skipped ) { <nl> + if ( skipped ) <nl> if ( ! skipped - > isRead ( ) ) <nl> downloadArticleTorrentIfMatching ( skipped ) ; <nl> - } <nl> } <nl> } <nl> } <nl> bool Feed : : refresh ( ) <nl> m_loading = true ; <nl> / / Download the RSS again <nl> Net : : DownloadHandler * handler = Net : : DownloadManager : : instance ( ) - > downloadUrl ( m_url ) ; <nl> - connect ( handler , SIGNAL ( downloadFinished ( QString , QByteArray ) ) , this , SLOT ( handleRssDownloadFinished ( QString , QByteArray ) ) ) ; <nl> - connect ( handler , SIGNAL ( downloadFailed ( QString , QString ) ) , this , SLOT ( handleRssDownloadFailed ( QString , QString ) ) ) ; <nl> + connect ( handler , SIGNAL ( downloadFinished ( QString , QByteArray ) ) , this , SLOT ( handleRssDownloadFinished ( QString , QByteArray ) ) ) ; <nl> + connect ( handler , SIGNAL ( downloadFailed ( QString , QString ) ) , this , SLOT ( handleRssDownloadFailed ( QString , QString ) ) ) ; <nl> return true ; <nl> } <nl> <nl> bool Feed : : hasCustomIcon ( ) const <nl> void Feed : : setIconPath ( const QString & path ) <nl> { <nl> QString nativePath = Utils : : Fs : : fromNativePath ( path ) ; <nl> - if ( nativePath = = m_icon | | nativePath . isEmpty ( ) | | ! QFile : : exists ( nativePath ) ) return ; <nl> + if ( ( nativePath = = m_icon ) | | nativePath . isEmpty ( ) | | ! QFile : : exists ( nativePath ) ) return ; <nl> <nl> if ( ! m_icon . startsWith ( " : / " ) & & QFile : : exists ( m_icon ) ) <nl> Utils : : Fs : : forceRemove ( m_icon ) ; <nl> void Feed : : markAsRead ( ) <nl> { <nl> ArticleHash : : ConstIterator it = m_articles . begin ( ) ; <nl> ArticleHash : : ConstIterator itend = m_articles . end ( ) ; <nl> - for ( ; it ! = itend ; + + it ) { <nl> + for ( ; it ! = itend ; + + it ) <nl> it . value ( ) - > markAsRead ( ) ; <nl> - } <nl> m_unreadCount = 0 ; <nl> m_manager - > forwardFeedInfosChanged ( m_url , displayName ( ) , 0 ) ; <nl> } <nl> ArticleList Feed : : unreadArticleListByDateDesc ( ) const <nl> <nl> ArticleList : : ConstIterator it = m_articlesByDate . begin ( ) ; <nl> ArticleList : : ConstIterator itend = m_articlesByDate . end ( ) ; <nl> - for ( ; it ! = itend ; + + it ) { <nl> + for ( ; it ! = itend ; + + it ) <nl> if ( ! ( * it ) - > isRead ( ) ) <nl> unreadNews < < * it ; <nl> - } <nl> return unreadNews ; <nl> } <nl> <nl> void Feed : : downloadArticleTorrentIfMatching ( const ArticlePtr & article ) <nl> void Feed : : recheckRssItemsForDownload ( ) <nl> { <nl> Q_ASSERT ( Preferences : : instance ( ) - > isRssDownloadingEnabled ( ) ) ; <nl> - foreach ( const ArticlePtr & article , m_articlesByDate ) { <nl> + foreach ( const ArticlePtr & article , m_articlesByDate ) <nl> if ( ! article - > isRead ( ) ) <nl> downloadArticleTorrentIfMatching ( article ) ; <nl> - } <nl> } <nl> <nl> void Feed : : handleNewArticle ( const QVariantHash & articleData ) <nl> void Feed : : handleNewArticle ( const QVariantHash & articleData ) <nl> m_manager - > forwardFeedInfosChanged ( m_url , displayName ( ) , m_unreadCount ) ; <nl> / / FIXME : We should forward the information here but this would seriously decrease <nl> / / performance with current design . <nl> - / / m_manager - > forwardFeedContentChanged ( m_url ) ; <nl> + / / m_manager - > forwardFeedContentChanged ( m_url ) ; <nl> } <nl> <nl> void Feed : : handleParsingFinished ( const QString & error ) <nl> mmm a / src / base / rss / rssfeed . h <nl> ppp b / src / base / rss / rssfeed . h <nl> namespace Rss <nl> Q_OBJECT <nl> <nl> public : <nl> - Feed ( const QString & url , Manager * manager ) ; <nl> + Feed ( const QString & url , Manager * manager ) ; <nl> ~ Feed ( ) ; <nl> <nl> bool refresh ( ) ; <nl> mmm a / src / gui / rss / automatedrssdownloader . cpp <nl> ppp b / src / gui / rss / automatedrssdownloader . cpp <nl> <nl> # include " ui_automatedrssdownloader . h " <nl> # include " automatedrssdownloader . h " <nl> <nl> - AutomatedRssDownloader : : AutomatedRssDownloader ( const QWeakPointer < Rss : : Manager > & manager , QWidget * parent ) : <nl> - QDialog ( parent ) , <nl> - ui ( new Ui : : AutomatedRssDownloader ) , <nl> - m_manager ( manager ) , m_editedRule ( 0 ) <nl> + AutomatedRssDownloader : : AutomatedRssDownloader ( const QWeakPointer < Rss : : Manager > & manager , QWidget * parent ) <nl> + : QDialog ( parent ) , <nl> + ui ( new Ui : : AutomatedRssDownloader ) , <nl> + m_manager ( manager ) , m_editedRule ( 0 ) <nl> { <nl> - ui - > setupUi ( this ) ; <nl> - / / Icons <nl> - ui - > removeRuleBtn - > setIcon ( GuiIconProvider : : instance ( ) - > getIcon ( " list - remove " ) ) ; <nl> - ui - > addRuleBtn - > setIcon ( GuiIconProvider : : instance ( ) - > getIcon ( " list - add " ) ) ; <nl> - <nl> - / / Ui Settings <nl> - ui - > listRules - > setSortingEnabled ( true ) ; <nl> - ui - > listRules - > setSelectionMode ( QAbstractItemView : : ExtendedSelection ) ; <nl> - ui - > treeMatchingArticles - > setSortingEnabled ( true ) ; <nl> - ui - > hsplitter - > setCollapsible ( 0 , false ) ; <nl> - ui - > hsplitter - > setCollapsible ( 1 , false ) ; <nl> - ui - > hsplitter - > setCollapsible ( 2 , true ) ; / / Only the preview list is collapsible <nl> - bool ok ; Q_UNUSED ( ok ) ; <nl> - ok = connect ( ui - > checkRegex , SIGNAL ( toggled ( bool ) ) , SLOT ( updateFieldsToolTips ( bool ) ) ) ; <nl> - Q_ASSERT ( ok ) ; <nl> - ok = connect ( ui - > listRules , SIGNAL ( customContextMenuRequested ( const QPoint & ) ) , this , SLOT ( displayRulesListMenu ( const QPoint & ) ) ) ; <nl> - Q_ASSERT ( ok ) ; <nl> - m_ruleList = manager . toStrongRef ( ) - > downloadRules ( ) ; <nl> - m_editableRuleList = new Rss : : DownloadRuleList ; / / Read rule list from disk <nl> - m_episodeValidator = new QRegExpValidator ( <nl> - QRegExp ( " ^ ( ^ [ 1 - 9 ] { 1 , 1 } \ \ d { 0 , 3 } x ( [ 1 - 9 ] { 1 , 1 } \ \ d { 0 , 3 } ( - ( [ 1 - 9 ] { 1 , 1 } \ \ d { 0 , 3 } ) ? ) ? ; ) { 1 , } ) { 1 , 1 } " , <nl> - Qt : : CaseInsensitive ) , <nl> - ui - > lineEFilter ) ; <nl> - ui - > lineEFilter - > setValidator ( m_episodeValidator ) ; <nl> - QString tip = " < p > " + tr ( " Matches articles based on episode filter . " ) + " < / p > < p > < b > " + tr ( " Example : " ) + <nl> - " 1x2 ; 8 - 15 ; 5 ; 30 - ; < / b > " + tr ( " will match 2 , 5 , 8 through 15 , 30 and onward episodes of season one " , " example X will match " ) + " < / p > " ; <nl> - tip + = " < p > " + tr ( " Episode filter rules : " ) + " < / p > < ul > < li > " + tr ( " Season number is a mandatory non - zero value " ) + " < / li > " + <nl> - " < li > " + tr ( " Episode number is a mandatory non - zero value " ) + " < / li > " + <nl> - " < li > " + tr ( " Filter must end with semicolon " ) + " < / li > " + <nl> - " < li > " + tr ( " Three range types for episodes are supported : " ) + " < / li > " + " < li > < ul > " <nl> - " < li > " + tr ( " Single number : < b > 1x25 ; < / b > matches episode 25 of season one " ) + " < / li > " + <nl> - " < li > " + tr ( " Normal range : < b > 1x25 - 40 ; < / b > matches episodes 25 through 40 of season one " ) + " < / li > " + <nl> - " < li > " + tr ( " Infinite range : < b > 1x25 - ; < / b > matches episodes 25 and upward of season one " ) + " < / li > " + " < / ul > < / li > < / ul > " ; <nl> - ui - > lineEFilter - > setToolTip ( tip ) ; <nl> - initCategoryCombobox ( ) ; <nl> - loadFeedList ( ) ; <nl> - loadSettings ( ) ; <nl> - ok = connect ( ui - > listRules , SIGNAL ( itemSelectionChanged ( ) ) , SLOT ( updateRuleDefinitionBox ( ) ) ) ; <nl> - Q_ASSERT ( ok ) ; <nl> - ok = connect ( ui - > listRules , SIGNAL ( itemSelectionChanged ( ) ) , SLOT ( updateFeedList ( ) ) ) ; <nl> - Q_ASSERT ( ok ) ; <nl> - ok = connect ( ui - > listFeeds , SIGNAL ( itemChanged ( QListWidgetItem * ) ) , SLOT ( handleFeedCheckStateChange ( QListWidgetItem * ) ) ) ; <nl> - Q_ASSERT ( ok ) ; <nl> - / / Update matching articles when necessary <nl> - ok = connect ( ui - > lineContains , SIGNAL ( textEdited ( QString ) ) , SLOT ( updateMatchingArticles ( ) ) ) ; <nl> - Q_ASSERT ( ok ) ; <nl> - ok = connect ( ui - > lineContains , SIGNAL ( textEdited ( QString ) ) , SLOT ( updateMustLineValidity ( ) ) ) ; <nl> - Q_ASSERT ( ok ) ; <nl> - ok = connect ( ui - > lineNotContains , SIGNAL ( textEdited ( QString ) ) , SLOT ( updateMatchingArticles ( ) ) ) ; <nl> - Q_ASSERT ( ok ) ; <nl> - ok = connect ( ui - > lineNotContains , SIGNAL ( textEdited ( QString ) ) , SLOT ( updateMustNotLineValidity ( ) ) ) ; <nl> - Q_ASSERT ( ok ) ; <nl> - ok = connect ( ui - > checkRegex , SIGNAL ( stateChanged ( int ) ) , SLOT ( updateMatchingArticles ( ) ) ) ; <nl> - Q_ASSERT ( ok ) ; <nl> - ok = connect ( ui - > checkRegex , SIGNAL ( stateChanged ( int ) ) , SLOT ( updateMustLineValidity ( ) ) ) ; <nl> - Q_ASSERT ( ok ) ; <nl> - ok = connect ( ui - > checkRegex , SIGNAL ( stateChanged ( int ) ) , SLOT ( updateMustNotLineValidity ( ) ) ) ; <nl> - Q_ASSERT ( ok ) ; <nl> - ok = connect ( this , SIGNAL ( finished ( int ) ) , SLOT ( onFinished ( int ) ) ) ; <nl> - Q_ASSERT ( ok ) ; <nl> - ok = connect ( ui - > lineEFilter , SIGNAL ( textEdited ( QString ) ) , SLOT ( updateMatchingArticles ( ) ) ) ; <nl> - Q_ASSERT ( ok ) ; <nl> - editHotkey = new QShortcut ( QKeySequence ( " F2 " ) , ui - > listRules , 0 , 0 , Qt : : WidgetShortcut ) ; <nl> - ok = connect ( editHotkey , SIGNAL ( activated ( ) ) , SLOT ( renameSelectedRule ( ) ) ) ; <nl> - Q_ASSERT ( ok ) ; <nl> - ok = connect ( ui - > listRules , SIGNAL ( doubleClicked ( QModelIndex ) ) , SLOT ( renameSelectedRule ( ) ) ) ; <nl> - Q_ASSERT ( ok ) ; <nl> - deleteHotkey = new QShortcut ( QKeySequence : : Delete , ui - > listRules , 0 , 0 , Qt : : WidgetShortcut ) ; <nl> - ok = connect ( deleteHotkey , SIGNAL ( activated ( ) ) , SLOT ( on_removeRuleBtn_clicked ( ) ) ) ; <nl> - Q_ASSERT ( ok ) ; <nl> - updateRuleDefinitionBox ( ) ; <nl> - updateFeedList ( ) ; <nl> + ui - > setupUi ( this ) ; <nl> + / / Icons <nl> + ui - > removeRuleBtn - > setIcon ( GuiIconProvider : : instance ( ) - > getIcon ( " list - remove " ) ) ; <nl> + ui - > addRuleBtn - > setIcon ( GuiIconProvider : : instance ( ) - > getIcon ( " list - add " ) ) ; <nl> + <nl> + / / Ui Settings <nl> + ui - > listRules - > setSortingEnabled ( true ) ; <nl> + ui - > listRules - > setSelectionMode ( QAbstractItemView : : ExtendedSelection ) ; <nl> + ui - > treeMatchingArticles - > setSortingEnabled ( true ) ; <nl> + ui - > hsplitter - > setCollapsible ( 0 , false ) ; <nl> + ui - > hsplitter - > setCollapsible ( 1 , false ) ; <nl> + ui - > hsplitter - > setCollapsible ( 2 , true ) ; / / Only the preview list is collapsible <nl> + bool ok ; Q_UNUSED ( ok ) ; <nl> + ok = connect ( ui - > checkRegex , SIGNAL ( toggled ( bool ) ) , SLOT ( updateFieldsToolTips ( bool ) ) ) ; <nl> + Q_ASSERT ( ok ) ; <nl> + ok = connect ( ui - > listRules , SIGNAL ( customContextMenuRequested ( const QPoint & ) ) , this , SLOT ( displayRulesListMenu ( const QPoint & ) ) ) ; <nl> + Q_ASSERT ( ok ) ; <nl> + m_ruleList = manager . toStrongRef ( ) - > downloadRules ( ) ; <nl> + m_editableRuleList = new Rss : : DownloadRuleList ; / / Read rule list from disk <nl> + m_episodeValidator = new QRegExpValidator ( <nl> + QRegExp ( " ^ ( ^ [ 1 - 9 ] { 1 , 1 } \ \ d { 0 , 3 } x ( [ 1 - 9 ] { 1 , 1 } \ \ d { 0 , 3 } ( - ( [ 1 - 9 ] { 1 , 1 } \ \ d { 0 , 3 } ) ? ) ? ; ) { 1 , } ) { 1 , 1 } " , <nl> + Qt : : CaseInsensitive ) , <nl> + ui - > lineEFilter ) ; <nl> + ui - > lineEFilter - > setValidator ( m_episodeValidator ) ; <nl> + QString tip = " < p > " + tr ( " Matches articles based on episode filter . " ) + " < / p > < p > < b > " + tr ( " Example : " ) <nl> + + " 1x2 ; 8 - 15 ; 5 ; 30 - ; < / b > " + tr ( " will match 2 , 5 , 8 through 15 , 30 and onward episodes of season one " , " example X will match " ) + " < / p > " ; <nl> + tip + = " < p > " + tr ( " Episode filter rules : " ) + " < / p > < ul > < li > " + tr ( " Season number is a mandatory non - zero value " ) + " < / li > " <nl> + + " < li > " + tr ( " Episode number is a mandatory non - zero value " ) + " < / li > " <nl> + + " < li > " + tr ( " Filter must end with semicolon " ) + " < / li > " <nl> + + " < li > " + tr ( " Three range types for episodes are supported : " ) + " < / li > " + " < li > < ul > " <nl> + " < li > " + tr ( " Single number : < b > 1x25 ; < / b > matches episode 25 of season one " ) + " < / li > " <nl> + + " < li > " + tr ( " Normal range : < b > 1x25 - 40 ; < / b > matches episodes 25 through 40 of season one " ) + " < / li > " <nl> + + " < li > " + tr ( " Infinite range : < b > 1x25 - ; < / b > matches episodes 25 and upward of season one " ) + " < / li > " + " < / ul > < / li > < / ul > " ; <nl> + ui - > lineEFilter - > setToolTip ( tip ) ; <nl> + initCategoryCombobox ( ) ; <nl> + loadFeedList ( ) ; <nl> + loadSettings ( ) ; <nl> + ok = connect ( ui - > listRules , SIGNAL ( itemSelectionChanged ( ) ) , SLOT ( updateRuleDefinitionBox ( ) ) ) ; <nl> + Q_ASSERT ( ok ) ; <nl> + ok = connect ( ui - > listRules , SIGNAL ( itemSelectionChanged ( ) ) , SLOT ( updateFeedList ( ) ) ) ; <nl> + Q_ASSERT ( ok ) ; <nl> + ok = connect ( ui - > listFeeds , SIGNAL ( itemChanged ( QListWidgetItem * ) ) , SLOT ( handleFeedCheckStateChange ( QListWidgetItem * ) ) ) ; <nl> + Q_ASSERT ( ok ) ; <nl> + / / Update matching articles when necessary <nl> + ok = connect ( ui - > lineContains , SIGNAL ( textEdited ( QString ) ) , SLOT ( updateMatchingArticles ( ) ) ) ; <nl> + Q_ASSERT ( ok ) ; <nl> + ok = connect ( ui - > lineContains , SIGNAL ( textEdited ( QString ) ) , SLOT ( updateMustLineValidity ( ) ) ) ; <nl> + Q_ASSERT ( ok ) ; <nl> + ok = connect ( ui - > lineNotContains , SIGNAL ( textEdited ( QString ) ) , SLOT ( updateMatchingArticles ( ) ) ) ; <nl> + Q_ASSERT ( ok ) ; <nl> + ok = connect ( ui - > lineNotContains , SIGNAL ( textEdited ( QString ) ) , SLOT ( updateMustNotLineValidity ( ) ) ) ; <nl> + Q_ASSERT ( ok ) ; <nl> + ok = connect ( ui - > checkRegex , SIGNAL ( stateChanged ( int ) ) , SLOT ( updateMatchingArticles ( ) ) ) ; <nl> + Q_ASSERT ( ok ) ; <nl> + ok = connect ( ui - > checkRegex , SIGNAL ( stateChanged ( int ) ) , SLOT ( updateMustLineValidity ( ) ) ) ; <nl> + Q_ASSERT ( ok ) ; <nl> + ok = connect ( ui - > checkRegex , SIGNAL ( stateChanged ( int ) ) , SLOT ( updateMustNotLineValidity ( ) ) ) ; <nl> + Q_ASSERT ( ok ) ; <nl> + ok = connect ( this , SIGNAL ( finished ( int ) ) , SLOT ( onFinished ( int ) ) ) ; <nl> + Q_ASSERT ( ok ) ; <nl> + ok = connect ( ui - > lineEFilter , SIGNAL ( textEdited ( QString ) ) , SLOT ( updateMatchingArticles ( ) ) ) ; <nl> + Q_ASSERT ( ok ) ; <nl> + editHotkey = new QShortcut ( QKeySequence ( " F2 " ) , ui - > listRules , 0 , 0 , Qt : : WidgetShortcut ) ; <nl> + ok = connect ( editHotkey , SIGNAL ( activated ( ) ) , SLOT ( renameSelectedRule ( ) ) ) ; <nl> + Q_ASSERT ( ok ) ; <nl> + ok = connect ( ui - > listRules , SIGNAL ( doubleClicked ( QModelIndex ) ) , SLOT ( renameSelectedRule ( ) ) ) ; <nl> + Q_ASSERT ( ok ) ; <nl> + deleteHotkey = new QShortcut ( QKeySequence : : Delete , ui - > listRules , 0 , 0 , Qt : : WidgetShortcut ) ; <nl> + ok = connect ( deleteHotkey , SIGNAL ( activated ( ) ) , SLOT ( on_removeRuleBtn_clicked ( ) ) ) ; <nl> + Q_ASSERT ( ok ) ; <nl> + updateRuleDefinitionBox ( ) ; <nl> + updateFeedList ( ) ; <nl> } <nl> <nl> AutomatedRssDownloader : : ~ AutomatedRssDownloader ( ) <nl> { <nl> - qDebug ( ) < < Q_FUNC_INFO ; <nl> - delete editHotkey ; <nl> - delete deleteHotkey ; <nl> - delete ui ; <nl> - delete m_editableRuleList ; <nl> - delete m_episodeValidator ; <nl> + qDebug ( ) < < Q_FUNC_INFO ; <nl> + delete editHotkey ; <nl> + delete deleteHotkey ; <nl> + delete ui ; <nl> + delete m_editableRuleList ; <nl> + delete m_episodeValidator ; <nl> } <nl> <nl> void AutomatedRssDownloader : : loadSettings ( ) <nl> { <nl> - / / load dialog geometry <nl> - const Preferences * const pref = Preferences : : instance ( ) ; <nl> - restoreGeometry ( pref - > getRssGeometry ( ) ) ; <nl> - ui - > checkEnableDownloader - > setChecked ( pref - > isRssDownloadingEnabled ( ) ) ; <nl> - ui - > hsplitter - > restoreState ( pref - > getRssHSplitterSizes ( ) ) ; <nl> - / / Display download rules <nl> - loadRulesList ( ) ; <nl> + / / load dialog geometry <nl> + const Preferences * const pref = Preferences : : instance ( ) ; <nl> + restoreGeometry ( pref - > getRssGeometry ( ) ) ; <nl> + ui - > checkEnableDownloader - > setChecked ( pref - > isRssDownloadingEnabled ( ) ) ; <nl> + ui - > hsplitter - > restoreState ( pref - > getRssHSplitterSizes ( ) ) ; <nl> + / / Display download rules <nl> + loadRulesList ( ) ; <nl> } <nl> <nl> void AutomatedRssDownloader : : saveSettings ( ) <nl> { <nl> - Preferences : : instance ( ) - > setRssDownloadingEnabled ( ui - > checkEnableDownloader - > isChecked ( ) ) ; <nl> - / / Save dialog geometry <nl> - Preferences * const pref = Preferences : : instance ( ) ; <nl> - pref - > setRssGeometry ( saveGeometry ( ) ) ; <nl> - pref - > setRssHSplitterSizes ( ui - > hsplitter - > saveState ( ) ) ; <nl> + Preferences : : instance ( ) - > setRssDownloadingEnabled ( ui - > checkEnableDownloader - > isChecked ( ) ) ; <nl> + / / Save dialog geometry <nl> + Preferences * const pref = Preferences : : instance ( ) ; <nl> + pref - > setRssGeometry ( saveGeometry ( ) ) ; <nl> + pref - > setRssHSplitterSizes ( ui - > hsplitter - > saveState ( ) ) ; <nl> } <nl> <nl> void AutomatedRssDownloader : : loadRulesList ( ) <nl> { <nl> - / / Make sure we save the current item before clearing <nl> - if ( m_editedRule ) { <nl> - saveEditedRule ( ) ; <nl> - } <nl> - ui - > listRules - > clear ( ) ; <nl> - foreach ( const QString & rule_name , m_editableRuleList - > ruleNames ( ) ) { <nl> - QListWidgetItem * item = new QListWidgetItem ( rule_name , ui - > listRules ) ; <nl> - item - > setFlags ( item - > flags ( ) | Qt : : ItemIsUserCheckable ) ; <nl> - if ( m_editableRuleList - > getRule ( rule_name ) - > isEnabled ( ) ) <nl> - item - > setCheckState ( Qt : : Checked ) ; <nl> - else <nl> - item - > setCheckState ( Qt : : Unchecked ) ; <nl> - } <nl> - if ( ui - > listRules - > count ( ) > 0 & & ! ui - > listRules - > currentItem ( ) ) <nl> - ui - > listRules - > setCurrentRow ( 0 ) ; <nl> + / / Make sure we save the current item before clearing <nl> + if ( m_editedRule ) <nl> + saveEditedRule ( ) ; <nl> + ui - > listRules - > clear ( ) ; <nl> + foreach ( const QString & rule_name , m_editableRuleList - > ruleNames ( ) ) { <nl> + QListWidgetItem * item = new QListWidgetItem ( rule_name , ui - > listRules ) ; <nl> + item - > setFlags ( item - > flags ( ) | Qt : : ItemIsUserCheckable ) ; <nl> + if ( m_editableRuleList - > getRule ( rule_name ) - > isEnabled ( ) ) <nl> + item - > setCheckState ( Qt : : Checked ) ; <nl> + else <nl> + item - > setCheckState ( Qt : : Unchecked ) ; <nl> + } <nl> + if ( ( ui - > listRules - > count ( ) > 0 ) & & ! ui - > listRules - > currentItem ( ) ) <nl> + ui - > listRules - > setCurrentRow ( 0 ) ; <nl> } <nl> <nl> void AutomatedRssDownloader : : loadFeedList ( ) <nl> { <nl> - const Preferences * const pref = Preferences : : instance ( ) ; <nl> - const QStringList feed_aliases = pref - > getRssFeedsAliases ( ) ; <nl> - const QStringList feed_urls = pref - > getRssFeedsUrls ( ) ; <nl> - QStringList existing_urls ; <nl> - for ( int i = 0 ; i < feed_aliases . size ( ) ; + + i ) { <nl> - QString feed_url = feed_urls . at ( i ) ; <nl> - feed_url = feed_url . split ( " \ \ " ) . last ( ) ; <nl> - qDebug ( ) < < Q_FUNC_INFO < < feed_url ; <nl> - if ( existing_urls . contains ( feed_url ) ) continue ; <nl> - QListWidgetItem * item = new QListWidgetItem ( feed_aliases . at ( i ) , ui - > listFeeds ) ; <nl> - item - > setData ( Qt : : UserRole , feed_url ) ; <nl> - item - > setFlags ( item - > flags ( ) | Qt : : ItemIsUserCheckable ) ; <nl> - existing_urls < < feed_url ; <nl> - } <nl> + const Preferences * const pref = Preferences : : instance ( ) ; <nl> + const QStringList feed_aliases = pref - > getRssFeedsAliases ( ) ; <nl> + const QStringList feed_urls = pref - > getRssFeedsUrls ( ) ; <nl> + QStringList existing_urls ; <nl> + for ( int i = 0 ; i < feed_aliases . size ( ) ; + + i ) { <nl> + QString feed_url = feed_urls . at ( i ) ; <nl> + feed_url = feed_url . split ( " \ \ " ) . last ( ) ; <nl> + qDebug ( ) < < Q_FUNC_INFO < < feed_url ; <nl> + if ( existing_urls . contains ( feed_url ) ) continue ; <nl> + QListWidgetItem * item = new QListWidgetItem ( feed_aliases . at ( i ) , ui - > listFeeds ) ; <nl> + item - > setData ( Qt : : UserRole , feed_url ) ; <nl> + item - > setFlags ( item - > flags ( ) | Qt : : ItemIsUserCheckable ) ; <nl> + existing_urls < < feed_url ; <nl> + } <nl> } <nl> <nl> void AutomatedRssDownloader : : updateFeedList ( ) <nl> { <nl> - disconnect ( ui - > listFeeds , SIGNAL ( itemChanged ( QListWidgetItem * ) ) , this , SLOT ( handleFeedCheckStateChange ( QListWidgetItem * ) ) ) ; <nl> - for ( int i = 0 ; i < ui - > listFeeds - > count ( ) ; + + i ) { <nl> - QListWidgetItem * item = ui - > listFeeds - > item ( i ) ; <nl> - const QString feed_url = item - > data ( Qt : : UserRole ) . toString ( ) ; <nl> - bool all_enabled = false ; <nl> - foreach ( const QListWidgetItem * ruleItem , ui - > listRules - > selectedItems ( ) ) { <nl> - Rss : : DownloadRulePtr rule = m_editableRuleList - > getRule ( ruleItem - > text ( ) ) ; <nl> - if ( ! rule ) continue ; <nl> - qDebug ( ) < < " Rule " < < rule - > name ( ) < < " affects " < < rule - > rssFeeds ( ) . size ( ) < < " feeds . " ; <nl> - foreach ( QString test , rule - > rssFeeds ( ) ) { <nl> - qDebug ( ) < < " Feed is " < < test ; <nl> - } <nl> - if ( rule - > rssFeeds ( ) . contains ( feed_url ) ) { <nl> - qDebug ( ) < < " Rule " < < rule - > name ( ) < < " affects feed " < < feed_url ; <nl> - all_enabled = true ; <nl> - } else { <nl> - qDebug ( ) < < " Rule " < < rule - > name ( ) < < " does NOT affect feed " < < feed_url ; <nl> - all_enabled = false ; <nl> - break ; <nl> - } <nl> + disconnect ( ui - > listFeeds , SIGNAL ( itemChanged ( QListWidgetItem * ) ) , this , SLOT ( handleFeedCheckStateChange ( QListWidgetItem * ) ) ) ; <nl> + for ( int i = 0 ; i < ui - > listFeeds - > count ( ) ; + + i ) { <nl> + QListWidgetItem * item = ui - > listFeeds - > item ( i ) ; <nl> + const QString feed_url = item - > data ( Qt : : UserRole ) . toString ( ) ; <nl> + bool all_enabled = false ; <nl> + foreach ( const QListWidgetItem * ruleItem , ui - > listRules - > selectedItems ( ) ) { <nl> + Rss : : DownloadRulePtr rule = m_editableRuleList - > getRule ( ruleItem - > text ( ) ) ; <nl> + if ( ! rule ) continue ; <nl> + qDebug ( ) < < " Rule " < < rule - > name ( ) < < " affects " < < rule - > rssFeeds ( ) . size ( ) < < " feeds . " ; <nl> + foreach ( QString test , rule - > rssFeeds ( ) ) <nl> + qDebug ( ) < < " Feed is " < < test ; <nl> + if ( rule - > rssFeeds ( ) . contains ( feed_url ) ) { <nl> + qDebug ( ) < < " Rule " < < rule - > name ( ) < < " affects feed " < < feed_url ; <nl> + all_enabled = true ; <nl> + } <nl> + else { <nl> + qDebug ( ) < < " Rule " < < rule - > name ( ) < < " does NOT affect feed " < < feed_url ; <nl> + all_enabled = false ; <nl> + break ; <nl> + } <nl> + } <nl> + if ( all_enabled ) <nl> + item - > setCheckState ( Qt : : Checked ) ; <nl> + else <nl> + item - > setCheckState ( Qt : : Unchecked ) ; <nl> } <nl> - if ( all_enabled ) <nl> - item - > setCheckState ( Qt : : Checked ) ; <nl> - else <nl> - item - > setCheckState ( Qt : : Unchecked ) ; <nl> - } <nl> - ui - > listFeeds - > setEnabled ( ! ui - > listRules - > selectedItems ( ) . isEmpty ( ) ) ; <nl> - connect ( ui - > listFeeds , SIGNAL ( itemChanged ( QListWidgetItem * ) ) , SLOT ( handleFeedCheckStateChange ( QListWidgetItem * ) ) ) ; <nl> - updateMatchingArticles ( ) ; <nl> + ui - > listFeeds - > setEnabled ( ! ui - > listRules - > selectedItems ( ) . isEmpty ( ) ) ; <nl> + connect ( ui - > listFeeds , SIGNAL ( itemChanged ( QListWidgetItem * ) ) , SLOT ( handleFeedCheckStateChange ( QListWidgetItem * ) ) ) ; <nl> + updateMatchingArticles ( ) ; <nl> } <nl> <nl> bool AutomatedRssDownloader : : isRssDownloaderEnabled ( ) const <nl> { <nl> - return ui - > checkEnableDownloader - > isChecked ( ) ; <nl> + return ui - > checkEnableDownloader - > isChecked ( ) ; <nl> } <nl> <nl> void AutomatedRssDownloader : : updateRuleDefinitionBox ( ) <nl> { <nl> - qDebug ( ) < < Q_FUNC_INFO ; <nl> - / / Save previous rule first <nl> - saveEditedRule ( ) ; <nl> - / / Update rule definition box <nl> - const QList < QListWidgetItem * > selection = ui - > listRules - > selectedItems ( ) ; <nl> - if ( selection . count ( ) = = 1 ) { <nl> - m_editedRule = selection . first ( ) ; <nl> - Rss : : DownloadRulePtr rule = getCurrentRule ( ) ; <nl> - if ( rule ) { <nl> - ui - > lineContains - > setText ( rule - > mustContain ( ) ) ; <nl> - ui - > lineNotContains - > setText ( rule - > mustNotContain ( ) ) ; <nl> - QString ep = rule - > episodeFilter ( ) ; <nl> - if ( ! ep . isEmpty ( ) ) <nl> - ui - > lineEFilter - > setText ( ep ) ; <nl> - else <nl> - ui - > lineEFilter - > clear ( ) ; <nl> - ui - > saveDiffDir_check - > setChecked ( ! rule - > savePath ( ) . isEmpty ( ) ) ; <nl> - ui - > lineSavePath - > setText ( Utils : : Fs : : toNativePath ( rule - > savePath ( ) ) ) ; <nl> - ui - > checkRegex - > blockSignals ( true ) ; <nl> - ui - > checkRegex - > setChecked ( rule - > useRegex ( ) ) ; <nl> - ui - > checkRegex - > blockSignals ( false ) ; <nl> - if ( rule - > category ( ) . isEmpty ( ) ) { <nl> - ui - > comboCategory - > setCurrentIndex ( - 1 ) ; <nl> - ui - > comboCategory - > clearEditText ( ) ; <nl> - } else { <nl> - ui - > comboCategory - > setCurrentIndex ( ui - > comboCategory - > findText ( rule - > category ( ) ) ) ; <nl> - } <nl> - ui - > comboAddPaused - > setCurrentIndex ( rule - > addPaused ( ) ) ; <nl> - ui - > spinIgnorePeriod - > setValue ( rule - > ignoreDays ( ) ) ; <nl> - QDateTime dateTime = rule - > lastMatch ( ) ; <nl> - QString lMatch ; <nl> - if ( dateTime . isValid ( ) ) <nl> - lMatch = tr ( " Last Match : % 1 days ago " ) . arg ( dateTime . daysTo ( QDateTime : : currentDateTime ( ) ) ) ; <nl> - else <nl> - lMatch = tr ( " Last Match : Unknown " ) ; <nl> - ui - > lblLastMatch - > setText ( lMatch ) ; <nl> - updateMustLineValidity ( ) ; <nl> - updateMustNotLineValidity ( ) ; <nl> - } else { <nl> - / / New rule <nl> - clearRuleDefinitionBox ( ) ; <nl> - ui - > lineContains - > setText ( selection . first ( ) - > text ( ) ) ; <nl> - ui - > comboAddPaused - > setCurrentIndex ( 0 ) ; <nl> + qDebug ( ) < < Q_FUNC_INFO ; <nl> + / / Save previous rule first <nl> + saveEditedRule ( ) ; <nl> + / / Update rule definition box <nl> + const QList < QListWidgetItem * > selection = ui - > listRules - > selectedItems ( ) ; <nl> + if ( selection . count ( ) = = 1 ) { <nl> + m_editedRule = selection . first ( ) ; <nl> + Rss : : DownloadRulePtr rule = getCurrentRule ( ) ; <nl> + if ( rule ) { <nl> + ui - > lineContains - > setText ( rule - > mustContain ( ) ) ; <nl> + ui - > lineNotContains - > setText ( rule - > mustNotContain ( ) ) ; <nl> + QString ep = rule - > episodeFilter ( ) ; <nl> + if ( ! ep . isEmpty ( ) ) <nl> + ui - > lineEFilter - > setText ( ep ) ; <nl> + else <nl> + ui - > lineEFilter - > clear ( ) ; <nl> + ui - > saveDiffDir_check - > setChecked ( ! rule - > savePath ( ) . isEmpty ( ) ) ; <nl> + ui - > lineSavePath - > setText ( Utils : : Fs : : toNativePath ( rule - > savePath ( ) ) ) ; <nl> + ui - > checkRegex - > blockSignals ( true ) ; <nl> + ui - > checkRegex - > setChecked ( rule - > useRegex ( ) ) ; <nl> + ui - > checkRegex - > blockSignals ( false ) ; <nl> + if ( rule - > category ( ) . isEmpty ( ) ) { <nl> + ui - > comboCategory - > setCurrentIndex ( - 1 ) ; <nl> + ui - > comboCategory - > clearEditText ( ) ; <nl> + } <nl> + else { <nl> + ui - > comboCategory - > setCurrentIndex ( ui - > comboCategory - > findText ( rule - > category ( ) ) ) ; <nl> + } <nl> + ui - > comboAddPaused - > setCurrentIndex ( rule - > addPaused ( ) ) ; <nl> + ui - > spinIgnorePeriod - > setValue ( rule - > ignoreDays ( ) ) ; <nl> + QDateTime dateTime = rule - > lastMatch ( ) ; <nl> + QString lMatch ; <nl> + if ( dateTime . isValid ( ) ) <nl> + lMatch = tr ( " Last Match : % 1 days ago " ) . arg ( dateTime . daysTo ( QDateTime : : currentDateTime ( ) ) ) ; <nl> + else <nl> + lMatch = tr ( " Last Match : Unknown " ) ; <nl> + ui - > lblLastMatch - > setText ( lMatch ) ; <nl> + updateMustLineValidity ( ) ; <nl> + updateMustNotLineValidity ( ) ; <nl> + } <nl> + else { <nl> + / / New rule <nl> + clearRuleDefinitionBox ( ) ; <nl> + ui - > lineContains - > setText ( selection . first ( ) - > text ( ) ) ; <nl> + ui - > comboAddPaused - > setCurrentIndex ( 0 ) ; <nl> + } <nl> + updateFieldsToolTips ( ui - > checkRegex - > isChecked ( ) ) ; <nl> + / / Enable <nl> + ui - > ruleDefBox - > setEnabled ( true ) ; <nl> + } <nl> + else { <nl> + m_editedRule = 0 ; <nl> + / / Clear <nl> + clearRuleDefinitionBox ( ) ; <nl> + ui - > ruleDefBox - > setEnabled ( false ) ; <nl> } <nl> - updateFieldsToolTips ( ui - > checkRegex - > isChecked ( ) ) ; <nl> - / / Enable <nl> - ui - > ruleDefBox - > setEnabled ( true ) ; <nl> - } else { <nl> - m_editedRule = 0 ; <nl> - / / Clear <nl> - clearRuleDefinitionBox ( ) ; <nl> - ui - > ruleDefBox - > setEnabled ( false ) ; <nl> - } <nl> } <nl> <nl> void AutomatedRssDownloader : : clearRuleDefinitionBox ( ) <nl> { <nl> - ui - > lineContains - > clear ( ) ; <nl> - ui - > lineNotContains - > clear ( ) ; <nl> - ui - > saveDiffDir_check - > setChecked ( false ) ; <nl> - ui - > lineSavePath - > clear ( ) ; <nl> - ui - > comboCategory - > clearEditText ( ) ; <nl> - ui - > checkRegex - > setChecked ( false ) ; <nl> - ui - > spinIgnorePeriod - > setValue ( 0 ) ; <nl> - updateFieldsToolTips ( ui - > checkRegex - > isChecked ( ) ) ; <nl> - updateMustLineValidity ( ) ; <nl> - updateMustNotLineValidity ( ) ; <nl> + ui - > lineContains - > clear ( ) ; <nl> + ui - > lineNotContains - > clear ( ) ; <nl> + ui - > saveDiffDir_check - > setChecked ( false ) ; <nl> + ui - > lineSavePath - > clear ( ) ; <nl> + ui - > comboCategory - > clearEditText ( ) ; <nl> + ui - > checkRegex - > setChecked ( false ) ; <nl> + ui - > spinIgnorePeriod - > setValue ( 0 ) ; <nl> + updateFieldsToolTips ( ui - > checkRegex - > isChecked ( ) ) ; <nl> + updateMustLineValidity ( ) ; <nl> + updateMustNotLineValidity ( ) ; <nl> } <nl> <nl> Rss : : DownloadRulePtr AutomatedRssDownloader : : getCurrentRule ( ) const <nl> { <nl> - QListWidgetItem * current_item = ui - > listRules - > currentItem ( ) ; <nl> - if ( current_item ) <nl> - return m_editableRuleList - > getRule ( current_item - > text ( ) ) ; <nl> - return Rss : : DownloadRulePtr ( ) ; <nl> + QListWidgetItem * current_item = ui - > listRules - > currentItem ( ) ; <nl> + if ( current_item ) <nl> + return m_editableRuleList - > getRule ( current_item - > text ( ) ) ; <nl> + return Rss : : DownloadRulePtr ( ) ; <nl> } <nl> <nl> void AutomatedRssDownloader : : initCategoryCombobox ( ) <nl> { <nl> - / / Load torrent categories <nl> - QStringList categories = BitTorrent : : Session : : instance ( ) - > categories ( ) ; <nl> - std : : sort ( categories . begin ( ) , categories . end ( ) , Utils : : String : : naturalCompareCaseInsensitive ) ; <nl> - ui - > comboCategory - > addItems ( categories ) ; <nl> + / / Load torrent categories <nl> + QStringList categories = BitTorrent : : Session : : instance ( ) - > categories ( ) ; <nl> + std : : sort ( categories . begin ( ) , categories . end ( ) , Utils : : String : : naturalCompareCaseInsensitive ) ; <nl> + ui - > comboCategory - > addItems ( categories ) ; <nl> } <nl> <nl> void AutomatedRssDownloader : : saveEditedRule ( ) <nl> { <nl> - if ( ! m_editedRule ) return ; <nl> - qDebug ( ) < < Q_FUNC_INFO < < m_editedRule ; <nl> - if ( ui - > listRules - > findItems ( m_editedRule - > text ( ) , Qt : : MatchExactly ) . isEmpty ( ) ) { <nl> - qDebug ( ) < < " Could not find rule " < < m_editedRule - > text ( ) < < " in the UI list " ; <nl> - qDebug ( ) < < " Probably removed the item , no need to save it " ; <nl> - return ; <nl> - } <nl> - Rss : : DownloadRulePtr rule = m_editableRuleList - > getRule ( m_editedRule - > text ( ) ) ; <nl> - if ( ! rule ) { <nl> - rule = Rss : : DownloadRulePtr ( new Rss : : DownloadRule ) ; <nl> - rule - > setName ( m_editedRule - > text ( ) ) ; <nl> - } <nl> - if ( m_editedRule - > checkState ( ) = = Qt : : Unchecked ) <nl> - rule - > setEnabled ( false ) ; <nl> - else <nl> - rule - > setEnabled ( true ) ; <nl> - rule - > setUseRegex ( ui - > checkRegex - > isChecked ( ) ) ; <nl> - rule - > setMustContain ( ui - > lineContains - > text ( ) ) ; <nl> - rule - > setMustNotContain ( ui - > lineNotContains - > text ( ) ) ; <nl> - rule - > setEpisodeFilter ( ui - > lineEFilter - > text ( ) ) ; <nl> - if ( ui - > saveDiffDir_check - > isChecked ( ) ) <nl> - rule - > setSavePath ( ui - > lineSavePath - > text ( ) ) ; <nl> - else <nl> - rule - > setSavePath ( " " ) ; <nl> - rule - > setCategory ( ui - > comboCategory - > currentText ( ) ) ; <nl> - <nl> - rule - > setAddPaused ( Rss : : DownloadRule : : AddPausedState ( ui - > comboAddPaused - > currentIndex ( ) ) ) ; <nl> - rule - > setIgnoreDays ( ui - > spinIgnorePeriod - > value ( ) ) ; <nl> - / / rule - > setRssFeeds ( getSelectedFeeds ( ) ) ; <nl> - / / Save it <nl> - m_editableRuleList - > saveRule ( rule ) ; <nl> + if ( ! m_editedRule ) return ; <nl> + qDebug ( ) < < Q_FUNC_INFO < < m_editedRule ; <nl> + if ( ui - > listRules - > findItems ( m_editedRule - > text ( ) , Qt : : MatchExactly ) . isEmpty ( ) ) { <nl> + qDebug ( ) < < " Could not find rule " < < m_editedRule - > text ( ) < < " in the UI list " ; <nl> + qDebug ( ) < < " Probably removed the item , no need to save it " ; <nl> + return ; <nl> + } <nl> + Rss : : DownloadRulePtr rule = m_editableRuleList - > getRule ( m_editedRule - > text ( ) ) ; <nl> + if ( ! rule ) { <nl> + rule = Rss : : DownloadRulePtr ( new Rss : : DownloadRule ) ; <nl> + rule - > setName ( m_editedRule - > text ( ) ) ; <nl> + } <nl> + if ( m_editedRule - > checkState ( ) = = Qt : : Unchecked ) <nl> + rule - > setEnabled ( false ) ; <nl> + else <nl> + rule - > setEnabled ( true ) ; <nl> + rule - > setUseRegex ( ui - > checkRegex - > isChecked ( ) ) ; <nl> + rule - > setMustContain ( ui - > lineContains - > text ( ) ) ; <nl> + rule - > setMustNotContain ( ui - > lineNotContains - > text ( ) ) ; <nl> + rule - > setEpisodeFilter ( ui - > lineEFilter - > text ( ) ) ; <nl> + if ( ui - > saveDiffDir_check - > isChecked ( ) ) <nl> + rule - > setSavePath ( ui - > lineSavePath - > text ( ) ) ; <nl> + else <nl> + rule - > setSavePath ( " " ) ; <nl> + rule - > setCategory ( ui - > comboCategory - > currentText ( ) ) ; <nl> + <nl> + rule - > setAddPaused ( Rss : : DownloadRule : : AddPausedState ( ui - > comboAddPaused - > currentIndex ( ) ) ) ; <nl> + rule - > setIgnoreDays ( ui - > spinIgnorePeriod - > value ( ) ) ; <nl> + / / rule - > setRssFeeds ( getSelectedFeeds ( ) ) ; <nl> + / / Save it <nl> + m_editableRuleList - > saveRule ( rule ) ; <nl> } <nl> <nl> - <nl> void AutomatedRssDownloader : : on_addRuleBtn_clicked ( ) <nl> { <nl> - / / Ask for a rule name <nl> - const QString rule_name = AutoExpandableDialog : : getText ( this , tr ( " New rule name " ) , tr ( " Please type the name of the new download rule . " ) ) ; <nl> - if ( rule_name . isEmpty ( ) ) return ; <nl> - / / Check if this rule name already exists <nl> - if ( m_editableRuleList - > getRule ( rule_name ) ) { <nl> - QMessageBox : : warning ( this , tr ( " Rule name conflict " ) , tr ( " A rule with this name already exists , please choose another name . " ) ) ; <nl> - return ; <nl> - } <nl> - / / Add the new rule to the list <nl> - QListWidgetItem * item = new QListWidgetItem ( rule_name , ui - > listRules ) ; <nl> - item - > setFlags ( item - > flags ( ) | Qt : : ItemIsUserCheckable ) ; <nl> - item - > setCheckState ( Qt : : Checked ) ; / / Enable as a default <nl> - ui - > listRules - > clearSelection ( ) ; <nl> - ui - > listRules - > setCurrentItem ( item ) ; <nl> + / / Ask for a rule name <nl> + const QString rule_name = AutoExpandableDialog : : getText ( this , tr ( " New rule name " ) , tr ( " Please type the name of the new download rule . " ) ) ; <nl> + if ( rule_name . isEmpty ( ) ) return ; <nl> + / / Check if this rule name already exists <nl> + if ( m_editableRuleList - > getRule ( rule_name ) ) { <nl> + QMessageBox : : warning ( this , tr ( " Rule name conflict " ) , tr ( " A rule with this name already exists , please choose another name . " ) ) ; <nl> + return ; <nl> + } <nl> + / / Add the new rule to the list <nl> + QListWidgetItem * item = new QListWidgetItem ( rule_name , ui - > listRules ) ; <nl> + item - > setFlags ( item - > flags ( ) | Qt : : ItemIsUserCheckable ) ; <nl> + item - > setCheckState ( Qt : : Checked ) ; / / Enable as a default <nl> + ui - > listRules - > clearSelection ( ) ; <nl> + ui - > listRules - > setCurrentItem ( item ) ; <nl> } <nl> <nl> void AutomatedRssDownloader : : on_removeRuleBtn_clicked ( ) <nl> { <nl> - const QList < QListWidgetItem * > selection = ui - > listRules - > selectedItems ( ) ; <nl> - if ( selection . isEmpty ( ) ) return ; <nl> - / / Ask for confirmation <nl> - QString confirm_text ; <nl> - if ( selection . count ( ) = = 1 ) <nl> - confirm_text = tr ( " Are you sure you want to remove the download rule named ' % 1 ' ? " ) . arg ( selection . first ( ) - > text ( ) ) ; <nl> - else <nl> - confirm_text = tr ( " Are you sure you want to remove the selected download rules ? " ) ; <nl> - if ( QMessageBox : : question ( this , tr ( " Rule deletion confirmation " ) , confirm_text , QMessageBox : : Yes , QMessageBox : : No ) ! = QMessageBox : : Yes ) <nl> - return ; <nl> - foreach ( QListWidgetItem * item , selection ) { <nl> - / / Actually remove the item <nl> - ui - > listRules - > removeItemWidget ( item ) ; <nl> - const QString rule_name = item - > text ( ) ; <nl> - / / Clean up memory <nl> - delete item ; <nl> - qDebug ( " Removed item for the UI list " ) ; <nl> - / / Remove it from the m_editableRuleList <nl> - m_editableRuleList - > removeRule ( rule_name ) ; <nl> - } <nl> + const QList < QListWidgetItem * > selection = ui - > listRules - > selectedItems ( ) ; <nl> + if ( selection . isEmpty ( ) ) return ; <nl> + / / Ask for confirmation <nl> + QString confirm_text ; <nl> + if ( selection . count ( ) = = 1 ) <nl> + confirm_text = tr ( " Are you sure you want to remove the download rule named ' % 1 ' ? " ) . arg ( selection . first ( ) - > text ( ) ) ; <nl> + else <nl> + confirm_text = tr ( " Are you sure you want to remove the selected download rules ? " ) ; <nl> + if ( QMessageBox : : question ( this , tr ( " Rule deletion confirmation " ) , confirm_text , QMessageBox : : Yes , QMessageBox : : No ) ! = QMessageBox : : Yes ) <nl> + return ; <nl> + foreach ( QListWidgetItem * item , selection ) { <nl> + / / Actually remove the item <nl> + ui - > listRules - > removeItemWidget ( item ) ; <nl> + const QString rule_name = item - > text ( ) ; <nl> + / / Clean up memory <nl> + delete item ; <nl> + qDebug ( " Removed item for the UI list " ) ; <nl> + / / Remove it from the m_editableRuleList <nl> + m_editableRuleList - > removeRule ( rule_name ) ; <nl> + } <nl> } <nl> <nl> void AutomatedRssDownloader : : on_browseSP_clicked ( ) <nl> { <nl> - QString save_path = QFileDialog : : getExistingDirectory ( this , tr ( " Destination directory " ) , QDir : : homePath ( ) ) ; <nl> - if ( ! save_path . isEmpty ( ) ) <nl> - ui - > lineSavePath - > setText ( Utils : : Fs : : toNativePath ( save_path ) ) ; <nl> + QString save_path = QFileDialog : : getExistingDirectory ( this , tr ( " Destination directory " ) , QDir : : homePath ( ) ) ; <nl> + if ( ! save_path . isEmpty ( ) ) <nl> + ui - > lineSavePath - > setText ( Utils : : Fs : : toNativePath ( save_path ) ) ; <nl> } <nl> <nl> void AutomatedRssDownloader : : on_exportBtn_clicked ( ) <nl> { <nl> - if ( m_editableRuleList - > isEmpty ( ) ) { <nl> - QMessageBox : : warning ( this , tr ( " Invalid action " ) , tr ( " The list is empty , there is nothing to export . " ) ) ; <nl> - return ; <nl> - } <nl> - / / Ask for a save path <nl> - QString save_path = QFileDialog : : getSaveFileName ( this , tr ( " Where would you like to save the list ? " ) , QDir : : homePath ( ) , tr ( " Rules list ( * . rssrules ) " ) ) ; <nl> - if ( save_path . isEmpty ( ) ) return ; <nl> - if ( ! save_path . endsWith ( " . rssrules " , Qt : : CaseInsensitive ) ) <nl> - save_path + = " . rssrules " ; <nl> - if ( ! m_editableRuleList - > serialize ( save_path ) ) { <nl> - QMessageBox : : warning ( this , tr ( " I / O Error " ) , tr ( " Failed to create the destination file " ) ) ; <nl> - return ; <nl> - } <nl> + if ( m_editableRuleList - > isEmpty ( ) ) { <nl> + QMessageBox : : warning ( this , tr ( " Invalid action " ) , tr ( " The list is empty , there is nothing to export . " ) ) ; <nl> + return ; <nl> + } <nl> + / / Ask for a save path <nl> + QString save_path = QFileDialog : : getSaveFileName ( this , tr ( " Where would you like to save the list ? " ) , QDir : : homePath ( ) , tr ( " Rules list ( * . rssrules ) " ) ) ; <nl> + if ( save_path . isEmpty ( ) ) return ; <nl> + if ( ! save_path . endsWith ( " . rssrules " , Qt : : CaseInsensitive ) ) <nl> + save_path + = " . rssrules " ; <nl> + if ( ! m_editableRuleList - > serialize ( save_path ) ) { <nl> + QMessageBox : : warning ( this , tr ( " I / O Error " ) , tr ( " Failed to create the destination file " ) ) ; <nl> + return ; <nl> + } <nl> } <nl> <nl> void AutomatedRssDownloader : : on_importBtn_clicked ( ) <nl> { <nl> - / / Ask for filter path <nl> - QString load_path = QFileDialog : : getOpenFileName ( this , tr ( " Please point to the RSS download rules file " ) , QDir : : homePath ( ) , tr ( " Rules list " ) + QString ( " ( * . rssrules * . filters ) " ) ) ; <nl> - if ( load_path . isEmpty ( ) | | ! QFile : : exists ( load_path ) ) return ; <nl> - / / Load it <nl> - if ( ! m_editableRuleList - > unserialize ( load_path ) ) { <nl> - QMessageBox : : warning ( this , tr ( " Import Error " ) , tr ( " Failed to import the selected rules file " ) ) ; <nl> - return ; <nl> - } <nl> - / / Reload the rule list <nl> - loadRulesList ( ) ; <nl> + / / Ask for filter path <nl> + QString load_path = QFileDialog : : getOpenFileName ( this , tr ( " Please point to the RSS download rules file " ) , QDir : : homePath ( ) , tr ( " Rules list " ) + QString ( " ( * . rssrules * . filters ) " ) ) ; <nl> + if ( load_path . isEmpty ( ) | | ! QFile : : exists ( load_path ) ) return ; <nl> + / / Load it <nl> + if ( ! m_editableRuleList - > unserialize ( load_path ) ) { <nl> + QMessageBox : : warning ( this , tr ( " Import Error " ) , tr ( " Failed to import the selected rules file " ) ) ; <nl> + return ; <nl> + } <nl> + / / Reload the rule list <nl> + loadRulesList ( ) ; <nl> } <nl> <nl> void AutomatedRssDownloader : : displayRulesListMenu ( const QPoint & pos ) <nl> { <nl> - Q_UNUSED ( pos ) ; <nl> - QMenu menu ; <nl> - QAction * addAct = menu . addAction ( GuiIconProvider : : instance ( ) - > getIcon ( " list - add " ) , tr ( " Add new rule . . . " ) ) ; <nl> - QAction * delAct = 0 ; <nl> - QAction * renameAct = 0 ; <nl> - const QList < QListWidgetItem * > selection = ui - > listRules - > selectedItems ( ) ; <nl> - if ( ! selection . isEmpty ( ) ) { <nl> - if ( selection . count ( ) = = 1 ) { <nl> - delAct = menu . addAction ( GuiIconProvider : : instance ( ) - > getIcon ( " list - remove " ) , tr ( " Delete rule " ) ) ; <nl> - menu . addSeparator ( ) ; <nl> - renameAct = menu . addAction ( GuiIconProvider : : instance ( ) - > getIcon ( " edit - rename " ) , tr ( " Rename rule . . . " ) ) ; <nl> - } else { <nl> - delAct = menu . addAction ( GuiIconProvider : : instance ( ) - > getIcon ( " list - remove " ) , tr ( " Delete selected rules " ) ) ; <nl> + Q_UNUSED ( pos ) ; <nl> + QMenu menu ; <nl> + QAction * addAct = menu . addAction ( GuiIconProvider : : instance ( ) - > getIcon ( " list - add " ) , tr ( " Add new rule . . . " ) ) ; <nl> + QAction * delAct = 0 ; <nl> + QAction * renameAct = 0 ; <nl> + const QList < QListWidgetItem * > selection = ui - > listRules - > selectedItems ( ) ; <nl> + if ( ! selection . isEmpty ( ) ) { <nl> + if ( selection . count ( ) = = 1 ) { <nl> + delAct = menu . addAction ( GuiIconProvider : : instance ( ) - > getIcon ( " list - remove " ) , tr ( " Delete rule " ) ) ; <nl> + menu . addSeparator ( ) ; <nl> + renameAct = menu . addAction ( GuiIconProvider : : instance ( ) - > getIcon ( " edit - rename " ) , tr ( " Rename rule . . . " ) ) ; <nl> + } <nl> + else { <nl> + delAct = menu . addAction ( GuiIconProvider : : instance ( ) - > getIcon ( " list - remove " ) , tr ( " Delete selected rules " ) ) ; <nl> + } <nl> + } <nl> + QAction * act = menu . exec ( QCursor : : pos ( ) ) ; <nl> + if ( ! act ) return ; <nl> + if ( act = = addAct ) { <nl> + on_addRuleBtn_clicked ( ) ; <nl> + return ; <nl> + } <nl> + if ( act = = delAct ) { <nl> + on_removeRuleBtn_clicked ( ) ; <nl> + return ; <nl> + } <nl> + if ( act = = renameAct ) { <nl> + renameSelectedRule ( ) ; <nl> + return ; <nl> } <nl> - } <nl> - QAction * act = menu . exec ( QCursor : : pos ( ) ) ; <nl> - if ( ! act ) return ; <nl> - if ( act = = addAct ) { <nl> - on_addRuleBtn_clicked ( ) ; <nl> - return ; <nl> - } <nl> - if ( act = = delAct ) { <nl> - on_removeRuleBtn_clicked ( ) ; <nl> - return ; <nl> - } <nl> - if ( act = = renameAct ) { <nl> - renameSelectedRule ( ) ; <nl> - return ; <nl> - } <nl> } <nl> <nl> void AutomatedRssDownloader : : renameSelectedRule ( ) <nl> { <nl> - const QList < QListWidgetItem * > selection = ui - > listRules - > selectedItems ( ) ; <nl> - if ( selection . isEmpty ( ) ) <nl> - return ; <nl> - <nl> - QListWidgetItem * item = selection . first ( ) ; <nl> - forever { <nl> - QString new_name = AutoExpandableDialog : : getText ( this , tr ( " Rule renaming " ) , tr ( " Please type the new rule name " ) , QLineEdit : : Normal , item - > text ( ) ) ; <nl> - new_name = new_name . trimmed ( ) ; <nl> - if ( new_name . isEmpty ( ) ) return ; <nl> - if ( m_editableRuleList - > ruleNames ( ) . contains ( new_name , Qt : : CaseInsensitive ) ) { <nl> - QMessageBox : : warning ( this , tr ( " Rule name conflict " ) , tr ( " A rule with this name already exists , please choose another name . " ) ) ; <nl> - } else { <nl> - / / Rename the rule <nl> - m_editableRuleList - > renameRule ( item - > text ( ) , new_name ) ; <nl> - item - > setText ( new_name ) ; <nl> - return ; <nl> + const QList < QListWidgetItem * > selection = ui - > listRules - > selectedItems ( ) ; <nl> + if ( selection . isEmpty ( ) ) <nl> + return ; <nl> + <nl> + QListWidgetItem * item = selection . first ( ) ; <nl> + forever { <nl> + QString new_name = AutoExpandableDialog : : getText ( this , tr ( " Rule renaming " ) , tr ( " Please type the new rule name " ) , QLineEdit : : Normal , item - > text ( ) ) ; <nl> + new_name = new_name . trimmed ( ) ; <nl> + if ( new_name . isEmpty ( ) ) return ; <nl> + if ( m_editableRuleList - > ruleNames ( ) . contains ( new_name , Qt : : CaseInsensitive ) ) { <nl> + QMessageBox : : warning ( this , tr ( " Rule name conflict " ) , tr ( " A rule with this name already exists , please choose another name . " ) ) ; <nl> + } <nl> + else { <nl> + / / Rename the rule <nl> + m_editableRuleList - > renameRule ( item - > text ( ) , new_name ) ; <nl> + item - > setText ( new_name ) ; <nl> + return ; <nl> + } <nl> } <nl> - } <nl> } <nl> <nl> void AutomatedRssDownloader : : handleFeedCheckStateChange ( QListWidgetItem * feed_item ) <nl> { <nl> - if ( ui - > ruleDefBox - > isEnabled ( ) ) { <nl> - / / Make sure the current rule is saved <nl> - saveEditedRule ( ) ; <nl> - } <nl> - const QString feed_url = feed_item - > data ( Qt : : UserRole ) . toString ( ) ; <nl> - foreach ( QListWidgetItem * rule_item , ui - > listRules - > selectedItems ( ) ) { <nl> - Rss : : DownloadRulePtr rule = m_editableRuleList - > getRule ( rule_item - > text ( ) ) ; <nl> - Q_ASSERT ( rule ) ; <nl> - QStringList affected_feeds = rule - > rssFeeds ( ) ; <nl> - if ( feed_item - > checkState ( ) = = Qt : : Checked ) { <nl> - if ( ! affected_feeds . contains ( feed_url ) ) <nl> - affected_feeds < < feed_url ; <nl> - } else { <nl> - if ( affected_feeds . contains ( feed_url ) ) <nl> - affected_feeds . removeOne ( feed_url ) ; <nl> + if ( ui - > ruleDefBox - > isEnabled ( ) ) <nl> + / / Make sure the current rule is saved <nl> + saveEditedRule ( ) ; <nl> + const QString feed_url = feed_item - > data ( Qt : : UserRole ) . toString ( ) ; <nl> + foreach ( QListWidgetItem * rule_item , ui - > listRules - > selectedItems ( ) ) { <nl> + Rss : : DownloadRulePtr rule = m_editableRuleList - > getRule ( rule_item - > text ( ) ) ; <nl> + Q_ASSERT ( rule ) ; <nl> + QStringList affected_feeds = rule - > rssFeeds ( ) ; <nl> + if ( feed_item - > checkState ( ) = = Qt : : Checked ) { <nl> + if ( ! affected_feeds . contains ( feed_url ) ) <nl> + affected_feeds < < feed_url ; <nl> + } <nl> + else if ( affected_feeds . contains ( feed_url ) ) <nl> + affected_feeds . removeOne ( feed_url ) ; <nl> + / / Save the updated rule <nl> + if ( affected_feeds . size ( ) ! = rule - > rssFeeds ( ) . size ( ) ) { <nl> + rule - > setRssFeeds ( affected_feeds ) ; <nl> + m_editableRuleList - > saveRule ( rule ) ; <nl> + } <nl> } <nl> - / / Save the updated rule <nl> - if ( affected_feeds . size ( ) ! = rule - > rssFeeds ( ) . size ( ) ) { <nl> - rule - > setRssFeeds ( affected_feeds ) ; <nl> - m_editableRuleList - > saveRule ( rule ) ; <nl> - } <nl> - } <nl> - / / Update Matching articles <nl> - updateMatchingArticles ( ) ; <nl> + / / Update Matching articles <nl> + updateMatchingArticles ( ) ; <nl> } <nl> <nl> void AutomatedRssDownloader : : updateMatchingArticles ( ) <nl> { <nl> - ui - > treeMatchingArticles - > clear ( ) ; <nl> - Rss : : ManagerPtr manager = m_manager . toStrongRef ( ) ; <nl> - if ( ! manager ) <nl> - return ; <nl> - const QHash < QString , Rss : : FeedPtr > all_feeds = manager - > rootFolder ( ) - > getAllFeedsAsHash ( ) ; <nl> - <nl> - saveEditedRule ( ) ; <nl> - foreach ( const QListWidgetItem * rule_item , ui - > listRules - > selectedItems ( ) ) { <nl> - Rss : : DownloadRulePtr rule = m_editableRuleList - > getRule ( rule_item - > text ( ) ) ; <nl> - if ( ! rule ) continue ; <nl> - foreach ( const QString & feed_url , rule - > rssFeeds ( ) ) { <nl> - qDebug ( ) < < Q_FUNC_INFO < < feed_url ; <nl> - if ( ! all_feeds . contains ( feed_url ) ) continue ; / / Feed was removed <nl> - Rss : : FeedPtr feed = all_feeds . value ( feed_url ) ; <nl> - Q_ASSERT ( feed ) ; <nl> - if ( ! feed ) continue ; <nl> - const QStringList matching_articles = rule - > findMatchingArticles ( feed ) ; <nl> - if ( ! matching_articles . isEmpty ( ) ) <nl> - addFeedArticlesToTree ( feed , matching_articles ) ; <nl> + ui - > treeMatchingArticles - > clear ( ) ; <nl> + Rss : : ManagerPtr manager = m_manager . toStrongRef ( ) ; <nl> + if ( ! manager ) <nl> + return ; <nl> + const QHash < QString , Rss : : FeedPtr > all_feeds = manager - > rootFolder ( ) - > getAllFeedsAsHash ( ) ; <nl> + <nl> + saveEditedRule ( ) ; <nl> + foreach ( const QListWidgetItem * rule_item , ui - > listRules - > selectedItems ( ) ) { <nl> + Rss : : DownloadRulePtr rule = m_editableRuleList - > getRule ( rule_item - > text ( ) ) ; <nl> + if ( ! rule ) continue ; <nl> + foreach ( const QString & feed_url , rule - > rssFeeds ( ) ) { <nl> + qDebug ( ) < < Q_FUNC_INFO < < feed_url ; <nl> + if ( ! all_feeds . contains ( feed_url ) ) continue ; / / Feed was removed <nl> + Rss : : FeedPtr feed = all_feeds . value ( feed_url ) ; <nl> + Q_ASSERT ( feed ) ; <nl> + if ( ! feed ) continue ; <nl> + const QStringList matching_articles = rule - > findMatchingArticles ( feed ) ; <nl> + if ( ! matching_articles . isEmpty ( ) ) <nl> + addFeedArticlesToTree ( feed , matching_articles ) ; <nl> + } <nl> } <nl> - } <nl> } <nl> <nl> - void AutomatedRssDownloader : : addFeedArticlesToTree ( const Rss : : FeedPtr & feed , const QStringList & articles ) <nl> + void AutomatedRssDownloader : : addFeedArticlesToTree ( const Rss : : FeedPtr & feed , const QStringList & articles ) <nl> { <nl> - / / Check if this feed is already in the tree <nl> - QTreeWidgetItem * treeFeedItem = 0 ; <nl> - for ( int i = 0 ; i < ui - > treeMatchingArticles - > topLevelItemCount ( ) ; + + i ) { <nl> - QTreeWidgetItem * item = ui - > treeMatchingArticles - > topLevelItem ( i ) ; <nl> - if ( item - > data ( 0 , Qt : : UserRole ) . toString ( ) = = feed - > url ( ) ) { <nl> - treeFeedItem = item ; <nl> - break ; <nl> + / / Check if this feed is already in the tree <nl> + QTreeWidgetItem * treeFeedItem = 0 ; <nl> + for ( int i = 0 ; i < ui - > treeMatchingArticles - > topLevelItemCount ( ) ; + + i ) { <nl> + QTreeWidgetItem * item = ui - > treeMatchingArticles - > topLevelItem ( i ) ; <nl> + if ( item - > data ( 0 , Qt : : UserRole ) . toString ( ) = = feed - > url ( ) ) { <nl> + treeFeedItem = item ; <nl> + break ; <nl> + } <nl> + } <nl> + / / If there is none , create it <nl> + if ( ! treeFeedItem ) { <nl> + treeFeedItem = new QTreeWidgetItem ( QStringList ( ) < < feed - > displayName ( ) ) ; <nl> + treeFeedItem - > setToolTip ( 0 , feed - > displayName ( ) ) ; <nl> + QFont f = treeFeedItem - > font ( 0 ) ; <nl> + f . setBold ( true ) ; <nl> + treeFeedItem - > setFont ( 0 , f ) ; <nl> + treeFeedItem - > setData ( 0 , Qt : : DecorationRole , GuiIconProvider : : instance ( ) - > getIcon ( " inode - directory " ) ) ; <nl> + treeFeedItem - > setData ( 0 , Qt : : UserRole , feed - > url ( ) ) ; <nl> + ui - > treeMatchingArticles - > addTopLevelItem ( treeFeedItem ) ; <nl> + } <nl> + / / Insert the articles <nl> + foreach ( const QString & art , articles ) { <nl> + QTreeWidgetItem * item = new QTreeWidgetItem ( QStringList ( ) < < art ) ; <nl> + item - > setToolTip ( 0 , art ) ; <nl> + treeFeedItem - > addChild ( item ) ; <nl> } <nl> - } <nl> - / / If there is none , create it <nl> - if ( ! treeFeedItem ) { <nl> - treeFeedItem = new QTreeWidgetItem ( QStringList ( ) < < feed - > displayName ( ) ) ; <nl> - treeFeedItem - > setToolTip ( 0 , feed - > displayName ( ) ) ; <nl> - QFont f = treeFeedItem - > font ( 0 ) ; <nl> - f . setBold ( true ) ; <nl> - treeFeedItem - > setFont ( 0 , f ) ; <nl> - treeFeedItem - > setData ( 0 , Qt : : DecorationRole , GuiIconProvider : : instance ( ) - > getIcon ( " inode - directory " ) ) ; <nl> - treeFeedItem - > setData ( 0 , Qt : : UserRole , feed - > url ( ) ) ; <nl> - ui - > treeMatchingArticles - > addTopLevelItem ( treeFeedItem ) ; <nl> - } <nl> - / / Insert the articles <nl> - foreach ( const QString & art , articles ) { <nl> - QTreeWidgetItem * item = new QTreeWidgetItem ( QStringList ( ) < < art ) ; <nl> - item - > setToolTip ( 0 , art ) ; <nl> - treeFeedItem - > addChild ( item ) ; <nl> - } <nl> - ui - > treeMatchingArticles - > expandItem ( treeFeedItem ) ; <nl> + ui - > treeMatchingArticles - > expandItem ( treeFeedItem ) ; <nl> } <nl> <nl> void AutomatedRssDownloader : : updateFieldsToolTips ( bool regex ) <nl> { <nl> - QString tip ; <nl> - if ( regex ) { <nl> - tip = tr ( " Regex mode : use Perl - like regular expressions " ) ; <nl> - ui - > lineContains - > setToolTip ( tip ) ; <nl> - ui - > lineNotContains - > setToolTip ( tip ) ; <nl> - } else { <nl> - tip = tr ( " Wildcard mode : you can use < ul > < li > ? to match any single character < / li > < li > * to match zero or more of any characters < / li > < li > Whitespaces count as AND operators < / li > < / ul > " ) ; <nl> - ui - > lineContains - > setToolTip ( tip ) ; <nl> - tip = tr ( " Wildcard mode : you can use < ul > < li > ? to match any single character < / li > < li > * to match zero or more of any characters < / li > < li > | is used as OR operator < / li > < / ul > " ) ; <nl> - ui - > lineNotContains - > setToolTip ( tip ) ; <nl> - } <nl> + QString tip ; <nl> + if ( regex ) { <nl> + tip = tr ( " Regex mode : use Perl - like regular expressions " ) ; <nl> + ui - > lineContains - > setToolTip ( tip ) ; <nl> + ui - > lineNotContains - > setToolTip ( tip ) ; <nl> + } <nl> + else { <nl> + tip = tr ( " Wildcard mode : you can use < ul > < li > ? to match any single character < / li > < li > * to match zero or more of any characters < / li > < li > Whitespaces count as AND operators < / li > < / ul > " ) ; <nl> + ui - > lineContains - > setToolTip ( tip ) ; <nl> + tip = tr ( " Wildcard mode : you can use < ul > < li > ? to match any single character < / li > < li > * to match zero or more of any characters < / li > < li > | is used as OR operator < / li > < / ul > " ) ; <nl> + ui - > lineNotContains - > setToolTip ( tip ) ; <nl> + } <nl> } <nl> <nl> void AutomatedRssDownloader : : updateMustLineValidity ( ) <nl> { <nl> - const QString text = ui - > lineContains - > text ( ) ; <nl> - bool valid = true ; <nl> - QStringList tokens ; <nl> - if ( ui - > checkRegex - > isChecked ( ) ) <nl> - tokens < < text ; <nl> - else <nl> - tokens < < text . split ( " " ) ; <nl> - foreach ( const QString & token , tokens ) { <nl> - QRegExp reg ( token , Qt : : CaseInsensitive , ui - > checkRegex - > isChecked ( ) ? QRegExp : : RegExp : QRegExp : : Wildcard ) ; <nl> - if ( ! reg . isValid ( ) ) { <nl> - valid = false ; <nl> - break ; <nl> + const QString text = ui - > lineContains - > text ( ) ; <nl> + bool valid = true ; <nl> + QStringList tokens ; <nl> + if ( ui - > checkRegex - > isChecked ( ) ) <nl> + tokens < < text ; <nl> + else <nl> + tokens < < text . split ( " " ) ; <nl> + foreach ( const QString & token , tokens ) { <nl> + QRegExp reg ( token , Qt : : CaseInsensitive , ui - > checkRegex - > isChecked ( ) ? QRegExp : : RegExp : QRegExp : : Wildcard ) ; <nl> + if ( ! reg . isValid ( ) ) { <nl> + valid = false ; <nl> + break ; <nl> + } <nl> + } <nl> + if ( valid ) { <nl> + ui - > lineContains - > setStyleSheet ( " " ) ; <nl> + ui - > lbl_must_stat - > setPixmap ( QPixmap ( ) ) ; <nl> + } <nl> + else { <nl> + ui - > lineContains - > setStyleSheet ( " QLineEdit { color : # ff0000 ; } " ) ; <nl> + ui - > lbl_must_stat - > setPixmap ( GuiIconProvider : : instance ( ) - > getIcon ( " task - attention " ) . pixmap ( 16 , 16 ) ) ; <nl> } <nl> - } <nl> - if ( valid ) { <nl> - ui - > lineContains - > setStyleSheet ( " " ) ; <nl> - ui - > lbl_must_stat - > setPixmap ( QPixmap ( ) ) ; <nl> - } else { <nl> - ui - > lineContains - > setStyleSheet ( " QLineEdit { color : # ff0000 ; } " ) ; <nl> - ui - > lbl_must_stat - > setPixmap ( GuiIconProvider : : instance ( ) - > getIcon ( " task - attention " ) . pixmap ( 16 , 16 ) ) ; <nl> - } <nl> } <nl> <nl> void AutomatedRssDownloader : : updateMustNotLineValidity ( ) <nl> { <nl> - const QString text = ui - > lineNotContains - > text ( ) ; <nl> - bool valid = true ; <nl> - QStringList tokens ; <nl> - if ( ui - > checkRegex - > isChecked ( ) ) <nl> - tokens < < text ; <nl> - else <nl> - tokens < < text . split ( " | " ) ; <nl> - foreach ( const QString & token , tokens ) { <nl> - QRegExp reg ( token , Qt : : CaseInsensitive , ui - > checkRegex - > isChecked ( ) ? QRegExp : : RegExp : QRegExp : : Wildcard ) ; <nl> - if ( ! reg . isValid ( ) ) { <nl> - valid = false ; <nl> - break ; <nl> + const QString text = ui - > lineNotContains - > text ( ) ; <nl> + bool valid = true ; <nl> + QStringList tokens ; <nl> + if ( ui - > checkRegex - > isChecked ( ) ) <nl> + tokens < < text ; <nl> + else <nl> + tokens < < text . split ( " | " ) ; <nl> + foreach ( const QString & token , tokens ) { <nl> + QRegExp reg ( token , Qt : : CaseInsensitive , ui - > checkRegex - > isChecked ( ) ? QRegExp : : RegExp : QRegExp : : Wildcard ) ; <nl> + if ( ! reg . isValid ( ) ) { <nl> + valid = false ; <nl> + break ; <nl> + } <nl> + } <nl> + if ( valid ) { <nl> + ui - > lineNotContains - > setStyleSheet ( " " ) ; <nl> + ui - > lbl_mustnot_stat - > setPixmap ( QPixmap ( ) ) ; <nl> + } <nl> + else { <nl> + ui - > lineNotContains - > setStyleSheet ( " QLineEdit { color : # ff0000 ; } " ) ; <nl> + ui - > lbl_mustnot_stat - > setPixmap ( GuiIconProvider : : instance ( ) - > getIcon ( " task - attention " ) . pixmap ( 16 , 16 ) ) ; <nl> } <nl> - } <nl> - if ( valid ) { <nl> - ui - > lineNotContains - > setStyleSheet ( " " ) ; <nl> - ui - > lbl_mustnot_stat - > setPixmap ( QPixmap ( ) ) ; <nl> - } else { <nl> - ui - > lineNotContains - > setStyleSheet ( " QLineEdit { color : # ff0000 ; } " ) ; <nl> - ui - > lbl_mustnot_stat - > setPixmap ( GuiIconProvider : : instance ( ) - > getIcon ( " task - attention " ) . pixmap ( 16 , 16 ) ) ; <nl> - } <nl> } <nl> <nl> - void AutomatedRssDownloader : : onFinished ( int result ) { <nl> - Q_UNUSED ( result ) ; <nl> - / / Save current item on exit <nl> - saveEditedRule ( ) ; <nl> - m_ruleList - > replace ( m_editableRuleList ) ; <nl> - m_ruleList - > saveRulesToStorage ( ) ; <nl> - saveSettings ( ) ; <nl> + void AutomatedRssDownloader : : onFinished ( int result ) <nl> + { <nl> + Q_UNUSED ( result ) ; <nl> + / / Save current item on exit <nl> + saveEditedRule ( ) ; <nl> + m_ruleList - > replace ( m_editableRuleList ) ; <nl> + m_ruleList - > saveRulesToStorage ( ) ; <nl> + saveSettings ( ) ; <nl> } <nl> mmm a / src / gui / rss / automatedrssdownloader . h <nl> ppp b / src / gui / rss / automatedrssdownloader . h <nl> <nl> <nl> QT_BEGIN_NAMESPACE <nl> namespace Ui { <nl> - class AutomatedRssDownloader ; <nl> + class AutomatedRssDownloader ; <nl> } <nl> QT_END_NAMESPACE <nl> <nl> QT_BEGIN_NAMESPACE <nl> class QListWidgetItem ; <nl> QT_END_NAMESPACE <nl> <nl> - class AutomatedRssDownloader : public QDialog <nl> + class AutomatedRssDownloader : public QDialog <nl> { <nl> - Q_OBJECT <nl> + Q_OBJECT <nl> <nl> public : <nl> - explicit AutomatedRssDownloader ( const QWeakPointer < Rss : : Manager > & manager , QWidget * parent = 0 ) ; <nl> - ~ AutomatedRssDownloader ( ) ; <nl> - bool isRssDownloaderEnabled ( ) const ; <nl> + explicit AutomatedRssDownloader ( const QWeakPointer < Rss : : Manager > & manager , QWidget * parent = 0 ) ; <nl> + ~ AutomatedRssDownloader ( ) ; <nl> + bool isRssDownloaderEnabled ( ) const ; <nl> <nl> protected slots : <nl> - void loadSettings ( ) ; <nl> - void saveSettings ( ) ; <nl> - void loadRulesList ( ) ; <nl> - void handleFeedCheckStateChange ( QListWidgetItem * feed_item ) ; <nl> - void updateRuleDefinitionBox ( ) ; <nl> - void clearRuleDefinitionBox ( ) ; <nl> - void saveEditedRule ( ) ; <nl> - void loadFeedList ( ) ; <nl> - void updateFeedList ( ) ; <nl> + void loadSettings ( ) ; <nl> + void saveSettings ( ) ; <nl> + void loadRulesList ( ) ; <nl> + void handleFeedCheckStateChange ( QListWidgetItem * feed_item ) ; <nl> + void updateRuleDefinitionBox ( ) ; <nl> + void clearRuleDefinitionBox ( ) ; <nl> + void saveEditedRule ( ) ; <nl> + void loadFeedList ( ) ; <nl> + void updateFeedList ( ) ; <nl> <nl> private slots : <nl> - void displayRulesListMenu ( const QPoint & pos ) ; <nl> - void on_addRuleBtn_clicked ( ) ; <nl> - void on_removeRuleBtn_clicked ( ) ; <nl> - void on_browseSP_clicked ( ) ; <nl> - void on_exportBtn_clicked ( ) ; <nl> - void on_importBtn_clicked ( ) ; <nl> - void renameSelectedRule ( ) ; <nl> - void updateMatchingArticles ( ) ; <nl> - void updateFieldsToolTips ( bool regex ) ; <nl> - void updateMustLineValidity ( ) ; <nl> - void updateMustNotLineValidity ( ) ; <nl> - void onFinished ( int result ) ; <nl> + void displayRulesListMenu ( const QPoint & pos ) ; <nl> + void on_addRuleBtn_clicked ( ) ; <nl> + void on_removeRuleBtn_clicked ( ) ; <nl> + void on_browseSP_clicked ( ) ; <nl> + void on_exportBtn_clicked ( ) ; <nl> + void on_importBtn_clicked ( ) ; <nl> + void renameSelectedRule ( ) ; <nl> + void updateMatchingArticles ( ) ; <nl> + void updateFieldsToolTips ( bool regex ) ; <nl> + void updateMustLineValidity ( ) ; <nl> + void updateMustNotLineValidity ( ) ; <nl> + void onFinished ( int result ) ; <nl> <nl> private : <nl> - Rss : : DownloadRulePtr getCurrentRule ( ) const ; <nl> - void initCategoryCombobox ( ) ; <nl> - void addFeedArticlesToTree ( const Rss : : FeedPtr & feed , const QStringList & articles ) ; <nl> + Rss : : DownloadRulePtr getCurrentRule ( ) const ; <nl> + void initCategoryCombobox ( ) ; <nl> + void addFeedArticlesToTree ( const Rss : : FeedPtr & feed , const QStringList & articles ) ; <nl> <nl> private : <nl> - Ui : : AutomatedRssDownloader * ui ; <nl> - QWeakPointer < Rss : : Manager > m_manager ; <nl> - QListWidgetItem * m_editedRule ; <nl> - Rss : : DownloadRuleList * m_ruleList ; <nl> - Rss : : DownloadRuleList * m_editableRuleList ; <nl> - QRegExpValidator * m_episodeValidator ; <nl> - QShortcut * editHotkey ; <nl> - QShortcut * deleteHotkey ; <nl> + Ui : : AutomatedRssDownloader * ui ; <nl> + QWeakPointer < Rss : : Manager > m_manager ; <nl> + QListWidgetItem * m_editedRule ; <nl> + Rss : : DownloadRuleList * m_ruleList ; <nl> + Rss : : DownloadRuleList * m_editableRuleList ; <nl> + QRegExpValidator * m_episodeValidator ; <nl> + QShortcut * editHotkey ; <nl> + QShortcut * deleteHotkey ; <nl> } ; <nl> <nl> # endif / / AUTOMATEDRSSDOWNLOADER_H <nl> mmm a / src / gui / rss / rss_imp . cpp <nl> ppp b / src / gui / rss / rss_imp . cpp <nl> namespace Article <nl> } <nl> <nl> / / display a right - click menu <nl> - void RSSImp : : displayRSSListMenu ( const QPoint & pos ) <nl> + void RSSImp : : displayRSSListMenu ( const QPoint & pos ) <nl> { <nl> if ( ! m_feedList - > indexAt ( pos ) . isValid ( ) ) <nl> / / No item under the mouse , clear selection <nl> m_feedList - > clearSelection ( ) ; <nl> QMenu myRSSListMenu ( this ) ; <nl> - QList < QTreeWidgetItem * > selectedItems = m_feedList - > selectedItems ( ) ; <nl> + QList < QTreeWidgetItem * > selectedItems = m_feedList - > selectedItems ( ) ; <nl> if ( selectedItems . size ( ) > 0 ) { <nl> myRSSListMenu . addAction ( actionUpdate ) ; <nl> myRSSListMenu . addAction ( actionMark_items_read ) ; <nl> void RSSImp : : displayRSSListMenu ( const QPoint & pos ) <nl> myRSSListMenu . exec ( QCursor : : pos ( ) ) ; <nl> } <nl> <nl> - void RSSImp : : displayItemsListMenu ( const QPoint & ) <nl> + void RSSImp : : displayItemsListMenu ( const QPoint & ) <nl> { <nl> QMenu myItemListMenu ( this ) ; <nl> - QList < QListWidgetItem * > selectedItems = listArticles - > selectedItems ( ) ; <nl> + QList < QListWidgetItem * > selectedItems = listArticles - > selectedItems ( ) ; <nl> if ( selectedItems . size ( ) < = 0 ) <nl> return ; <nl> <nl> bool hasTorrent = false ; <nl> bool hasLink = false ; <nl> - foreach ( const QListWidgetItem * item , selectedItems ) { <nl> + foreach ( const QListWidgetItem * item , selectedItems ) { <nl> if ( ! item ) continue ; <nl> Rss : : FeedPtr feed = m_feedList - > getRSSItemFromUrl ( item - > data ( Article : : FeedUrlRole ) . toString ( ) ) ; <nl> if ( ! feed ) continue ; <nl> void RSSImp : : displayItemsListMenu ( const QPoint & ) <nl> <nl> void RSSImp : : askNewFolder ( ) <nl> { <nl> - QTreeWidgetItem * parent_item = 0 ; <nl> + QTreeWidgetItem * parent_item = 0 ; <nl> Rss : : FolderPtr rss_parent ; <nl> if ( m_feedList - > selectedItems ( ) . size ( ) > 0 ) { <nl> parent_item = m_feedList - > selectedItems ( ) . at ( 0 ) ; <nl> void RSSImp : : askNewFolder ( ) <nl> <nl> Rss : : FolderPtr newFolder ( new Rss : : Folder ( new_name ) ) ; <nl> rss_parent - > addFile ( newFolder ) ; <nl> - QTreeWidgetItem * folderItem = createFolderListItem ( newFolder ) ; <nl> + QTreeWidgetItem * folderItem = createFolderListItem ( newFolder ) ; <nl> if ( parent_item ) <nl> parent_item - > addChild ( folderItem ) ; <nl> else <nl> void RSSImp : : on_newFeedButton_clicked ( ) <nl> { <nl> / / Determine parent folder for new feed <nl> QTreeWidgetItem * parent_item = 0 ; <nl> - QList < QTreeWidgetItem * > selected_items = m_feedList - > selectedItems ( ) ; <nl> + QList < QTreeWidgetItem * > selected_items = m_feedList - > selectedItems ( ) ; <nl> if ( ! selected_items . empty ( ) ) { <nl> parent_item = selected_items . first ( ) ; <nl> / / Consider the case where the user clicked on Unread item <nl> void RSSImp : : on_newFeedButton_clicked ( ) <nl> Rss : : FeedPtr stream ( new Rss : : Feed ( newUrl , m_rssManager . data ( ) ) ) ; <nl> rss_parent - > addFile ( stream ) ; <nl> / / Create TreeWidget item <nl> - QTreeWidgetItem * item = createFolderListItem ( stream ) ; <nl> + QTreeWidgetItem * item = createFolderListItem ( stream ) ; <nl> if ( parent_item ) <nl> parent_item - > addChild ( item ) ; <nl> else <nl> void RSSImp : : on_newFeedButton_clicked ( ) <nl> / / delete a stream by a button <nl> void RSSImp : : deleteSelectedItems ( ) <nl> { <nl> - QList < QTreeWidgetItem * > selectedItems = m_feedList - > selectedItems ( ) ; <nl> + QList < QTreeWidgetItem * > selectedItems = m_feedList - > selectedItems ( ) ; <nl> if ( selectedItems . isEmpty ( ) ) <nl> return ; <nl> if ( ( selectedItems . size ( ) = = 1 ) & & ( selectedItems . first ( ) = = m_feedList - > stickyUnreadItem ( ) ) ) <nl> return ; <nl> <nl> QMessageBox : : StandardButton answer = QMessageBox : : question ( this , tr ( " Deletion confirmation " ) , <nl> - tr ( " Are you sure you want to delete the selected RSS feeds ? " ) , <nl> - QMessageBox : : Yes | QMessageBox : : No , QMessageBox : : No ) ; <nl> + tr ( " Are you sure you want to delete the selected RSS feeds ? " ) , <nl> + QMessageBox : : Yes | QMessageBox : : No , QMessageBox : : No ) ; <nl> if ( answer = = QMessageBox : : No ) <nl> return ; <nl> <nl> - foreach ( QTreeWidgetItem * item , selectedItems ) { <nl> + foreach ( QTreeWidgetItem * item , selectedItems ) { <nl> if ( item = = m_feedList - > stickyUnreadItem ( ) ) <nl> continue ; <nl> Rss : : FilePtr rss_item = m_feedList - > getRSSItem ( item ) ; <nl> - QTreeWidgetItem * parent = item - > parent ( ) ; <nl> + QTreeWidgetItem * parent = item - > parent ( ) ; <nl> / / Notify TreeWidget <nl> m_feedList - > itemAboutToBeRemoved ( item ) ; <nl> / / Actually delete the item <nl> void RSSImp : : deleteSelectedItems ( ) <nl> updateItemInfos ( m_feedList - > stickyUnreadItem ( ) ) ; <nl> if ( m_feedList - > currentItem ( ) = = m_feedList - > stickyUnreadItem ( ) ) <nl> populateArticleList ( m_feedList - > stickyUnreadItem ( ) ) ; <nl> - <nl> } <nl> <nl> void RSSImp : : loadFoldersOpenState ( ) <nl> { <nl> QStringList open_folders = Preferences : : instance ( ) - > getRssOpenFolders ( ) ; <nl> - foreach ( const QString & var_path , open_folders ) { <nl> + foreach ( const QString & var_path , open_folders ) { <nl> QStringList path = var_path . split ( " \ \ " ) ; <nl> - QTreeWidgetItem * parent = 0 ; <nl> - foreach ( const QString & name , path ) { <nl> + QTreeWidgetItem * parent = 0 ; <nl> + foreach ( const QString & name , path ) { <nl> int nbChildren = 0 ; <nl> if ( parent ) <nl> nbChildren = parent - > childCount ( ) ; <nl> else <nl> nbChildren = m_feedList - > topLevelItemCount ( ) ; <nl> for ( int i = 0 ; i < nbChildren ; + + i ) { <nl> - QTreeWidgetItem * child ; <nl> + QTreeWidgetItem * child ; <nl> if ( parent ) <nl> child = parent - > child ( i ) ; <nl> else <nl> void RSSImp : : loadFoldersOpenState ( ) <nl> void RSSImp : : saveFoldersOpenState ( ) <nl> { <nl> QStringList open_folders ; <nl> - QList < QTreeWidgetItem * > items = m_feedList - > getAllOpenFolders ( ) ; <nl> - foreach ( QTreeWidgetItem * item , items ) { <nl> + QList < QTreeWidgetItem * > items = m_feedList - > getAllOpenFolders ( ) ; <nl> + foreach ( QTreeWidgetItem * item , items ) { <nl> QString path = m_feedList - > getItemPath ( item ) . join ( " \ \ " ) ; <nl> qDebug ( " saving open folder : % s " , qPrintable ( path ) ) ; <nl> open_folders < < path ; <nl> void RSSImp : : saveFoldersOpenState ( ) <nl> / / refresh all streams by a button <nl> void RSSImp : : refreshAllFeeds ( ) <nl> { <nl> - foreach ( QTreeWidgetItem * item , m_feedList - > getAllFeedItems ( ) ) <nl> + foreach ( QTreeWidgetItem * item , m_feedList - > getAllFeedItems ( ) ) <nl> item - > setData ( 0 , Qt : : DecorationRole , QVariant ( QIcon ( " : / icons / loading . png " ) ) ) ; <nl> m_rssManager - > refresh ( ) ; <nl> } <nl> <nl> void RSSImp : : downloadSelectedTorrents ( ) <nl> { <nl> - QList < QListWidgetItem * > selected_items = listArticles - > selectedItems ( ) ; <nl> + QList < QListWidgetItem * > selected_items = listArticles - > selectedItems ( ) ; <nl> if ( selected_items . size ( ) < = 0 ) <nl> return ; <nl> - foreach ( QListWidgetItem * item , selected_items ) { <nl> + foreach ( QListWidgetItem * item , selected_items ) { <nl> if ( ! item ) continue ; <nl> Rss : : FeedPtr feed = m_feedList - > getRSSItemFromUrl ( item - > data ( Article : : FeedUrlRole ) . toString ( ) ) ; <nl> if ( ! feed ) continue ; <nl> void RSSImp : : downloadSelectedTorrents ( ) <nl> / / open the url of the selected RSS articles in the Web browser <nl> void RSSImp : : openSelectedArticlesUrls ( ) <nl> { <nl> - QList < QListWidgetItem * > selected_items = listArticles - > selectedItems ( ) ; <nl> + QList < QListWidgetItem * > selected_items = listArticles - > selectedItems ( ) ; <nl> if ( selected_items . size ( ) < = 0 ) <nl> return ; <nl> - foreach ( QListWidgetItem * item , selected_items ) { <nl> + foreach ( QListWidgetItem * item , selected_items ) { <nl> if ( ! item ) continue ; <nl> Rss : : FeedPtr feed = m_feedList - > getRSSItemFromUrl ( item - > data ( Article : : FeedUrlRole ) . toString ( ) ) ; <nl> if ( ! feed ) continue ; <nl> void RSSImp : : openSelectedArticlesUrls ( ) <nl> updateItemInfos ( m_feedList - > getTreeItemFromUrl ( selected_items . first ( ) - > data ( Article : : FeedUrlRole ) . toString ( ) ) ) ; <nl> } <nl> <nl> - / / right - click on stream : give it an alias <nl> + / / right - click on stream : give it an alias <nl> void RSSImp : : renameSelectedRssFile ( ) <nl> { <nl> - QList < QTreeWidgetItem * > selectedItems = m_feedList - > selectedItems ( ) ; <nl> + QList < QTreeWidgetItem * > selectedItems = m_feedList - > selectedItems ( ) ; <nl> if ( selectedItems . size ( ) ! = 1 ) <nl> return ; <nl> - QTreeWidgetItem * item = selectedItems . first ( ) ; <nl> + QTreeWidgetItem * item = selectedItems . first ( ) ; <nl> if ( item = = m_feedList - > stickyUnreadItem ( ) ) <nl> return ; <nl> Rss : : FilePtr rss_item = m_feedList - > getRSSItem ( item ) ; <nl> void RSSImp : : renameSelectedRssFile ( ) <nl> / / right - click on stream : refresh it <nl> void RSSImp : : refreshSelectedItems ( ) <nl> { <nl> - QList < QTreeWidgetItem * > selectedItems = m_feedList - > selectedItems ( ) ; <nl> - foreach ( QTreeWidgetItem * item , selectedItems ) { <nl> + QList < QTreeWidgetItem * > selectedItems = m_feedList - > selectedItems ( ) ; <nl> + foreach ( QTreeWidgetItem * item , selectedItems ) { <nl> Rss : : FilePtr file = m_feedList - > getRSSItem ( item ) ; <nl> / / Update icons <nl> if ( item = = m_feedList - > stickyUnreadItem ( ) ) { <nl> void RSSImp : : refreshSelectedItems ( ) <nl> void RSSImp : : copySelectedFeedsURL ( ) <nl> { <nl> QStringList URLs ; <nl> - QList < QTreeWidgetItem * > selectedItems = m_feedList - > selectedItems ( ) ; <nl> - QTreeWidgetItem * item ; <nl> + QList < QTreeWidgetItem * > selectedItems = m_feedList - > selectedItems ( ) ; <nl> + QTreeWidgetItem * item ; <nl> foreach ( item , selectedItems ) <nl> if ( m_feedList - > isFeed ( item ) ) <nl> URLs < < m_feedList - > getItemID ( item ) ; <nl> void RSSImp : : copySelectedFeedsURL ( ) <nl> <nl> void RSSImp : : on_markReadButton_clicked ( ) <nl> { <nl> - QList < QTreeWidgetItem * > selectedItems = m_feedList - > selectedItems ( ) ; <nl> - foreach ( QTreeWidgetItem * item , selectedItems ) { <nl> + QList < QTreeWidgetItem * > selectedItems = m_feedList - > selectedItems ( ) ; <nl> + foreach ( QTreeWidgetItem * item , selectedItems ) { <nl> Rss : : FilePtr rss_item = m_feedList - > getRSSItem ( item ) ; <nl> Q_ASSERT ( rss_item ) ; <nl> rss_item - > markAsRead ( ) ; <nl> void RSSImp : : on_markReadButton_clicked ( ) <nl> populateArticleList ( m_feedList - > currentItem ( ) ) ; <nl> } <nl> <nl> - QTreeWidgetItem * RSSImp : : createFolderListItem ( const Rss : : FilePtr & rssFile ) <nl> + QTreeWidgetItem * RSSImp : : createFolderListItem ( const Rss : : FilePtr & rssFile ) <nl> { <nl> Q_ASSERT ( rssFile ) ; <nl> - QTreeWidgetItem * item = new QTreeWidgetItem ; <nl> + QTreeWidgetItem * item = new QTreeWidgetItem ; <nl> item - > setData ( 0 , Qt : : DisplayRole , QVariant ( rssFile - > displayName ( ) + QString : : fromUtf8 ( " ( " ) + QString : : number ( rssFile - > unreadCount ( ) ) + QString ( " ) " ) ) ) ; <nl> item - > setData ( 0 , Qt : : DecorationRole , QIcon ( rssFile - > iconPath ( ) ) ) ; <nl> <nl> return item ; <nl> } <nl> <nl> - void RSSImp : : fillFeedsList ( QTreeWidgetItem * parent , const Rss : : FolderPtr & rss_parent ) <nl> + void RSSImp : : fillFeedsList ( QTreeWidgetItem * parent , const Rss : : FolderPtr & rss_parent ) <nl> { <nl> QList < Rss : : FilePtr > children ; <nl> if ( parent ) <nl> children = rss_parent - > getContent ( ) ; <nl> else <nl> children = m_rssManager - > rootFolder ( ) - > getContent ( ) ; <nl> - foreach ( const Rss : : FilePtr & rssFile , children ) { <nl> - QTreeWidgetItem * item = createFolderListItem ( rssFile ) ; <nl> + foreach ( const Rss : : FilePtr & rssFile , children ) { <nl> + QTreeWidgetItem * item = createFolderListItem ( rssFile ) ; <nl> Q_ASSERT ( item ) ; <nl> if ( parent ) <nl> parent - > addChild ( item ) ; <nl> void RSSImp : : fillFeedsList ( QTreeWidgetItem * parent , const Rss : : FolderPtr & rss_pa <nl> } <nl> } <nl> <nl> - QListWidgetItem * RSSImp : : createArticleListItem ( const Rss : : ArticlePtr & article ) <nl> + QListWidgetItem * RSSImp : : createArticleListItem ( const Rss : : ArticlePtr & article ) <nl> { <nl> Q_ASSERT ( article ) ; <nl> - QListWidgetItem * item = new QListWidgetItem ; <nl> + QListWidgetItem * item = new QListWidgetItem ; <nl> <nl> item - > setData ( Article : : TitleRole , article - > title ( ) ) ; <nl> item - > setData ( Article : : FeedUrlRole , article - > parent ( ) - > url ( ) ) ; <nl> QListWidgetItem * RSSImp : : createArticleListItem ( const Rss : : ArticlePtr & article ) <nl> } <nl> <nl> / / fills the newsList <nl> - void RSSImp : : populateArticleList ( QTreeWidgetItem * item ) <nl> + void RSSImp : : populateArticleList ( QTreeWidgetItem * item ) <nl> { <nl> if ( ! item ) { <nl> listArticles - > clear ( ) ; <nl> void RSSImp : : populateArticleList ( QTreeWidgetItem * item ) <nl> articles = rss_item - > articleListByDateDesc ( ) ; <nl> <nl> qDebug ( " Got the list of news " ) ; <nl> - foreach ( const Rss : : ArticlePtr & article , articles ) { <nl> - QListWidgetItem * articleItem = createArticleListItem ( article ) ; <nl> + foreach ( const Rss : : ArticlePtr & article , articles ) { <nl> + QListWidgetItem * articleItem = createArticleListItem ( article ) ; <nl> listArticles - > addItem ( articleItem ) ; <nl> } <nl> qDebug ( " Added all news to the GUI " ) ; <nl> void RSSImp : : populateArticleList ( QTreeWidgetItem * item ) <nl> / / display a news <nl> void RSSImp : : refreshTextBrowser ( ) <nl> { <nl> - QList < QListWidgetItem * > selection = listArticles - > selectedItems ( ) ; <nl> + QList < QListWidgetItem * > selection = listArticles - > selectedItems ( ) ; <nl> if ( selection . empty ( ) ) return ; <nl> QListWidgetItem * item = selection . first ( ) ; <nl> Q_ASSERT ( item ) ; <nl> void RSSImp : : refreshTextBrowser ( ) <nl> html + = " < div style = ' background - color : # efefef ; ' > < b > " + tr ( " Author : " ) + " < / b > " + article - > author ( ) + " < / div > " ; <nl> html + = " < / div > " ; <nl> html + = " < div style = ' margin - left : 5px ; margin - right : 5px ; ' > " ; <nl> - if ( Qt : : mightBeRichText ( article - > description ( ) ) ) { <nl> + if ( Qt : : mightBeRichText ( article - > description ( ) ) ) { <nl> html + = article - > description ( ) ; <nl> } <nl> else { <nl> void RSSImp : : refreshTextBrowser ( ) <nl> void RSSImp : : saveSlidersPosition ( ) <nl> { <nl> / / Remember sliders positions <nl> - Preferences * const pref = Preferences : : instance ( ) ; <nl> + Preferences * const pref = Preferences : : instance ( ) ; <nl> pref - > setRssSideSplitterState ( splitterSide - > saveState ( ) ) ; <nl> pref - > setRssMainSplitterState ( splitterMain - > saveState ( ) ) ; <nl> qDebug ( " Splitters position saved " ) ; <nl> void RSSImp : : saveSlidersPosition ( ) <nl> <nl> void RSSImp : : restoreSlidersPosition ( ) <nl> { <nl> - const Preferences * const pref = Preferences : : instance ( ) ; <nl> + const Preferences * const pref = Preferences : : instance ( ) ; <nl> const QByteArray stateSide = pref - > getRssSideSplitterState ( ) ; <nl> if ( ! stateSide . isEmpty ( ) ) <nl> splitterSide - > restoreState ( stateSide ) ; <nl> void RSSImp : : restoreSlidersPosition ( ) <nl> splitterMain - > restoreState ( stateMain ) ; <nl> } <nl> <nl> - void RSSImp : : updateItemsInfos ( const QList < QTreeWidgetItem * > & items ) <nl> + void RSSImp : : updateItemsInfos ( const QList < QTreeWidgetItem * > & items ) <nl> { <nl> - foreach ( QTreeWidgetItem * item , items ) <nl> + foreach ( QTreeWidgetItem * item , items ) <nl> updateItemInfos ( item ) ; <nl> } <nl> <nl> void RSSImp : : updateItemInfos ( QTreeWidgetItem * item ) <nl> name = tr ( " Unread " ) ; <nl> emit updateRSSCount ( rss_item - > unreadCount ( ) ) ; <nl> } <nl> - else <nl> + else { <nl> name = rss_item - > displayName ( ) ; <nl> + } <nl> item - > setText ( 0 , name + QString : : fromUtf8 ( " ( " ) + QString : : number ( rss_item - > unreadCount ( ) ) + QString ( " ) " ) ) ; <nl> / / If item has a parent , update it too <nl> if ( item - > parent ( ) ) <nl> updateItemInfos ( item - > parent ( ) ) ; <nl> } <nl> <nl> - void RSSImp : : updateFeedIcon ( const QString & url , const QString & iconPath ) <nl> + void RSSImp : : updateFeedIcon ( const QString & url , const QString & iconPath ) <nl> { <nl> - QTreeWidgetItem * item = m_feedList - > getTreeItemFromUrl ( url ) ; <nl> + QTreeWidgetItem * item = m_feedList - > getTreeItemFromUrl ( url ) ; <nl> item - > setData ( 0 , Qt : : DecorationRole , QVariant ( QIcon ( iconPath ) ) ) ; <nl> } <nl> <nl> - void RSSImp : : updateFeedInfos ( const QString & url , const QString & display_name , uint nbUnread ) <nl> + void RSSImp : : updateFeedInfos ( const QString & url , const QString & display_name , uint nbUnread ) <nl> { <nl> qDebug ( ) < < Q_FUNC_INFO < < display_name ; <nl> QTreeWidgetItem * item = m_feedList - > getTreeItemFromUrl ( url ) ; <nl> void RSSImp : : updateFeedInfos ( const QString & url , const QString & display_name , ui <nl> updateItemInfos ( m_feedList - > stickyUnreadItem ( ) ) ; <nl> } <nl> <nl> - void RSSImp : : onFeedContentChanged ( const QString & url ) <nl> + void RSSImp : : onFeedContentChanged ( const QString & url ) <nl> { <nl> qDebug ( ) < < Q_FUNC_INFO < < url ; <nl> QTreeWidgetItem * item = m_feedList - > getTreeItemFromUrl ( url ) ; <nl> void RSSImp : : updateRefreshInterval ( uint val ) <nl> m_rssManager - > updateRefreshInterval ( val ) ; <nl> } <nl> <nl> - RSSImp : : RSSImp ( QWidget * parent ) : <nl> - QWidget ( parent ) , <nl> + RSSImp : : RSSImp ( QWidget * parent ) <nl> + : QWidget ( parent ) , <nl> m_rssManager ( new Rss : : Manager ) <nl> { <nl> setupUi ( this ) ; <nl> RSSImp : : RSSImp ( QWidget * parent ) : <nl> populateArticleList ( m_feedList - > currentItem ( ) ) ; <nl> <nl> loadFoldersOpenState ( ) ; <nl> - connect ( m_rssManager . data ( ) , SIGNAL ( feedInfosChanged ( QString , QString , unsigned int ) ) , SLOT ( updateFeedInfos ( QString , QString , unsigned int ) ) ) ; <nl> + connect ( m_rssManager . data ( ) , SIGNAL ( feedInfosChanged ( QString , QString , unsigned int ) ) , SLOT ( updateFeedInfos ( QString , QString , unsigned int ) ) ) ; <nl> connect ( m_rssManager . data ( ) , SIGNAL ( feedContentChanged ( QString ) ) , SLOT ( onFeedContentChanged ( QString ) ) ) ; <nl> - connect ( m_rssManager . data ( ) , SIGNAL ( feedIconChanged ( QString , QString ) ) , SLOT ( updateFeedIcon ( QString , QString ) ) ) ; <nl> + connect ( m_rssManager . data ( ) , SIGNAL ( feedIconChanged ( QString , QString ) ) , SLOT ( updateFeedIcon ( QString , QString ) ) ) ; <nl> <nl> - connect ( m_feedList , SIGNAL ( customContextMenuRequested ( const QPoint & ) ) , SLOT ( displayRSSListMenu ( const QPoint & ) ) ) ; <nl> - connect ( listArticles , SIGNAL ( customContextMenuRequested ( const QPoint & ) ) , SLOT ( displayItemsListMenu ( const QPoint & ) ) ) ; <nl> + connect ( m_feedList , SIGNAL ( customContextMenuRequested ( const QPoint & ) ) , SLOT ( displayRSSListMenu ( const QPoint & ) ) ) ; <nl> + connect ( listArticles , SIGNAL ( customContextMenuRequested ( const QPoint & ) ) , SLOT ( displayItemsListMenu ( const QPoint & ) ) ) ; <nl> <nl> / / Feeds list actions <nl> connect ( actionDelete , SIGNAL ( triggered ( ) ) , this , SLOT ( deleteSelectedItems ( ) ) ) ; <nl> RSSImp : : RSSImp ( QWidget * parent ) : <nl> connect ( actionOpen_news_URL , SIGNAL ( triggered ( ) ) , this , SLOT ( openSelectedArticlesUrls ( ) ) ) ; <nl> connect ( actionDownload_torrent , SIGNAL ( triggered ( ) ) , this , SLOT ( downloadSelectedTorrents ( ) ) ) ; <nl> <nl> - connect ( m_feedList , SIGNAL ( currentItemChanged ( QTreeWidgetItem * , QTreeWidgetItem * ) ) , this , SLOT ( populateArticleList ( QTreeWidgetItem * ) ) ) ; <nl> - connect ( m_feedList , SIGNAL ( foldersAltered ( QList < QTreeWidgetItem * > ) ) , this , SLOT ( updateItemsInfos ( QList < QTreeWidgetItem * > ) ) ) ; <nl> + connect ( m_feedList , SIGNAL ( currentItemChanged ( QTreeWidgetItem * , QTreeWidgetItem * ) ) , this , SLOT ( populateArticleList ( QTreeWidgetItem * ) ) ) ; <nl> + connect ( m_feedList , SIGNAL ( foldersAltered ( QList < QTreeWidgetItem * > ) ) , this , SLOT ( updateItemsInfos ( QList < QTreeWidgetItem * > ) ) ) ; <nl> <nl> connect ( listArticles , SIGNAL ( itemSelectionChanged ( ) ) , this , SLOT ( refreshTextBrowser ( ) ) ) ; <nl> connect ( listArticles , SIGNAL ( itemDoubleClicked ( QListWidgetItem * ) ) , this , SLOT ( downloadSelectedTorrents ( ) ) ) ; <nl> RSSImp : : RSSImp ( QWidget * parent ) : <nl> / / Restore sliders position <nl> restoreSlidersPosition ( ) ; <nl> / / Bind saveSliders slots <nl> - connect ( splitterMain , SIGNAL ( splitterMoved ( int , int ) ) , this , SLOT ( saveSlidersPosition ( ) ) ) ; <nl> - connect ( splitterSide , SIGNAL ( splitterMoved ( int , int ) ) , this , SLOT ( saveSlidersPosition ( ) ) ) ; <nl> + connect ( splitterMain , SIGNAL ( splitterMoved ( int , int ) ) , this , SLOT ( saveSlidersPosition ( ) ) ) ; <nl> + connect ( splitterSide , SIGNAL ( splitterMoved ( int , int ) ) , this , SLOT ( saveSlidersPosition ( ) ) ) ; <nl> <nl> qDebug ( " RSSImp constructed " ) ; <nl> } <nl> mmm a / src / gui / rss / rss_imp . h <nl> ppp b / src / gui / rss / rss_imp . h <nl> class RSSImp : public QWidget , public Ui : : RSS <nl> Q_OBJECT <nl> <nl> public : <nl> - RSSImp ( QWidget * parent ) ; <nl> + RSSImp ( QWidget * parent ) ; <nl> ~ RSSImp ( ) ; <nl> <nl> public slots : <nl> private slots : <nl> void on_newFeedButton_clicked ( ) ; <nl> void refreshAllFeeds ( ) ; <nl> void on_markReadButton_clicked ( ) ; <nl> - void displayRSSListMenu ( const QPoint & ) ; <nl> - void displayItemsListMenu ( const QPoint & ) ; <nl> + void displayRSSListMenu ( const QPoint & ) ; <nl> + void displayItemsListMenu ( const QPoint & ) ; <nl> void renameSelectedRssFile ( ) ; <nl> void refreshSelectedItems ( ) ; <nl> void copySelectedFeedsURL ( ) ; <nl> - void populateArticleList ( QTreeWidgetItem * item ) ; <nl> + void populateArticleList ( QTreeWidgetItem * item ) ; <nl> void refreshTextBrowser ( ) ; <nl> void updateFeedIcon ( const QString & url , const QString & icon_path ) ; <nl> void updateFeedInfos ( const QString & url , const QString & display_name , uint nbUnread ) ; <nl> - void onFeedContentChanged ( const QString & url ) ; <nl> - void updateItemsInfos ( const QList < QTreeWidgetItem * > & items ) ; <nl> + void onFeedContentChanged ( const QString & url ) ; <nl> + void updateItemsInfos ( const QList < QTreeWidgetItem * > & items ) ; <nl> void updateItemInfos ( QTreeWidgetItem * item ) ; <nl> void openSelectedArticlesUrls ( ) ; <nl> void downloadSelectedTorrents ( ) ; <nl> - void fillFeedsList ( QTreeWidgetItem * parent = 0 , const Rss : : FolderPtr & rss_parent = Rss : : FolderPtr ( ) ) ; <nl> + void fillFeedsList ( QTreeWidgetItem * parent = 0 , const Rss : : FolderPtr & rss_parent = Rss : : FolderPtr ( ) ) ; <nl> void saveSlidersPosition ( ) ; <nl> void restoreSlidersPosition ( ) ; <nl> void askNewFolder ( ) ; <nl> private slots : <nl> void on_rssDownloaderBtn_clicked ( ) ; <nl> <nl> private : <nl> - static QListWidgetItem * createArticleListItem ( const Rss : : ArticlePtr & article ) ; <nl> - static QTreeWidgetItem * createFolderListItem ( const Rss : : FilePtr & rssFile ) ; <nl> + static QListWidgetItem * createArticleListItem ( const Rss : : ArticlePtr & article ) ; <nl> + static QTreeWidgetItem * createFolderListItem ( const Rss : : FilePtr & rssFile ) ; <nl> <nl> private : <nl> Rss : : ManagerPtr m_rssManager ; <nl> FeedListWidget * m_feedList ; <nl> - QListWidgetItem * m_currentArticle ; <nl> + QListWidgetItem * m_currentArticle ; <nl> QShortcut * editHotkey ; <nl> QShortcut * deleteHotkey ; <nl> - <nl> } ; <nl> <nl> # endif <nl> mmm a / src / gui / torrentmodel . cpp <nl> ppp b / src / gui / torrentmodel . cpp <nl> TorrentModel : : TorrentModel ( QObject * parent ) <nl> addTorrent ( torrent ) ; <nl> <nl> / / Listen for torrent changes <nl> - connect ( BitTorrent : : Session : : instance ( ) , SIGNAL ( torrentAdded ( BitTorrent : : TorrentHandle * const ) ) , SLOT ( addTorrent ( BitTorrent : : TorrentHandle * const ) ) ) ; <nl> - connect ( BitTorrent : : Session : : instance ( ) , SIGNAL ( torrentAboutToBeRemoved ( BitTorrent : : TorrentHandle * const ) ) , SLOT ( handleTorrentAboutToBeRemoved ( BitTorrent : : TorrentHandle * const ) ) ) ; <nl> + connect ( BitTorrent : : Session : : instance ( ) , SIGNAL ( torrentAdded ( BitTorrent : : TorrentHandle * const ) ) , SLOT ( addTorrent ( BitTorrent : : TorrentHandle * const ) ) ) ; <nl> + connect ( BitTorrent : : Session : : instance ( ) , SIGNAL ( torrentAboutToBeRemoved ( BitTorrent : : TorrentHandle * const ) ) , SLOT ( handleTorrentAboutToBeRemoved ( BitTorrent : : TorrentHandle * const ) ) ) ; <nl> connect ( BitTorrent : : Session : : instance ( ) , SIGNAL ( torrentsUpdated ( ) ) , SLOT ( handleTorrentsUpdated ( ) ) ) ; <nl> <nl> - connect ( BitTorrent : : Session : : instance ( ) , SIGNAL ( torrentFinished ( BitTorrent : : TorrentHandle * const ) ) , SLOT ( handleTorrentStatusUpdated ( BitTorrent : : TorrentHandle * const ) ) ) ; <nl> - connect ( BitTorrent : : Session : : instance ( ) , SIGNAL ( torrentMetadataLoaded ( BitTorrent : : TorrentHandle * const ) ) , SLOT ( handleTorrentStatusUpdated ( BitTorrent : : TorrentHandle * const ) ) ) ; <nl> - connect ( BitTorrent : : Session : : instance ( ) , SIGNAL ( torrentResumed ( BitTorrent : : TorrentHandle * const ) ) , SLOT ( handleTorrentStatusUpdated ( BitTorrent : : TorrentHandle * const ) ) ) ; <nl> - connect ( BitTorrent : : Session : : instance ( ) , SIGNAL ( torrentPaused ( BitTorrent : : TorrentHandle * const ) ) , SLOT ( handleTorrentStatusUpdated ( BitTorrent : : TorrentHandle * const ) ) ) ; <nl> - connect ( BitTorrent : : Session : : instance ( ) , SIGNAL ( torrentFinishedChecking ( BitTorrent : : TorrentHandle * const ) ) , SLOT ( handleTorrentStatusUpdated ( BitTorrent : : TorrentHandle * const ) ) ) ; <nl> + connect ( BitTorrent : : Session : : instance ( ) , SIGNAL ( torrentFinished ( BitTorrent : : TorrentHandle * const ) ) , SLOT ( handleTorrentStatusUpdated ( BitTorrent : : TorrentHandle * const ) ) ) ; <nl> + connect ( BitTorrent : : Session : : instance ( ) , SIGNAL ( torrentMetadataLoaded ( BitTorrent : : TorrentHandle * const ) ) , SLOT ( handleTorrentStatusUpdated ( BitTorrent : : TorrentHandle * const ) ) ) ; <nl> + connect ( BitTorrent : : Session : : instance ( ) , SIGNAL ( torrentResumed ( BitTorrent : : TorrentHandle * const ) ) , SLOT ( handleTorrentStatusUpdated ( BitTorrent : : TorrentHandle * const ) ) ) ; <nl> + connect ( BitTorrent : : Session : : instance ( ) , SIGNAL ( torrentPaused ( BitTorrent : : TorrentHandle * const ) ) , SLOT ( handleTorrentStatusUpdated ( BitTorrent : : TorrentHandle * const ) ) ) ; <nl> + connect ( BitTorrent : : Session : : instance ( ) , SIGNAL ( torrentFinishedChecking ( BitTorrent : : TorrentHandle * const ) ) , SLOT ( handleTorrentStatusUpdated ( BitTorrent : : TorrentHandle * const ) ) ) ; <nl> } <nl> <nl> int TorrentModel : : rowCount ( const QModelIndex & index ) const <nl> QVariant TorrentModel : : headerData ( int section , Qt : : Orientation orientation , int <nl> { <nl> if ( orientation = = Qt : : Horizontal ) { <nl> if ( role = = Qt : : DisplayRole ) { <nl> - switch ( section ) { <nl> + switch ( section ) { <nl> case TR_PRIORITY : return " # " ; <nl> case TR_NAME : return tr ( " Name " , " i . e : torrent name " ) ; <nl> case TR_SIZE : return tr ( " Size " , " i . e : torrent size " ) ; <nl> QVariant TorrentModel : : headerData ( int section , Qt : : Orientation orientation , int <nl> } <nl> } <nl> else if ( role = = Qt : : TextAlignmentRole ) { <nl> - switch ( section ) { <nl> + switch ( section ) { <nl> case TR_AMOUNT_DOWNLOADED : <nl> case TR_AMOUNT_UPLOADED : <nl> case TR_AMOUNT_DOWNLOADED_SESSION : <nl> QVariant TorrentModel : : data ( const QModelIndex & index , int role ) const <nl> if ( ( role ! = Qt : : DisplayRole ) & & ( role ! = Qt : : UserRole ) ) <nl> return QVariant ( ) ; <nl> <nl> - switch ( index . column ( ) ) { <nl> + switch ( index . column ( ) ) { <nl> case TR_NAME : <nl> return torrent - > name ( ) ; <nl> case TR_PRIORITY : <nl> QVariant TorrentModel : : data ( const QModelIndex & index , int role ) const <nl> return - 1 ; <nl> return torrent - > timeSinceActivity ( ) ; <nl> case TR_TOTAL_SIZE : <nl> - return torrent - > totalSize ( ) ; <nl> + return torrent - > totalSize ( ) ; <nl> default : <nl> return QVariant ( ) ; <nl> } <nl> bool TorrentModel : : setData ( const QModelIndex & index , const QVariant & value , int <nl> if ( ! torrent ) return false ; <nl> <nl> / / Category , seed date and Name columns can be edited <nl> - switch ( index . column ( ) ) { <nl> + switch ( index . column ( ) ) { <nl> case TR_NAME : <nl> torrent - > setName ( value . toString ( ) ) ; <nl> break ; <nl> | Merge pull request from magao / issue2192 | qbittorrent/qBittorrent | c8ddd68a7a4636b9bfe52cb7422add7b4abba6c2 | 2017-01-20T21:13:06Z |
new file mode 100644 <nl> index 0000000000 . . 5c30a4bb87 <nl> mmm / dev / null <nl> ppp b / code / bit - manipulation / power_of_2 / power_of_2 . go <nl> <nl> + / / Part of Cosmos by OpenGenus Foundation <nl> + / / @ Author : Chanwit Piromplad <nl> + / / @ Date : 2017 - 10 - 15 20 : 57 <nl> + <nl> + package main <nl> + <nl> + import ( <nl> + " fmt " <nl> + ) <nl> + <nl> + func isPowerOf2 ( n int ) bool { <nl> + return n > 0 & & ( n & ( n - 1 ) = = 0 ) <nl> + } <nl> + <nl> + func main ( ) { <nl> + fmt . Println ( isPowerOf2 ( 64 ) ) <nl> + } <nl> | Merge pull request from kingkong64 / master | OpenGenus/cosmos | 7c1f1e6cac97509aa2a07c0405a9a496527a5b6e | 2017-10-15T15:23:08Z |
mmm a / doc / tutorials / calib3d / real_time_pose / real_time_pose . rst <nl> ppp b / doc / tutorials / calib3d / real_time_pose / real_time_pose . rst <nl> The tutorial consists of two main programs : <nl> <nl> 1 . * * Model registration * * <nl> <nl> - This applicaton is exclusive to whom don ' t have a 3D textured model of the object to be detected . You can use this program to create your own textured 3D model . This program only works for planar objects , then if you want to model an object with complex shape you should use a sophisticated software to create it . <nl> + This applicaton is exclusive to whom don ' t have a 3D textured model of the object to be detected . You can use this program to create your own textured 3D model . This program only works for planar objects , then if you want to model an object with complex shape you should use a sophisticated software to create it . <nl> <nl> - The application needs an input image of the object to be registered and its 3D mesh . We have also to provide the intrinsic parameters of the camera with which the input image was taken . All the files need to be specified using the absolute path or the relative one from your application ’ s working directory . If none files are specified the program will try to open the provided default parameters . <nl> + The application needs an input image of the object to be registered and its 3D mesh . We have also to provide the intrinsic parameters of the camera with which the input image was taken . All the files need to be specified using the absolute path or the relative one from your application ’ s working directory . If none files are specified the program will try to open the provided default parameters . <nl> <nl> - The application starts up extracting the ORB features and descriptors from the input image and then uses the mesh along with the ` Möller – Trumbore intersection algorithm < http : / / http : / / en . wikipedia . org / wiki / M % C3 % B6ller % E2 % 80 % 93Trumbore_intersection_algorithm / > ` _ to compute the 3D coordinates of the found features . Finally , the 3D points and the descriptors are stored in different lists in a file with YAML format which each row is a different point . The technical background on how to store the files can be found in the : ref : ` fileInputOutputXMLYAML ` tutorial . <nl> + The application starts up extracting the ORB features and descriptors from the input image and then uses the mesh along with the ` Möller – Trumbore intersection algorithm < http : / / http : / / en . wikipedia . org / wiki / M % C3 % B6ller % E2 % 80 % 93Trumbore_intersection_algorithm / > ` _ to compute the 3D coordinates of the found features . Finally , the 3D points and the descriptors are stored in different lists in a file with YAML format which each row is a different point . The technical background on how to store the files can be found in the : ref : ` fileInputOutputXMLYAML ` tutorial . <nl> <nl> . . image : : images / registration . png <nl> : alt : Model registration <nl> : align : center <nl> <nl> <nl> - # . * * Model detection * * <nl> + 2 . * * Model detection * * <nl> <nl> - The aim of this application is estimate in real time the object pose given its 3D textured model . <nl> + The aim of this application is estimate in real time the object pose given its 3D textured model . <nl> <nl> - The application starts up loading the 3D textured model in YAML file format with the same structure explained in the model registration program . From the scene the ORB features and descriptors are detected and extracted . Then , is used : flann_based_matcher : ` FlannBasedMatcher < > ` with : flann : ` LshIndexParams < flann - index - t - index > ` to do the matching between the scene descriptors and the model descriptors . Using the found matches along with : calib3d : ` solvePnPRansac < solvepnpransac > ` function the : math : ` R ` and : math : ` t ` of the camera are computed . Finally , a : video : ` KalmanFilter < kalmanfilter > ` is applied in order to reject bad poses . <nl> + The application starts up loading the 3D textured model in YAML file format with the same structure explained in the model registration program . From the scene , the ORB features and descriptors are detected and extracted . Then , is used : flann_based_matcher : ` FlannBasedMatcher < > ` with : flann : ` LshIndexParams < flann - index - t - index > ` to do the matching between the scene descriptors and the model descriptors . Using the found matches along with : calib3d : ` solvePnPRansac < solvepnpransac > ` function the : math : ` R ` and : math : ` t ` of the camera are computed . Finally , a : video : ` KalmanFilter < kalmanfilter > ` is applied in order to reject bad poses . <nl> + <nl> + In the case that you compiled OpenCV with the samples , you can find it in : file : ` opencv / build / bin / cpp - tutorial - pnp_detection ` . Then you can run the application and change some parameters : <nl> + <nl> + . . code - block : : cpp <nl> + <nl> + This program shows how to detect an object given its 3D textured model . You can choose to use a recorded video or the webcam . <nl> + Usage : <nl> + . / cpp - tutorial - pnp_detection - help <nl> + Keys : <nl> + ' esc ' - to quit . <nl> + mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> + <nl> + Usage : cpp - tutorial - pnp_detection [ params ] <nl> + <nl> + - c , - - confidence ( value : 0 . 95 ) <nl> + RANSAC confidence <nl> + - e , - - error ( value : 2 . 0 ) <nl> + RANSAC reprojection errror <nl> + - f , - - fast ( value : true ) <nl> + use of robust fast match <nl> + - h , - - help ( value : true ) <nl> + print this message <nl> + - - in , - - inliers ( value : 30 ) <nl> + minimum inliers for Kalman update <nl> + - - it , - - iterations ( value : 500 ) <nl> + RANSAC maximum iterations count <nl> + - k , - - keypoints ( value : 2000 ) <nl> + number of keypoints to detect <nl> + - - mesh <nl> + path to ply mesh <nl> + - - method , - - pnp ( value : 0 ) <nl> + PnP method : ( 0 ) ITERATIVE - ( 1 ) EPNP - ( 2 ) P3P - ( 3 ) DLS <nl> + - - model <nl> + path to yml model <nl> + - r , - - ratio ( value : 0 . 7 ) <nl> + threshold for ratio test <nl> + - v , - - video <nl> + path to recorded video <nl> + <nl> + For example , you can run the application changing the pnp method : <nl> + <nl> + . . code - block : : cpp <nl> + <nl> + . / cpp - tutorial - pnp_detection - - method = 2 <nl> <nl> <nl> Explanation <nl> Here is explained in detail the code for the real time application : <nl> <nl> 1 . * * Read 3D textured object model and object mesh . * * <nl> <nl> - In order to load the textured model I implemented the * class * * * Model * * which has the function * load ( ) * that opens a YAML file and take the stored 3D points with its corresponding descriptors . You can find an example of a 3D textured model in : file : ` samples / cpp / tutorial_code / calib3d / real_time_pose_estimation / Data / cookies_ORB . yml ` . <nl> + In order to load the textured model I implemented the * class * * * Model * * which has the function * load ( ) * that opens a YAML file and take the stored 3D points with its corresponding descriptors . You can find an example of a 3D textured model in : file : ` samples / cpp / tutorial_code / calib3d / real_time_pose_estimation / Data / cookies_ORB . yml ` . <nl> <nl> . . code - block : : cpp <nl> <nl> In order to load the textured model I implemented the * class * * * Model * * which ha <nl> <nl> } <nl> <nl> - In the main program the model is loaded as follows : <nl> + In the main program the model is loaded as follows : <nl> <nl> . . code - block : : cpp <nl> <nl> Model model ; / / instantiate Model object <nl> model . load ( yml_read_path ) ; / / load a 3D textured object model <nl> <nl> - <nl> - <nl> - In order to read the model mesh I implemented a * class * * * Mesh * * which has a function * load ( ) * that opens a : math : ` * ` . ply file and store the 3D points of the object and also the composed triangles . You can find an example of a model mesh in : file : ` samples / cpp / tutorial_code / calib3d / real_time_pose_estimation / Data / box . ply ` . <nl> + In order to read the model mesh I implemented a * class * * * Mesh * * which has a function * load ( ) * that opens a : math : ` * ` . ply file and store the 3D points of the object and also the composed triangles . You can find an example of a model mesh in : file : ` samples / cpp / tutorial_code / calib3d / real_time_pose_estimation / Data / box . ply ` . <nl> <nl> . . code - block : : cpp <nl> <nl> In order to read the model mesh I implemented a * class * * * Mesh * * which has a fun <nl> <nl> } <nl> <nl> - In the main program the mesh is loaded as follows : <nl> + In the main program the mesh is loaded as follows : <nl> <nl> . . code - block : : cpp <nl> <nl> Mesh mesh ; / / instantiate Mesh object <nl> mesh . load ( ply_read_path ) ; / / load an object mesh <nl> <nl> + You can also load different model and mesh : <nl> + <nl> + . . code - block : : cpp <nl> + <nl> + . / cpp - tutorial - pnp_detection - - mesh = / absolute_path_to_your_mesh . ply - - model = / absolute_path_to_your_model . yml <nl> <nl> - # . * * Take input from Camera or Video * * <nl> <nl> - To detect is necessary capture video . It ' s done loading a recorded video by passing the absolute path where it is located in your machine or using the default camera device . In order to test the application you can find a recorded video in : file : ` samples / cpp / tutorial_code / calib3d / real_time_pose_estimation / Data / box . mp4 ` . <nl> + 2 . * * Take input from Camera or Video * * <nl> + <nl> + To detect is necessary capture video . It ' s done loading a recorded video by passing the absolute path where it is located in your machine . In order to test the application you can find a recorded video in : file : ` samples / cpp / tutorial_code / calib3d / real_time_pose_estimation / Data / box . mp4 ` . <nl> <nl> . . code - block : : cpp <nl> <nl> - cv : : VideoCapture cap ; / / instantiate VideoCapture <nl> - ( argc < 2 ) ? cap . open ( 0 ) : cap . open ( argv [ 1 ] ) ; / / open the default camera device <nl> - / / or a recorder video <nl> + cv : : VideoCapture cap ; / / instantiate VideoCapture <nl> + cap . open ( video_read_path ) ; / / open a recorded video <nl> <nl> - if ( ! cap . isOpened ( ) ) / / check if we succeeded <nl> + if ( ! cap . isOpened ( ) ) / / check if we succeeded <nl> { <nl> - std : : cout < < " Could not open the camera device " < < std : : endl ; <nl> - return - 1 ; <nl> + std : : cout < < " Could not open the camera device " < < std : : endl ; <nl> + return - 1 ; <nl> } <nl> <nl> - Then the algorithm is computed frame per frame : <nl> + Then the algorithm is computed frame per frame : <nl> <nl> . . code - block : : cpp <nl> <nl> cv : : Mat frame , frame_vis ; <nl> <nl> - while ( cap . read ( frame ) & & cv : : waitKey ( 30 ) ! = 27 ) / / capture frame until ESC is pressed <nl> + while ( cap . read ( frame ) & & cv : : waitKey ( 30 ) ! = 27 ) / / capture frame until ESC is pressed <nl> { <nl> <nl> - frame_vis = frame . clone ( ) ; / / refresh visualisation frame <nl> + frame_vis = frame . clone ( ) ; / / refresh visualisation frame <nl> <nl> / / MAIN ALGORITHM <nl> <nl> } <nl> <nl> + You can also load different recorded video : <nl> <nl> - # . * * Extract ORB features and descriptors from the scene * * <nl> + . . code - block : : cpp <nl> <nl> - The next step is to detect the scene features and extract it descriptors . For this task I implemented a * class * * * RobustMatcher * * which has a function for keypoints detection and features extraction . You can find it in : file : ` samples / cpp / tutorial_code / calib3d / real_time_pose_estimation / src / RobusMatcher . cpp ` . In your * RobusMatch * object you can use any of the 2D features detectors of OpenCV . In this case I used : feature_detection_and_description : ` ORB < orb > ` features because is based on : feature_detection_and_description : ` FAST < fast > ` to detect the keypoints and : descriptor_extractor : ` BRIEF < briefdescriptorextractor > ` to extract the descriptors which means that is fast and robust to rotations . You can find more detailed information about * ORB * in the documentation . <nl> + . / cpp - tutorial - pnp_detection - - video = / absolute_path_to_your_video . mp4 <nl> <nl> - The following code is how to instantiate and set the features detector and the descriptors extractor : <nl> + <nl> + 3 . * * Extract ORB features and descriptors from the scene * * <nl> + <nl> + The next step is to detect the scene features and extract it descriptors . For this task I implemented a * class * * * RobustMatcher * * which has a function for keypoints detection and features extraction . You can find it in : file : ` samples / cpp / tutorial_code / calib3d / real_time_pose_estimation / src / RobusMatcher . cpp ` . In your * RobusMatch * object you can use any of the 2D features detectors of OpenCV . In this case I used : feature_detection_and_description : ` ORB < orb > ` features because is based on : feature_detection_and_description : ` FAST < fast > ` to detect the keypoints and : descriptor_extractor : ` BRIEF < briefdescriptorextractor > ` to extract the descriptors which means that is fast and robust to rotations . You can find more detailed information about * ORB * in the documentation . <nl> + <nl> + The following code is how to instantiate and set the features detector and the descriptors extractor : <nl> <nl> . . code - block : : cpp <nl> <nl> The following code is how to instantiate and set the features detector and the d <nl> rmatcher . setFeatureDetector ( detector ) ; / / set feature detector <nl> rmatcher . setDescriptorExtractor ( extractor ) ; / / set descriptor extractor <nl> <nl> - The features and descriptors will be computed by the * RobustMatcher * inside the matching function . <nl> + The features and descriptors will be computed by the * RobustMatcher * inside the matching function . <nl> <nl> <nl> - # . * * Match scene descriptors with model descriptors using Flann matcher * * <nl> + 4 . * * Match scene descriptors with model descriptors using Flann matcher * * <nl> <nl> - It is the first step in our detection algorithm . The main idea is to match the scene descriptors with our model descriptors in order to know the 3D coordinates of the found features into the current scene . <nl> + It is the first step in our detection algorithm . The main idea is to match the scene descriptors with our model descriptors in order to know the 3D coordinates of the found features into the current scene . <nl> <nl> - Firstly , we have to set which matcher we want to use . In this case is used : flann_based_matcher : ` FlannBasedMatcher < > ` matcher which in terms of computational cost is faster than the : brute_force_matcher : ` BruteForceMatcher < bfmatcher > ` matcher as we increase the trained collectction of features . Then , for FlannBased matcher the index created is * Multi - Probe LSH : Efficient Indexing for High - Dimensional Similarity Search * due to * ORB * descriptors are binary . <nl> + Firstly , we have to set which matcher we want to use . In this case is used : flann_based_matcher : ` FlannBasedMatcher < > ` matcher which in terms of computational cost is faster than the : brute_force_matcher : ` BruteForceMatcher < bfmatcher > ` matcher as we increase the trained collectction of features . Then , for FlannBased matcher the index created is * Multi - Probe LSH : Efficient Indexing for High - Dimensional Similarity Search * due to * ORB * descriptors are binary . <nl> <nl> - You can tune the * LSH * and search parameters to improve the matching efficiency : <nl> + You can tune the * LSH * and search parameters to improve the matching efficiency : <nl> <nl> - . . code - block : : cpp <nl> + . . code - block : : cpp <nl> <nl> cv : : Ptr < cv : : flann : : IndexParams > indexParams = cv : : makePtr < cv : : flann : : LshIndexParams > ( 6 , 12 , 1 ) ; / / instantiate LSH index parameters <nl> cv : : Ptr < cv : : flann : : SearchParams > searchParams = cv : : makePtr < cv : : flann : : SearchParams > ( 50 ) ; / / instantiate flann search parameters <nl> You can tune the * LSH * and search parameters to improve the matching efficiency : <nl> rmatcher . setDescriptorMatcher ( matcher ) ; / / set matcher <nl> <nl> <nl> - Secondly , we have to call the matcher by using * robustMatch ( ) * or * fastRobustMatch ( ) * function . The difference of using this two functions is its computational cost . The first method is slower but more robust at filtering good matches because uses two ratio test and a symmetry test . In contrast , the second method is faster but less robust because only applies a single ratio test to the matches . <nl> + Secondly , we have to call the matcher by using * robustMatch ( ) * or * fastRobustMatch ( ) * function . The difference of using this two functions is its computational cost . The first method is slower but more robust at filtering good matches because uses two ratio test and a symmetry test . In contrast , the second method is faster but less robust because only applies a single ratio test to the matches . <nl> <nl> - The following code is to get the model 3D points and its descriptors and then call the matcher in the main program : <nl> + The following code is to get the model 3D points and its descriptors and then call the matcher in the main program : <nl> <nl> - . . code - block : : cpp <nl> + . . code - block : : cpp <nl> <nl> / / Get the MODEL INFO <nl> <nl> std : : vector < cv : : Point3f > list_points3d_model = model . get_points3d ( ) ; / / list with model 3D coordinates <nl> cv : : Mat descriptors_model = model . get_descriptors ( ) ; / / list with descriptors of each 3D coordinate <nl> <nl> - . . code - block : : cpp <nl> + . . code - block : : cpp <nl> <nl> / / - - Step 1 : Robust matching between model descriptors and scene descriptors <nl> <nl> The following code is to get the model 3D points and its descriptors and then ca <nl> rmatcher . robustMatch ( frame , good_matches , keypoints_scene , descriptors_model ) ; <nl> } <nl> <nl> - The following code corresponds to the * robustMatch ( ) * function which belongs to the * RobustMatcher * class . This function uses the given image to detect the keypoints and extract the descriptors , match using * two Nearest Neighbour * the extracted descriptors with the given model descriptors and vice versa . Then , a ratio test is applied to the two direction matches in order to remove these matches which its distance ratio between the first and second best match is larger than a given threshold . Finally , a symmetry test is applied in order the remove non symmetrical matches . <nl> + The following code corresponds to the * robustMatch ( ) * function which belongs to the * RobustMatcher * class . This function uses the given image to detect the keypoints and extract the descriptors , match using * two Nearest Neighbour * the extracted descriptors with the given model descriptors and vice versa . Then , a ratio test is applied to the two direction matches in order to remove these matches which its distance ratio between the first and second best match is larger than a given threshold . Finally , a symmetry test is applied in order the remove non symmetrical matches . <nl> <nl> - . . code - block : : cpp <nl> + . . code - block : : cpp <nl> <nl> void RobustMatcher : : robustMatch ( const cv : : Mat & frame , std : : vector < cv : : DMatch > & good_matches , <nl> - std : : vector < cv : : KeyPoint > & keypoints_frame , <nl> - const std : : vector < cv : : KeyPoint > & keypoints_model , const cv : : Mat & descriptors_model ) <nl> + std : : vector < cv : : KeyPoint > & keypoints_frame , <nl> + const std : : vector < cv : : KeyPoint > & keypoints_model , const cv : : Mat & descriptors_model ) <nl> { <nl> <nl> / / 1a . Detection of the ORB features <nl> The following code corresponds to the * robustMatch ( ) * function which belongs to <nl> <nl> } <nl> <nl> - After the matches filtering we have to subtract the 2D and 3D correspondences from the found scene keypoints and our 3D model using the obtained * DMatches * vector . For more information about : basicstructures : ` DMatch < dmatch > ` check the documentation . <nl> + After the matches filtering we have to subtract the 2D and 3D correspondences from the found scene keypoints and our 3D model using the obtained * DMatches * vector . For more information about : basicstructures : ` DMatch < dmatch > ` check the documentation . <nl> <nl> - . . code - block : : cpp <nl> + . . code - block : : cpp <nl> <nl> / / - - Step 2 : Find out the 2D / 3D correspondences <nl> <nl> After the matches filtering we have to subtract the 2D and 3D correspondences fr <nl> <nl> for ( unsigned int match_index = 0 ; match_index < good_matches . size ( ) ; + + match_index ) <nl> { <nl> - cv : : Point3f point3d_model = list_points3d_model [ good_matches [ match_index ] . trainIdx ] ; / / 3D point from model <nl> + cv : : Point3f point3d_model = list_points3d_model [ good_matches [ match_index ] . trainIdx ] ; / / 3D point from model <nl> cv : : Point2f point2d_scene = keypoints_scene [ good_matches [ match_index ] . queryIdx ] . pt ; / / 2D point from the scene <nl> - list_points3d_model_match . push_back ( point3d_model ) ; / / add 3D point <nl> - list_points2d_scene_match . push_back ( point2d_scene ) ; / / add 2D point <nl> + list_points3d_model_match . push_back ( point3d_model ) ; / / add 3D point <nl> + list_points2d_scene_match . push_back ( point2d_scene ) ; / / add 2D point <nl> } <nl> <nl> + You can also change the ratio test threshold , the number of keypoints to detect as well as use or not the robust matcher : <nl> <nl> - # . * * Pose estimation using PnP + Ransac * * <nl> + . . code - block : : cpp <nl> <nl> - Once with the 2D and 3D correspondences we have to apply a PnP algorithm in order to estimate the camera pose . The reason why we have to use : calib3d : ` solvePnPRansac < solvepnpransac > ` instead of : calib3d : ` solvePnP < solvepnp > ` is due to the fact that after the matching not all the found correspondences are correct and , as like as not , there are false correspondences or also called * outliers * . The ` Random Sample Consensus < http : / / en . wikipedia . org / wiki / RANSAC > ` _ or * Ransac * is a non - deterministic iterative method which estimate parameters of a mathematical model from observed data producing an aproximate result as the number of iterations increase . After appyling * Ransac * all the * outliers * will be eliminated to then estimate the camera pose with a certain probability to obtain a good solution . <nl> + . / cpp - tutorial - pnp_detection - - ratio = 0 . 8 - - keypoints = 1000 - - fast = false <nl> <nl> - For the camera pose estimation I have implemented a * class * * * PnPProblem * * . This * class * has 4 atributes : a given calibration matrix , the rotation matrix , the translation matrix and the rotation - translation matrix . The intrinsic calibration parameters of the camera which you are using to estimate the pose are necessary . In order to obtain the parameters you can check : ref : ` CameraCalibrationSquareChessBoardTutorial ` and : ref : ` cameraCalibrationOpenCV ` tutorials . <nl> <nl> - The following code is how to declare the * PnPProblem class * in the main program : <nl> + 5 . * * Pose estimation using PnP + Ransac * * <nl> <nl> - . . code - block : : cpp <nl> + Once with the 2D and 3D correspondences we have to apply a PnP algorithm in order to estimate the camera pose . The reason why we have to use : calib3d : ` solvePnPRansac < solvepnpransac > ` instead of : calib3d : ` solvePnP < solvepnp > ` is due to the fact that after the matching not all the found correspondences are correct and , as like as not , there are false correspondences or also called * outliers * . The ` Random Sample Consensus < http : / / en . wikipedia . org / wiki / RANSAC > ` _ or * Ransac * is a non - deterministic iterative method which estimate parameters of a mathematical model from observed data producing an aproximate result as the number of iterations increase . After appyling * Ransac * all the * outliers * will be eliminated to then estimate the camera pose with a certain probability to obtain a good solution . <nl> + <nl> + For the camera pose estimation I have implemented a * class * * * PnPProblem * * . This * class * has 4 atributes : a given calibration matrix , the rotation matrix , the translation matrix and the rotation - translation matrix . The intrinsic calibration parameters of the camera which you are using to estimate the pose are necessary . In order to obtain the parameters you can check : ref : ` CameraCalibrationSquareChessBoardTutorial ` and : ref : ` cameraCalibrationOpenCV ` tutorials . <nl> + <nl> + The following code is how to declare the * PnPProblem class * in the main program : <nl> + <nl> + . . code - block : : cpp <nl> <nl> - / * <nl> - * Set up the intrinsic camera parameters : UVC WEBCAM <nl> - * / <nl> + / / Intrinsic camera parameters : UVC WEBCAM <nl> <nl> double f = 55 ; / / focal length in mm <nl> double sx = 22 . 3 , sy = 14 . 9 ; / / sensor size <nl> double width = 640 , height = 480 ; / / image size <nl> <nl> double params_WEBCAM [ ] = { width * f / sx , / / fx <nl> - height * f / sy , / / fy <nl> - width / 2 , / / cx <nl> - height / 2 } ; / / cy <nl> + height * f / sy , / / fy <nl> + width / 2 , / / cx <nl> + height / 2 } ; / / cy <nl> <nl> PnPProblem pnp_detection ( params_WEBCAM ) ; / / instantiate PnPProblem class <nl> <nl> - The following code is how the * PnPProblem class * initialises its atributes : <nl> + The following code is how the * PnPProblem class * initialises its atributes : <nl> <nl> - . . code - block : : cpp <nl> + . . code - block : : cpp <nl> <nl> / / Custom constructor given the intrinsic camera parameters <nl> <nl> The following code is how the * PnPProblem class * initialises its atributes : <nl> <nl> } <nl> <nl> - OpenCV provides four PnP methods : ITERATIVE , EPNP , P3P and DLS . Depending on the application type , the estimation method will be different . In the case that we want to make a real time application , the more suitable methods are EPNP and P3P due to that are faster than ITERATIVE and DLS at finding an optimal solution . However , EPNP and P3P are not especially robust in front of planar surfaces and sometimes the pose estimation seems to have a mirror effect . Therefore , in this this tutorial is used ITERATIVE method due to the object to be detected has planar surfaces . <nl> + OpenCV provides four PnP methods : ITERATIVE , EPNP , P3P and DLS . Depending on the application type , the estimation method will be different . In the case that we want to make a real time application , the more suitable methods are EPNP and P3P due to that are faster than ITERATIVE and DLS at finding an optimal solution . However , EPNP and P3P are not especially robust in front of planar surfaces and sometimes the pose estimation seems to have a mirror effect . Therefore , in this this tutorial is used ITERATIVE method due to the object to be detected has planar surfaces . <nl> <nl> - The OpenCV Ransac implementation wants you to provide three parameters : the maximum number of iterations until stop the algorithm , the maximum allowed distance between the observed and computed point projections to consider it an inlier and the confidence to obtain a good result . You can tune these paramaters in order to improve your algorithm performance . Increasing the number of iterations you will have a more accurate solution , but will take more time to find a solution . Increasing the reprojection error will reduce the computation time , but your solution will be unaccurate . Decreasing the confidence your arlgorithm will be faster , but the obtained solution will be unaccurate . <nl> + The OpenCV Ransac implementation wants you to provide three parameters : the maximum number of iterations until stop the algorithm , the maximum allowed distance between the observed and computed point projections to consider it an inlier and the confidence to obtain a good result . You can tune these paramaters in order to improve your algorithm performance . Increasing the number of iterations you will have a more accurate solution , but will take more time to find a solution . Increasing the reprojection error will reduce the computation time , but your solution will be unaccurate . Decreasing the confidence your arlgorithm will be faster , but the obtained solution will be unaccurate . <nl> <nl> - The following parameters work for this application : <nl> + The following parameters work for this application : <nl> <nl> - . . code - block : : cpp <nl> + . . code - block : : cpp <nl> <nl> / / RANSAC parameters <nl> <nl> - int iterationsCount = 500 ; / / number of Ransac iterations . <nl> + int iterationsCount = 500 ; / / number of Ransac iterations . <nl> float reprojectionError = 2 . 0 ; / / maximum allowed distance to consider it an inlier . <nl> - float confidence = 0 . 95 ; / / ransac successful confidence . <nl> + float confidence = 0 . 95 ; / / ransac successful confidence . <nl> <nl> <nl> - The following code corresponds to the * estimatePoseRANSAC ( ) * function which belongs to the * PnPProblem class * . This function estimates the rotation and translation matrix given a set of 2D / 3D correspondences , the desired PnP method to use , the output inliers container and the Ransac parameters : <nl> + The following code corresponds to the * estimatePoseRANSAC ( ) * function which belongs to the * PnPProblem class * . This function estimates the rotation and translation matrix given a set of 2D / 3D correspondences , the desired PnP method to use , the output inliers container and the Ransac parameters : <nl> <nl> - . . code - block : : cpp <nl> + . . code - block : : cpp <nl> <nl> / / Estimate the pose given a list of 2D / 3D correspondences with RANSAC and the method to use <nl> <nl> - void PnPProblem : : estimatePoseRANSAC ( const std : : vector < cv : : Point3f > & list_points3d , / / list with model 3D coordinates <nl> - const std : : vector < cv : : Point2f > & list_points2d , / / list with scene 2D coordinates <nl> - int flags , cv : : Mat & inliers , int iterationsCount , / / PnP method ; inliers container <nl> - float reprojectionError , float confidence ) / / Ransac parameters <nl> + void PnPProblem : : estimatePoseRANSAC ( const std : : vector < cv : : Point3f > & list_points3d , / / list with model 3D coordinates <nl> + const std : : vector < cv : : Point2f > & list_points2d , / / list with scene 2D coordinates <nl> + int flags , cv : : Mat & inliers , int iterationsCount , / / PnP method ; inliers container <nl> + float reprojectionError , float confidence ) / / Ransac parameters <nl> { <nl> cv : : Mat distCoeffs = cv : : Mat : : zeros ( 4 , 1 , CV_64FC1 ) ; / / vector of distortion coefficients <nl> cv : : Mat rvec = cv : : Mat : : zeros ( 3 , 1 , CV_64FC1 ) ; / / output rotation vector <nl> - cv : : Mat tvec = cv : : Mat : : zeros ( 3 , 1 , CV_64FC1 ) ; / / output translation vector <nl> + cv : : Mat tvec = cv : : Mat : : zeros ( 3 , 1 , CV_64FC1 ) ; / / output translation vector <nl> <nl> bool useExtrinsicGuess = false ; / / if true the function uses the provided rvec and tvec values as <nl> - / / initial approximations of the rotation and translation vectors <nl> + / / initial approximations of the rotation and translation vectors <nl> <nl> cv : : solvePnPRansac ( list_points3d , list_points2d , _A_matrix , distCoeffs , rvec , tvec , <nl> - useExtrinsicGuess , iterationsCount , reprojectionError , confidence , <nl> - inliers , flags ) ; <nl> + useExtrinsicGuess , iterationsCount , reprojectionError , confidence , <nl> + inliers , flags ) ; <nl> <nl> - Rodrigues ( rvec , _R_matrix ) ; / / converts Rotation Vector to Matrix <nl> - _t_matrix = tvec ; / / set translation matrix <nl> + Rodrigues ( rvec , _R_matrix ) ; / / converts Rotation Vector to Matrix <nl> + _t_matrix = tvec ; / / set translation matrix <nl> <nl> this - > set_P_matrix ( _R_matrix , _t_matrix ) ; / / set rotation - translation matrix <nl> <nl> } <nl> <nl> - In the following code are the 3th and 4th steps of the main algorithm . The first , calling the above function and the second taking the output inliers vector from Ransac to get the 2D scene points for drawing purpose . As seen in the code we must be sure to apply Ransac if we have matches , in the other case , the function : calib3d : ` solvePnPRansac < solvepnpransac > ` crashes due to any OpenCV * bug * . <nl> + In the following code are the 3th and 4th steps of the main algorithm . The first , calling the above function and the second taking the output inliers vector from Ransac to get the 2D scene points for drawing purpose . As seen in the code we must be sure to apply Ransac if we have matches , in the other case , the function : calib3d : ` solvePnPRansac < solvepnpransac > ` crashes due to any OpenCV * bug * . <nl> <nl> - . . code - block : : cpp <nl> + . . code - block : : cpp <nl> <nl> if ( good_matches . size ( ) > 0 ) / / None matches , then RANSAC crashes <nl> { <nl> <nl> / / - - Step 3 : Estimate the pose using RANSAC approach <nl> pnp_detection . estimatePoseRANSAC ( list_points3d_model_match , list_points2d_scene_match , <nl> - cv : : ITERATIVE , inliers_idx , <nl> - iterationsCount , reprojectionError , minInliersCount ) ; <nl> + pnpMethod , inliers_idx , iterationsCount , reprojectionError , confidence ) ; <nl> <nl> <nl> / / - - Step 4 : Catch the inliers keypoints to draw <nl> In the following code are the 3th and 4th steps of the main algorithm . The first <nl> } <nl> <nl> <nl> - Finally , once the camera pose has been estimated we can use the : math : ` R ` and : math : ` t ` in order to compute the 2D projection onto the image of a given 3D point expressed in a world reference frame using the showed formula on * Theory * . <nl> + Finally , once the camera pose has been estimated we can use the : math : ` R ` and : math : ` t ` in order to compute the 2D projection onto the image of a given 3D point expressed in a world reference frame using the showed formula on * Theory * . <nl> <nl> - The following code corresponds to the * backproject3DPoint ( ) * function which belongs to the * PnPProblem class * . The function backproject a given 3D point expressed in a world reference frame onto a 2D image : <nl> + The following code corresponds to the * backproject3DPoint ( ) * function which belongs to the * PnPProblem class * . The function backproject a given 3D point expressed in a world reference frame onto a 2D image : <nl> <nl> - . . code - block : : cpp <nl> + . . code - block : : cpp <nl> <nl> / / Backproject a 3D point to 2D using the estimated pose parameters <nl> <nl> The following code corresponds to the * backproject3DPoint ( ) * function which belo <nl> return point2d ; <nl> } <nl> <nl> - The above function is used to compute all the 3D points of the object * Mesh * to show the pose of the object . <nl> + The above function is used to compute all the 3D points of the object * Mesh * to show the pose of the object . <nl> + <nl> + You can also change RANSAC parameters and PnP method : <nl> <nl> + . . code - block : : cpp <nl> <nl> - # . * * Linear Kalman Filter for bad poses rejection * * <nl> + . / cpp - tutorial - pnp_detection - - error = 0 . 25 - - confidence = 0 . 90 - - iterations = 250 - - method = 3 <nl> <nl> - Is it common in computer vision or robotics fields that after applying detection or tracking techniques , bad results are obtained due to some sensor errors . In order to avoid these bad detections in this tutorial is explained how to implement a Linear Kalman Filter . The Kalman Filter will be applied after detected a given number of inliers . <nl> <nl> - You can find more information about what ` Kalman Filter < http : / / en . wikipedia . org / wiki / Kalman_filter > ` _ is . In this tutorial it ' s used the OpenCV implementation of the : video : ` Kalman Filter < kalmanfilter > ` based on ` Linear Kalman Filter for position and orientation tracking < http : / / campar . in . tum . de / Chair / KalmanFilter > ` _ to set the dynamics and measurement models . <nl> + 6 . * * Linear Kalman Filter for bad poses rejection * * <nl> <nl> - Firstly , we have to define our state vector which will have 18 states : the positional data ( x , y , z ) with its first and second derivatives ( velocity and acceleration ) , then rotation is added in form of three euler angles ( roll , pitch , jaw ) together with their first and second derivatives ( angular velocity and acceleration ) <nl> + Is it common in computer vision or robotics fields that after applying detection or tracking techniques , bad results are obtained due to some sensor errors . In order to avoid these bad detections in this tutorial is explained how to implement a Linear Kalman Filter . The Kalman Filter will be applied after detected a given number of inliers . <nl> + <nl> + You can find more information about what ` Kalman Filter < http : / / en . wikipedia . org / wiki / Kalman_filter > ` _ is . In this tutorial it ' s used the OpenCV implementation of the : video : ` Kalman Filter < kalmanfilter > ` based on ` Linear Kalman Filter for position and orientation tracking < http : / / campar . in . tum . de / Chair / KalmanFilter > ` _ to set the dynamics and measurement models . <nl> + <nl> + Firstly , we have to define our state vector which will have 18 states : the positional data ( x , y , z ) with its first and second derivatives ( velocity and acceleration ) , then rotation is added in form of three euler angles ( roll , pitch , jaw ) together with their first and second derivatives ( angular velocity and acceleration ) <nl> <nl> . . math : : <nl> <nl> X = ( x , y , z , \ dot x , \ dot y , \ dot z , \ ddot x , \ ddot y , \ ddot z , \ psi , \ theta , \ phi , \ dot \ psi , \ dot \ theta , \ dot \ phi , \ ddot \ psi , \ ddot \ theta , \ ddot \ phi ) ^ T <nl> <nl> - Secondly , we have to define the number of measuremnts which will be 6 : from : math : ` R ` and : math : ` t ` we can extract : math : ` ( x , y , z ) ` and : math : ` ( \ psi , \ theta , \ phi ) ` . In addition , we have to define the number of control actions to apply to the system which in this case will be * zero * . Finally , we have to define the differential time between measurements which in this case is : math : ` 1 / T ` , where * T * is the frame rate of the video . <nl> + Secondly , we have to define the number of measuremnts which will be 6 : from : math : ` R ` and : math : ` t ` we can extract : math : ` ( x , y , z ) ` and : math : ` ( \ psi , \ theta , \ phi ) ` . In addition , we have to define the number of control actions to apply to the system which in this case will be * zero * . Finally , we have to define the differential time between measurements which in this case is : math : ` 1 / T ` , where * T * is the frame rate of the video . <nl> <nl> - . . code - block : : cpp <nl> + . . code - block : : cpp <nl> <nl> cv : : KalmanFilter KF ; / / instantiate Kalman Filter <nl> <nl> Secondly , we have to define the number of measuremnts which will be 6 : from : mat <nl> initKalmanFilter ( KF , nStates , nMeasurements , nInputs , dt ) ; / / init function <nl> <nl> <nl> - The following code corresponds to the * Kalman Filter * initialisation . Firstly , is set the process noise , the measurement noise and the error covariance matrix . Secondly , are set the transition matrix which is the dynamic model and finally the measurement matrix , which is the measurement model . <nl> + The following code corresponds to the * Kalman Filter * initialisation . Firstly , is set the process noise , the measurement noise and the error covariance matrix . Secondly , are set the transition matrix which is the dynamic model and finally the measurement matrix , which is the measurement model . <nl> <nl> - You can tune the process and measurement noise to improve the * Kalman Filter * performance . As the measurement noise is reduced the faster will converge doing the algorithm sensitive in front of bad measurements . <nl> + You can tune the process and measurement noise to improve the * Kalman Filter * performance . As the measurement noise is reduced the faster will converge doing the algorithm sensitive in front of bad measurements . <nl> <nl> - . . code - block : : cpp <nl> + . . code - block : : cpp <nl> <nl> void initKalmanFilter ( cv : : KalmanFilter & KF , int nStates , int nMeasurements , int nInputs , double dt ) <nl> { <nl> You can tune the process and measurement noise to improve the * Kalman Filter * pe <nl> KF . measurementMatrix . at < double > ( 4 , 10 ) = 1 ; / / pitch <nl> KF . measurementMatrix . at < double > ( 5 , 11 ) = 1 ; / / yaw <nl> <nl> - std : : cout < < " A " < < std : : endl < < KF . transitionMatrix < < std : : endl ; <nl> - std : : cout < < " C " < < std : : endl < < KF . measurementMatrix < < std : : endl ; <nl> - <nl> } <nl> <nl> - In the following code is the 5th step of the main algorithm . When the obtained number of inliers after * Ransac * is over the threshold , the measurements matrix is filled and then the * Kalman Filter * is updated : <nl> + In the following code is the 5th step of the main algorithm . When the obtained number of inliers after * Ransac * is over the threshold , the measurements matrix is filled and then the * Kalman Filter * is updated : <nl> <nl> - . . code - block : : cpp <nl> + . . code - block : : cpp <nl> <nl> / / - - Step 5 : Kalman Filter <nl> <nl> In the following code is the 5th step of the main algorithm . When the obtained n <nl> updateKalmanFilter ( KF , measurements , <nl> translation_estimated , rotation_estimated ) ; <nl> <nl> - The following code corresponds to the * fillMeasurements ( ) * function which converts the measured ` Rotation Matrix to Eulers angles < http : / / euclideanspace . com / maths / geometry / rotations / conversions / matrixToEuler / index . htm > ` _ and fill the measurements matrix along with the measured translation vector : <nl> + The following code corresponds to the * fillMeasurements ( ) * function which converts the measured ` Rotation Matrix to Eulers angles < http : / / euclideanspace . com / maths / geometry / rotations / conversions / matrixToEuler / index . htm > ` _ and fill the measurements matrix along with the measured translation vector : <nl> <nl> - . . code - block : : cpp <nl> + . . code - block : : cpp <nl> <nl> void fillMeasurements ( cv : : Mat & measurements , <nl> const cv : : Mat & translation_measured , const cv : : Mat & rotation_measured ) <nl> The following code corresponds to the * fillMeasurements ( ) * function which conver <nl> } <nl> <nl> <nl> - The following code corresponds to the * updateKalmanFilter ( ) * function which update the Kalman Filter and set the estimated Rotation Matrix and translation vector . The estimated Rotation Matrix comes from the estimated ` Euler angles to Rotation Matrix < http : / / euclideanspace . com / maths / geometry / rotations / conversions / eulerToMatrix / index . htm > ` _ . <nl> + The following code corresponds to the * updateKalmanFilter ( ) * function which update the Kalman Filter and set the estimated Rotation Matrix and translation vector . The estimated Rotation Matrix comes from the estimated ` Euler angles to Rotation Matrix < http : / / euclideanspace . com / maths / geometry / rotations / conversions / eulerToMatrix / index . htm > ` _ . <nl> <nl> - . . code - block : : cpp <nl> + . . code - block : : cpp <nl> <nl> void updateKalmanFilter ( cv : : KalmanFilter & KF , cv : : Mat & measurement , <nl> cv : : Mat & translation_estimated , cv : : Mat & rotation_estimated ) <nl> The following code corresponds to the * updateKalmanFilter ( ) * function which upda <nl> <nl> } <nl> <nl> - The 6th step is set the estimated rotation - translation matrix : <nl> + The 6th step is set the estimated rotation - translation matrix : <nl> <nl> - . . code - block : : cpp <nl> + . . code - block : : cpp <nl> <nl> / / - - Step 6 : Set estimated projection matrix <nl> pnp_detection_est . set_P_matrix ( rotation_estimated , translation_estimated ) ; <nl> <nl> <nl> - The last and optional step is draw the found pose . To do it I implemented a function to draw all the mesh 3D points and an extra reference axis : <nl> + The last and optional step is draw the found pose . To do it I implemented a function to draw all the mesh 3D points and an extra reference axis : <nl> <nl> - . . code - block : : cpp <nl> + . . code - block : : cpp <nl> <nl> / / - - Step X : Draw pose <nl> <nl> drawObjectMesh ( frame_vis , & mesh , & pnp_detection , green ) ; / / draw current pose <nl> - drawObjectMesh ( frame_vis , & mesh , & pnp_detection_est , yellow ) ; / / draw estimated pose <nl> + drawObjectMesh ( frame_vis , & mesh , & pnp_detection_est , yellow ) ; / / draw estimated pose <nl> <nl> double l = 5 ; <nl> std : : vector < cv : : Point2f > pose_points2d ; <nl> The last and optional step is draw the found pose . To do it I implemented a func <nl> pose_points2d . push_back ( pnp_detection_est . backproject3DPoint ( cv : : Point3f ( l , 0 , 0 ) ) ) ; / / axis x <nl> pose_points2d . push_back ( pnp_detection_est . backproject3DPoint ( cv : : Point3f ( 0 , l , 0 ) ) ) ; / / axis y <nl> pose_points2d . push_back ( pnp_detection_est . backproject3DPoint ( cv : : Point3f ( 0 , 0 , l ) ) ) ; / / axis z <nl> - draw3DCoordinateAxes ( frame_vis , pose_points2d ) ; / / draw axes <nl> + draw3DCoordinateAxes ( frame_vis , pose_points2d ) ; / / draw axes <nl> + <nl> + You can also modify the minimum inliers to update Kalman Filter : <nl> + <nl> + . . code - block : : cpp <nl> + <nl> + . / cpp - tutorial - pnp_detection - - inliers = 20 <nl> <nl> <nl> Results <nl> Results <nl> <nl> The following videos are the results of pose estimation in real time using the explained detection algorithm using the following parameters : <nl> <nl> - . . code - block : : cpp <nl> + . . code - block : : cpp <nl> <nl> / / Robust Matcher parameters <nl> <nl> You can watch the real time pose estimation on the ` YouTube here < https : / / www . yo <nl> < div align = " center " > <nl> < iframe title = " Pose estimation for the Google Summer Code 2014 using OpenCV libraries . " width = " 560 " height = " 349 " src = " http : / / www . youtube . com / embed / msFFuHsiUns ? rel = 0 & loop = 1 " frameborder = " 0 " allowfullscreen align = " middle " > < / iframe > <nl> < / div > <nl> + <nl> + < div align = " center " > <nl> + < iframe title = " Pose estimation for the Google Summer Code 2014 using OpenCV libraries . " width = " 560 " height = " 349 " src = " http : / / www . youtube . com / embed / _E4vhmBJYLU ? rel = 0 & loop = 1 " frameborder = " 0 " allowfullscreen align = " middle " > < / iframe > <nl> + < / div > <nl> | Update tutorial | opencv/opencv | 95471105332def964a99737e72fd7e783a9d0176 | 2014-08-09T17:47:42Z |
mmm a / doc / conf . py <nl> ppp b / doc / conf . py <nl> <nl> <nl> # General information about the project . <nl> project = u ' format ' <nl> - copyright = u ' 2012 , Victor Zverovich ' <nl> + copyright = u ' 1990 - 2012 , Python Software Foundation ' <nl> <nl> # The version info for the project you ' re documenting , acts as replacement for <nl> # | version | and | release | , also used in various other places throughout the <nl> | Preserve original copyright . | fmtlib/fmt | b1da947d759bca2daf4629d33bc70f302d270260 | 2012-12-19T17:17:20Z |
mmm a / tensorflow / python / framework / test_util . py <nl> ppp b / tensorflow / python / framework / test_util . py <nl> def assertArrayNear ( self , farray1 , farray2 , err ) : <nl> farray2 : a list of float values . <nl> err : a float value . <nl> " " " <nl> + self . assertEqual ( len ( farray1 ) , len ( farray2 ) ) <nl> for f1 , f2 in zip ( farray1 , farray2 ) : <nl> - self . assertNear ( f1 , f2 , err ) <nl> + self . assertNear ( float ( f1 ) , float ( f2 ) , err ) <nl> <nl> def _NDArrayNear ( self , ndarray1 , ndarray2 , err ) : <nl> return np . linalg . norm ( ndarray1 - ndarray2 ) < err <nl> mmm a / tensorflow / python / framework / test_util_test . py <nl> ppp b / tensorflow / python / framework / test_util_test . py <nl> def testAllCloseScalars ( self ) : <nl> with self . assertRaisesRegexp ( AssertionError , r " Not equal to tolerance " ) : <nl> self . assertAllClose ( 7 , 8 ) <nl> <nl> + def testArrayNear ( self ) : <nl> + a = [ 1 , 2 ] <nl> + b = [ 1 , 2 , 5 ] <nl> + with self . assertRaises ( AssertionError ) : <nl> + self . assertArrayNear ( a , b , 0 . 001 ) <nl> + a = [ 1 , 2 ] <nl> + b = [ [ 1 , 2 ] , [ 3 , 4 ] ] <nl> + with self . assertRaises ( TypeError ) : <nl> + self . assertArrayNear ( a , b , 0 . 001 ) <nl> + a = [ 1 , 2 ] <nl> + b = [ 1 , 2 ] <nl> + self . assertArrayNear ( a , b , 0 . 001 ) <nl> + <nl> def testForceGPU ( self ) : <nl> with self . assertRaisesRegexp ( errors . InvalidArgumentError , <nl> " Cannot assign a device to node " ) : <nl> | In assertArrayNear ( ) check that the arrays have the same length . | tensorflow/tensorflow | 4acc2dad8a31e1890e182a9727499024c6dd5558 | 2016-03-29T23:35:10Z |
mmm a / hphp / system / php / redis / Redis . php <nl> ppp b / hphp / system / php / redis / Redis . php <nl> protected function processDoubleResponse ( ) { <nl> ( $ type = = = self : : TYPE_BULK & & is_numeric ( $ resp ) ) ) { <nl> return ( float ) $ resp ; <nl> } <nl> - return null ; <nl> + return false ; <nl> } <nl> $ this - > multiHandler [ ] = [ ' cb ' = > [ $ this , ' processDoubleResponse ' ] ] ; <nl> if ( ( $ this - > mode = = = self : : MULTI ) & & ! $ this - > processQueuedResponse ( ) ) { <nl> new file mode 100644 <nl> index 00000000000 . . eb9a3a844ff <nl> mmm / dev / null <nl> ppp b / hphp / test / slow / ext_redis / zScoreReturn . php <nl> <nl> + < ? php <nl> + <nl> + include ( __DIR__ . ' / redis . inc ' ) ; <nl> + <nl> + $ redis = NewRedisTestInstance ( ) ; <nl> + $ connect = $ redis - > connect ( ' 127 . 0 . 0 . 1 ' , 6379 ) ; <nl> + var_dump ( $ connect ) ; <nl> + $ redis - > zAdd ( ' myzset ' , 1 , ' one ' ) ; <nl> + $ result = $ redis - > zScore ( ' myzset ' , " one " ) ; <nl> + var_dump ( $ result ) ; <nl> + $ result = $ redis - > zScore ( ' myzset ' , " one3 " ) ; <nl> + var_dump ( $ result ) ; <nl> new file mode 100644 <nl> index 00000000000 . . 57d7cdfaeb6 <nl> mmm / dev / null <nl> ppp b / hphp / test / slow / ext_redis / zScoreReturn . php . expect <nl> <nl> + bool ( true ) <nl> + float ( 1 ) <nl> + bool ( false ) <nl> new file mode 100644 <nl> index 00000000000 . . 60e41c65d73 <nl> mmm / dev / null <nl> ppp b / hphp / test / slow / ext_redis / zScoreReturn . php . skipif <nl> <nl> + < ? php <nl> + <nl> + if ( ! getenv ( ' REDIS_TEST_HOST ' ) ) { <nl> + echo ' skip ' ; <nl> + } else { <nl> + / / Some people might have this variable set , but don ' t have the server running <nl> + $ output = array ( ) ; <nl> + exec ( " redis - cli ping " , $ output ) ; <nl> + if ( $ output [ 0 ] ! = = " PONG " ) { <nl> + echo ' skip ' ; <nl> + } <nl> + } <nl> \ No newline at end of file <nl> | redis responseDouble returns false on error , not null | facebook/hhvm | 3d305a8db27fbf905e96ddb6907117fa0c05dfce | 2015-04-17T15:00:29Z |
mmm a / tensorflow / core / kernels / mkl_conv_grad_filter_ops . cc <nl> ppp b / tensorflow / core / kernels / mkl_conv_grad_filter_ops . cc <nl> limitations under the License . <nl> # include < algorithm > <nl> # include < vector > <nl> <nl> + # include " mkldnn . hpp " <nl> # include " tensorflow / core / framework / numeric_op . h " <nl> # include " tensorflow / core / framework / op_kernel . h " <nl> # include " tensorflow / core / framework / register_types . h " <nl> limitations under the License . <nl> # include " tensorflow / core / lib / gtl / array_slice . h " <nl> # include " tensorflow / core / platform / logging . h " <nl> # include " tensorflow / core / platform / macros . h " <nl> + # include " tensorflow / core / util / mkl_util . h " <nl> # include " tensorflow / core / util / padding . h " <nl> # include " tensorflow / core / util / tensor_format . h " <nl> # include " tensorflow / core / util / use_cudnn . h " <nl> # include " tensorflow / core / util / work_sharder . h " <nl> <nl> - # include " mkldnn . hpp " <nl> - # include " tensorflow / core / util / mkl_util . h " <nl> - <nl> using mkldnn : : convolution_backward_weights ; <nl> using mkldnn : : memory ; <nl> using mkldnn : : prop_kind ; <nl> mmm a / tensorflow / core / kernels / mkl_conv_grad_input_ops . cc <nl> ppp b / tensorflow / core / kernels / mkl_conv_grad_input_ops . cc <nl> limitations under the License . <nl> # define EIGEN_USE_THREADS <nl> # include < algorithm > <nl> # include < vector > <nl> + # include " mkldnn . hpp " <nl> # include " tensorflow / core / framework / numeric_op . h " <nl> # include " tensorflow / core / framework / op_kernel . h " <nl> # include " tensorflow / core / framework / register_types . h " <nl> limitations under the License . <nl> # include " tensorflow / core / util / use_cudnn . h " <nl> # include " tensorflow / core / util / work_sharder . h " <nl> <nl> - # include " mkldnn . hpp " <nl> - <nl> using mkldnn : : convolution_backward_data ; <nl> using mkldnn : : prop_kind ; <nl> using mkldnn : : stream ; <nl> mmm a / tensorflow / core / kernels / mkl_conv_ops . h <nl> ppp b / tensorflow / core / kernels / mkl_conv_ops . h <nl> limitations under the License . <nl> # include < vector > <nl> # include < memory > <nl> <nl> + # include " mkldnn . hpp " <nl> # include " tensorflow / core / framework / numeric_op . h " <nl> # include " tensorflow / core / framework / op_kernel . h " <nl> # include " tensorflow / core / framework / register_types . h " <nl> limitations under the License . <nl> # include " tensorflow / core / util / mkl_util . h " <nl> # include " tensorflow / core / util / padding . h " <nl> # include " tensorflow / core / util / tensor_format . h " <nl> - # include " mkldnn . hpp " <nl> <nl> - using mkldnn : : prop_kind ; <nl> - using mkldnn : : stream ; <nl> using mkldnn : : convolution_direct ; <nl> using mkldnn : : convolution_forward ; <nl> + using mkldnn : : prop_kind ; <nl> + using mkldnn : : stream ; <nl> <nl> namespace tensorflow { <nl> <nl> | adjust headers inclusion order per review suggestion | tensorflow/tensorflow | a0653f833684787bcba74ee1870b6c81b016f42a | 2018-10-12T18:05:23Z |
mmm a / doc / xds - test - descriptions . md <nl> ppp b / doc / xds - test - descriptions . md <nl> This test verifies that every backend receives traffic . <nl> Client parameters : <nl> <nl> 1 . - - num_channels = 1 <nl> - 1 . - - qps = 10 <nl> + 1 . - - qps = 100 <nl> 1 . - - fail_on_failed_rpc = true <nl> <nl> Load balancer configuration : <nl> robin policy . <nl> Client parameters : <nl> <nl> 1 . - - num_channels = 1 <nl> - 1 . - - qps = 10 <nl> + 1 . - - qps = 100 <nl> 1 . - - fail_on_failed_rpc = true <nl> <nl> Load balancer configuration : <nl> of backends that is stopped and then resumed . <nl> Client parameters : <nl> <nl> 1 . - - num_channels = 1 <nl> - 1 . - - qps = 10 <nl> + 1 . - - qps = 100 <nl> <nl> Load balancer configuration : <nl> <nl> all backends in the primary locality fail . <nl> Client parameters : <nl> <nl> 1 . - - num_channels = 1 <nl> - 1 . - - qps = 10 <nl> + 1 . - - qps = 100 <nl> <nl> Load balancer configuration : <nl> <nl> changes to this test case . <nl> Client parameters : <nl> <nl> 1 . - - num_channels = 1 <nl> - 1 . - - qps = 10 <nl> + 1 . - - qps = 100 <nl> <nl> Load balancer configuration : <nl> <nl> same zone receive traffic . <nl> Client parameters : <nl> <nl> 1 . - - num_channels = 1 <nl> - 1 . - - qps = 10 <nl> + 1 . - - qps = 100 <nl> 1 . - - fail_on_failed_rpc = true <nl> <nl> Load balancer configuration : <nl> after removal of another instance group in the same zone . <nl> Client parameters : <nl> <nl> 1 . - - num_channels = 1 <nl> - 1 . - - qps = 10 <nl> + 1 . - - qps = 100 <nl> <nl> Load balancer configuration : <nl> <nl> to the new backends . <nl> Client parameters : <nl> <nl> 1 . - - num_channels = 1 <nl> - 1 . - - qps = 10 <nl> + 1 . - - qps = 100 <nl> 1 . - - fail_on_failed_rpc = true <nl> <nl> Load balancer configuration : <nl> | Merge pull request from ericgribkoff / qps | grpc/grpc | 3f4b0d5f946c4737e8316eb70a2987c35bf63335 | 2020-06-14T05:15:53Z |
mmm a / src / runtime . js <nl> ppp b / src / runtime . js <nl> var Runtime = { <nl> / / we align i64s and doubles on 64 - bit boundaries , unlike x86 <nl> # if TARGET_LE32 <nl> if ( type = = ' i64 ' | | type = = ' double ' | | vararg ) return 8 ; <nl> + if ( ! type ) return Math . min ( size , 8 ) ; / / align structures internally to 64 bits <nl> # endif <nl> return Math . min ( size | | ( type ? Runtime . getNativeFieldSize ( type ) : 0 ) , Runtime . QUANTUM_SIZE ) ; <nl> } , <nl> mmm a / tests / runner . py <nl> ppp b / tests / runner . py <nl> def test_unaligned ( self ) : <nl> except Exception , e : <nl> assert ' must be aligned ' in str ( e ) , e # expected to fail without emulation <nl> <nl> + def test_align64 ( self ) : <nl> + src = r ' ' ' <nl> + # include < stdio . h > <nl> + <nl> + / / inspired by poppler <nl> + <nl> + enum Type { <nl> + A = 10 , <nl> + B = 20 <nl> + } ; <nl> + <nl> + struct Object { <nl> + Type type ; <nl> + union { <nl> + int intg ; <nl> + double real ; <nl> + char * name ; <nl> + } ; <nl> + } ; <nl> + <nl> + struct Principal { <nl> + double x ; <nl> + Object a ; <nl> + double y ; <nl> + } ; <nl> + <nl> + int main ( int argc , char * * argv ) <nl> + { <nl> + int base = argc - 1 ; <nl> + Object * o = NULL ; <nl> + printf ( " % d , % d \ n " , sizeof ( Object ) , sizeof ( Principal ) ) ; <nl> + printf ( " % d , % d , % d , % d \ n " , ( int ) & o [ base ] . type , ( int ) & o [ base ] . intg , ( int ) & o [ base ] . real , ( int ) & o [ base ] . name ) ; <nl> + printf ( " % d , % d , % d , % d \ n " , ( int ) & o [ base + 1 ] . type , ( int ) & o [ base + 1 ] . intg , ( int ) & o [ base + 1 ] . real , ( int ) & o [ base + 1 ] . name ) ; <nl> + Principal p , q ; <nl> + p . x = p . y = q . x = q . y = 0 ; <nl> + p . a . type = A ; <nl> + p . a . real = 123 . 456 ; <nl> + * ( & q . a ) = p . a ; <nl> + printf ( " % . 2f , % d , % . 2f , % . 2f : % . 2f , % d , % . 2f , % . 2f \ n " , p . x , p . a . type , p . a . real , p . y , q . x , q . a . type , q . a . real , q . y ) ; <nl> + return 0 ; <nl> + } <nl> + ' ' ' <nl> + <nl> + if ' le32 - unknown - nacl ' in COMPILER_OPTS : <nl> + self . do_run ( src , ' ' ' 16 , 32 <nl> + 0 , 8 , 8 , 8 <nl> + 16 , 24 , 24 , 24 <nl> + 0 . 00 , 10 , 123 . 46 , 0 . 00 : 0 . 00 , 10 , 123 . 46 , 0 . 00 <nl> + ' ' ' ) <nl> + elif ' i386 - pc - linux - gnu ' in COMPILER_OPTS : <nl> + self . do_run ( src , ' ' ' 12 , 28 <nl> + 0 , 4 , 4 , 4 <nl> + 12 , 16 , 16 , 16 <nl> + 0 . 00 , 10 , 123 . 46 , 0 . 00 : 0 . 00 , 10 , 123 . 46 , 0 . 00 <nl> + ' ' ' ) <nl> + else : <nl> + raise Exception ( ' unknown arch ' ) <nl> + <nl> def test_unsigned ( self ) : <nl> Settings . CORRECT_SIGNS = 1 # We test for exactly this sort of thing here <nl> Settings . CHECK_SIGNS = 0 <nl> | align struct fields to 64 - bit in le32 | emscripten-core/emscripten | 200c188d210cb8a3a2c7e87b3dbab7744a14a49a | 2013-04-29T20:02:33Z |
mmm a / xbmc / GUIInfoManager . cpp <nl> ppp b / xbmc / GUIInfoManager . cpp <nl> int CGUIInfoManager : : TranslateSingleString ( const std : : string & strCondition , bool <nl> if ( prop . name = = player_times [ i ] . str ) <nl> return AddMultiInfo ( GUIInfo ( player_times [ i ] . val , TranslateTimeFormat ( prop . param ( ) ) ) ) ; <nl> } <nl> + if ( prop . name = = " process " & & prop . num_params ( ) ) <nl> + { <nl> + for ( size_t i = 0 ; i < sizeof ( player_process ) / sizeof ( infomap ) ; i + + ) <nl> + { <nl> + if ( prop . param ( ) = = player_process [ i ] . str ) <nl> + return player_process [ i ] . val ; <nl> + } <nl> + } <nl> if ( prop . num_params ( ) = = 1 ) <nl> { <nl> for ( size_t i = 0 ; i < sizeof ( player_param ) / sizeof ( infomap ) ; i + + ) <nl> int CGUIInfoManager : : TranslateSingleString ( const std : : string & strCondition , bool <nl> return AddMultiInfo ( GUIInfo ( player_times [ i ] . val , TranslateTimeFormat ( prop . param ( ) ) ) ) ; <nl> } <nl> if ( prop . name = = " content " & & prop . num_params ( ) ) <nl> + { <nl> return AddMultiInfo ( GUIInfo ( VIDEOPLAYER_CONTENT , ConditionalStringParameter ( prop . param ( ) ) , 0 ) ) ; <nl> + } <nl> for ( size_t i = 0 ; i < sizeof ( videoplayer ) / sizeof ( infomap ) ; i + + ) <nl> { <nl> if ( prop . name = = videoplayer [ i ] . str ) <nl> return videoplayer [ i ] . val ; <nl> } <nl> } <nl> - else if ( cat . name = = " player_process " ) <nl> - { <nl> - for ( size_t i = 0 ; i < sizeof ( player_process ) / sizeof ( infomap ) ; i + + ) <nl> - { <nl> - if ( prop . name = = player_process [ i ] . str ) <nl> - return player_process [ i ] . val ; <nl> - } <nl> - } <nl> else if ( cat . name = = " slideshow " ) <nl> { <nl> for ( size_t i = 0 ; i < sizeof ( slideshow ) / sizeof ( infomap ) ; i + + ) <nl> std : : string CGUIInfoManager : : GetLabel ( int info , int contextWindow , std : : string * <nl> case PLAYER_PROCESS_VIDEODAR : <nl> strLabel = StringUtils : : FormatNumber ( CServiceBroker : : GetDataCacheCore ( ) . GetVideoDAR ( ) ) ; <nl> break ; <nl> + case PLAYER_PROCESS_VIDEOWIDTH : <nl> + strLabel = StringUtils : : FormatNumber ( CServiceBroker : : GetDataCacheCore ( ) . GetVideoWidth ( ) ) ; <nl> + break ; <nl> + case PLAYER_PROCESS_VIDEOHEIGHT : <nl> + strLabel = StringUtils : : FormatNumber ( CServiceBroker : : GetDataCacheCore ( ) . GetVideoHeight ( ) ) ; <nl> + break ; <nl> case PLAYER_PROCESS_AUDIODECODER : <nl> strLabel = CServiceBroker : : GetDataCacheCore ( ) . GetAudioDecoderName ( ) ; <nl> break ; <nl> case PLAYER_PROCESS_AUDIOCHANNELS : <nl> strLabel = CServiceBroker : : GetDataCacheCore ( ) . GetAudioChannels ( ) ; <nl> break ; <nl> + case PLAYER_PROCESS_AUDIOSAMPLERATE : <nl> + strLabel = StringUtils : : FormatNumber ( CServiceBroker : : GetDataCacheCore ( ) . GetAudioSampleRate ( ) ) ; <nl> + break ; <nl> + case PLAYER_PROCESS_AUDIOBITSPERSAMPLE : <nl> + strLabel = StringUtils : : FormatNumber ( CServiceBroker : : GetDataCacheCore ( ) . GetAudioBitsPerSampe ( ) ) ; <nl> + break ; <nl> case RDS_AUDIO_LANG : <nl> case RDS_CHANNEL_COUNTRY : <nl> case RDS_TITLE : <nl> bool CGUIInfoManager : : GetInt ( int & value , int info , int contextWindow , const CGUI <nl> case SYSTEM_BATTERY_LEVEL : <nl> value = g_powerManager . BatteryLevel ( ) ; <nl> return true ; <nl> - case PLAYER_PROCESS_VIDEOWIDTH : <nl> - value = CServiceBroker : : GetDataCacheCore ( ) . GetVideoWidth ( ) ; <nl> - return true ; <nl> - case PLAYER_PROCESS_VIDEOHEIGHT : <nl> - value = CServiceBroker : : GetDataCacheCore ( ) . GetVideoHeight ( ) ; <nl> - return true ; <nl> - case PLAYER_PROCESS_AUDIOSAMPLERATE : <nl> - value = CServiceBroker : : GetDataCacheCore ( ) . GetAudioSampleRate ( ) ; <nl> - return true ; <nl> - case PLAYER_PROCESS_AUDIOBITSPERSAMPLE : <nl> - value = CServiceBroker : : GetDataCacheCore ( ) . GetAudioBitsPerSampe ( ) ; <nl> - return true ; <nl> } <nl> return false ; <nl> } <nl> mmm a / xbmc / cores / VideoPlayer / DVDCodecs / Video / DVDVideoCodecFFmpeg . cpp <nl> ppp b / xbmc / cores / VideoPlayer / DVDCodecs / Video / DVDVideoCodecFFmpeg . cpp <nl> enum AVPixelFormat CDVDVideoCodecFFmpeg : : GetFormat ( struct AVCodecContext * avct <nl> / / if frame threading is enabled hw accel is not allowed <nl> if ( ctx - > m_decoderState ! = STATE_HW_SINGLE ) <nl> { <nl> - return avcodec_default_get_format ( avctx , fmt ) ; <nl> + AVPixelFormat defaultFmt = avcodec_default_get_format ( avctx , fmt ) ; <nl> + pixFmtName = av_get_pix_fmt_name ( defaultFmt ) ; <nl> + ctx - > m_processInfo . SetVideoPixelFormat ( pixFmtName ? pixFmtName : " " ) ; <nl> + return defaultFmt ; <nl> } <nl> <nl> / / fix an ffmpeg issue here , it calls us with an invalid profile <nl> bool CDVDVideoCodecFFmpeg : : Open ( CDVDStreamInfo & hints , CDVDCodecOptions & options <nl> <nl> UpdateName ( ) ; <nl> <nl> - m_processInfo . SetVideoDecoderName ( m_name , m_pHardware ? true : false ) ; <nl> m_processInfo . SetVideoDimensions ( m_pCodecContext - > coded_width , m_pCodecContext - > coded_height ) ; <nl> return true ; <nl> } <nl> void CDVDVideoCodecFFmpeg : : UpdateName ( ) <nl> if ( m_pHardware ) <nl> m_name + = " - " + m_pHardware - > Name ( ) ; <nl> <nl> + m_processInfo . SetVideoDecoderName ( m_name , m_pHardware ? true : false ) ; <nl> + <nl> CLog : : Log ( LOGDEBUG , " CDVDVideoCodecFFmpeg - Updated codec : % s " , m_name . c_str ( ) ) ; <nl> } <nl> <nl> int CDVDVideoCodecFFmpeg : : FilterOpen ( const std : : string & filters , bool scale ) <nl> <nl> avfilter_inout_free ( & outputs ) ; <nl> avfilter_inout_free ( & inputs ) ; <nl> + <nl> + if ( filters . compare ( 0 , 5 , " yadif " ) = = 0 ) <nl> + { <nl> + m_processInfo . SetVideoDeintMethod ( filters ) ; <nl> + } <nl> } <nl> else <nl> { <nl> int CDVDVideoCodecFFmpeg : : FilterOpen ( const std : : string & filters , bool scale ) <nl> CLog : : Log ( LOGERROR , " CDVDVideoCodecFFmpeg : : FilterOpen - avfilter_link " ) ; <nl> return result ; <nl> } <nl> + <nl> + m_processInfo . SetVideoDeintMethod ( " none " ) ; <nl> } <nl> <nl> if ( ( result = avfilter_graph_config ( m_pFilterGraph , nullptr ) ) < 0 ) <nl> mmm a / xbmc / cores / VideoPlayer / Process / ProcessInfo . cpp <nl> ppp b / xbmc / cores / VideoPlayer / Process / ProcessInfo . cpp <nl> void CProcessInfo : : SetAudioDecoderName ( std : : string name ) <nl> CSingleLock lock ( m_audioCodecSection ) ; <nl> <nl> m_audioDecoderName = name ; <nl> + <nl> + CServiceBroker : : GetDataCacheCore ( ) . SetAudioDecoderName ( m_audioDecoderName ) ; <nl> } <nl> <nl> std : : string CProcessInfo : : GetAudioDecoderName ( ) <nl> void CProcessInfo : : SetAudioChannels ( std : : string channels ) <nl> CSingleLock lock ( m_audioCodecSection ) ; <nl> <nl> m_audioChannels = channels ; <nl> + <nl> + CServiceBroker : : GetDataCacheCore ( ) . SetAudioChannels ( m_audioChannels ) ; <nl> } <nl> <nl> std : : string CProcessInfo : : GetAudioChannels ( ) <nl> void CProcessInfo : : SetAudioSampleRate ( int sampleRate ) <nl> CSingleLock lock ( m_audioCodecSection ) ; <nl> <nl> m_audioSampleRate = sampleRate ; <nl> + <nl> + CServiceBroker : : GetDataCacheCore ( ) . SetAudioSampleRate ( m_audioSampleRate ) ; <nl> } <nl> <nl> int CProcessInfo : : GetAudioSampleRate ( ) <nl> void CProcessInfo : : SetAudioBitsPerSample ( int bitsPerSample ) <nl> CSingleLock lock ( m_audioCodecSection ) ; <nl> <nl> m_audioBitsPerSample = bitsPerSample ; <nl> + <nl> + CServiceBroker : : GetDataCacheCore ( ) . SetAudioBitsPerSample ( m_audioBitsPerSample ) ; <nl> } <nl> <nl> int CProcessInfo : : GetAudioBitsPerSampe ( ) <nl> | Merge pull request from FernetMenta / codecinfo | xbmc/xbmc | 76b5a4bda4a341b3e2ade87c82cb4143a1ee21bc | 2016-07-05T16:40:16Z |
mmm a / include / swift / AST / Expr . h <nl> ppp b / include / swift / AST / Expr . h <nl> class DotSyntaxCallExpr : public ThisApplyExpr { <nl> } <nl> <nl> SourceLoc getDotLoc ( ) const { return DotLoc ; } <nl> - SourceLoc getLoc ( ) const { return getArg ( ) - > getStartLoc ( ) ; } <nl> + SourceLoc getLoc ( ) const { <nl> + return DotLoc . isValid ( ) ? getArg ( ) - > getStartLoc ( ) : getFn ( ) - > getStartLoc ( ) ; <nl> + } <nl> SourceLoc getEndLoc ( ) const { <nl> - return DotLoc . isValid ( ) ? getFn ( ) - > getEndLoc ( ) : getArg ( ) - > getEndLoc ( ) ; <nl> + return getFn ( ) - > getEndLoc ( ) ; <nl> } <nl> <nl> SourceRange getSourceRange ( ) const { <nl> | Fix getLoc ( ) for DotSyntaxCallExpr . | apple/swift | 2947962120f44446b92a1ab78f462786456b648e | 2012-05-25T21:22:41Z |
mmm a / include / internal / catch_runner_impl . hpp <nl> ppp b / include / internal / catch_runner_impl . hpp <nl> namespace Catch { <nl> <nl> return true ; <nl> } <nl> + bool testForMissingAssertions ( Counts & assertions ) { <nl> + if ( assertions . total ( ) ! = 0 | | <nl> + ! m_config - > warnAboutMissingAssertions ( ) | | <nl> + m_testCaseTracker - > currentSectionHasChildren ( ) ) <nl> + return false ; <nl> + m_totals . assertions . failed + + ; <nl> + assertions . failed + + ; <nl> + return true ; <nl> + } <nl> <nl> virtual void sectionEnded ( SectionInfo const & info , Counts const & prevAssertions ) { <nl> if ( std : : uncaught_exception ( ) ) { <nl> namespace Catch { <nl> } <nl> <nl> Counts assertions = m_totals . assertions - prevAssertions ; <nl> - bool missingAssertions = false ; <nl> - if ( assertions . total ( ) = = 0 & & <nl> - m_config - > warnAboutMissingAssertions ( ) & & <nl> - ! m_testCaseTracker - > currentSectionHasChildren ( ) ) { <nl> - m_totals . assertions . failed + + ; <nl> - assertions . failed + + ; <nl> - missingAssertions = true ; <nl> + bool missingAssertions = testForMissingAssertions ( assertions ) ; <nl> <nl> - } <nl> m_testCaseTracker - > leaveSection ( ) ; <nl> <nl> m_reporter - > sectionEnded ( SectionStats ( info , assertions , missingAssertions ) ) ; <nl> namespace Catch { <nl> m_messages . clear ( ) ; <nl> <nl> Counts assertions = m_totals . assertions - prevAssertions ; <nl> - / / ! TBD ? <nl> - bool missingAssertions = false ; <nl> - if ( assertions . total ( ) = = 0 & & <nl> - m_config - > warnAboutMissingAssertions ( ) & & <nl> - ! m_testCaseTracker - > currentSectionHasChildren ( ) ) { <nl> - m_totals . assertions . failed + + ; <nl> - assertions . failed + + ; <nl> - missingAssertions = true ; <nl> - <nl> - } <nl> + bool missingAssertions = testForMissingAssertions ( assertions ) ; <nl> <nl> SectionStats testCaseSectionStats ( testCaseSection , assertions , missingAssertions ) ; <nl> m_reporter - > sectionEnded ( testCaseSectionStats ) ; <nl> | Refactored missing assertions handling | catchorg/Catch2 | e8cf726a23483083dcf534e70704cb860d6e1ffd | 2013-07-26T18:26:08Z |
mmm a / docs / en / operations / table_engines / kafka . md <nl> ppp b / docs / en / operations / table_engines / kafka . md <nl> If you want to change the target table by using ` ALTER ` , we recommend disabling <nl> <nl> # # Configuration <nl> <nl> - Similar to GraphiteMergeTree , the Kafka engine supports extended configuration using the ClickHouse config file . There are two configuration keys that you can use : global ( ` kafka ` ) and topic - level ( ` kafka_topic_ * ` ) . The global configuration is applied first , and then the topic - level configuration is applied ( if it exists ) . <nl> + Similar to GraphiteMergeTree , the Kafka engine supports extended configuration using the ClickHouse config file . There are two configuration keys that you can use : global ( ` kafka ` ) and topic - level ( ` kafka_ * ` ) . The global configuration is applied first , and then the topic - level configuration is applied ( if it exists ) . <nl> <nl> ` ` ` xml <nl> < ! - - Global configuration options for all tables of Kafka engine type - - > <nl> Similar to GraphiteMergeTree , the Kafka engine supports extended configuration u <nl> < / kafka > <nl> <nl> < ! - - Configuration specific for topic " logs " - - > <nl> - < kafka_topic_logs > <nl> + < kafka_logs > <nl> < retry_backoff_ms > 250 < / retry_backoff_ms > <nl> < fetch_min_bytes > 100000 < / fetch_min_bytes > <nl> - < / kafka_topic_logs > <nl> + < / kafka_logs > <nl> ` ` ` <nl> <nl> For a list of possible configuration options , see the [ librdkafka configuration reference ] ( https : / / github . com / edenhill / librdkafka / blob / master / CONFIGURATION . md ) . Use the underscore ( ` _ ` ) instead of a dot in the ClickHouse configuration . For example , ` check . crcs = true ` will be ` < check_crcs > true < / check_crcs > ` . <nl> mmm a / docs / ru / operations / table_engines / kafka . md <nl> ppp b / docs / ru / operations / table_engines / kafka . md <nl> Kafka SETTINGS <nl> <nl> # # Конфигурация <nl> <nl> - Аналогично GraphiteMergeTree , движок Kafka поддерживает расширенную конфигурацию с помощью конфигурационного файла ClickHouse . Существует два конфигурационных ключа , которые можно использовать - глобальный ( ` kafka ` ) и по топикам ( ` kafka_topic_ * ` ) . Сначала применяется глобальная конфигурация , затем конфигурация по топикам ( если она существует ) . <nl> + Аналогично GraphiteMergeTree , движок Kafka поддерживает расширенную конфигурацию с помощью конфигурационного файла ClickHouse . Существует два конфигурационных ключа , которые можно использовать - глобальный ( ` kafka ` ) и по топикам ( ` kafka_ * ` ) . Сначала применяется глобальная конфигурация , затем конфигурация по топикам ( если она существует ) . <nl> <nl> ` ` ` xml <nl> < ! - - Global configuration options for all tables of Kafka engine type - - > <nl> Kafka SETTINGS <nl> < / kafka > <nl> <nl> < ! - - Configuration specific for topic " logs " - - > <nl> - < kafka_topic_logs > <nl> + < kafka_logs > <nl> < retry_backoff_ms > 250 < / retry_backoff_ms > <nl> < fetch_min_bytes > 100000 < / fetch_min_bytes > <nl> - < / kafka_topic_logs > <nl> + < / kafka_logs > <nl> ` ` ` <nl> <nl> В документе [ librdkafka configuration reference ] ( https : / / github . com / edenhill / librdkafka / blob / master / CONFIGURATION . md ) можно увидеть список возможных опций конфигурации . Используйте подчёркивания ( ` _ ` ) вместо точек в конфигурации ClickHouse , например , ` check . crcs = true ` будет соответствовать ` < check_crcs > true < / check_crcs > ` . <nl> | fix documentation kafka per topic configuration | ClickHouse/ClickHouse | b319c29aaf71213afdcc6fc22daca6110f88143a | 2018-09-18T12:59:12Z |
mmm a / atom / common / api / atom_api_clipboard . cc <nl> ppp b / atom / common / api / atom_api_clipboard . cc <nl> void Initialize ( v8 : : Local < v8 : : Object > exports , v8 : : Local < v8 : : Value > unused , <nl> dict . SetMethod ( " writeImage " , & WriteImage ) ; <nl> dict . SetMethod ( " clear " , & Clear ) ; <nl> <nl> - / / TODO Remove in 2 . 0 , deprecate before then with warnings <nl> + / / TODO ( kevinsawicki ) : Remove in 2 . 0 , deprecate before then with warnings <nl> dict . SetMethod ( " readRtf " , & ReadRtf ) ; <nl> dict . SetMethod ( " writeRtf " , & WriteRtf ) ; <nl> dict . SetMethod ( " readHtml " , & ReadHtml ) ; <nl> | Use correct TODO format | electron/electron | 23962e133e6ddd69f1c8ea807581e3b4af2f37aa | 2016-05-26T21:28:33Z |
mmm a / src / bloom . cpp <nl> ppp b / src / bloom . cpp <nl> <nl> # include " hash . h " <nl> # include " script / script . h " <nl> # include " script / standard . h " <nl> + # include " random . h " <nl> # include " streams . h " <nl> <nl> # include < math . h > <nl> void CBloomFilter : : clear ( ) <nl> isEmpty = true ; <nl> } <nl> <nl> + void CBloomFilter : : reset ( unsigned int nNewTweak ) <nl> + { <nl> + clear ( ) ; <nl> + nTweak = nNewTweak ; <nl> + } <nl> + <nl> bool CBloomFilter : : IsWithinSizeConstraints ( ) const <nl> { <nl> return vData . size ( ) < = MAX_BLOOM_FILTER_SIZE & & nHashFuncs < = MAX_HASH_FUNCS ; <nl> void CBloomFilter : : UpdateEmptyFull ( ) <nl> isEmpty = empty ; <nl> } <nl> <nl> - CRollingBloomFilter : : CRollingBloomFilter ( unsigned int nElements , double fpRate , unsigned int nTweak ) : <nl> - b1 ( nElements * 2 , fpRate , nTweak ) , b2 ( nElements * 2 , fpRate , nTweak ) <nl> + CRollingBloomFilter : : CRollingBloomFilter ( unsigned int nElements , double fpRate ) : <nl> + b1 ( nElements * 2 , fpRate , 0 ) , b2 ( nElements * 2 , fpRate , 0 ) <nl> { <nl> / / Implemented using two bloom filters of 2 * nElements each . <nl> / / We fill them up , and clear them , staggered , every nElements <nl> / / inserted , so at least one always contains the last nElements <nl> / / inserted . <nl> - nBloomSize = nElements * 2 ; <nl> nInsertions = 0 ; <nl> + nBloomSize = nElements * 2 ; <nl> + <nl> + reset ( ) ; <nl> } <nl> <nl> void CRollingBloomFilter : : insert ( const std : : vector < unsigned char > & vKey ) <nl> void CRollingBloomFilter : : insert ( const std : : vector < unsigned char > & vKey ) <nl> } <nl> } <nl> <nl> + void CRollingBloomFilter : : insert ( const uint256 & hash ) <nl> + { <nl> + vector < unsigned char > data ( hash . begin ( ) , hash . end ( ) ) ; <nl> + insert ( data ) ; <nl> + } <nl> + <nl> bool CRollingBloomFilter : : contains ( const std : : vector < unsigned char > & vKey ) const <nl> { <nl> if ( nInsertions < nBloomSize / 2 ) { <nl> bool CRollingBloomFilter : : contains ( const std : : vector < unsigned char > & vKey ) const <nl> return b1 . contains ( vKey ) ; <nl> } <nl> <nl> - void CRollingBloomFilter : : clear ( ) <nl> + bool CRollingBloomFilter : : contains ( const uint256 & hash ) const <nl> + { <nl> + vector < unsigned char > data ( hash . begin ( ) , hash . end ( ) ) ; <nl> + return contains ( data ) ; <nl> + } <nl> + <nl> + void CRollingBloomFilter : : reset ( ) <nl> { <nl> - b1 . clear ( ) ; <nl> - b2 . clear ( ) ; <nl> + unsigned int nNewTweak = GetRand ( std : : numeric_limits < unsigned int > : : max ( ) ) ; <nl> + b1 . reset ( nNewTweak ) ; <nl> + b2 . reset ( nNewTweak ) ; <nl> nInsertions = 0 ; <nl> } <nl> mmm a / src / bloom . h <nl> ppp b / src / bloom . h <nl> class CBloomFilter <nl> bool contains ( const uint256 & hash ) const ; <nl> <nl> void clear ( ) ; <nl> + void reset ( unsigned int nNewTweak ) ; <nl> <nl> / / ! True if the size is < = MAX_BLOOM_FILTER_SIZE and the number of hash functions is < = MAX_HASH_FUNCS <nl> / / ! ( catch a filter which was just deserialized which was too big ) <nl> class CBloomFilter <nl> <nl> / * * <nl> * RollingBloomFilter is a probabilistic " keep track of most recently inserted " set . <nl> - * Construct it with the number of items to keep track of , and a false - positive rate . <nl> + * Construct it with the number of items to keep track of , and a false - positive <nl> + * rate . Unlike CBloomFilter , by default nTweak is set to a cryptographically <nl> + * secure random value for you . Similarly rather than clear ( ) the method <nl> + * reset ( ) is provided , which also changes nTweak to decrease the impact of <nl> + * false - positives . <nl> * <nl> * contains ( item ) will always return true if item was one of the last N things <nl> * insert ( ) ' ed . . . but may also return true for items that were not inserted . <nl> class CBloomFilter <nl> class CRollingBloomFilter <nl> { <nl> public : <nl> - CRollingBloomFilter ( unsigned int nElements , double nFPRate , unsigned int nTweak ) ; <nl> + / / A random bloom filter calls GetRand ( ) at creation time . <nl> + / / Don ' t create global CRollingBloomFilter objects , as they may be <nl> + / / constructed before the randomizer is properly initialized . <nl> + CRollingBloomFilter ( unsigned int nElements , double nFPRate ) ; <nl> <nl> void insert ( const std : : vector < unsigned char > & vKey ) ; <nl> + void insert ( const uint256 & hash ) ; <nl> bool contains ( const std : : vector < unsigned char > & vKey ) const ; <nl> + bool contains ( const uint256 & hash ) const ; <nl> <nl> - void clear ( ) ; <nl> + void reset ( ) ; <nl> <nl> private : <nl> unsigned int nBloomSize ; <nl> mmm a / src / main . cpp <nl> ppp b / src / main . cpp <nl> namespace { <nl> * / <nl> map < uint256 , NodeId > mapBlockSource ; <nl> <nl> + / * * <nl> + * Filter for transactions that were recently rejected by <nl> + * AcceptToMemoryPool . These are not rerequested until the chain tip <nl> + * changes , at which point the entire filter is reset . Protected by <nl> + * cs_main . <nl> + * <nl> + * Without this filter we ' d be re - requesting txs from each of our peers , <nl> + * increasing bandwidth consumption considerably . For instance , with 100 <nl> + * peers , half of which relay a tx we don ' t accept , that might be a 50x <nl> + * bandwidth increase . A flooding attacker attempting to roll - over the <nl> + * filter using minimum - sized , 60byte , transactions might manage to send <nl> + * 1000 / sec if we have fast peers , so we pick 120 , 000 to give our peers a <nl> + * two minute window to send invs to us . <nl> + * <nl> + * Decreasing the false positive rate is fairly cheap , so we pick one in a <nl> + * million to make it highly unlikely for users to have issues with this <nl> + * filter . <nl> + * <nl> + * Memory used : 1 . 7MB <nl> + * / <nl> + boost : : scoped_ptr < CRollingBloomFilter > recentRejects ; <nl> + uint256 hashRecentRejectsChainTip ; <nl> + <nl> / * * Blocks that are in flight , and that are in the queue to be downloaded . Protected by cs_main . * / <nl> struct QueuedBlock { <nl> uint256 hash ; <nl> void UnloadBlockIndex ( ) <nl> setDirtyBlockIndex . clear ( ) ; <nl> setDirtyFileInfo . clear ( ) ; <nl> mapNodeState . clear ( ) ; <nl> + recentRejects . reset ( NULL ) ; <nl> <nl> BOOST_FOREACH ( BlockMap : : value_type & entry , mapBlockIndex ) { <nl> delete entry . second ; <nl> bool LoadBlockIndex ( ) <nl> bool InitBlockIndex ( ) { <nl> const CChainParams & chainparams = Params ( ) ; <nl> LOCK ( cs_main ) ; <nl> + <nl> + / / Initialize global variables that cannot be constructed at startup . <nl> + recentRejects . reset ( new CRollingBloomFilter ( 120000 , 0 . 000001 ) ) ; <nl> + <nl> / / Check whether we ' re already initialized <nl> if ( chainActive . Genesis ( ) ! = NULL ) <nl> return true ; <nl> bool static AlreadyHave ( const CInv & inv ) EXCLUSIVE_LOCKS_REQUIRED ( cs_main ) <nl> { <nl> case MSG_TX : <nl> { <nl> - bool txInMap = false ; <nl> - txInMap = mempool . exists ( inv . hash ) ; <nl> - return txInMap | | mapOrphanTransactions . count ( inv . hash ) | | <nl> - pcoinsTip - > HaveCoins ( inv . hash ) ; <nl> + assert ( recentRejects ) ; <nl> + if ( chainActive . Tip ( ) - > GetBlockHash ( ) ! = hashRecentRejectsChainTip ) <nl> + { <nl> + / / If the chain tip has changed previously rejected transactions <nl> + / / might be now valid , e . g . due to a nLockTime ' d tx becoming valid , <nl> + / / or a double - spend . Reset the rejects filter and give those <nl> + / / txs a second chance . <nl> + hashRecentRejectsChainTip = chainActive . Tip ( ) - > GetBlockHash ( ) ; <nl> + recentRejects - > reset ( ) ; <nl> + } <nl> + <nl> + return recentRejects - > contains ( inv . hash ) | | <nl> + mempool . exists ( inv . hash ) | | <nl> + mapOrphanTransactions . count ( inv . hash ) | | <nl> + pcoinsTip - > HaveCoins ( inv . hash ) ; <nl> } <nl> case MSG_BLOCK : <nl> return mapBlockIndex . count ( inv . hash ) ; <nl> bool static ProcessMessage ( CNode * pfrom , string strCommand , CDataStream & vRecv , <nl> / / Probably non - standard or insufficient fee / priority <nl> LogPrint ( " mempool " , " removed orphan tx % s \ n " , orphanHash . ToString ( ) ) ; <nl> vEraseQueue . push_back ( orphanHash ) ; <nl> + assert ( recentRejects ) ; <nl> + recentRejects - > insert ( orphanHash ) ; <nl> } <nl> mempool . check ( pcoinsTip ) ; <nl> } <nl> bool static ProcessMessage ( CNode * pfrom , string strCommand , CDataStream & vRecv , <nl> unsigned int nEvicted = LimitOrphanTxSize ( nMaxOrphanTx ) ; <nl> if ( nEvicted > 0 ) <nl> LogPrint ( " mempool " , " mapOrphan overflow , removed % u tx \ n " , nEvicted ) ; <nl> - } else if ( pfrom - > fWhitelisted ) { <nl> - / / Always relay transactions received from whitelisted peers , even <nl> - / / if they are already in the mempool ( allowing the node to function <nl> - / / as a gateway for nodes hidden behind it ) . <nl> - RelayTransaction ( tx ) ; <nl> + } else { <nl> + / / AcceptToMemoryPool ( ) returned false , possibly because the tx is <nl> + / / already in the mempool ; if the tx isn ' t in the mempool that <nl> + / / means it was rejected and we shouldn ' t ask for it again . <nl> + if ( ! mempool . exists ( tx . GetHash ( ) ) ) { <nl> + assert ( recentRejects ) ; <nl> + recentRejects - > insert ( tx . GetHash ( ) ) ; <nl> + } <nl> + if ( pfrom - > fWhitelisted ) { <nl> + / / Always relay transactions received from whitelisted peers , even <nl> + / / if they were rejected from the mempool , allowing the node to <nl> + / / function as a gateway for nodes hidden behind it . <nl> + / / <nl> + / / FIXME : This includes invalid transactions , which means a <nl> + / / whitelisted peer could get us banned ! We may want to change <nl> + / / that . <nl> + RelayTransaction ( tx ) ; <nl> + } <nl> } <nl> int nDoS = 0 ; <nl> if ( state . IsInvalid ( nDoS ) ) <nl> bool SendMessages ( CNode * pto , bool fSendTrickle ) <nl> { <nl> / / Periodically clear addrKnown to allow refresh broadcasts <nl> if ( nLastRebroadcast ) <nl> - pnode - > addrKnown . clear ( ) ; <nl> + pnode - > addrKnown . reset ( ) ; <nl> <nl> / / Rebroadcast our address <nl> AdvertizeLocal ( pnode ) ; <nl> mmm a / src / net . cpp <nl> ppp b / src / net . cpp <nl> unsigned int SendBufferSize ( ) { return 1000 * GetArg ( " - maxsendbuffer " , 1 * 1000 ) ; } <nl> <nl> CNode : : CNode ( SOCKET hSocketIn , const CAddress & addrIn , const std : : string & addrNameIn , bool fInboundIn ) : <nl> ssSend ( SER_NETWORK , INIT_PROTO_VERSION ) , <nl> - addrKnown ( 5000 , 0 . 001 , insecure_rand ( ) ) , <nl> + addrKnown ( 5000 , 0 . 001 ) , <nl> setInventoryKnown ( SendBufferSize ( ) / 1000 ) <nl> { <nl> nServices = 0 ; <nl> mmm a / src / test / bloom_tests . cpp <nl> ppp b / src / test / bloom_tests . cpp <nl> static std : : vector < unsigned char > RandomData ( ) <nl> BOOST_AUTO_TEST_CASE ( rolling_bloom ) <nl> { <nl> / / last - 100 - entry , 1 % false positive : <nl> - CRollingBloomFilter rb1 ( 100 , 0 . 01 , 0 ) ; <nl> + CRollingBloomFilter rb1 ( 100 , 0 . 01 ) ; <nl> <nl> / / Overfill : <nl> static const int DATASIZE = 399 ; <nl> BOOST_AUTO_TEST_CASE ( rolling_bloom ) <nl> BOOST_CHECK ( nHits < 175 ) ; <nl> <nl> BOOST_CHECK ( rb1 . contains ( data [ DATASIZE - 1 ] ) ) ; <nl> - rb1 . clear ( ) ; <nl> + rb1 . reset ( ) ; <nl> BOOST_CHECK ( ! rb1 . contains ( data [ DATASIZE - 1 ] ) ) ; <nl> <nl> / / Now roll through data , make sure last 100 entries <nl> BOOST_AUTO_TEST_CASE ( rolling_bloom ) <nl> BOOST_CHECK ( nHits < 100 ) ; <nl> <nl> / / last - 1000 - entry , 0 . 01 % false positive : <nl> - CRollingBloomFilter rb2 ( 1000 , 0 . 001 , 0 ) ; <nl> + CRollingBloomFilter rb2 ( 1000 , 0 . 001 ) ; <nl> for ( int i = 0 ; i < DATASIZE ; i + + ) { <nl> rb2 . insert ( data [ i ] ) ; <nl> } <nl> | Merge pull request | bitcoin/bitcoin | 219b916545f3be194eb53801bfb8d0694978fb00 | 2015-08-03T18:13:43Z |
mmm a / include / fmt / format . h <nl> ppp b / include / fmt / format . h <nl> <nl> # endif <nl> # endif <nl> <nl> + # if FMT_HAS_GXX_CXX11 | | FMT_MSC_VER > = 1600 <nl> + # define FMT_USE_TRAILING_RETURN 1 <nl> + # endif <nl> + <nl> / / __builtin_clz is broken in clang with Microsoft CodeGen : <nl> / / https : / / github . com / fmtlib / fmt / issues / 519 <nl> # ifndef _MSC_VER <nl> arg_join < It , wchar_t > join ( It begin , It end , wstring_view sep ) { <nl> return arg_join < It , wchar_t > ( begin , end , sep ) ; <nl> } <nl> <nl> - # if FMT_HAS_GXX_CXX11 <nl> + # if FMT_USE_TRAILING_RETURN <nl> template < typename Range > <nl> auto join ( const Range & range , string_view sep ) <nl> - > arg_join < decltype ( std : : begin ( range ) ) , char > { <nl> | Enable join on msvc | fmtlib/fmt | a7ae5666a02b1b9cee5e44a07758dcaa244b5b62 | 2018-02-19T21:03:51Z |
mmm a / test / cctest / test - heap . cc <nl> ppp b / test / cctest / test - heap . cc <nl> TEST ( TestSizeOfRegExpCode ) { <nl> <nl> int size_of_regexp_code = size_with_regexp - initial_size ; <nl> <nl> - CHECK_LE ( size_of_regexp_code , 500 * KB ) ; <nl> + CHECK_LE ( size_of_regexp_code , 1 * MB ) ; <nl> <nl> / / Small regexp is half the size , but compiles to more than twice the code <nl> / / due to the optimization steps . <nl> | Bump the limit for test - heap / TestSizeOfRegExpCode | v8/v8 | d5e6462d8629e54b37decb4a6d29f3c7b1373ae6 | 2014-12-16T14:29:06Z |
mmm a / CMake / HHVMExtensionConfig . cmake <nl> ppp b / CMake / HHVMExtensionConfig . cmake <nl> function ( HHVM_EXTENSION_INTERNAL_HANDLE_LIBRARY_DEPENDENCY extensionID dependen <nl> link_libraries ( $ { BZIP2_LIBRARIES } ) <nl> add_definitions ( " - DHAVE_LIBBZIP2 " ) <nl> endif ( ) <nl> + elseif ( $ { libraryName } STREQUAL " cclient " ) <nl> + find_package ( CClient $ { requiredVersion } ) <nl> + if ( NOT CCLIENT_INCLUDE_PATH OR NOT CCLIENT_LIBRARY ) <nl> + HHVM_EXTENSION_INTERNAL_SET_FAILED_DEPENDENCY ( $ { extensionID } $ { dependencyName } ) <nl> + return ( ) <nl> + endif ( ) <nl> + <nl> + CONTAINS_STRING ( " $ { CCLIENT_INCLUDE_PATH } / utf8 . h " U8T_DECOMPOSE RECENT_CCLIENT ) <nl> + if ( NOT RECENT_CCLIENT ) <nl> + unset ( RECENT_CCLIENT CACHE ) <nl> + if ( $ { addPaths } ) <nl> + message ( FATAL_ERROR " Your version of c - client is too old , you need 2007 " ) <nl> + else ( ) <nl> + message ( STATUS " Your version of c - client is too old , you need 2007 " ) <nl> + HHVM_EXTENSION_INTERNAL_SET_FAILED_DEPENDENCY ( $ { extensionID } $ { dependencyName } ) <nl> + return ( ) <nl> + endif ( ) <nl> + endif ( ) <nl> + <nl> + if ( $ { addPaths } ) <nl> + include_directories ( $ { CCLIENT_INCLUDE_PATH } ) <nl> + link_libraries ( $ { CCLIENT_LIBRARY } ) <nl> + add_definitions ( " - DHAVE_LIBCCLIENT " ) <nl> + <nl> + if ( EXISTS " $ { CCLIENT_INCLUDE_PATH } / linkage . c " ) <nl> + CONTAINS_STRING ( " $ { CCLIENT_INCLUDE_PATH } / linkage . c " auth_gss CCLIENT_HAS_GSS ) <nl> + elseif ( EXISTS " $ { CCLIENT_INCLUDE_PATH } / linkage . h " ) <nl> + CONTAINS_STRING ( " $ { CCLIENT_INCLUDE_PATH } / linkage . h " auth_gss CCLIENT_HAS_GSS ) <nl> + endif ( ) <nl> + if ( NOT CCLIENT_HAS_GSS ) <nl> + add_definitions ( " - DSKIP_IMAP_GSS = 1 " ) <nl> + endif ( ) <nl> + <nl> + if ( EXISTS " $ { CCLIENT_INCLUDE_PATH } / linkage . c " ) <nl> + CONTAINS_STRING ( " $ { CCLIENT_INCLUDE_PATH } / linkage . c " ssl_onceonlyinit CCLIENT_HAS_SSL ) <nl> + elseif ( EXISTS " $ { CCLIENT_INCLUDE_PATH } / linkage . h " ) <nl> + CONTAINS_STRING ( " $ { CCLIENT_INCLUDE_PATH } / linkage . h " ssl_onceonlyinit CCLIENT_HAS_SSL ) <nl> + endif ( ) <nl> + if ( NOT CCLIENT_HAS_SSL ) <nl> + add_definitions ( " - DSKIP_IMAP_SSL = 1 " ) <nl> + endif ( ) <nl> + endif ( ) <nl> elseif ( $ { libraryName } STREQUAL " curl " ) <nl> find_package ( CURL $ { requiredVersion } ) <nl> if ( NOT CURL_INCLUDE_DIR OR NOT CURL_LIBRARIES ) <nl> function ( HHVM_EXTENSION_INTERNAL_HANDLE_LIBRARY_DEPENDENCY extensionID dependen <nl> add_definitions ( " - DXML_STATIC " ) <nl> endif ( ) <nl> endif ( ) <nl> + elseif ( $ { libraryName } STREQUAL " freetype " ) <nl> + find_package ( LibFreetype $ { requiredVersion } ) <nl> + if ( NOT FREETYPE_INCLUDE_DIRS OR NOT FREETYPE_LIBRARIES ) <nl> + HHVM_EXTENSION_INTERNAL_SET_FAILED_DEPENDENCY ( $ { extensionID } $ { dependencyName } ) <nl> + return ( ) <nl> + endif ( ) <nl> + <nl> + if ( $ { addPaths } ) <nl> + include_directories ( $ { FREETYPE_INCLUDE_DIRS } ) <nl> + link_libraries ( $ { FREETYPE_LIBRARIES } ) <nl> + add_definitions ( " - DHAVE_LIBFREETYPE " ) <nl> + add_definitions ( " - DHAVE_GD_FREETYPE " ) <nl> + add_definitions ( " - DENABLE_GD_TTF " ) <nl> + endif ( ) <nl> elseif ( $ { libraryName } STREQUAL " fribidi " ) <nl> find_package ( fribidi $ { requiredVersion } ) <nl> if ( NOT FRIBIDI_INCLUDE_DIR OR NOT FRIBIDI_LIBRARY ) <nl> function ( HHVM_EXTENSION_INTERNAL_HANDLE_LIBRARY_DEPENDENCY extensionID dependen <nl> link_libraries ( $ { GMP_LIBRARY } ) <nl> add_definitions ( " - DHAVE_LIBGMP " ) <nl> endif ( ) <nl> + elseif ( $ { libraryName } STREQUAL " iconv " ) <nl> + find_package ( Libiconv $ { requiredVersion } ) <nl> + if ( NOT LIBICONV_INCLUDE_DIR OR NOT LIBICONV_LIBRARY ) <nl> + HHVM_EXTENSION_INTERNAL_SET_FAILED_DEPENDENCY ( $ { extensionID } $ { dependencyName } ) <nl> + return ( ) <nl> + endif ( ) <nl> + <nl> + if ( $ { addPaths } ) <nl> + include_directories ( $ { LIBICONV_INCLUDE_DIR } ) <nl> + link_libraries ( $ { LIBICONV_LIBRARY } ) <nl> + add_definitions ( " - DHAVE_ICONV " ) <nl> + add_definitions ( " - DHAVE_LIBICONV " ) <nl> + if ( LIBICONV_CONST ) <nl> + message ( STATUS " Using const for input to iconv ( ) call " ) <nl> + add_definitions ( " - DICONV_CONST = const " ) <nl> + endif ( ) <nl> + endif ( ) <nl> elseif ( $ { libraryName } STREQUAL " icu " ) <nl> find_package ( ICU $ { requiredVersion } ) <nl> if ( NOT ICU_FOUND OR NOT ICU_DATA_LIBRARIES OR NOT ICU_I18N_LIBRARIES OR NOT ICU_LIBRARIES ) <nl> function ( HHVM_EXTENSION_INTERNAL_HANDLE_LIBRARY_DEPENDENCY extensionID dependen <nl> link_libraries ( $ { ICU_DATA_LIBRARIES } $ { ICU_I18N_LIBRARIES } $ { ICU_LIBRARIES } ) <nl> add_definitions ( " - DHAVE_LIBICU " ) <nl> endif ( ) <nl> + elseif ( $ { libraryName } STREQUAL " jpeg " ) <nl> + find_package ( LibJpeg $ { requiredVersion } ) <nl> + if ( NOT LIBJPEG_INCLUDE_DIRS OR NOT LIBJPEG_LIBRARIES ) <nl> + HHVM_EXTENSION_INTERNAL_SET_FAILED_DEPENDENCY ( $ { extensionID } $ { dependencyName } ) <nl> + return ( ) <nl> + endif ( ) <nl> + <nl> + if ( $ { addPaths } ) <nl> + include_directories ( $ { LIBJPEG_INCLUDE_DIRS } ) <nl> + link_libraries ( $ { LIBJPEG_LIBRARIES } ) <nl> + add_definitions ( " - DHAVE_LIBJPEG " ) <nl> + add_definitions ( " - DHAVE_GD_JPG " ) <nl> + endif ( ) <nl> elseif ( $ { libraryName } STREQUAL " jsonc " ) <nl> find_package ( Libjsonc $ { requiredVersion } ) <nl> if ( NOT LIBJSONC_INCLUDE_DIR OR NOT LIBJSONC_LIBRARY ) <nl> function ( HHVM_EXTENSION_INTERNAL_HANDLE_LIBRARY_DEPENDENCY extensionID dependen <nl> if ( $ { addPaths } ) <nl> link_libraries ( $ { MYSQL_CLIENT_LIBS } ) <nl> endif ( ) <nl> + elseif ( $ { libraryName } STREQUAL " png " ) <nl> + find_package ( LibPng $ { requiredVersion } ) <nl> + if ( NOT LIBPNG_INCLUDE_DIRS OR NOT LIBPNG_LIBRARIES ) <nl> + HHVM_EXTENSION_INTERNAL_SET_FAILED_DEPENDENCY ( $ { extensionID } $ { dependencyName } ) <nl> + return ( ) <nl> + endif ( ) <nl> + <nl> + if ( $ { addPaths } ) <nl> + include_directories ( $ { LIBPNG_INCLUDE_DIRS } ) <nl> + link_libraries ( $ { LIBPNG_LIBRARIES } ) <nl> + add_definitions ( " - DHAVE_LIBPNG " ) <nl> + add_definitions ( " - DHAVE_GD_PNG " ) <nl> + add_definitions ( " - DPNG_SKIP_SETJMP_CHECK " ) <nl> + endif ( ) <nl> + elseif ( $ { libraryName } STREQUAL " vpx " ) <nl> + find_package ( LibVpx $ { requiredVersion } ) <nl> + if ( NOT LIBVPX_INCLUDE_DIRS OR NOT LIBVPX_LIBRARIES ) <nl> + HHVM_EXTENSION_INTERNAL_SET_FAILED_DEPENDENCY ( $ { extensionID } $ { dependencyName } ) <nl> + return ( ) <nl> + endif ( ) <nl> + <nl> + if ( $ { addPaths } ) <nl> + include_directories ( $ { LIBVPX_INCLUDE_DIRS } ) <nl> + link_libraries ( $ { LIBVPX_LIBRARIES } ) <nl> + add_definitions ( " - DHAVE_LIBVPX " ) <nl> + endif ( ) <nl> elseif ( $ { libraryName } STREQUAL " xml2 " ) <nl> find_package ( LibXml2 $ { requiredVersion } ) <nl> if ( NOT LIBXML2_INCLUDE_DIR OR NOT LIBXML2_LIBRARIES ) <nl> mmm a / hphp / runtime / ext / gd / config . cmake <nl> ppp b / hphp / runtime / ext / gd / config . cmake <nl> <nl> - if ( ( NOT DEFINED EXT_GD ) OR ( EXT_GD STREQUAL " ON " ) ) <nl> - HHVM_EXTENSION ( gd <nl> + HHVM_DEFINE_EXTENSION ( " gd " <nl> + IS_ENABLED EXT_GD <nl> + SOURCES <nl> ext_gd . cpp <nl> libgd / gd_arc . cpp <nl> libgd / gd_arc_f_buggy . cpp <nl> if ( ( NOT DEFINED EXT_GD ) OR ( EXT_GD STREQUAL " ON " ) ) <nl> libgd / gd_webp . cpp <nl> libgd / wbmp . cpp <nl> libgd / webpimg . cpp <nl> - libgd / xbm . cpp ) <nl> - HHVM_SYSTEMLIB ( gd ext_gd . php ext_exif . php ) <nl> - <nl> - # GD checks <nl> - HHVM_DEFINE ( gd - DPNG_SKIP_SETJMP_CHECK ) <nl> - find_package ( LibJpeg REQUIRED ) <nl> - if ( LIBJPEG_INCLUDE_DIRS AND LIBJPEG_LIBRARIES ) <nl> - HHVM_LINK_LIBRARIES ( gd $ { LIBJPEG_LIBRARIES } ) <nl> - HHVM_ADD_INCLUDES ( gd $ { LIBJPEG_INCLUDE_DIRS } ) <nl> - HHVM_DEFINE ( gd " - DHAVE_GD_JPG " ) <nl> - endif ( ) <nl> - find_package ( LibPng REQUIRED ) <nl> - if ( LIBPNG_INCLUDE_DIRS AND LIBPNG_LIBRARIES ) <nl> - HHVM_LINK_LIBRARIES ( gd $ { LIBPNG_LIBRARIES } ) <nl> - HHVM_ADD_INCLUDES ( gd $ { LIBPNG_INCLUDE_DIRS } ) <nl> - HHVM_DEFINE ( gd " - DHAVE_GD_PNG " ) <nl> - endif ( ) <nl> - find_package ( LibVpx ) <nl> - if ( LIBVPX_INCLUDE_DIRS AND LIBVPX_LIBRARIES ) <nl> - HHVM_LINK_LIBRARIES ( gd $ { LIBVPX_LIBRARIES } ) <nl> - HHVM_ADD_INCLUDES ( gd $ { LIBVPX_INCLUDE_DIRS } ) <nl> - HHVM_DEFINE ( gd " - DHAVE_LIBVPX " ) <nl> - endif ( ) <nl> - find_package ( Freetype ) <nl> - if ( FREETYPE_INCLUDE_DIRS AND FREETYPE_LIBRARIES ) <nl> - HHVM_LINK_LIBRARIES ( gd $ { FREETYPE_LIBRARIES } ) <nl> - HHVM_ADD_INCLUDES ( gd $ { FREETYPE_INCLUDE_DIRS } ) <nl> - HHVM_DEFINE ( gd " - DHAVE_LIBFREETYPE - DHAVE_GD_FREETYPE - DENABLE_GD_TTF " ) <nl> - endif ( ) <nl> - <nl> - endif ( ) <nl> + libgd / xbm . cpp <nl> + HEADERS <nl> + ext_gd . h <nl> + libgd / gd . h <nl> + libgd / gd_intern . h <nl> + libgd / gd_io . h <nl> + libgd / gdcache . h <nl> + libgd / gdfontg . h <nl> + libgd / gdfontl . h <nl> + libgd / gdfontmb . h <nl> + libgd / gdfonts . h <nl> + libgd / gdfontt . h <nl> + libgd / jisx0208 . h <nl> + libgd / php . h <nl> + libgd / php_compat . h <nl> + libgd / wbmp . h <nl> + libgd / webpimg . h <nl> + SYSTEMLIB <nl> + ext_exif . php <nl> + ext_gd . php <nl> + DEPENDS <nl> + libFreetype OPTIONAL <nl> + libJpeg OPTIONAL <nl> + libIConv <nl> + libPng OPTIONAL <nl> + libVpx OPTIONAL <nl> + ) <nl> mmm a / hphp / runtime / ext / imap / config . cmake <nl> ppp b / hphp / runtime / ext / imap / config . cmake <nl> <nl> - HHVM_EXT_OPTION ( IMAP CClient ) <nl> - <nl> - if ( CCLIENT_INCLUDE_PATH AND CCLIENT_LIBRARY ) <nl> - CONTAINS_STRING ( " $ { CCLIENT_INCLUDE_PATH } / utf8 . h " U8T_DECOMPOSE RECENT_CCLIENT ) <nl> - if ( NOT RECENT_CCLIENT ) <nl> - unset ( RECENT_CCLIENT CACHE ) <nl> - if ( EXT_IMAP STREQUAL " ON " ) <nl> - message ( FATAL_ERROR " Your version of c - client is too old , you need 2007 " ) <nl> - endif ( ) <nl> - else ( ) <nl> - HHVM_EXTENSION ( imap ext_imap . cpp ) <nl> - HHVM_SYSTEMLIB ( imap ext_imap . php ) <nl> - HHVM_ADD_INCLUDES ( imap $ { CCLIENT_INCLUDE_PATH } ) <nl> - HHVM_LINK_LIBRARIES ( imap $ { CCLIENT_LIBRARY } ) <nl> - <nl> - if ( EXISTS " $ { CCLIENT_INCLUDE_PATH } / linkage . c " ) <nl> - CONTAINS_STRING ( " $ { CCLIENT_INCLUDE_PATH } / linkage . c " auth_gss CCLIENT_HAS_GSS ) <nl> - elseif ( EXISTS " $ { CCLIENT_INCLUDE_PATH } / linkage . h " ) <nl> - CONTAINS_STRING ( " $ { CCLIENT_INCLUDE_PATH } / linkage . h " auth_gss CCLIENT_HAS_GSS ) <nl> - endif ( ) <nl> - <nl> - if ( NOT CCLIENT_HAS_GSS ) <nl> - HHVM_DEFINE ( IMAP - DSKIP_IMAP_GSS = 1 ) <nl> - endif ( ) <nl> - <nl> - if ( EXISTS " $ { CCLIENT_INCLUDE_PATH } / linkage . c " ) <nl> - CONTAINS_STRING ( " $ { CCLIENT_INCLUDE_PATH } / linkage . c " ssl_onceonlyinit CCLIENT_HAS_SSL ) <nl> - elseif ( EXISTS " $ { CCLIENT_INCLUDE_PATH } / linkage . h " ) <nl> - CONTAINS_STRING ( " $ { CCLIENT_INCLUDE_PATH } / linkage . h " ssl_onceonlyinit CCLIENT_HAS_SSL ) <nl> - endif ( ) <nl> - <nl> - if ( NOT CCLIENT_HAS_SSL ) <nl> - HHVM_DEFINE ( IMAP - DSKIP_IMAP_SSL = 1 ) <nl> - endif ( ) <nl> - endif ( ) <nl> - endif ( ) <nl> \ No newline at end of file <nl> + HHVM_DEFINE_EXTENSION ( " imap " IMPLICIT <nl> + IS_ENABLED EXT_IMAP <nl> + SOURCES <nl> + ext_imap . cpp <nl> + SYSTEMLIB <nl> + ext_imap . php <nl> + DEPENDS <nl> + libCClient <nl> + ) <nl> | Convert ext_gd and ext_imap to use the new extension config mechanism | facebook/hhvm | 7d1a9ccfb25c3bd3eb6112451c1b22ac5346bc26 | 2015-08-27T19:32:35Z |
mmm a / BUILD . gn <nl> ppp b / BUILD . gn <nl> action ( " js2c " ) { <nl> " src / js / prologue . js " , <nl> " src / js / array . js " , <nl> " src / js / typedarray . js " , <nl> - " src / debug / liveedit . js " , <nl> ] <nl> <nl> outputs = [ <nl> v8_source_set ( " v8_base " ) { <nl> " src / runtime / runtime - interpreter . cc " , <nl> " src / runtime / runtime - intl . cc " , <nl> " src / runtime / runtime - literals . cc " , <nl> - " src / runtime / runtime - liveedit . cc " , <nl> " src / runtime / runtime - maths . cc " , <nl> " src / runtime / runtime - module . cc " , <nl> " src / runtime / runtime - numbers . cc " , <nl> mmm a / src / compiler . cc <nl> ppp b / src / compiler . cc <nl> bool Compiler : : CompileOptimized ( Handle < JSFunction > function , <nl> return true ; <nl> } <nl> <nl> - MaybeHandle < JSArray > Compiler : : CompileForLiveEdit ( Handle < Script > script ) { <nl> - Isolate * isolate = script - > GetIsolate ( ) ; <nl> - DCHECK ( AllowCompilation : : IsAllowed ( isolate ) ) ; <nl> - <nl> - / / In order to ensure that live edit function info collection finds the newly <nl> - / / generated shared function infos , clear the script ' s list temporarily <nl> - / / and restore it at the end of this method . <nl> - Handle < WeakFixedArray > old_function_infos ( script - > shared_function_infos ( ) , <nl> - isolate ) ; <nl> - script - > set_shared_function_infos ( isolate - > heap ( ) - > empty_weak_fixed_array ( ) ) ; <nl> - <nl> - / / Start a compilation . <nl> - ParseInfo parse_info ( isolate , script ) ; <nl> - parse_info . set_eager ( ) ; <nl> - <nl> - / / TODO ( 635 ) : support extensions . <nl> - Handle < JSArray > infos ; <nl> - Handle < SharedFunctionInfo > shared_info ; <nl> - if ( CompileToplevel ( & parse_info , isolate ) . ToHandle ( & shared_info ) ) { <nl> - / / Check postconditions on success . <nl> - DCHECK ( ! isolate - > has_pending_exception ( ) ) ; <nl> - infos = LiveEditFunctionTracker : : Collect ( parse_info . literal ( ) , script , <nl> - parse_info . zone ( ) , isolate ) ; <nl> - } <nl> - <nl> - / / Restore the original function info list in order to remain side - effect <nl> - / / free as much as possible , since some code expects the old shared function <nl> - / / infos to stick around . <nl> - script - > set_shared_function_infos ( * old_function_infos ) ; <nl> - <nl> - return infos ; <nl> + MaybeHandle < SharedFunctionInfo > Compiler : : CompileForLiveEdit ( <nl> + ParseInfo * parse_info , Isolate * isolate ) { <nl> + return CompileToplevel ( parse_info , isolate ) ; <nl> } <nl> <nl> MaybeHandle < JSFunction > Compiler : : GetFunctionFromEval ( <nl> mmm a / src / compiler . h <nl> ppp b / src / compiler . h <nl> class V8_EXPORT_PRIVATE Compiler : public AllStatic { <nl> ClearExceptionFlag flag ) ; <nl> static bool Compile ( Handle < JSFunction > function , ClearExceptionFlag flag ) ; <nl> static bool CompileOptimized ( Handle < JSFunction > function , ConcurrencyMode ) ; <nl> - static MaybeHandle < JSArray > CompileForLiveEdit ( Handle < Script > script ) ; <nl> + <nl> + V8_WARN_UNUSED_RESULT static MaybeHandle < SharedFunctionInfo > <nl> + CompileForLiveEdit ( ParseInfo * parse_info , Isolate * isolate ) ; <nl> <nl> / / Creates a new task that when run will parse and compile the streamed <nl> / / script associated with | streaming_data | and can be finalized with <nl> mmm a / src / debug / debug - interface . h <nl> ppp b / src / debug / debug - interface . h <nl> void BreakRightNow ( Isolate * isolate ) ; <nl> <nl> bool AllFramesOnStackAreBlackboxed ( Isolate * isolate ) ; <nl> <nl> + class Script ; <nl> + <nl> struct LiveEditResult { <nl> enum Status { <nl> OK , <nl> struct LiveEditResult { <nl> } ; <nl> Status status = OK ; <nl> bool stack_changed = false ; <nl> + / / Available only for OK . <nl> + v8 : : Local < v8 : : debug : : Script > script ; <nl> / / Fields below are available only for COMPILE_ERROR . <nl> v8 : : Local < v8 : : String > message ; <nl> int line_number = - 1 ; <nl> mmm a / src / debug / debug . cc <nl> ppp b / src / debug / debug . cc <nl> bool Debug : : CanBreakAtEntry ( Handle < SharedFunctionInfo > shared ) { <nl> } <nl> <nl> bool Debug : : SetScriptSource ( Handle < Script > script , Handle < String > source , <nl> - bool preview , debug : : LiveEditResult * output ) { <nl> - SaveContext save ( isolate_ ) ; <nl> - StackFrame : : Id frame_id = break_frame_id ( ) ; <nl> + bool preview , debug : : LiveEditResult * result ) { <nl> DebugScope debug_scope ( this ) ; <nl> - if ( debug_scope . failed ( ) ) return false ; <nl> - isolate_ - > set_context ( * debug_context ( ) ) ; <nl> - <nl> - if ( frame_id ! = StackFrame : : NO_ID ) { <nl> - thread_local_ . break_frame_id_ = frame_id ; <nl> - } <nl> - <nl> - Handle < Object > script_wrapper = Script : : GetWrapper ( script ) ; <nl> - Handle < Object > argv [ ] = { script_wrapper , source , <nl> - isolate_ - > factory ( ) - > ToBoolean ( preview ) , <nl> - isolate_ - > factory ( ) - > NewJSArray ( 0 ) } ; <nl> - Handle < Object > result ; <nl> - MaybeHandle < Object > maybe_exception ; <nl> running_live_edit_ = true ; <nl> - if ( ! CallFunction ( " SetScriptSource " , arraysize ( argv ) , argv , & maybe_exception ) <nl> - . ToHandle ( & result ) ) { <nl> - Handle < Object > pending_exception = maybe_exception . ToHandleChecked ( ) ; <nl> - if ( pending_exception - > IsJSObject ( ) ) { <nl> - Handle < JSObject > exception = Handle < JSObject > : : cast ( pending_exception ) ; <nl> - Handle < String > message = Handle < String > : : cast ( <nl> - JSReceiver : : GetProperty ( isolate_ , exception , " message " ) <nl> - . ToHandleChecked ( ) ) ; <nl> - Handle < String > blocked_message = <nl> - isolate_ - > factory ( ) - > NewStringFromAsciiChecked ( <nl> - " Blocked by functions on stack " ) ; <nl> - if ( blocked_message - > Equals ( * message ) ) { <nl> - output - > status = debug : : LiveEditResult : : <nl> - BLOCKED_BY_FUNCTION_BELOW_NON_DROPPABLE_FRAME ; <nl> - } else { <nl> - Handle < JSObject > details = Handle < JSObject > : : cast ( <nl> - JSReceiver : : GetProperty ( isolate_ , exception , " details " ) <nl> - . ToHandleChecked ( ) ) ; <nl> - Handle < String > error = Handle < String > : : cast ( <nl> - JSReceiver : : GetProperty ( isolate_ , details , " syntaxErrorMessage " ) <nl> - . ToHandleChecked ( ) ) ; <nl> - output - > status = debug : : LiveEditResult : : COMPILE_ERROR ; <nl> - output - > line_number = kNoSourcePosition ; <nl> - output - > column_number = kNoSourcePosition ; <nl> - output - > message = Utils : : ToLocal ( error ) ; <nl> - } <nl> - } <nl> - running_live_edit_ = false ; <nl> - return false ; <nl> - } <nl> - Handle < Object > stack_changed_value = <nl> - JSReceiver : : GetProperty ( isolate_ , Handle < JSObject > : : cast ( result ) , <nl> - " stack_modified " ) <nl> - . ToHandleChecked ( ) ; <nl> - output - > stack_changed = stack_changed_value - > IsTrue ( isolate_ ) ; <nl> - output - > status = debug : : LiveEditResult : : OK ; <nl> + LiveEdit : : PatchScript ( isolate_ , script , source , preview , result ) ; <nl> running_live_edit_ = false ; <nl> - return true ; <nl> + return result - > status = = debug : : LiveEditResult : : OK ; <nl> } <nl> <nl> void Debug : : OnCompileError ( Handle < Script > script ) { <nl> void Debug : : OnAfterCompile ( Handle < Script > script ) { <nl> } <nl> <nl> void Debug : : ProcessCompileEvent ( bool has_compile_error , Handle < Script > script ) { <nl> + / / TODO ( kozyatinskiy ) : teach devtools to work with liveedit scripts better <nl> + / / first and then remove this fast return . <nl> + if ( running_live_edit_ ) return ; <nl> / / Attach the correct debug id to the script . The debug id is used by the <nl> / / inspector to filter scripts by native context . <nl> script - > set_context_data ( isolate_ - > native_context ( ) - > debug_context_id ( ) ) ; <nl> void Debug : : ProcessCompileEvent ( bool has_compile_error , Handle < Script > script ) { <nl> running_live_edit_ , has_compile_error ) ; <nl> } <nl> <nl> - <nl> Handle < Context > Debug : : GetDebugContext ( ) { <nl> if ( ! is_loaded ( ) ) return Handle < Context > ( ) ; <nl> DebugScope debug_scope ( this ) ; <nl> mmm a / src / debug / debug . h <nl> ppp b / src / debug / debug . h <nl> class Debug { <nl> / / source position for break points . <nl> static const int kBreakAtEntryPosition = 0 ; <nl> <nl> + void RemoveBreakInfoAndMaybeFree ( Handle < DebugInfo > debug_info ) ; <nl> + <nl> private : <nl> explicit Debug ( Isolate * isolate ) ; <nl> ~ Debug ( ) ; <nl> class Debug { <nl> typedef std : : function < void ( Handle < DebugInfo > ) > DebugInfoClearFunction ; <nl> void ClearAllDebugInfos ( DebugInfoClearFunction clear_function ) ; <nl> <nl> - void RemoveBreakInfoAndMaybeFree ( Handle < DebugInfo > debug_info ) ; <nl> void FindDebugInfo ( Handle < DebugInfo > debug_info , DebugInfoListNode * * prev , <nl> DebugInfoListNode * * curr ) ; <nl> void FreeDebugInfoListNode ( DebugInfoListNode * prev , DebugInfoListNode * node ) ; <nl> mmm a / src / debug / liveedit . cc <nl> ppp b / src / debug / liveedit . cc <nl> <nl> <nl> # include " src / debug / liveedit . h " <nl> <nl> - # include " src / assembler - inl . h " <nl> + # include " src / api . h " <nl> + # include " src / ast / ast - traversal - visitor . h " <nl> + # include " src / ast / ast . h " <nl> # include " src / ast / scopes . h " <nl> - # include " src / code - stubs . h " <nl> # include " src / compilation - cache . h " <nl> # include " src / compiler . h " <nl> + # include " src / debug / debug - interface . h " <nl> # include " src / debug / debug . h " <nl> - # include " src / deoptimizer . h " <nl> # include " src / frames - inl . h " <nl> - # include " src / global - handles . h " <nl> # include " src / isolate - inl . h " <nl> # include " src / messages . h " <nl> # include " src / objects - inl . h " <nl> + # include " src / objects / hash - table - inl . h " <nl> + # include " src / parsing / parse - info . h " <nl> + # include " src / parsing / parsing . h " <nl> # include " src / source - position - table . h " <nl> # include " src / v8 . h " <nl> - # include " src / v8memory . h " <nl> <nl> namespace v8 { <nl> namespace internal { <nl> class Comparator { <nl> static void CalculateDifference ( Input * input , Output * result_writer ) ; <nl> } ; <nl> <nl> - void SetElementSloppy ( Handle < JSObject > object , <nl> - uint32_t index , <nl> - Handle < Object > value ) { <nl> - / / Ignore return value from SetElement . It can only be a failure if there <nl> - / / are element setters causing exceptions and the debugger context has none <nl> - / / of these . <nl> - Object : : SetElement ( object - > GetIsolate ( ) , object , index , value , <nl> - LanguageMode : : kSloppy ) <nl> - . Assert ( ) ; <nl> - } <nl> - <nl> / / A simple implementation of dynamic programming algorithm . It solves <nl> / / the problem of finding the difference of 2 arrays . It uses a table of results <nl> / / of subproblems . Each cell contains a number together with 2 - bit flag <nl> void NarrowDownInput ( SubrangableInput * input , SubrangableOutput * output ) { <nl> } <nl> } <nl> <nl> - <nl> - / / A helper class that writes chunk numbers into JSArray . <nl> - / / Each chunk is stored as 3 array elements : ( pos1_begin , pos1_end , pos2_end ) . <nl> - class CompareOutputArrayWriter { <nl> - public : <nl> - explicit CompareOutputArrayWriter ( Isolate * isolate ) <nl> - : array_ ( isolate - > factory ( ) - > NewJSArray ( 10 ) ) , current_size_ ( 0 ) { } <nl> - <nl> - Handle < JSArray > GetResult ( ) { <nl> - return array_ ; <nl> - } <nl> - <nl> - void WriteChunk ( int char_pos1 , int char_pos2 , int char_len1 , int char_len2 ) { <nl> - Isolate * isolate = array_ - > GetIsolate ( ) ; <nl> - SetElementSloppy ( array_ , <nl> - current_size_ , <nl> - Handle < Object > ( Smi : : FromInt ( char_pos1 ) , isolate ) ) ; <nl> - SetElementSloppy ( array_ , <nl> - current_size_ + 1 , <nl> - Handle < Object > ( Smi : : FromInt ( char_pos1 + char_len1 ) , <nl> - isolate ) ) ; <nl> - SetElementSloppy ( array_ , <nl> - current_size_ + 2 , <nl> - Handle < Object > ( Smi : : FromInt ( char_pos2 + char_len2 ) , <nl> - isolate ) ) ; <nl> - current_size_ + = 3 ; <nl> - } <nl> - <nl> - private : <nl> - Handle < JSArray > array_ ; <nl> - int current_size_ ; <nl> - } ; <nl> - <nl> - <nl> / / Represents 2 strings as 2 arrays of tokens . <nl> / / TODO ( LiveEdit ) : Currently it ' s actually an array of charactres . <nl> / / Make array of tokens instead . <nl> class TokenizingLineArrayCompareOutput : public SubrangableOutput { <nl> int subrange_offset2_ ; <nl> std : : vector < SourceChangeRange > * output_ ; <nl> } ; <nl> - } / / anonymous namespace <nl> - <nl> - Handle < JSArray > LiveEdit : : CompareStrings ( Isolate * isolate , Handle < String > s1 , <nl> - Handle < String > s2 ) { <nl> - std : : vector < SourceChangeRange > changes ; <nl> - CompareStrings ( isolate , s1 , s2 , & changes ) ; <nl> - CompareOutputArrayWriter writer ( isolate ) ; <nl> - for ( const auto & change : changes ) { <nl> - writer . WriteChunk ( change . start_position , change . new_start_position , <nl> - change . end_position - change . start_position , <nl> - change . new_end_position - change . new_start_position ) ; <nl> - } <nl> - return writer . GetResult ( ) ; <nl> - } <nl> - <nl> - / / Unwraps JSValue object , returning its field " value " <nl> - static Handle < Object > UnwrapJSValue ( Handle < JSValue > jsValue ) { <nl> - return Handle < Object > ( jsValue - > value ( ) , jsValue - > GetIsolate ( ) ) ; <nl> - } <nl> - <nl> - / / Wraps any object into a OpaqueReference , that will hide the object <nl> - / / from JavaScript . <nl> - static Handle < JSValue > WrapInJSValue ( Isolate * isolate , <nl> - Handle < HeapObject > object ) { <nl> - Handle < JSFunction > constructor = isolate - > opaque_reference_function ( ) ; <nl> - Handle < JSValue > result = <nl> - Handle < JSValue > : : cast ( isolate - > factory ( ) - > NewJSObject ( constructor ) ) ; <nl> - result - > set_value ( * object ) ; <nl> - return result ; <nl> - } <nl> - <nl> - <nl> - static Handle < SharedFunctionInfo > UnwrapSharedFunctionInfoFromJSValue ( <nl> - Handle < JSValue > jsValue ) { <nl> - Object * shared = jsValue - > value ( ) ; <nl> - CHECK ( shared - > IsSharedFunctionInfo ( ) ) ; <nl> - return Handle < SharedFunctionInfo > ( SharedFunctionInfo : : cast ( shared ) , <nl> - jsValue - > GetIsolate ( ) ) ; <nl> - } <nl> <nl> + struct SourcePositionEvent { <nl> + enum Type { LITERAL_STARTS , LITERAL_ENDS , DIFF_STARTS , DIFF_ENDS } ; <nl> <nl> - static int GetArrayLength ( Handle < JSArray > array ) { <nl> - Object * length = array - > length ( ) ; <nl> - CHECK ( length - > IsSmi ( ) ) ; <nl> - return Smi : : ToInt ( length ) ; <nl> - } <nl> - <nl> - void FunctionInfoWrapper : : SetInitialProperties ( Handle < String > name , <nl> - int start_position , <nl> - int end_position , int param_num , <nl> - int parent_index , <nl> - int function_literal_id ) { <nl> - HandleScope scope ( isolate ( ) ) ; <nl> - this - > SetField ( kFunctionNameOffset_ , name ) ; <nl> - this - > SetSmiValueField ( kStartPositionOffset_ , start_position ) ; <nl> - this - > SetSmiValueField ( kEndPositionOffset_ , end_position ) ; <nl> - this - > SetSmiValueField ( kParamNumOffset_ , param_num ) ; <nl> - this - > SetSmiValueField ( kParentIndexOffset_ , parent_index ) ; <nl> - this - > SetSmiValueField ( kFunctionLiteralIdOffset_ , function_literal_id ) ; <nl> - } <nl> - <nl> - void FunctionInfoWrapper : : SetSharedFunctionInfo ( <nl> - Isolate * isolate , Handle < SharedFunctionInfo > info ) { <nl> - Handle < JSValue > info_holder = WrapInJSValue ( isolate , info ) ; <nl> - this - > SetField ( kSharedFunctionInfoOffset_ , info_holder ) ; <nl> - } <nl> - <nl> - Handle < SharedFunctionInfo > FunctionInfoWrapper : : GetSharedFunctionInfo ( ) { <nl> - Handle < Object > element = this - > GetField ( kSharedFunctionInfoOffset_ ) ; <nl> - Handle < JSValue > value_wrapper = Handle < JSValue > : : cast ( element ) ; <nl> - Handle < Object > raw_result = UnwrapJSValue ( value_wrapper ) ; <nl> - CHECK ( raw_result - > IsSharedFunctionInfo ( ) ) ; <nl> - return Handle < SharedFunctionInfo > : : cast ( raw_result ) ; <nl> - } <nl> + int position ; <nl> + Type type ; <nl> <nl> - void SharedInfoWrapper : : SetProperties ( Handle < String > name , <nl> - int start_position , <nl> - int end_position , <nl> - Handle < SharedFunctionInfo > info ) { <nl> - HandleScope scope ( isolate ( ) ) ; <nl> - this - > SetField ( kFunctionNameOffset_ , name ) ; <nl> - Handle < JSValue > info_holder = WrapInJSValue ( scope . isolate ( ) , info ) ; <nl> - this - > SetField ( kSharedInfoOffset_ , info_holder ) ; <nl> - this - > SetSmiValueField ( kStartPositionOffset_ , start_position ) ; <nl> - this - > SetSmiValueField ( kEndPositionOffset_ , end_position ) ; <nl> - } <nl> - <nl> - <nl> - Handle < SharedFunctionInfo > SharedInfoWrapper : : GetInfo ( ) { <nl> - Handle < Object > element = this - > GetField ( kSharedInfoOffset_ ) ; <nl> - Handle < JSValue > value_wrapper = Handle < JSValue > : : cast ( element ) ; <nl> - return UnwrapSharedFunctionInfoFromJSValue ( value_wrapper ) ; <nl> - } <nl> - <nl> - void LiveEdit : : InitializeThreadLocal ( Debug * debug ) { <nl> - debug - > thread_local_ . restart_fp_ = 0 ; <nl> - } <nl> - <nl> - MaybeHandle < JSArray > LiveEdit : : GatherCompileInfo ( Isolate * isolate , <nl> - Handle < Script > script , <nl> - Handle < String > source ) { <nl> - MaybeHandle < JSArray > infos ; <nl> - Handle < Object > original_source = <nl> - Handle < Object > ( script - > source ( ) , isolate ) ; <nl> - script - > set_source ( * source ) ; <nl> + union { <nl> + FunctionLiteral * literal ; <nl> + int pos_diff ; <nl> + } ; <nl> <nl> - { <nl> - / / Creating verbose TryCatch from public API is currently the only way to <nl> - / / force code save location . We do not use this the object directly . <nl> - v8 : : TryCatch try_catch ( reinterpret_cast < v8 : : Isolate * > ( isolate ) ) ; <nl> - try_catch . SetVerbose ( true ) ; <nl> - <nl> - / / A logical ' try ' section . <nl> - infos = Compiler : : CompileForLiveEdit ( script ) ; <nl> - } <nl> - <nl> - / / A logical ' catch ' section . <nl> - Handle < JSObject > rethrow_exception ; <nl> - if ( isolate - > has_pending_exception ( ) ) { <nl> - Handle < Object > exception ( isolate - > pending_exception ( ) , isolate ) ; <nl> - MessageLocation message_location = isolate - > GetMessageLocation ( ) ; <nl> - <nl> - isolate - > clear_pending_message ( ) ; <nl> - isolate - > clear_pending_exception ( ) ; <nl> - <nl> - / / If possible , copy positions from message object to exception object . <nl> - if ( exception - > IsJSObject ( ) & & ! message_location . script ( ) . is_null ( ) ) { <nl> - rethrow_exception = Handle < JSObject > : : cast ( exception ) ; <nl> - <nl> - Factory * factory = isolate - > factory ( ) ; <nl> - Handle < String > start_pos_key = factory - > InternalizeOneByteString ( <nl> - STATIC_CHAR_VECTOR ( " startPosition " ) ) ; <nl> - Handle < String > end_pos_key = <nl> - factory - > InternalizeOneByteString ( STATIC_CHAR_VECTOR ( " endPosition " ) ) ; <nl> - Handle < String > script_obj_key = <nl> - factory - > InternalizeOneByteString ( STATIC_CHAR_VECTOR ( " scriptObject " ) ) ; <nl> - Handle < Smi > start_pos ( <nl> - Smi : : FromInt ( message_location . start_pos ( ) ) , isolate ) ; <nl> - Handle < Smi > end_pos ( Smi : : FromInt ( message_location . end_pos ( ) ) , isolate ) ; <nl> - Handle < JSObject > script_obj = <nl> - Script : : GetWrapper ( message_location . script ( ) ) ; <nl> - Object : : SetProperty ( rethrow_exception , start_pos_key , start_pos , <nl> - LanguageMode : : kSloppy ) <nl> - . Assert ( ) ; <nl> - Object : : SetProperty ( rethrow_exception , end_pos_key , end_pos , <nl> - LanguageMode : : kSloppy ) <nl> - . Assert ( ) ; <nl> - Object : : SetProperty ( rethrow_exception , script_obj_key , script_obj , <nl> - LanguageMode : : kSloppy ) <nl> - . Assert ( ) ; <nl> + SourcePositionEvent ( FunctionLiteral * literal , bool is_start ) <nl> + : position ( is_start ? literal - > start_position ( ) <nl> + : literal - > end_position ( ) ) , <nl> + type ( is_start ? LITERAL_STARTS : LITERAL_ENDS ) , <nl> + literal ( literal ) { } <nl> + SourcePositionEvent ( const SourceChangeRange & change , bool is_start ) <nl> + : position ( is_start ? change . start_position : change . end_position ) , <nl> + type ( is_start ? DIFF_STARTS : DIFF_ENDS ) , <nl> + pos_diff ( ( change . new_end_position - change . new_start_position ) - <nl> + ( change . end_position - change . start_position ) ) { } <nl> + <nl> + static bool LessThan ( const SourcePositionEvent & a , <nl> + const SourcePositionEvent & b ) { <nl> + if ( a . position ! = b . position ) return a . position < b . position ; <nl> + if ( a . type ! = b . type ) return a . type < b . type ; <nl> + if ( a . type = = LITERAL_STARTS & & b . type = = LITERAL_STARTS ) { <nl> + return a . literal - > end_position ( ) < b . literal - > end_position ( ) ; <nl> + } else if ( a . type = = LITERAL_ENDS & & b . type = = LITERAL_ENDS ) { <nl> + return a . literal - > start_position ( ) > b . literal - > start_position ( ) ; <nl> + } else { <nl> + return a . pos_diff < b . pos_diff ; <nl> } <nl> } <nl> + } ; <nl> <nl> - / / A logical ' finally ' section . <nl> - script - > set_source ( * original_source ) ; <nl> + struct FunctionLiteralChange { <nl> + / / If any of start / end position is kNoSourcePosition , this literal is <nl> + / / considered damaged and will not be mapped and edited at all . <nl> + int new_start_position ; <nl> + int new_end_position ; <nl> + bool has_changes ; <nl> + FunctionLiteral * outer_literal ; <nl> + <nl> + explicit FunctionLiteralChange ( int new_start_position , FunctionLiteral * outer ) <nl> + : new_start_position ( new_start_position ) , <nl> + new_end_position ( kNoSourcePosition ) , <nl> + has_changes ( false ) , <nl> + outer_literal ( outer ) { } <nl> + } ; <nl> <nl> - if ( rethrow_exception . is_null ( ) ) { <nl> - return infos . ToHandleChecked ( ) ; <nl> - } else { <nl> - return isolate - > Throw < JSArray > ( rethrow_exception ) ; <nl> + using FunctionLiteralChanges = <nl> + std : : unordered_map < FunctionLiteral * , FunctionLiteralChange > ; <nl> + void CalculateFunctionLiteralChanges ( <nl> + const std : : vector < FunctionLiteral * > & literals , <nl> + const std : : vector < SourceChangeRange > & diffs , <nl> + FunctionLiteralChanges * result ) { <nl> + std : : vector < SourcePositionEvent > events ; <nl> + events . reserve ( literals . size ( ) * 2 + diffs . size ( ) * 2 ) ; <nl> + for ( FunctionLiteral * literal : literals ) { <nl> + events . emplace_back ( literal , true ) ; <nl> + events . emplace_back ( literal , false ) ; <nl> + } <nl> + for ( const SourceChangeRange & diff : diffs ) { <nl> + events . emplace_back ( diff , true ) ; <nl> + events . emplace_back ( diff , false ) ; <nl> + } <nl> + std : : sort ( events . begin ( ) , events . end ( ) , SourcePositionEvent : : LessThan ) ; <nl> + bool inside_diff = false ; <nl> + int delta = 0 ; <nl> + std : : stack < std : : pair < FunctionLiteral * , FunctionLiteralChange > > literal_stack ; <nl> + for ( const SourcePositionEvent & event : events ) { <nl> + switch ( event . type ) { <nl> + case SourcePositionEvent : : DIFF_ENDS : <nl> + DCHECK ( inside_diff ) ; <nl> + inside_diff = false ; <nl> + delta + = event . pos_diff ; <nl> + break ; <nl> + case SourcePositionEvent : : LITERAL_ENDS : { <nl> + DCHECK_EQ ( literal_stack . top ( ) . first , event . literal ) ; <nl> + FunctionLiteralChange & change = literal_stack . top ( ) . second ; <nl> + change . new_end_position = inside_diff <nl> + ? kNoSourcePosition <nl> + : event . literal - > end_position ( ) + delta ; <nl> + result - > insert ( literal_stack . top ( ) ) ; <nl> + literal_stack . pop ( ) ; <nl> + break ; <nl> + } <nl> + case SourcePositionEvent : : LITERAL_STARTS : <nl> + literal_stack . push ( std : : make_pair ( <nl> + event . literal , <nl> + FunctionLiteralChange ( <nl> + inside_diff ? kNoSourcePosition <nl> + : event . literal - > start_position ( ) + delta , <nl> + literal_stack . empty ( ) ? nullptr : literal_stack . top ( ) . first ) ) ) ; <nl> + break ; <nl> + case SourcePositionEvent : : DIFF_STARTS : <nl> + DCHECK ( ! inside_diff ) ; <nl> + inside_diff = true ; <nl> + if ( ! literal_stack . empty ( ) ) { <nl> + / / Note that outer literal has not necessarily changed , unless the <nl> + / / diff goes past the end of this literal . In this case , we ' ll mark <nl> + / / this function as damaged and parent as changed later in <nl> + / / MapLiterals . <nl> + literal_stack . top ( ) . second . has_changes = true ; <nl> + } <nl> + break ; <nl> + } <nl> } <nl> } <nl> <nl> - / / Patch function feedback vector . <nl> - / / The feedback vector is a cache for complex object boilerplates and for a <nl> - / / native context . We must clean cached values , or if the structure of the <nl> - / / vector itself changes we need to allocate a new one . <nl> - class FeedbackVectorFixer { <nl> - public : <nl> - static void PatchFeedbackVector ( FunctionInfoWrapper * compile_info_wrapper , <nl> - Handle < SharedFunctionInfo > shared_info , <nl> - Isolate * isolate ) { <nl> - / / When feedback metadata changes , we have to create new array instances . <nl> - / / Since we cannot create instances when iterating heap , we should first <nl> - / / collect all functions and fix their literal arrays . <nl> - Handle < FixedArray > function_instances = <nl> - CollectJSFunctions ( shared_info , isolate ) ; <nl> - <nl> - for ( int i = 0 ; i < function_instances - > length ( ) ; i + + ) { <nl> - Handle < JSFunction > fun ( JSFunction : : cast ( function_instances - > get ( i ) ) , <nl> - isolate ) ; <nl> - Handle < FeedbackCell > feedback_cell = <nl> - isolate - > factory ( ) - > NewManyClosuresCell ( <nl> - isolate - > factory ( ) - > undefined_value ( ) ) ; <nl> - fun - > set_feedback_cell ( * feedback_cell ) ; <nl> - / / Only create feedback vectors if we already have the metadata . <nl> - if ( shared_info - > is_compiled ( ) ) JSFunction : : EnsureFeedbackVector ( fun ) ; <nl> + / / Function which has not changed itself , but if any variable in its <nl> + / / outer context has been added / removed , we must consider this function <nl> + / / as damaged and not update references to it . <nl> + / / This is because old compiled function has hardcoded references to <nl> + / / it ' s outer context . <nl> + bool HasChangedScope ( FunctionLiteral * a , FunctionLiteral * b ) { <nl> + Scope * scope_a = a - > scope ( ) - > outer_scope ( ) ; <nl> + Scope * scope_b = b - > scope ( ) - > outer_scope ( ) ; <nl> + while ( scope_a & & scope_b ) { <nl> + std : : unordered_map < int , Handle < String > > vars ; <nl> + for ( Variable * var : * scope_a - > locals ( ) ) { <nl> + if ( ! var - > IsContextSlot ( ) ) continue ; <nl> + vars [ var - > index ( ) ] = var - > name ( ) ; <nl> + } <nl> + for ( Variable * var : * scope_b - > locals ( ) ) { <nl> + if ( ! var - > IsContextSlot ( ) ) continue ; <nl> + auto it = vars . find ( var - > index ( ) ) ; <nl> + if ( it = = vars . end ( ) ) return true ; <nl> + if ( * it - > second ! = * var - > name ( ) ) return true ; <nl> } <nl> + scope_a = scope_a - > outer_scope ( ) ; <nl> + scope_b = scope_b - > outer_scope ( ) ; <nl> } <nl> + return scope_a ! = scope_b ; <nl> + } <nl> <nl> - private : <nl> - / / Iterates all function instances in the HEAP that refers to the <nl> - / / provided shared_info . <nl> - template < typename Visitor > <nl> - static void IterateJSFunctions ( Handle < SharedFunctionInfo > shared_info , <nl> - Visitor * visitor ) { <nl> - HeapIterator iterator ( shared_info - > GetHeap ( ) ) ; <nl> - for ( HeapObject * obj = iterator . next ( ) ; obj ! = nullptr ; <nl> - obj = iterator . next ( ) ) { <nl> - if ( obj - > IsJSFunction ( ) ) { <nl> - JSFunction * function = JSFunction : : cast ( obj ) ; <nl> - if ( function - > shared ( ) = = * shared_info ) { <nl> - visitor - > visit ( function ) ; <nl> - } <nl> + enum ChangeState { UNCHANGED , CHANGED , DAMAGED } ; <nl> + <nl> + using LiteralMap = std : : unordered_map < FunctionLiteral * , FunctionLiteral * > ; <nl> + void MapLiterals ( const FunctionLiteralChanges & changes , <nl> + const std : : vector < FunctionLiteral * > & new_literals , <nl> + LiteralMap * unchanged , LiteralMap * changed ) { <nl> + std : : map < std : : pair < int , int > , FunctionLiteral * > position_to_new_literal ; <nl> + for ( FunctionLiteral * literal : new_literals ) { <nl> + DCHECK ( literal - > start_position ( ) ! = kNoSourcePosition ) ; <nl> + DCHECK ( literal - > end_position ( ) ! = kNoSourcePosition ) ; <nl> + position_to_new_literal [ std : : make_pair ( literal - > start_position ( ) , <nl> + literal - > end_position ( ) ) ] = literal ; <nl> + } <nl> + LiteralMap mappings ; <nl> + std : : unordered_map < FunctionLiteral * , ChangeState > change_state ; <nl> + for ( const auto & change_pair : changes ) { <nl> + FunctionLiteral * literal = change_pair . first ; <nl> + const FunctionLiteralChange & change = change_pair . second ; <nl> + auto it = position_to_new_literal . find ( <nl> + std : : make_pair ( change . new_start_position , change . new_end_position ) ) ; <nl> + if ( it = = position_to_new_literal . end ( ) | | <nl> + HasChangedScope ( literal , it - > second ) ) { <nl> + change_state [ literal ] = ChangeState : : DAMAGED ; <nl> + if ( ! change . outer_literal ) continue ; <nl> + if ( change_state [ change . outer_literal ] ! = ChangeState : : DAMAGED ) { <nl> + change_state [ change . outer_literal ] = ChangeState : : CHANGED ; <nl> + } <nl> + } else { <nl> + mappings [ literal ] = it - > second ; <nl> + if ( change_state . find ( literal ) = = change_state . end ( ) ) { <nl> + change_state [ literal ] = <nl> + change . has_changes ? ChangeState : : CHANGED : ChangeState : : UNCHANGED ; <nl> } <nl> } <nl> } <nl> - <nl> - / / Finds all instances of JSFunction that refers to the provided shared_info <nl> - / / and returns array with them . <nl> - static Handle < FixedArray > CollectJSFunctions ( <nl> - Handle < SharedFunctionInfo > shared_info , Isolate * isolate ) { <nl> - CountVisitor count_visitor ; <nl> - count_visitor . count = 0 ; <nl> - IterateJSFunctions ( shared_info , & count_visitor ) ; <nl> - int size = count_visitor . count ; <nl> - <nl> - Handle < FixedArray > result = isolate - > factory ( ) - > NewFixedArray ( size ) ; <nl> - if ( size > 0 ) { <nl> - CollectVisitor collect_visitor ( result ) ; <nl> - IterateJSFunctions ( shared_info , & collect_visitor ) ; <nl> + for ( const auto & mapping : mappings ) { <nl> + if ( change_state [ mapping . first ] = = ChangeState : : UNCHANGED ) { <nl> + ( * unchanged ) [ mapping . first ] = mapping . second ; <nl> + } else if ( change_state [ mapping . first ] = = ChangeState : : CHANGED ) { <nl> + ( * changed ) [ mapping . first ] = mapping . second ; <nl> } <nl> - return result ; <nl> } <nl> + } <nl> <nl> - class CountVisitor { <nl> - public : <nl> - void visit ( JSFunction * fun ) { <nl> - count + + ; <nl> - } <nl> - int count ; <nl> - } ; <nl> + class CollectFunctionLiterals final <nl> + : public AstTraversalVisitor < CollectFunctionLiterals > { <nl> + public : <nl> + CollectFunctionLiterals ( Isolate * isolate , AstNode * root ) <nl> + : AstTraversalVisitor < CollectFunctionLiterals > ( isolate , root ) { } <nl> + void VisitFunctionLiteral ( FunctionLiteral * lit ) { <nl> + AstTraversalVisitor : : VisitFunctionLiteral ( lit ) ; <nl> + literals_ - > push_back ( lit ) ; <nl> + } <nl> + void Run ( std : : vector < FunctionLiteral * > * literals ) { <nl> + literals_ = literals ; <nl> + AstTraversalVisitor : : Run ( ) ; <nl> + literals_ = nullptr ; <nl> + } <nl> <nl> - class CollectVisitor { <nl> - public : <nl> - explicit CollectVisitor ( Handle < FixedArray > output ) <nl> - : m_output ( output ) , m_pos ( 0 ) { } <nl> + private : <nl> + std : : vector < FunctionLiteral * > * literals_ ; <nl> + } ; <nl> <nl> - void visit ( JSFunction * fun ) { <nl> - m_output - > set ( m_pos , fun ) ; <nl> - m_pos + + ; <nl> + bool ParseScript ( Isolate * isolate , ParseInfo * parse_info , bool compile_as_well , <nl> + std : : vector < FunctionLiteral * > * literals , <nl> + debug : : LiveEditResult * result ) { <nl> + parse_info - > set_eager ( ) ; <nl> + v8 : : TryCatch try_catch ( reinterpret_cast < v8 : : Isolate * > ( isolate ) ) ; <nl> + Handle < SharedFunctionInfo > shared ; <nl> + bool success = false ; <nl> + if ( compile_as_well ) { <nl> + success = <nl> + Compiler : : CompileForLiveEdit ( parse_info , isolate ) . ToHandle ( & shared ) ; <nl> + } else { <nl> + success = parsing : : ParseProgram ( parse_info , isolate ) ; <nl> + if ( success ) { <nl> + success = Compiler : : Analyze ( parse_info ) ; <nl> + parse_info - > ast_value_factory ( ) - > Internalize ( isolate ) ; <nl> } <nl> - private : <nl> - Handle < FixedArray > m_output ; <nl> - int m_pos ; <nl> + } <nl> + if ( ! success ) { <nl> + isolate - > OptionalRescheduleException ( false ) ; <nl> + DCHECK ( try_catch . HasCaught ( ) ) ; <nl> + result - > message = try_catch . Message ( ) - > Get ( ) ; <nl> + auto self = Utils : : OpenHandle ( * try_catch . Message ( ) ) ; <nl> + auto msg = i : : Handle < i : : JSMessageObject > : : cast ( self ) ; <nl> + result - > line_number = msg - > GetLineNumber ( ) ; <nl> + result - > column_number = msg - > GetColumnNumber ( ) ; <nl> + result - > status = debug : : LiveEditResult : : COMPILE_ERROR ; <nl> + return false ; <nl> + } <nl> + CollectFunctionLiterals ( isolate , parse_info - > literal ( ) ) . Run ( literals ) ; <nl> + return true ; <nl> + } <nl> + <nl> + struct FunctionData { <nl> + FunctionData ( FunctionLiteral * literal , bool should_restart ) <nl> + : literal ( literal ) , <nl> + stack_position ( NOT_ON_STACK ) , <nl> + should_restart ( should_restart ) { } <nl> + <nl> + FunctionLiteral * literal ; <nl> + MaybeHandle < SharedFunctionInfo > shared ; <nl> + std : : vector < Handle < JSFunction > > js_functions ; <nl> + std : : vector < Handle < JSGeneratorObject > > running_generators ; <nl> + / / In case of multiple functions with different stack position , the latest <nl> + / / one ( in the order below ) is used , since it is the most restrictive . <nl> + / / This is important only for functions to be restarted . <nl> + enum StackPosition { <nl> + NOT_ON_STACK , <nl> + ABOVE_BREAK_FRAME , <nl> + PATCHABLE , <nl> + BELOW_NON_DROPPABLE_FRAME , <nl> + ARCHIVED_THREAD , <nl> } ; <nl> + StackPosition stack_position ; <nl> + bool should_restart ; <nl> } ; <nl> <nl> + class FunctionDataMap : public ThreadVisitor { <nl> + public : <nl> + void AddInterestingLiteral ( int script_id , FunctionLiteral * literal , <nl> + bool should_restart ) { <nl> + map_ . emplace ( std : : make_pair ( script_id , literal - > function_literal_id ( ) ) , <nl> + FunctionData { literal , should_restart } ) ; <nl> + } <nl> <nl> - void LiveEdit : : ReplaceFunctionCode ( <nl> - Handle < JSArray > new_compile_info_array , <nl> - Handle < JSArray > shared_info_array ) { <nl> - Isolate * isolate = new_compile_info_array - > GetIsolate ( ) ; <nl> - <nl> - FunctionInfoWrapper compile_info_wrapper ( new_compile_info_array ) ; <nl> - SharedInfoWrapper shared_info_wrapper ( shared_info_array ) ; <nl> - <nl> - Handle < SharedFunctionInfo > shared_info = shared_info_wrapper . GetInfo ( ) ; <nl> - Handle < SharedFunctionInfo > new_shared_info = <nl> - compile_info_wrapper . GetSharedFunctionInfo ( ) ; <nl> - <nl> - if ( shared_info - > is_compiled ( ) ) { <nl> - if ( shared_info - > HasBreakInfo ( ) ) { <nl> - / / Existing break points will be re - applied . Reset the debug info here . <nl> - isolate - > debug ( ) - > RemoveBreakInfoAndMaybeFree ( <nl> - handle ( shared_info - > GetDebugInfo ( ) , isolate ) ) ; <nl> + bool Lookup ( SharedFunctionInfo * sfi , FunctionData * * data ) { <nl> + if ( ! sfi - > script ( ) - > IsScript ( ) | | sfi - > function_literal_id ( ) = = - 1 ) { <nl> + return false ; <nl> } <nl> - <nl> - / / Clear old bytecode . This will trigger self - healing if we do not install <nl> - / / new bytecode . <nl> - shared_info - > FlushCompiled ( ) ; <nl> - if ( new_shared_info - > HasInterpreterData ( ) ) { <nl> - shared_info - > set_interpreter_data ( new_shared_info - > interpreter_data ( ) ) ; <nl> - } else { <nl> - shared_info - > set_bytecode_array ( new_shared_info - > GetBytecodeArray ( ) ) ; <nl> + Script * script = Script : : cast ( sfi - > script ( ) ) ; <nl> + return Lookup ( script - > id ( ) , sfi - > function_literal_id ( ) , data ) ; <nl> + } <nl> + <nl> + bool Lookup ( Handle < Script > script , FunctionLiteral * literal , <nl> + FunctionData * * data ) { <nl> + return Lookup ( script - > id ( ) , literal - > function_literal_id ( ) , data ) ; <nl> + } <nl> + <nl> + void Fill ( Isolate * isolate , Address * restart_frame_fp ) { <nl> + { <nl> + HeapIterator iterator ( isolate - > heap ( ) , HeapIterator : : kFilterUnreachable ) ; <nl> + while ( HeapObject * obj = iterator . next ( ) ) { <nl> + if ( obj - > IsSharedFunctionInfo ( ) ) { <nl> + SharedFunctionInfo * sfi = SharedFunctionInfo : : cast ( obj ) ; <nl> + FunctionData * data = nullptr ; <nl> + if ( ! Lookup ( sfi , & data ) ) continue ; <nl> + data - > shared = handle ( sfi , isolate ) ; <nl> + } else if ( obj - > IsJSFunction ( ) ) { <nl> + JSFunction * js_function = JSFunction : : cast ( obj ) ; <nl> + SharedFunctionInfo * sfi = js_function - > shared ( ) ; <nl> + FunctionData * data = nullptr ; <nl> + if ( ! Lookup ( sfi , & data ) ) continue ; <nl> + data - > js_functions . emplace_back ( js_function , isolate ) ; <nl> + } else if ( obj - > IsJSGeneratorObject ( ) ) { <nl> + JSGeneratorObject * gen = JSGeneratorObject : : cast ( obj ) ; <nl> + if ( gen - > is_closed ( ) ) continue ; <nl> + SharedFunctionInfo * sfi = gen - > function ( ) - > shared ( ) ; <nl> + FunctionData * data = nullptr ; <nl> + if ( ! Lookup ( sfi , & data ) ) continue ; <nl> + data - > running_generators . emplace_back ( gen , isolate ) ; <nl> + } <nl> + } <nl> + } <nl> + FunctionData : : StackPosition stack_position = <nl> + isolate - > debug ( ) - > break_frame_id ( ) = = StackFrame : : NO_ID <nl> + ? FunctionData : : PATCHABLE <nl> + : FunctionData : : ABOVE_BREAK_FRAME ; <nl> + for ( StackFrameIterator it ( isolate ) ; ! it . done ( ) ; it . Advance ( ) ) { <nl> + StackFrame * frame = it . frame ( ) ; <nl> + if ( stack_position = = FunctionData : : ABOVE_BREAK_FRAME ) { <nl> + if ( frame - > id ( ) = = isolate - > debug ( ) - > break_frame_id ( ) ) { <nl> + stack_position = FunctionData : : PATCHABLE ; <nl> + } <nl> + } <nl> + if ( stack_position = = FunctionData : : PATCHABLE & & <nl> + ( frame - > is_exit ( ) | | frame - > is_builtin_exit ( ) ) ) { <nl> + stack_position = FunctionData : : BELOW_NON_DROPPABLE_FRAME ; <nl> + continue ; <nl> + } <nl> + if ( ! frame - > is_java_script ( ) ) continue ; <nl> + std : : vector < Handle < SharedFunctionInfo > > sfis ; <nl> + JavaScriptFrame : : cast ( frame ) - > GetFunctions ( & sfis ) ; <nl> + for ( auto & sfi : sfis ) { <nl> + if ( stack_position = = FunctionData : : PATCHABLE & & <nl> + IsResumableFunction ( sfi - > kind ( ) ) ) { <nl> + stack_position = FunctionData : : BELOW_NON_DROPPABLE_FRAME ; <nl> + } <nl> + FunctionData * data = nullptr ; <nl> + if ( ! Lookup ( * sfi , & data ) ) continue ; <nl> + if ( ! data - > should_restart ) continue ; <nl> + data - > stack_position = stack_position ; <nl> + * restart_frame_fp = frame - > fp ( ) ; <nl> + } <nl> } <nl> <nl> - shared_info - > set_scope_info ( new_shared_info - > scope_info ( ) ) ; <nl> - shared_info - > set_feedback_metadata ( new_shared_info - > feedback_metadata ( ) ) ; <nl> - shared_info - > DisableOptimization ( BailoutReason : : kLiveEdit ) ; <nl> - } else { <nl> - / / There should not be any feedback metadata . Keep the outer scope info the <nl> - / / same . <nl> - DCHECK ( ! shared_info - > HasFeedbackMetadata ( ) ) ; <nl> + isolate - > thread_manager ( ) - > IterateArchivedThreads ( this ) ; <nl> } <nl> <nl> - int start_position = compile_info_wrapper . GetStartPosition ( ) ; <nl> - int end_position = compile_info_wrapper . GetEndPosition ( ) ; <nl> - / / TODO ( cbruni ) : only store position information on the SFI . <nl> - shared_info - > set_raw_start_position ( start_position ) ; <nl> - shared_info - > set_raw_end_position ( end_position ) ; <nl> - if ( shared_info - > scope_info ( ) - > HasPositionInfo ( ) ) { <nl> - shared_info - > scope_info ( ) - > SetPositionInfo ( start_position , end_position ) ; <nl> + private : <nl> + bool Lookup ( int script_id , int function_literal_id , FunctionData * * data ) { <nl> + auto it = map_ . find ( std : : make_pair ( script_id , function_literal_id ) ) ; <nl> + if ( it = = map_ . end ( ) ) return false ; <nl> + * data = & it - > second ; <nl> + return true ; <nl> + } <nl> + <nl> + void VisitThread ( Isolate * isolate , ThreadLocalTop * top ) override { <nl> + for ( JavaScriptFrameIterator it ( isolate , top ) ; ! it . done ( ) ; it . Advance ( ) ) { <nl> + std : : vector < Handle < SharedFunctionInfo > > sfis ; <nl> + it . frame ( ) - > GetFunctions ( & sfis ) ; <nl> + for ( auto & sfi : sfis ) { <nl> + FunctionData * data = nullptr ; <nl> + if ( ! Lookup ( * sfi , & data ) ) continue ; <nl> + data - > stack_position = FunctionData : : ARCHIVED_THREAD ; <nl> + } <nl> + } <nl> } <nl> <nl> - FeedbackVectorFixer : : PatchFeedbackVector ( & compile_info_wrapper , shared_info , <nl> - isolate ) ; <nl> - <nl> - isolate - > debug ( ) - > DeoptimizeFunction ( shared_info ) ; <nl> - } <nl> - <nl> - void LiveEdit : : FunctionSourceUpdated ( Handle < JSArray > shared_info_array , <nl> - int new_function_literal_id ) { <nl> - SharedInfoWrapper shared_info_wrapper ( shared_info_array ) ; <nl> - Handle < SharedFunctionInfo > shared_info = shared_info_wrapper . GetInfo ( ) ; <nl> - <nl> - shared_info - > set_function_literal_id ( new_function_literal_id ) ; <nl> - shared_info_array - > GetIsolate ( ) - > debug ( ) - > DeoptimizeFunction ( shared_info ) ; <nl> - } <nl> + using UniqueLiteralId = std : : pair < int , int > ; / / script_id + literal_id <nl> + std : : map < UniqueLiteralId , FunctionData > map_ ; <nl> + } ; <nl> <nl> - void LiveEdit : : FixupScript ( Isolate * isolate , Handle < Script > script , <nl> - int max_function_literal_id ) { <nl> - Handle < WeakFixedArray > old_infos ( script - > shared_function_infos ( ) , isolate ) ; <nl> - Handle < WeakFixedArray > new_infos ( <nl> - isolate - > factory ( ) - > NewWeakFixedArray ( max_function_literal_id + 1 ) ) ; <nl> - script - > set_shared_function_infos ( * new_infos ) ; <nl> - SharedFunctionInfo : : ScriptIterator iterator ( isolate , old_infos ) ; <nl> - while ( SharedFunctionInfo * shared = iterator . Next ( ) ) { <nl> - / / We can ' t use SharedFunctionInfo : : SetScript ( info , undefined_value ( ) ) here , <nl> - / / as we severed the link from the Script to the SharedFunctionInfo above . <nl> - Handle < SharedFunctionInfo > info ( shared , isolate ) ; <nl> - info - > set_script ( isolate - > heap ( ) - > undefined_value ( ) ) ; <nl> - Handle < Object > new_noscript_list = FixedArrayOfWeakCells : : Add ( <nl> - isolate , isolate - > factory ( ) - > noscript_shared_function_infos ( ) , info ) ; <nl> - isolate - > heap ( ) - > SetRootNoScriptSharedFunctionInfos ( * new_noscript_list ) ; <nl> - <nl> - / / Put the SharedFunctionInfo at its new , correct location . <nl> - SharedFunctionInfo : : SetScript ( info , script ) ; <nl> + bool CanPatchScript ( const LiteralMap & changed , Handle < Script > script , <nl> + Handle < Script > new_script , <nl> + FunctionDataMap & function_data_map , <nl> + debug : : LiveEditResult * result ) { <nl> + debug : : LiveEditResult : : Status status = debug : : LiveEditResult : : OK ; <nl> + for ( const auto & mapping : changed ) { <nl> + FunctionData * data = nullptr ; <nl> + function_data_map . Lookup ( script , mapping . first , & data ) ; <nl> + FunctionData * new_data = nullptr ; <nl> + function_data_map . Lookup ( new_script , mapping . second , & new_data ) ; <nl> + Handle < SharedFunctionInfo > sfi ; <nl> + if ( ! data - > shared . ToHandle ( & sfi ) ) { <nl> + continue ; <nl> + } else if ( ! data - > should_restart ) { <nl> + UNREACHABLE ( ) ; <nl> + } else if ( data - > stack_position = = FunctionData : : ABOVE_BREAK_FRAME ) { <nl> + status = debug : : LiveEditResult : : BLOCKED_BY_FUNCTION_ABOVE_BREAK_FRAME ; <nl> + } else if ( data - > stack_position = = <nl> + FunctionData : : BELOW_NON_DROPPABLE_FRAME ) { <nl> + status = <nl> + debug : : LiveEditResult : : BLOCKED_BY_FUNCTION_BELOW_NON_DROPPABLE_FRAME ; <nl> + } else if ( ! data - > running_generators . empty ( ) ) { <nl> + status = debug : : LiveEditResult : : BLOCKED_BY_RUNNING_GENERATOR ; <nl> + } else if ( data - > stack_position = = FunctionData : : ARCHIVED_THREAD ) { <nl> + status = debug : : LiveEditResult : : BLOCKED_BY_ACTIVE_FUNCTION ; <nl> + } <nl> + if ( status ! = debug : : LiveEditResult : : OK ) { <nl> + result - > status = status ; <nl> + return false ; <nl> + } <nl> } <nl> + return true ; <nl> } <nl> <nl> - void LiveEdit : : SetFunctionScript ( Handle < JSValue > function_wrapper , <nl> - Handle < Object > script_handle ) { <nl> - Handle < SharedFunctionInfo > shared_info = <nl> - UnwrapSharedFunctionInfoFromJSValue ( function_wrapper ) ; <nl> - Isolate * isolate = function_wrapper - > GetIsolate ( ) ; <nl> - CHECK ( script_handle - > IsScript ( ) | | script_handle - > IsUndefined ( isolate ) ) ; <nl> - SharedFunctionInfo : : SetScript ( shared_info , script_handle ) ; <nl> - shared_info - > DisableOptimization ( BailoutReason : : kLiveEdit ) ; <nl> - <nl> - isolate - > compilation_cache ( ) - > Remove ( shared_info ) ; <nl> - } <nl> - <nl> - namespace { <nl> - / / For a script text change ( defined as position_change_array ) , translates <nl> - / / position in unchanged text to position in changed text . <nl> - / / Text change is a set of non - overlapping regions in text , that have changed <nl> - / / their contents and length . It is specified as array of groups of 3 numbers : <nl> - / / ( change_begin , change_end , change_end_new_position ) . <nl> - / / Each group describes a change in text ; groups are sorted by change_begin . <nl> - / / Only position in text beyond any changes may be successfully translated . <nl> - / / If a positions is inside some region that changed , result is currently <nl> - / / undefined . <nl> - static int TranslatePosition2 ( int original_position , <nl> - Handle < JSArray > position_change_array ) { <nl> - int position_diff = 0 ; <nl> - int array_len = GetArrayLength ( position_change_array ) ; <nl> - Isolate * isolate = position_change_array - > GetIsolate ( ) ; <nl> - / / TODO ( 635 ) : binary search may be used here <nl> - for ( int i = 0 ; i < array_len ; i + = 3 ) { <nl> - HandleScope scope ( isolate ) ; <nl> - Handle < Object > element = <nl> - JSReceiver : : GetElement ( isolate , position_change_array , i ) <nl> - . ToHandleChecked ( ) ; <nl> - CHECK ( element - > IsSmi ( ) ) ; <nl> - int chunk_start = Handle < Smi > : : cast ( element ) - > value ( ) ; <nl> - if ( original_position < chunk_start ) { <nl> + bool CanRestartFrame ( Isolate * isolate , Address fp , <nl> + FunctionDataMap & function_data_map , <nl> + const LiteralMap & changed , debug : : LiveEditResult * result ) { <nl> + DCHECK_GT ( fp , 0 ) ; <nl> + StackFrame * restart_frame = nullptr ; <nl> + StackFrameIterator it ( isolate ) ; <nl> + for ( ; ! it . done ( ) ; it . Advance ( ) ) { <nl> + if ( it . frame ( ) - > fp ( ) = = fp ) { <nl> + restart_frame = it . frame ( ) ; <nl> break ; <nl> } <nl> - element = JSReceiver : : GetElement ( isolate , position_change_array , i + 1 ) <nl> - . ToHandleChecked ( ) ; <nl> - CHECK ( element - > IsSmi ( ) ) ; <nl> - int chunk_end = Handle < Smi > : : cast ( element ) - > value ( ) ; <nl> - / / Position mustn ' t be inside a chunk . <nl> - DCHECK ( original_position > = chunk_end ) ; <nl> - element = JSReceiver : : GetElement ( isolate , position_change_array , i + 2 ) <nl> - . ToHandleChecked ( ) ; <nl> - CHECK ( element - > IsSmi ( ) ) ; <nl> - int chunk_changed_end = Handle < Smi > : : cast ( element ) - > value ( ) ; <nl> - position_diff = chunk_changed_end - chunk_end ; <nl> - } <nl> - <nl> - return original_position + position_diff ; <nl> + } <nl> + DCHECK ( restart_frame & & restart_frame - > is_java_script ( ) ) ; <nl> + if ( ! LiveEdit : : kFrameDropperSupported ) { <nl> + result - > status = debug : : LiveEditResult : : FRAME_RESTART_IS_NOT_SUPPORTED ; <nl> + return false ; <nl> + } <nl> + std : : vector < Handle < SharedFunctionInfo > > sfis ; <nl> + JavaScriptFrame : : cast ( restart_frame ) - > GetFunctions ( & sfis ) ; <nl> + for ( auto & sfi : sfis ) { <nl> + FunctionData * data = nullptr ; <nl> + if ( ! function_data_map . Lookup ( * sfi , & data ) ) continue ; <nl> + auto new_literal_it = changed . find ( data - > literal ) ; <nl> + if ( new_literal_it = = changed . end ( ) ) continue ; <nl> + if ( new_literal_it - > second - > scope ( ) - > new_target_var ( ) ) { <nl> + result - > status = <nl> + debug : : LiveEditResult : : BLOCKED_BY_NEW_TARGET_IN_RESTART_FRAME ; <nl> + return false ; <nl> + } <nl> + } <nl> + return true ; <nl> } <nl> <nl> void TranslateSourcePositionTable ( Handle < BytecodeArray > code , <nl> - Handle < JSArray > position_change_array ) { <nl> - Isolate * isolate = position_change_array - > GetIsolate ( ) ; <nl> + const std : : vector < SourceChangeRange > & diffs ) { <nl> + Isolate * isolate = code - > GetIsolate ( ) ; <nl> SourcePositionTableBuilder builder ; <nl> <nl> Handle < ByteArray > source_position_table ( code - > SourcePositionTable ( ) , isolate ) ; <nl> void TranslateSourcePositionTable ( Handle < BytecodeArray > code , <nl> ! iterator . done ( ) ; iterator . Advance ( ) ) { <nl> SourcePosition position = iterator . source_position ( ) ; <nl> position . SetScriptOffset ( <nl> - TranslatePosition2 ( position . ScriptOffset ( ) , position_change_array ) ) ; <nl> + LiveEdit : : TranslatePosition ( diffs , position . ScriptOffset ( ) ) ) ; <nl> builder . AddPosition ( iterator . code_offset ( ) , position , <nl> iterator . is_statement ( ) ) ; <nl> } <nl> void TranslateSourcePositionTable ( Handle < BytecodeArray > code , <nl> CodeLinePosInfoRecordEvent ( code - > GetFirstBytecodeAddress ( ) , <nl> * new_source_position_table ) ) ; <nl> } <nl> - } / / namespace <nl> - <nl> - void LiveEdit : : PatchFunctionPositions ( Handle < JSArray > shared_info_array , <nl> - Handle < JSArray > position_change_array ) { <nl> - SharedInfoWrapper shared_info_wrapper ( shared_info_array ) ; <nl> - Handle < SharedFunctionInfo > info = shared_info_wrapper . GetInfo ( ) ; <nl> - <nl> - int old_function_start = info - > StartPosition ( ) ; <nl> - int new_function_start = <nl> - TranslatePosition2 ( old_function_start , position_change_array ) ; <nl> - int new_function_end = <nl> - TranslatePosition2 ( info - > EndPosition ( ) , position_change_array ) ; <nl> - int new_function_token_pos = TranslatePosition2 ( <nl> - info - > function_token_position ( ) , position_change_array ) ; <nl> - <nl> - info - > set_raw_start_position ( new_function_start ) ; <nl> - info - > set_raw_end_position ( new_function_end ) ; <nl> - / / TODO ( cbruni ) : Allocate helper ScopeInfo once the position fields are gone <nl> - / / on the SFI . <nl> - if ( info - > scope_info ( ) - > HasPositionInfo ( ) ) { <nl> - info - > scope_info ( ) - > SetPositionInfo ( new_function_start , new_function_end ) ; <nl> - } <nl> - info - > set_function_token_position ( new_function_token_pos ) ; <nl> - <nl> - if ( info - > HasBytecodeArray ( ) ) { <nl> - TranslateSourcePositionTable ( <nl> - handle ( info - > GetBytecodeArray ( ) , shared_info_wrapper . isolate ( ) ) , <nl> - position_change_array ) ; <nl> - } <nl> - if ( info - > HasBreakInfo ( ) ) { <nl> - / / Existing break points will be re - applied . Reset the debug info here . <nl> - shared_info_wrapper . isolate ( ) - > debug ( ) - > RemoveBreakInfoAndMaybeFree ( <nl> - handle ( info - > GetDebugInfo ( ) , shared_info_wrapper . isolate ( ) ) ) ; <nl> - } <nl> - } <nl> <nl> - static Handle < Script > CreateScriptCopy ( Isolate * isolate , <nl> - Handle < Script > original ) { <nl> - Handle < String > original_source ( String : : cast ( original - > source ( ) ) , isolate ) ; <nl> - Handle < Script > copy = isolate - > factory ( ) - > NewScript ( original_source ) ; <nl> - <nl> - copy - > set_name ( original - > name ( ) ) ; <nl> - copy - > set_line_offset ( original - > line_offset ( ) ) ; <nl> - copy - > set_column_offset ( original - > column_offset ( ) ) ; <nl> - copy - > set_type ( original - > type ( ) ) ; <nl> - copy - > set_context_data ( original - > context_data ( ) ) ; <nl> - copy - > set_eval_from_shared_or_wrapped_arguments ( <nl> - original - > eval_from_shared_or_wrapped_arguments ( ) ) ; <nl> - copy - > set_eval_from_position ( original - > eval_from_position ( ) ) ; <nl> - <nl> - Handle < WeakFixedArray > infos ( isolate - > factory ( ) - > NewWeakFixedArray ( <nl> - original - > shared_function_infos ( ) - > length ( ) ) ) ; <nl> - copy - > set_shared_function_infos ( * infos ) ; <nl> - <nl> - / / Copy all the flags , but clear compilation state . <nl> - copy - > set_flags ( original - > flags ( ) ) ; <nl> - copy - > set_compilation_state ( Script : : COMPILATION_STATE_INITIAL ) ; <nl> - <nl> - return copy ; <nl> + void UpdatePositions ( Isolate * isolate , Handle < SharedFunctionInfo > sfi , <nl> + const std : : vector < SourceChangeRange > & diffs ) { <nl> + int old_start_position = sfi - > StartPosition ( ) ; <nl> + int new_start_position = <nl> + LiveEdit : : TranslatePosition ( diffs , old_start_position ) ; <nl> + int new_end_position = LiveEdit : : TranslatePosition ( diffs , sfi - > EndPosition ( ) ) ; <nl> + int new_function_token_position = <nl> + LiveEdit : : TranslatePosition ( diffs , sfi - > function_token_position ( ) ) ; <nl> + sfi - > set_raw_start_position ( new_start_position ) ; <nl> + sfi - > set_raw_end_position ( new_end_position ) ; <nl> + sfi - > set_function_token_position ( new_function_token_position ) ; <nl> + if ( sfi - > scope_info ( ) - > HasPositionInfo ( ) ) { <nl> + sfi - > scope_info ( ) - > SetPositionInfo ( new_start_position , new_end_position ) ; <nl> + } <nl> + if ( sfi - > HasBytecodeArray ( ) ) { <nl> + TranslateSourcePositionTable ( handle ( sfi - > GetBytecodeArray ( ) , isolate ) , <nl> + diffs ) ; <nl> + } <nl> } <nl> + } / / anonymous namespace <nl> <nl> - Handle < Object > LiveEdit : : ChangeScriptSource ( Isolate * isolate , <nl> - Handle < Script > original_script , <nl> - Handle < String > new_source , <nl> - Handle < Object > old_script_name ) { <nl> - Handle < Object > old_script_object ; <nl> - if ( old_script_name - > IsString ( ) ) { <nl> - Handle < Script > old_script = CreateScriptCopy ( isolate , original_script ) ; <nl> - old_script - > set_name ( String : : cast ( * old_script_name ) ) ; <nl> - old_script_object = old_script ; <nl> - isolate - > debug ( ) - > OnAfterCompile ( old_script ) ; <nl> - } else { <nl> - old_script_object = isolate - > factory ( ) - > null_value ( ) ; <nl> + void LiveEdit : : PatchScript ( Isolate * isolate , Handle < Script > script , <nl> + Handle < String > new_source , bool preview , <nl> + debug : : LiveEditResult * result ) { <nl> + std : : vector < SourceChangeRange > diffs ; <nl> + LiveEdit : : CompareStrings ( isolate , <nl> + handle ( String : : cast ( script - > source ( ) ) , isolate ) , <nl> + new_source , & diffs ) ; <nl> + if ( diffs . empty ( ) ) { <nl> + result - > status = debug : : LiveEditResult : : OK ; <nl> + return ; <nl> } <nl> <nl> - original_script - > set_source ( * new_source ) ; <nl> - <nl> - / / Drop line ends so that they will be recalculated . <nl> - original_script - > set_line_ends ( isolate - > heap ( ) - > undefined_value ( ) ) ; <nl> + ParseInfo parse_info ( isolate , script ) ; <nl> + std : : vector < FunctionLiteral * > literals ; <nl> + if ( ! ParseScript ( isolate , & parse_info , false , & literals , result ) ) return ; <nl> <nl> - return old_script_object ; <nl> - } <nl> - <nl> - void LiveEdit : : ReplaceRefToNestedFunction ( <nl> - Heap * heap , Handle < JSValue > parent_function_wrapper , <nl> - Handle < JSValue > orig_function_wrapper , <nl> - Handle < JSValue > subst_function_wrapper ) { <nl> - Handle < SharedFunctionInfo > parent_shared = <nl> - UnwrapSharedFunctionInfoFromJSValue ( parent_function_wrapper ) ; <nl> - Handle < SharedFunctionInfo > orig_shared = <nl> - UnwrapSharedFunctionInfoFromJSValue ( orig_function_wrapper ) ; <nl> - Handle < SharedFunctionInfo > subst_shared = <nl> - UnwrapSharedFunctionInfoFromJSValue ( subst_function_wrapper ) ; <nl> - <nl> - for ( RelocIterator it ( parent_shared - > GetCode ( ) ) ; ! it . done ( ) ; it . next ( ) ) { <nl> - if ( it . rinfo ( ) - > rmode ( ) = = RelocInfo : : EMBEDDED_OBJECT ) { <nl> - if ( it . rinfo ( ) - > target_object ( ) = = * orig_shared ) { <nl> - it . rinfo ( ) - > set_target_object ( heap , * subst_shared ) ; <nl> - } <nl> - } <nl> + Handle < Script > new_script = isolate - > factory ( ) - > CloneScript ( script ) ; <nl> + new_script - > set_source ( * new_source ) ; <nl> + std : : vector < FunctionLiteral * > new_literals ; <nl> + ParseInfo new_parse_info ( isolate , new_script ) ; <nl> + if ( ! ParseScript ( isolate , & new_parse_info , true , & new_literals , result ) ) { <nl> + return ; <nl> } <nl> - } <nl> <nl> + FunctionLiteralChanges literal_changes ; <nl> + CalculateFunctionLiteralChanges ( literals , diffs , & literal_changes ) ; <nl> <nl> - / / Check an activation against list of functions . If there is a function <nl> - / / that matches , its status in result array is changed to status argument value . <nl> - static bool CheckActivation ( Handle < JSArray > shared_info_array , <nl> - Handle < JSArray > result , <nl> - StackFrame * frame , <nl> - LiveEdit : : FunctionPatchabilityStatus status ) { <nl> - if ( ! frame - > is_java_script ( ) ) return false ; <nl> + LiteralMap changed ; <nl> + LiteralMap unchanged ; <nl> + MapLiterals ( literal_changes , new_literals , & unchanged , & changed ) ; <nl> <nl> - Handle < JSFunction > function ( JavaScriptFrame : : cast ( frame ) - > function ( ) , <nl> - frame - > isolate ( ) ) ; <nl> - <nl> - Isolate * isolate = shared_info_array - > GetIsolate ( ) ; <nl> - int len = GetArrayLength ( shared_info_array ) ; <nl> - for ( int i = 0 ; i < len ; i + + ) { <nl> - HandleScope scope ( isolate ) ; <nl> - Handle < Object > element = <nl> - JSReceiver : : GetElement ( isolate , shared_info_array , i ) . ToHandleChecked ( ) ; <nl> - Handle < JSValue > jsvalue = Handle < JSValue > : : cast ( element ) ; <nl> - Handle < SharedFunctionInfo > shared = <nl> - UnwrapSharedFunctionInfoFromJSValue ( jsvalue ) ; <nl> - <nl> - if ( function - > shared ( ) = = * shared | | <nl> - ( function - > code ( ) - > is_optimized_code ( ) & & <nl> - function - > code ( ) - > Inlines ( * shared ) ) ) { <nl> - SetElementSloppy ( result , i , Handle < Smi > ( Smi : : FromInt ( status ) , isolate ) ) ; <nl> - return true ; <nl> - } <nl> + FunctionDataMap function_data_map ; <nl> + for ( const auto & mapping : changed ) { <nl> + function_data_map . AddInterestingLiteral ( script - > id ( ) , mapping . first , true ) ; <nl> + function_data_map . AddInterestingLiteral ( new_script - > id ( ) , mapping . second , <nl> + false ) ; <nl> } <nl> - return false ; <nl> - } <nl> - <nl> - / / Describes a set of call frames that execute any of listed functions . <nl> - / / Finding no such frames does not mean error . <nl> - class MultipleFunctionTarget { <nl> - public : <nl> - MultipleFunctionTarget ( Handle < JSArray > old_shared_array , <nl> - Handle < JSArray > new_shared_array , <nl> - Handle < JSArray > result ) <nl> - : old_shared_array_ ( old_shared_array ) , <nl> - new_shared_array_ ( new_shared_array ) , <nl> - result_ ( result ) { } <nl> - bool MatchActivation ( StackFrame * frame , <nl> - LiveEdit : : FunctionPatchabilityStatus status ) { <nl> - return CheckActivation ( old_shared_array_ , result_ , frame , status ) ; <nl> - } <nl> - const char * GetNotFoundMessage ( ) const { return nullptr ; } <nl> - bool FrameUsesNewTarget ( StackFrame * frame ) { <nl> - if ( ! frame - > is_java_script ( ) ) return false ; <nl> - JavaScriptFrame * jsframe = JavaScriptFrame : : cast ( frame ) ; <nl> - Handle < SharedFunctionInfo > old_shared ( jsframe - > function ( ) - > shared ( ) , <nl> - jsframe - > isolate ( ) ) ; <nl> - Isolate * isolate = jsframe - > isolate ( ) ; <nl> - int len = GetArrayLength ( old_shared_array_ ) ; <nl> - / / Find corresponding new shared function info and return whether it <nl> - / / references new . target . <nl> - for ( int i = 0 ; i < len ; i + + ) { <nl> - HandleScope scope ( isolate ) ; <nl> - Handle < Object > old_element = <nl> - JSReceiver : : GetElement ( isolate , old_shared_array_ , i ) <nl> - . ToHandleChecked ( ) ; <nl> - if ( ! old_shared . is_identical_to ( UnwrapSharedFunctionInfoFromJSValue ( <nl> - Handle < JSValue > : : cast ( old_element ) ) ) ) { <nl> - continue ; <nl> - } <nl> - <nl> - Handle < Object > new_element = <nl> - JSReceiver : : GetElement ( isolate , new_shared_array_ , i ) <nl> - . ToHandleChecked ( ) ; <nl> - if ( new_element - > IsUndefined ( isolate ) ) return false ; <nl> - Handle < SharedFunctionInfo > new_shared = <nl> - UnwrapSharedFunctionInfoFromJSValue ( <nl> - Handle < JSValue > : : cast ( new_element ) ) ; <nl> - if ( new_shared - > scope_info ( ) - > HasNewTarget ( ) ) { <nl> - SetElementSloppy ( <nl> - result_ , i , <nl> - Handle < Smi > ( <nl> - Smi : : FromInt ( <nl> - LiveEdit : : FUNCTION_BLOCKED_NO_NEW_TARGET_ON_RESTART ) , <nl> - isolate ) ) ; <nl> - return true ; <nl> - } <nl> - return false ; <nl> - } <nl> - return false ; <nl> + for ( const auto & mapping : unchanged ) { <nl> + function_data_map . AddInterestingLiteral ( script - > id ( ) , mapping . first , false ) ; <nl> } <nl> + Address restart_frame_fp = 0 ; <nl> + function_data_map . Fill ( isolate , & restart_frame_fp ) ; <nl> <nl> - void set_status ( LiveEdit : : FunctionPatchabilityStatus status ) { <nl> - Isolate * isolate = old_shared_array_ - > GetIsolate ( ) ; <nl> - int len = GetArrayLength ( old_shared_array_ ) ; <nl> - for ( int i = 0 ; i < len ; + + i ) { <nl> - Handle < Object > old_element = <nl> - JSReceiver : : GetElement ( isolate , result_ , i ) . ToHandleChecked ( ) ; <nl> - if ( ! old_element - > IsSmi ( ) | | <nl> - Smi : : ToInt ( * old_element ) = = LiveEdit : : FUNCTION_AVAILABLE_FOR_PATCH ) { <nl> - SetElementSloppy ( result_ , i , <nl> - Handle < Smi > ( Smi : : FromInt ( status ) , isolate ) ) ; <nl> - } <nl> - } <nl> + if ( ! CanPatchScript ( changed , script , new_script , function_data_map , result ) ) { <nl> + return ; <nl> + } <nl> + if ( restart_frame_fp & & <nl> + ! CanRestartFrame ( isolate , restart_frame_fp , function_data_map , changed , <nl> + result ) ) { <nl> + return ; <nl> } <nl> <nl> - private : <nl> - Handle < JSArray > old_shared_array_ ; <nl> - Handle < JSArray > new_shared_array_ ; <nl> - Handle < JSArray > result_ ; <nl> - } ; <nl> + if ( preview ) { <nl> + result - > status = debug : : LiveEditResult : : OK ; <nl> + return ; <nl> + } <nl> <nl> + for ( const auto & mapping : unchanged ) { <nl> + FunctionData * data = nullptr ; <nl> + if ( ! function_data_map . Lookup ( script , mapping . first , & data ) ) continue ; <nl> + Handle < SharedFunctionInfo > sfi ; <nl> + if ( ! data - > shared . ToHandle ( & sfi ) ) continue ; <nl> <nl> - / / Drops all call frame matched by target and all frames above them . <nl> - template < typename TARGET > <nl> - static const char * DropActivationsInActiveThreadImpl ( Isolate * isolate , <nl> - TARGET & target , / / NOLINT <nl> - bool do_drop ) { <nl> - Debug * debug = isolate - > debug ( ) ; <nl> - Zone zone ( isolate - > allocator ( ) , ZONE_NAME ) ; <nl> - Vector < StackFrame * > frames = CreateStackMap ( isolate , & zone ) ; <nl> - <nl> - int top_frame_index = - 1 ; <nl> - int frame_index = 0 ; <nl> - for ( ; frame_index < frames . length ( ) ; frame_index + + ) { <nl> - StackFrame * frame = frames [ frame_index ] ; <nl> - if ( frame - > id ( ) = = debug - > break_frame_id ( ) ) { <nl> - top_frame_index = frame_index ; <nl> - break ; <nl> + isolate - > compilation_cache ( ) - > Remove ( sfi ) ; <nl> + isolate - > debug ( ) - > DeoptimizeFunction ( sfi ) ; <nl> + if ( sfi - > HasDebugInfo ( ) ) { <nl> + Handle < DebugInfo > debug_info ( sfi - > GetDebugInfo ( ) , isolate ) ; <nl> + isolate - > debug ( ) - > RemoveBreakInfoAndMaybeFree ( debug_info ) ; <nl> } <nl> - if ( target . MatchActivation ( <nl> - frame , LiveEdit : : FUNCTION_BLOCKED_UNDER_NATIVE_CODE ) ) { <nl> - / / We are still above break_frame . It is not a target frame , <nl> - / / it is a problem . <nl> - return " Debugger mark - up on stack is not found " ; <nl> - } <nl> - } <nl> + UpdatePositions ( isolate , sfi , diffs ) ; <nl> <nl> - if ( top_frame_index = = - 1 ) { <nl> - / / We haven ' t found break frame , but no function is blocking us anyway . <nl> - return target . GetNotFoundMessage ( ) ; <nl> - } <nl> + sfi - > set_function_literal_id ( mapping . second - > function_literal_id ( ) ) ; <nl> + sfi - > set_script ( * new_script ) ; <nl> + Handle < WeakFixedArray > new_script_sfis = <nl> + handle ( new_script - > shared_function_infos ( ) , isolate ) ; <nl> + new_script_sfis - > Set ( mapping . second - > function_literal_id ( ) , <nl> + HeapObjectReference : : Weak ( * sfi ) ) ; <nl> <nl> - bool target_frame_found = false ; <nl> - int bottom_js_frame_index = top_frame_index ; <nl> - bool non_droppable_frame_found = false ; <nl> - LiveEdit : : FunctionPatchabilityStatus non_droppable_reason ; <nl> + if ( sfi - > HasPreParsedScopeData ( ) ) sfi - > ClearPreParsedScopeData ( ) ; <nl> <nl> - for ( ; frame_index < frames . length ( ) ; frame_index + + ) { <nl> - StackFrame * frame = frames [ frame_index ] ; <nl> - if ( frame - > is_exit ( ) | | frame - > is_builtin_exit ( ) ) { <nl> - non_droppable_frame_found = true ; <nl> - non_droppable_reason = LiveEdit : : FUNCTION_BLOCKED_UNDER_NATIVE_CODE ; <nl> - break ; <nl> + for ( auto & js_function : data - > js_functions ) { <nl> + js_function - > set_feedback_cell ( * isolate - > factory ( ) - > many_closures_cell ( ) ) ; <nl> + if ( ! js_function - > is_compiled ( ) ) continue ; <nl> + JSFunction : : EnsureFeedbackVector ( js_function ) ; <nl> } <nl> - if ( frame - > is_java_script ( ) ) { <nl> - SharedFunctionInfo * shared = <nl> - JavaScriptFrame : : cast ( frame ) - > function ( ) - > shared ( ) ; <nl> - if ( IsResumableFunction ( shared - > kind ( ) ) ) { <nl> - non_droppable_frame_found = true ; <nl> - non_droppable_reason = LiveEdit : : FUNCTION_BLOCKED_UNDER_GENERATOR ; <nl> - break ; <nl> - } <nl> - } <nl> - if ( target . MatchActivation ( <nl> - frame , LiveEdit : : FUNCTION_BLOCKED_ON_ACTIVE_STACK ) ) { <nl> - target_frame_found = true ; <nl> - bottom_js_frame_index = frame_index ; <nl> - } <nl> - } <nl> <nl> - if ( non_droppable_frame_found ) { <nl> - / / There is a C or generator frame on stack . We can ' t drop C frames , and we <nl> - / / can ' t restart generators . Check that there are no target frames below <nl> - / / them . <nl> - for ( ; frame_index < frames . length ( ) ; frame_index + + ) { <nl> - StackFrame * frame = frames [ frame_index ] ; <nl> - if ( frame - > is_java_script ( ) ) { <nl> - if ( target . MatchActivation ( frame , non_droppable_reason ) ) { <nl> - / / Fail . <nl> - return nullptr ; <nl> - } <nl> - if ( non_droppable_reason = = <nl> - LiveEdit : : FUNCTION_BLOCKED_UNDER_GENERATOR & & <nl> - ! target_frame_found ) { <nl> - / / Fail . <nl> - target . set_status ( non_droppable_reason ) ; <nl> - return nullptr ; <nl> - } <nl> + if ( ! sfi - > HasBytecodeArray ( ) ) continue ; <nl> + Handle < BytecodeArray > bytecode ( sfi - > GetBytecodeArray ( ) , isolate ) ; <nl> + Handle < FixedArray > constants ( bytecode - > constant_pool ( ) , isolate ) ; <nl> + for ( int i = 0 ; i < constants - > length ( ) ; + + i ) { <nl> + if ( ! constants - > get ( i ) - > IsSharedFunctionInfo ( ) ) continue ; <nl> + FunctionData * data = nullptr ; <nl> + if ( ! function_data_map . Lookup ( SharedFunctionInfo : : cast ( constants - > get ( i ) ) , <nl> + & data ) ) { <nl> + continue ; <nl> } <nl> + auto change_it = changed . find ( data - > literal ) ; <nl> + if ( change_it = = changed . end ( ) ) continue ; <nl> + if ( ! function_data_map . Lookup ( new_script , change_it - > second , & data ) ) { <nl> + continue ; <nl> + } <nl> + Handle < SharedFunctionInfo > new_sfi ; <nl> + if ( ! data - > shared . ToHandle ( & new_sfi ) ) continue ; <nl> + constants - > set ( i , * new_sfi ) ; <nl> } <nl> } <nl> + for ( const auto & mapping : changed ) { <nl> + FunctionData * data = nullptr ; <nl> + if ( ! function_data_map . Lookup ( new_script , mapping . second , & data ) ) continue ; <nl> + Handle < SharedFunctionInfo > new_sfi = data - > shared . ToHandleChecked ( ) ; <nl> <nl> - / / We cannot restart a frame that uses new . target . <nl> - if ( target . FrameUsesNewTarget ( frames [ bottom_js_frame_index ] ) ) return nullptr ; <nl> - <nl> - if ( ! do_drop ) { <nl> - / / We are in check - only mode . <nl> - return nullptr ; <nl> - } <nl> - <nl> - if ( ! target_frame_found ) { <nl> - / / Nothing to drop . <nl> - return target . GetNotFoundMessage ( ) ; <nl> - } <nl> - <nl> - if ( ! LiveEdit : : kFrameDropperSupported ) { <nl> - return " Stack manipulations are not supported in this architecture . " ; <nl> - } <nl> - <nl> - debug - > ScheduleFrameRestart ( frames [ bottom_js_frame_index ] ) ; <nl> - return nullptr ; <nl> - } <nl> - <nl> + if ( ! function_data_map . Lookup ( script , mapping . first , & data ) ) continue ; <nl> + Handle < SharedFunctionInfo > sfi ; <nl> + if ( ! data - > shared . ToHandle ( & sfi ) ) continue ; <nl> <nl> - / / Fills result array with statuses of functions . Modifies the stack <nl> - / / removing all listed function if possible and if do_drop is true . <nl> - static const char * DropActivationsInActiveThread ( <nl> - Handle < JSArray > old_shared_array , Handle < JSArray > new_shared_array , <nl> - Handle < JSArray > result , bool do_drop ) { <nl> - MultipleFunctionTarget target ( old_shared_array , new_shared_array , result ) ; <nl> - Isolate * isolate = old_shared_array - > GetIsolate ( ) ; <nl> + isolate - > debug ( ) - > DeoptimizeFunction ( sfi ) ; <nl> + isolate - > compilation_cache ( ) - > Remove ( sfi ) ; <nl> + for ( auto & js_function : data - > js_functions ) { <nl> + js_function - > set_shared ( * new_sfi ) ; <nl> + js_function - > set_code ( js_function - > shared ( ) - > GetCode ( ) ) ; <nl> <nl> - const char * message = <nl> - DropActivationsInActiveThreadImpl ( isolate , target , do_drop ) ; <nl> - if ( message ) { <nl> - return message ; <nl> - } <nl> - <nl> - int array_len = GetArrayLength ( old_shared_array ) ; <nl> - <nl> - / / Replace " blocked on active " with " replaced on active " status . <nl> - for ( int i = 0 ; i < array_len ; i + + ) { <nl> - Handle < Object > obj = <nl> - JSReceiver : : GetElement ( isolate , result , i ) . ToHandleChecked ( ) ; <nl> - if ( * obj = = Smi : : FromInt ( LiveEdit : : FUNCTION_BLOCKED_ON_ACTIVE_STACK ) ) { <nl> - Handle < Object > replaced ( <nl> - Smi : : FromInt ( LiveEdit : : FUNCTION_REPLACED_ON_ACTIVE_STACK ) , isolate ) ; <nl> - SetElementSloppy ( result , i , replaced ) ; <nl> + js_function - > set_feedback_cell ( * isolate - > factory ( ) - > many_closures_cell ( ) ) ; <nl> + if ( ! js_function - > is_compiled ( ) ) continue ; <nl> + JSFunction : : EnsureFeedbackVector ( js_function ) ; <nl> } <nl> } <nl> - return nullptr ; <nl> - } <nl> - <nl> - bool LiveEdit : : FindActiveGenerators ( Isolate * isolate , <nl> - Handle < FixedArray > shared_info_array , <nl> - Handle < FixedArray > result , int len ) { <nl> - bool found_suspended_activations = false ; <nl> - <nl> - DCHECK_LE ( len , result - > length ( ) ) ; <nl> - <nl> - FunctionPatchabilityStatus active = FUNCTION_BLOCKED_ACTIVE_GENERATOR ; <nl> <nl> - Heap * heap = isolate - > heap ( ) ; <nl> - HeapIterator iterator ( heap , HeapIterator : : kFilterUnreachable ) ; <nl> - HeapObject * obj = nullptr ; <nl> - while ( ( obj = iterator . next ( ) ) ! = nullptr ) { <nl> - if ( ! obj - > IsJSGeneratorObject ( ) ) continue ; <nl> - <nl> - JSGeneratorObject * gen = JSGeneratorObject : : cast ( obj ) ; <nl> - if ( gen - > is_closed ( ) ) continue ; <nl> - <nl> - HandleScope scope ( isolate ) ; <nl> - <nl> - for ( int i = 0 ; i < len ; i + + ) { <nl> - Handle < JSValue > jsvalue = Handle < JSValue > : : cast ( <nl> - FixedArray : : get ( * shared_info_array , i , isolate ) ) ; <nl> - Handle < SharedFunctionInfo > shared = <nl> - UnwrapSharedFunctionInfoFromJSValue ( jsvalue ) ; <nl> - <nl> - if ( gen - > function ( ) - > shared ( ) = = * shared ) { <nl> - result - > set ( i , Smi : : FromInt ( active ) ) ; <nl> - found_suspended_activations = true ; <nl> + if ( restart_frame_fp ) { <nl> + for ( StackFrameIterator it ( isolate ) ; ! it . done ( ) ; it . Advance ( ) ) { <nl> + if ( it . frame ( ) - > fp ( ) = = restart_frame_fp ) { <nl> + isolate - > debug ( ) - > ScheduleFrameRestart ( it . frame ( ) ) ; <nl> + result - > stack_changed = true ; <nl> + break ; <nl> } <nl> } <nl> } <nl> <nl> - return found_suspended_activations ; <nl> + int script_id = script - > id ( ) ; <nl> + script - > set_id ( new_script - > id ( ) ) ; <nl> + new_script - > set_id ( script_id ) ; <nl> + result - > status = debug : : LiveEditResult : : OK ; <nl> + result - > script = ToApiHandle < v8 : : debug : : Script > ( new_script ) ; <nl> } <nl> <nl> - <nl> - class InactiveThreadActivationsChecker : public ThreadVisitor { <nl> - public : <nl> - InactiveThreadActivationsChecker ( Handle < JSArray > old_shared_array , <nl> - Handle < JSArray > result ) <nl> - : old_shared_array_ ( old_shared_array ) , <nl> - result_ ( result ) , <nl> - has_blocked_functions_ ( false ) { } <nl> - void VisitThread ( Isolate * isolate , ThreadLocalTop * top ) { <nl> - for ( StackFrameIterator it ( isolate , top ) ; ! it . done ( ) ; it . Advance ( ) ) { <nl> - has_blocked_functions_ | = <nl> - CheckActivation ( old_shared_array_ , result_ , it . frame ( ) , <nl> - LiveEdit : : FUNCTION_BLOCKED_ON_OTHER_STACK ) ; <nl> - } <nl> - } <nl> - bool HasBlockedFunctions ( ) { <nl> - return has_blocked_functions_ ; <nl> - } <nl> - <nl> - private : <nl> - Handle < JSArray > old_shared_array_ ; <nl> - Handle < JSArray > result_ ; <nl> - bool has_blocked_functions_ ; <nl> - } ; <nl> - <nl> - <nl> - Handle < JSArray > LiveEdit : : CheckAndDropActivations ( <nl> - Handle < JSArray > old_shared_array , Handle < JSArray > new_shared_array , <nl> - bool do_drop ) { <nl> - Isolate * isolate = old_shared_array - > GetIsolate ( ) ; <nl> - int len = GetArrayLength ( old_shared_array ) ; <nl> - <nl> - DCHECK ( old_shared_array - > HasFastElements ( ) ) ; <nl> - Handle < FixedArray > old_shared_array_elements ( <nl> - FixedArray : : cast ( old_shared_array - > elements ( ) ) , isolate ) ; <nl> - <nl> - Handle < JSArray > result = isolate - > factory ( ) - > NewJSArray ( len ) ; <nl> - result - > set_length ( Smi : : FromInt ( len ) ) ; <nl> - JSObject : : EnsureWritableFastElements ( result ) ; <nl> - Handle < FixedArray > result_elements = <nl> - handle ( FixedArray : : cast ( result - > elements ( ) ) , isolate ) ; <nl> - <nl> - / / Fill the default values . <nl> - for ( int i = 0 ; i < len ; i + + ) { <nl> - FunctionPatchabilityStatus status = FUNCTION_AVAILABLE_FOR_PATCH ; <nl> - result_elements - > set ( i , Smi : : FromInt ( status ) ) ; <nl> - } <nl> - <nl> - / / Scan the heap for active generators - - those that are either currently <nl> - / / running ( as we wouldn ' t want to restart them , because we don ' t know where <nl> - / / to restart them from ) or suspended . Fail if any one corresponds to the set <nl> - / / of functions being edited . <nl> - if ( FindActiveGenerators ( isolate , old_shared_array_elements , result_elements , <nl> - len ) ) { <nl> - return result ; <nl> - } <nl> - <nl> - / / Check inactive threads . Fail if some functions are blocked there . <nl> - InactiveThreadActivationsChecker inactive_threads_checker ( old_shared_array , <nl> - result ) ; <nl> - isolate - > thread_manager ( ) - > IterateArchivedThreads ( <nl> - & inactive_threads_checker ) ; <nl> - if ( inactive_threads_checker . HasBlockedFunctions ( ) ) { <nl> - return result ; <nl> - } <nl> - <nl> - / / Try to drop activations from the current stack . <nl> - const char * error_message = DropActivationsInActiveThread ( <nl> - old_shared_array , new_shared_array , result , do_drop ) ; <nl> - if ( error_message ! = nullptr ) { <nl> - / / Add error message as an array extra element . <nl> - Handle < String > str = <nl> - isolate - > factory ( ) - > NewStringFromAsciiChecked ( error_message ) ; <nl> - SetElementSloppy ( result , len , str ) ; <nl> - } <nl> - return result ; <nl> + void LiveEdit : : InitializeThreadLocal ( Debug * debug ) { <nl> + debug - > thread_local_ . restart_fp_ = 0 ; <nl> } <nl> <nl> bool LiveEdit : : RestartFrame ( JavaScriptFrame * frame ) { <nl> if ( ! LiveEdit : : kFrameDropperSupported ) return false ; <nl> Isolate * isolate = frame - > isolate ( ) ; <nl> - Zone zone ( isolate - > allocator ( ) , ZONE_NAME ) ; <nl> - Vector < StackFrame * > frames = CreateStackMap ( isolate , & zone ) ; <nl> StackFrame : : Id break_frame_id = isolate - > debug ( ) - > break_frame_id ( ) ; <nl> bool break_frame_found = break_frame_id = = StackFrame : : NO_ID ; <nl> - for ( StackFrame * current : frames ) { <nl> + for ( StackFrameIterator it ( isolate ) ; ! it . done ( ) ; it . Advance ( ) ) { <nl> + StackFrame * current = it . frame ( ) ; <nl> break_frame_found = break_frame_found | | break_frame_id = = current - > id ( ) ; <nl> if ( current - > fp ( ) = = frame - > fp ( ) ) { <nl> if ( break_frame_found ) { <nl> bool LiveEdit : : RestartFrame ( JavaScriptFrame * frame ) { <nl> return false ; <nl> } <nl> <nl> - Handle < JSArray > LiveEditFunctionTracker : : Collect ( FunctionLiteral * node , <nl> - Handle < Script > script , <nl> - Zone * zone , Isolate * isolate ) { <nl> - LiveEditFunctionTracker visitor ( script , zone , isolate ) ; <nl> - visitor . VisitFunctionLiteral ( node ) ; <nl> - return visitor . result_ ; <nl> - } <nl> - <nl> - LiveEditFunctionTracker : : LiveEditFunctionTracker ( Handle < Script > script , <nl> - Zone * zone , Isolate * isolate ) <nl> - : AstTraversalVisitor < LiveEditFunctionTracker > ( isolate ) { <nl> - current_parent_index_ = - 1 ; <nl> - isolate_ = isolate ; <nl> - len_ = 0 ; <nl> - result_ = isolate - > factory ( ) - > NewJSArray ( 10 ) ; <nl> - script_ = script ; <nl> - zone_ = zone ; <nl> - } <nl> - <nl> - void LiveEditFunctionTracker : : VisitFunctionLiteral ( FunctionLiteral * node ) { <nl> - / / FunctionStarted is called in pre - order . <nl> - FunctionStarted ( node ) ; <nl> - / / Recurse using the regular traversal . <nl> - AstTraversalVisitor : : VisitFunctionLiteral ( node ) ; <nl> - / / FunctionDone are called in post - order . <nl> - Handle < SharedFunctionInfo > info = <nl> - script_ - > FindSharedFunctionInfo ( isolate_ , node ) . ToHandleChecked ( ) ; <nl> - FunctionDone ( info , node - > scope ( ) ) ; <nl> - } <nl> - <nl> - void LiveEditFunctionTracker : : FunctionStarted ( FunctionLiteral * fun ) { <nl> - HandleScope handle_scope ( isolate_ ) ; <nl> - FunctionInfoWrapper info = FunctionInfoWrapper : : Create ( isolate_ ) ; <nl> - info . SetInitialProperties ( fun - > name ( isolate_ ) , fun - > start_position ( ) , <nl> - fun - > end_position ( ) , fun - > parameter_count ( ) , <nl> - current_parent_index_ , fun - > function_literal_id ( ) ) ; <nl> - current_parent_index_ = len_ ; <nl> - SetElementSloppy ( result_ , len_ , info . GetJSArray ( ) ) ; <nl> - len_ + + ; <nl> - } <nl> - <nl> - / / Saves full information about a function : its code , its scope info <nl> - / / and a SharedFunctionInfo object . <nl> - void LiveEditFunctionTracker : : FunctionDone ( Handle < SharedFunctionInfo > shared , <nl> - Scope * scope ) { <nl> - HandleScope handle_scope ( isolate_ ) ; <nl> - FunctionInfoWrapper info = FunctionInfoWrapper : : cast ( <nl> - * JSReceiver : : GetElement ( isolate_ , result_ , current_parent_index_ ) <nl> - . ToHandleChecked ( ) ) ; <nl> - info . SetSharedFunctionInfo ( isolate_ , shared ) ; <nl> - <nl> - Handle < Object > scope_info_list = SerializeFunctionScope ( scope ) ; <nl> - info . SetFunctionScopeInfo ( scope_info_list ) ; <nl> - <nl> - current_parent_index_ = info . GetParentIndex ( ) ; <nl> - } <nl> - <nl> - Handle < Object > LiveEditFunctionTracker : : SerializeFunctionScope ( Scope * scope ) { <nl> - Handle < JSArray > scope_info_list = isolate_ - > factory ( ) - > NewJSArray ( 10 ) ; <nl> - int scope_info_length = 0 ; <nl> - <nl> - / / Saves some description of scope . It stores name and indexes of <nl> - / / variables in the whole scope chain . Null - named slots delimit <nl> - / / scopes of this chain . <nl> - Scope * current_scope = scope ; <nl> - while ( current_scope ! = nullptr ) { <nl> - HandleScope handle_scope ( isolate_ ) ; <nl> - for ( Variable * var : * current_scope - > locals ( ) ) { <nl> - if ( ! var - > IsContextSlot ( ) ) continue ; <nl> - int context_index = var - > index ( ) - Context : : MIN_CONTEXT_SLOTS ; <nl> - int location = scope_info_length + context_index * 2 ; <nl> - SetElementSloppy ( scope_info_list , location , var - > name ( ) ) ; <nl> - SetElementSloppy ( scope_info_list , location + 1 , <nl> - handle ( Smi : : FromInt ( var - > index ( ) ) , isolate_ ) ) ; <nl> - } <nl> - scope_info_length + = current_scope - > ContextLocalCount ( ) * 2 ; <nl> - SetElementSloppy ( scope_info_list , scope_info_length , <nl> - isolate_ - > factory ( ) - > null_value ( ) ) ; <nl> - scope_info_length + + ; <nl> - <nl> - current_scope = current_scope - > outer_scope ( ) ; <nl> - } <nl> - <nl> - return scope_info_list ; <nl> - } <nl> - <nl> void LiveEdit : : CompareStrings ( Isolate * isolate , Handle < String > s1 , <nl> Handle < String > s2 , <nl> - std : : vector < SourceChangeRange > * changes ) { <nl> + std : : vector < SourceChangeRange > * diffs ) { <nl> s1 = String : : Flatten ( isolate , s1 ) ; <nl> s2 = String : : Flatten ( isolate , s2 ) ; <nl> <nl> void LiveEdit : : CompareStrings ( Isolate * isolate , Handle < String > s1 , <nl> <nl> LineArrayCompareInput input ( s1 , s2 , line_ends1 , line_ends2 ) ; <nl> TokenizingLineArrayCompareOutput output ( isolate , line_ends1 , line_ends2 , s1 , <nl> - s2 , changes ) ; <nl> + s2 , diffs ) ; <nl> <nl> NarrowDownInput ( & input , & output ) ; <nl> <nl> Comparator : : CalculateDifference ( & input , & output ) ; <nl> } <nl> <nl> - int LiveEdit : : TranslatePosition ( const std : : vector < SourceChangeRange > & changes , <nl> + int LiveEdit : : TranslatePosition ( const std : : vector < SourceChangeRange > & diffs , <nl> int position ) { <nl> - auto it = std : : lower_bound ( changes . begin ( ) , changes . end ( ) , position , <nl> + auto it = std : : lower_bound ( diffs . begin ( ) , diffs . end ( ) , position , <nl> [ ] ( const SourceChangeRange & change , int position ) { <nl> return change . end_position < position ; <nl> } ) ; <nl> - if ( it ! = changes . end ( ) & & position = = it - > end_position ) { <nl> + if ( it ! = diffs . end ( ) & & position = = it - > end_position ) { <nl> return it - > new_end_position ; <nl> } <nl> - if ( it = = changes . begin ( ) ) return position ; <nl> - DCHECK ( it = = changes . end ( ) | | position < = it - > start_position ) ; <nl> + if ( it = = diffs . begin ( ) ) return position ; <nl> + DCHECK ( it = = diffs . end ( ) | | position < = it - > start_position ) ; <nl> it = std : : prev ( it ) ; <nl> return position + ( it - > new_end_position - it - > end_position ) ; <nl> } <nl> - <nl> - void LiveEdit : : PatchScript ( Handle < Script > script , Handle < String > new_source , <nl> - debug : : LiveEditResult * result ) { <nl> - script - > GetIsolate ( ) - > debug ( ) - > SetScriptSource ( script , new_source , false , <nl> - result ) ; <nl> - } <nl> } / / namespace internal <nl> } / / namespace v8 <nl> mmm a / src / debug / liveedit . h <nl> ppp b / src / debug / liveedit . h <nl> <nl> # ifndef V8_DEBUG_LIVEEDIT_H_ <nl> # define V8_DEBUG_LIVEEDIT_H_ <nl> <nl> + # include < vector > <nl> <nl> - / / Live Edit feature implementation . <nl> - / / User should be able to change script on already running VM . This feature <nl> - / / matches hot swap features in other frameworks . <nl> - / / <nl> - / / The basic use - case is when user spots some mistake in function body <nl> - / / from debugger and wishes to change the algorithm without restart . <nl> - / / <nl> - / / A single change always has a form of a simple replacement ( in pseudo - code ) : <nl> - / / script . source [ positions , positions + length ] = new_string ; <nl> - / / Implementation first determines , which function ' s body includes this <nl> - / / change area . Then both old and new versions of script are fully compiled <nl> - / / in order to analyze , whether the function changed its outer scope <nl> - / / expectations ( or number of parameters ) . If it didn ' t , function ' s code is <nl> - / / patched with a newly compiled code . If it did change , enclosing function <nl> - / / gets patched . All inner functions are left untouched , whatever happened <nl> - / / to them in a new script version . However , new version of code will <nl> - / / instantiate newly compiled functions . <nl> - <nl> - <nl> - # include " src / allocation . h " <nl> - # include " src / ast / ast - traversal - visitor . h " <nl> + # include " src / globals . h " <nl> + # include " src / handles . h " <nl> <nl> namespace v8 { <nl> namespace debug { <nl> struct LiveEditResult ; <nl> } <nl> namespace internal { <nl> <nl> + class Script ; <nl> + class String ; <nl> + class Debug ; <nl> class JavaScriptFrame ; <nl> <nl> struct SourceChangeRange { <nl> struct SourceChangeRange { <nl> int new_end_position ; <nl> } ; <nl> <nl> - / / This class collects some specific information on structure of functions <nl> - / / in a particular script . <nl> - / / <nl> - / / The primary interest of the Tracker is to record function scope structures <nl> - / / in order to analyze whether function code may be safely patched ( with new <nl> - / / code successfully reading existing data from function scopes ) . The Tracker <nl> - / / also collects compiled function codes . <nl> - class LiveEditFunctionTracker <nl> - : public AstTraversalVisitor < LiveEditFunctionTracker > { <nl> - public : <nl> - / / Traverses the entire AST , and records information about all <nl> - / / FunctionLiterals for further use by LiveEdit code patching . The collected <nl> - / / information is returned as a serialized array . <nl> - static Handle < JSArray > Collect ( FunctionLiteral * node , Handle < Script > script , <nl> - Zone * zone , Isolate * isolate ) ; <nl> - <nl> - protected : <nl> - friend AstTraversalVisitor < LiveEditFunctionTracker > ; <nl> - void VisitFunctionLiteral ( FunctionLiteral * node ) ; <nl> - <nl> - private : <nl> - LiveEditFunctionTracker ( Handle < Script > script , Zone * zone , Isolate * isolate ) ; <nl> - <nl> - void FunctionStarted ( FunctionLiteral * fun ) ; <nl> - void FunctionDone ( Handle < SharedFunctionInfo > shared , Scope * scope ) ; <nl> - Handle < Object > SerializeFunctionScope ( Scope * scope ) ; <nl> - <nl> - Handle < Script > script_ ; <nl> - Zone * zone_ ; <nl> - Isolate * isolate_ ; <nl> - <nl> - Handle < JSArray > result_ ; <nl> - int len_ ; <nl> - int current_parent_index_ ; <nl> - <nl> - DISALLOW_COPY_AND_ASSIGN ( LiveEditFunctionTracker ) ; <nl> - } ; <nl> + / * * <nl> + Liveedit step - by - step : <nl> + 1 . calculate diff between old source and new source , <nl> + 2 . map function literals from old source to new source , <nl> + 3 . create new script for new_source , <nl> + 4 . mark literals with changed code as changed , all others as unchanged , <nl> + 5 . check that for changed literals there are no : <nl> + - running generators in the heap , <nl> + - non droppable frames ( e . g . running generator ) above them on stack . <nl> + 6 . mark the bottom most frame with changed function as scheduled for restart <nl> + if any , <nl> + 7 . for unchanged functions : <nl> + - deoptimize , <nl> + - remove from cache , <nl> + - update source positions , <nl> + - move to new script , <nl> + - reset feedback information and preparsed scope information if any , <nl> + - replace any sfi in constant pool with changed one if any . <nl> + 8 . for changed functions : <nl> + - deoptimize <nl> + - remove from cache , <nl> + - reset feedback information , <nl> + - update all links from js functions to old shared with new one . <nl> + 9 . swap scripts . <nl> + * / <nl> <nl> class LiveEdit : AllStatic { <nl> public : <nl> static void InitializeThreadLocal ( Debug * debug ) ; <nl> <nl> - V8_WARN_UNUSED_RESULT static MaybeHandle < JSArray > GatherCompileInfo ( <nl> - Isolate * isolate , Handle < Script > script , Handle < String > source ) ; <nl> - <nl> - static void ReplaceFunctionCode ( Handle < JSArray > new_compile_info_array , <nl> - Handle < JSArray > shared_info_array ) ; <nl> - <nl> - static void FixupScript ( Isolate * isolate , Handle < Script > script , <nl> - int max_function_literal_id ) ; <nl> - <nl> - static void FunctionSourceUpdated ( Handle < JSArray > shared_info_array , <nl> - int new_function_literal_id ) ; <nl> - <nl> - / / Updates script field in FunctionSharedInfo . <nl> - static void SetFunctionScript ( Handle < JSValue > function_wrapper , <nl> - Handle < Object > script_handle ) ; <nl> - <nl> - static void PatchFunctionPositions ( Handle < JSArray > shared_info_array , <nl> - Handle < JSArray > position_change_array ) ; <nl> - <nl> - / / For a script updates its source field . If old_script_name is provided <nl> - / / ( i . e . is a String ) , also creates a copy of the script with its original <nl> - / / source and sends notification to debugger . <nl> - static Handle < Object > ChangeScriptSource ( Isolate * isolate , <nl> - Handle < Script > original_script , <nl> - Handle < String > new_source , <nl> - Handle < Object > old_script_name ) ; <nl> - <nl> - / / In a code of a parent function replaces original function as embedded <nl> - / / object with a substitution one . <nl> - static void ReplaceRefToNestedFunction ( Heap * heap , <nl> - Handle < JSValue > parent_function_shared , <nl> - Handle < JSValue > orig_function_shared , <nl> - Handle < JSValue > subst_function_shared ) ; <nl> - <nl> - / / Find open generator activations , and set corresponding " result " elements to <nl> - / / FUNCTION_BLOCKED_ACTIVE_GENERATOR . <nl> - static bool FindActiveGenerators ( Isolate * isolate , <nl> - Handle < FixedArray > shared_info_array , <nl> - Handle < FixedArray > result , int len ) ; <nl> - <nl> - / / Checks listed functions on stack and return array with corresponding <nl> - / / FunctionPatchabilityStatus statuses ; extra array element may <nl> - / / contain general error message . Modifies the current stack and <nl> - / / has restart the lowest found frames and drops all other frames above <nl> - / / if possible and if do_drop is true . <nl> - static Handle < JSArray > CheckAndDropActivations ( <nl> - Handle < JSArray > old_shared_array , Handle < JSArray > new_shared_array , <nl> - bool do_drop ) ; <nl> - <nl> / / Restarts the call frame and completely drops all frames above it . <nl> static bool RestartFrame ( JavaScriptFrame * frame ) ; <nl> <nl> static void CompareStrings ( Isolate * isolate , Handle < String > a , <nl> Handle < String > b , <nl> - std : : vector < SourceChangeRange > * changes ) ; <nl> + std : : vector < SourceChangeRange > * diffs ) ; <nl> static int TranslatePosition ( const std : : vector < SourceChangeRange > & changed , <nl> int position ) ; <nl> - static void PatchScript ( Handle < Script > script , Handle < String > source , <nl> + static void PatchScript ( Isolate * isolate , Handle < Script > script , <nl> + Handle < String > source , bool preview , <nl> debug : : LiveEditResult * result ) ; <nl> - <nl> - / / A copy of this is in liveedit . js . <nl> - enum FunctionPatchabilityStatus { <nl> - FUNCTION_AVAILABLE_FOR_PATCH = 1 , <nl> - FUNCTION_BLOCKED_ON_ACTIVE_STACK = 2 , <nl> - FUNCTION_BLOCKED_ON_OTHER_STACK = 3 , <nl> - FUNCTION_BLOCKED_UNDER_NATIVE_CODE = 4 , <nl> - FUNCTION_REPLACED_ON_ACTIVE_STACK = 5 , <nl> - FUNCTION_BLOCKED_UNDER_GENERATOR = 6 , <nl> - FUNCTION_BLOCKED_ACTIVE_GENERATOR = 7 , <nl> - FUNCTION_BLOCKED_NO_NEW_TARGET_ON_RESTART = 8 <nl> - } ; <nl> - <nl> - / / Compares 2 strings line - by - line , then token - wise and returns diff in form <nl> - / / of array of triplets ( pos1 , pos1_end , pos2_end ) describing list <nl> - / / of diff chunks . <nl> - static Handle < JSArray > CompareStrings ( Isolate * isolate , Handle < String > s1 , <nl> - Handle < String > s2 ) ; <nl> - <nl> / / Architecture - specific constant . <nl> static const bool kFrameDropperSupported ; <nl> } ; <nl> - <nl> - / / Simple helper class that creates more or less typed structures over <nl> - / / JSArray object . This is an adhoc method of passing structures from C + + <nl> - / / to JavaScript . <nl> - template < typename S > <nl> - class JSArrayBasedStruct { <nl> - public : <nl> - static S Create ( Isolate * isolate ) { <nl> - Factory * factory = isolate - > factory ( ) ; <nl> - Handle < JSArray > array = factory - > NewJSArray ( S : : kSize_ ) ; <nl> - return S ( array ) ; <nl> - } <nl> - <nl> - static S cast ( Object * object ) { <nl> - JSArray * array = JSArray : : cast ( object ) ; <nl> - Handle < JSArray > array_handle ( array , array - > GetIsolate ( ) ) ; <nl> - return S ( array_handle ) ; <nl> - } <nl> - <nl> - explicit JSArrayBasedStruct ( Handle < JSArray > array ) : array_ ( array ) { <nl> - } <nl> - <nl> - Handle < JSArray > GetJSArray ( ) { <nl> - return array_ ; <nl> - } <nl> - <nl> - Isolate * isolate ( ) const { <nl> - return array_ - > GetIsolate ( ) ; <nl> - } <nl> - <nl> - protected : <nl> - void SetField ( int field_position , Handle < Object > value ) { <nl> - Object : : SetElement ( isolate ( ) , array_ , field_position , value , <nl> - LanguageMode : : kSloppy ) <nl> - . Assert ( ) ; <nl> - } <nl> - <nl> - void SetSmiValueField ( int field_position , int value ) { <nl> - SetField ( field_position , Handle < Smi > ( Smi : : FromInt ( value ) , isolate ( ) ) ) ; <nl> - } <nl> - <nl> - Handle < Object > GetField ( int field_position ) { <nl> - return JSReceiver : : GetElement ( isolate ( ) , array_ , field_position ) <nl> - . ToHandleChecked ( ) ; <nl> - } <nl> - <nl> - int GetSmiValueField ( int field_position ) { <nl> - Handle < Object > res = GetField ( field_position ) ; <nl> - return Handle < Smi > : : cast ( res ) - > value ( ) ; <nl> - } <nl> - <nl> - private : <nl> - Handle < JSArray > array_ ; <nl> - } ; <nl> - <nl> - <nl> - / / Represents some function compilation details . This structure will be used <nl> - / / from JavaScript . It contains Code object , which is kept wrapped <nl> - / / into a BlindReference for sanitizing reasons . <nl> - class FunctionInfoWrapper : public JSArrayBasedStruct < FunctionInfoWrapper > { <nl> - public : <nl> - explicit FunctionInfoWrapper ( Handle < JSArray > array ) <nl> - : JSArrayBasedStruct < FunctionInfoWrapper > ( array ) { <nl> - } <nl> - <nl> - void SetInitialProperties ( Handle < String > name , int start_position , <nl> - int end_position , int param_num , int parent_index , <nl> - int function_literal_id ) ; <nl> - <nl> - void SetFunctionScopeInfo ( Handle < Object > scope_info_array ) { <nl> - this - > SetField ( kFunctionScopeInfoOffset_ , scope_info_array ) ; <nl> - } <nl> - <nl> - void SetSharedFunctionInfo ( Isolate * isolate , Handle < SharedFunctionInfo > info ) ; <nl> - <nl> - Handle < SharedFunctionInfo > GetSharedFunctionInfo ( ) ; <nl> - <nl> - int GetParentIndex ( ) { <nl> - return this - > GetSmiValueField ( kParentIndexOffset_ ) ; <nl> - } <nl> - <nl> - int GetStartPosition ( ) { <nl> - return this - > GetSmiValueField ( kStartPositionOffset_ ) ; <nl> - } <nl> - <nl> - int GetEndPosition ( ) { return this - > GetSmiValueField ( kEndPositionOffset_ ) ; } <nl> - <nl> - private : <nl> - static const int kFunctionNameOffset_ = 0 ; <nl> - static const int kStartPositionOffset_ = 1 ; <nl> - static const int kEndPositionOffset_ = 2 ; <nl> - static const int kParamNumOffset_ = 3 ; <nl> - static const int kFunctionScopeInfoOffset_ = 4 ; <nl> - static const int kParentIndexOffset_ = 5 ; <nl> - static const int kSharedFunctionInfoOffset_ = 6 ; <nl> - static const int kFunctionLiteralIdOffset_ = 7 ; <nl> - static const int kSize_ = 8 ; <nl> - <nl> - friend class JSArrayBasedStruct < FunctionInfoWrapper > ; <nl> - } ; <nl> - <nl> - <nl> - / / Wraps SharedFunctionInfo along with some of its fields for passing it <nl> - / / back to JavaScript . SharedFunctionInfo object itself is additionally <nl> - / / wrapped into BlindReference for sanitizing reasons . <nl> - class SharedInfoWrapper : public JSArrayBasedStruct < SharedInfoWrapper > { <nl> - public : <nl> - static bool IsInstance ( Handle < JSArray > array ) { <nl> - if ( array - > length ( ) ! = Smi : : FromInt ( kSize_ ) ) return false ; <nl> - Handle < Object > element ( <nl> - JSReceiver : : GetElement ( array - > GetIsolate ( ) , array , kSharedInfoOffset_ ) <nl> - . ToHandleChecked ( ) ) ; <nl> - if ( ! element - > IsJSValue ( ) ) return false ; <nl> - return Handle < JSValue > : : cast ( element ) - > value ( ) - > IsSharedFunctionInfo ( ) ; <nl> - } <nl> - <nl> - explicit SharedInfoWrapper ( Handle < JSArray > array ) <nl> - : JSArrayBasedStruct < SharedInfoWrapper > ( array ) { <nl> - } <nl> - <nl> - void SetProperties ( Handle < String > name , <nl> - int start_position , <nl> - int end_position , <nl> - Handle < SharedFunctionInfo > info ) ; <nl> - <nl> - Handle < SharedFunctionInfo > GetInfo ( ) ; <nl> - <nl> - private : <nl> - static const int kFunctionNameOffset_ = 0 ; <nl> - static const int kStartPositionOffset_ = 1 ; <nl> - static const int kEndPositionOffset_ = 2 ; <nl> - static const int kSharedInfoOffset_ = 3 ; <nl> - static const int kSize_ = 4 ; <nl> - <nl> - friend class JSArrayBasedStruct < SharedInfoWrapper > ; <nl> - } ; <nl> - <nl> } / / namespace internal <nl> } / / namespace v8 <nl> <nl> deleted file mode 100644 <nl> index 79255674c39 . . 00000000000 <nl> mmm a / src / debug / liveedit . js <nl> ppp / dev / null <nl> <nl> - / / Copyright 2012 the V8 project authors . All rights reserved . <nl> - / / Use of this source code is governed by a BSD - style license that can be <nl> - / / found in the LICENSE file . <nl> - <nl> - / / LiveEdit feature implementation . The script should be executed after <nl> - / / debug . js . <nl> - <nl> - / / A LiveEdit namespace . It contains functions that modifies JavaScript code <nl> - / / according to changes of script source ( if possible ) . <nl> - / / <nl> - / / When new script source is put in , the difference is calculated textually , <nl> - / / in form of list of delete / add / change chunks . The functions that include <nl> - / / change chunk ( s ) get recompiled , or their enclosing functions are <nl> - / / recompiled instead . <nl> - / / If the function may not be recompiled ( e . g . it was completely erased in new <nl> - / / version of the script ) it remains unchanged , but the code that could <nl> - / / create a new instance of this function goes away . An old version of script <nl> - / / is created to back up this obsolete function . <nl> - / / All unchanged functions have their positions updated accordingly . <nl> - / / <nl> - / / LiveEdit namespace is declared inside a single function constructor . <nl> - <nl> - ( function ( global , utils ) { <nl> - " use strict " ; <nl> - <nl> - / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - <nl> - / / Imports <nl> - <nl> - var GlobalArray = global . Array ; <nl> - var MathFloor = global . Math . floor ; <nl> - var MathMax = global . Math . max ; <nl> - var SyntaxError = global . SyntaxError ; <nl> - <nl> - / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - <nl> - <nl> - function FindScriptSourcePosition ( script , opt_line , opt_column ) { <nl> - var location = % ScriptLocationFromLine ( script , opt_line , opt_column , 0 ) ; <nl> - return location ? location . position : null ; <nl> - } ; <nl> - <nl> - / / Forward declaration for minifier . <nl> - var FunctionStatus ; <nl> - <nl> - / / Applies the change to the script . <nl> - / / The change is in form of list of chunks encoded in a single array as <nl> - / / a series of triplets ( pos1_start , pos1_end , pos2_end ) <nl> - function ApplyPatchMultiChunk ( script , diff_array , new_source , preview_only , <nl> - change_log ) { <nl> - <nl> - var old_source = script . source ; <nl> - <nl> - / / Gather compile information about old version of script . <nl> - var old_compile_info = GatherCompileInfo ( old_source , script ) ; <nl> - <nl> - / / Build tree structures for old and new versions of the script . <nl> - var root_old_node = BuildCodeInfoTree ( old_compile_info ) ; <nl> - <nl> - var pos_translator = new PosTranslator ( diff_array ) ; <nl> - <nl> - / / Analyze changes . <nl> - MarkChangedFunctions ( root_old_node , pos_translator . GetChunks ( ) ) ; <nl> - <nl> - / / Find all SharedFunctionInfo ' s that were compiled from this script . <nl> - FindLiveSharedInfos ( root_old_node , script ) ; <nl> - <nl> - / / Gather compile information about new version of script . <nl> - var new_compile_info ; <nl> - try { <nl> - new_compile_info = GatherCompileInfo ( new_source , script ) ; <nl> - } catch ( e ) { <nl> - var failure = <nl> - new Failure ( " Failed to compile new version of script : " + e ) ; <nl> - if ( e instanceof SyntaxError ) { <nl> - var details = { <nl> - type : " liveedit_compile_error " , <nl> - syntaxErrorMessage : e . message <nl> - } ; <nl> - CopyErrorPositionToDetails ( e , details ) ; <nl> - failure . details = details ; <nl> - } <nl> - throw failure ; <nl> - } <nl> - <nl> - var max_function_literal_id = new_compile_info . reduce ( <nl> - ( max , info ) = > MathMax ( max , info . function_literal_id ) , 0 ) ; <nl> - <nl> - var root_new_node = BuildCodeInfoTree ( new_compile_info ) ; <nl> - <nl> - / / Link recompiled script data with other data . <nl> - FindCorrespondingFunctions ( root_old_node , root_new_node ) ; <nl> - <nl> - / / Prepare to - do lists . <nl> - var replace_code_list = new GlobalArray ( ) ; <nl> - var link_to_old_script_list = new GlobalArray ( ) ; <nl> - var link_to_original_script_list = new GlobalArray ( ) ; <nl> - var update_positions_list = new GlobalArray ( ) ; <nl> - <nl> - function HarvestTodo ( old_node ) { <nl> - function CollectDamaged ( node ) { <nl> - link_to_old_script_list . push ( node ) ; <nl> - for ( var i = 0 ; i < node . children . length ; i + + ) { <nl> - CollectDamaged ( node . children [ i ] ) ; <nl> - } <nl> - } <nl> - <nl> - / / Recursively collects all newly compiled functions that are going into <nl> - / / business and should have link to the actual script updated . <nl> - function CollectNew ( node_list ) { <nl> - for ( var i = 0 ; i < node_list . length ; i + + ) { <nl> - link_to_original_script_list . push ( node_list [ i ] ) ; <nl> - CollectNew ( node_list [ i ] . children ) ; <nl> - } <nl> - } <nl> - <nl> - if ( old_node . status = = FunctionStatus . DAMAGED ) { <nl> - CollectDamaged ( old_node ) ; <nl> - return ; <nl> - } <nl> - if ( old_node . status = = FunctionStatus . UNCHANGED ) { <nl> - update_positions_list . push ( old_node ) ; <nl> - } else if ( old_node . status = = FunctionStatus . SOURCE_CHANGED ) { <nl> - update_positions_list . push ( old_node ) ; <nl> - } else if ( old_node . status = = FunctionStatus . CHANGED ) { <nl> - replace_code_list . push ( old_node ) ; <nl> - CollectNew ( old_node . unmatched_new_nodes ) ; <nl> - } <nl> - for ( var i = 0 ; i < old_node . children . length ; i + + ) { <nl> - HarvestTodo ( old_node . children [ i ] ) ; <nl> - } <nl> - } <nl> - <nl> - var preview_description = { <nl> - change_tree : DescribeChangeTree ( root_old_node ) , <nl> - textual_diff : { <nl> - old_len : old_source . length , <nl> - new_len : new_source . length , <nl> - chunks : diff_array <nl> - } , <nl> - updated : false <nl> - } ; <nl> - <nl> - if ( preview_only ) { <nl> - return preview_description ; <nl> - } <nl> - <nl> - HarvestTodo ( root_old_node ) ; <nl> - <nl> - / / Collect shared infos for functions whose code need to be patched . <nl> - var replaced_function_old_infos = new GlobalArray ( ) ; <nl> - var replaced_function_new_infos = new GlobalArray ( ) ; <nl> - for ( var i = 0 ; i < replace_code_list . length ; i + + ) { <nl> - var old_infos = replace_code_list [ i ] . live_shared_function_infos ; <nl> - var new_info = <nl> - replace_code_list [ i ] . corresponding_node . info . shared_function_info ; <nl> - <nl> - if ( old_infos ) { <nl> - for ( var j = 0 ; j < old_infos . length ; j + + ) { <nl> - replaced_function_old_infos . push ( old_infos [ j ] ) ; <nl> - replaced_function_new_infos . push ( new_info ) ; <nl> - } <nl> - } <nl> - } <nl> - <nl> - / / We haven ' t changed anything before this line yet . <nl> - / / Committing all changes . <nl> - <nl> - / / Check that function being patched is not currently on stack or drop them . <nl> - var dropped_functions_number = <nl> - CheckStackActivations ( replaced_function_old_infos , <nl> - replaced_function_new_infos , <nl> - change_log ) ; <nl> - <nl> - / / Our current implementation requires client to manually issue " step in " <nl> - / / command for correct stack state if the stack was modified . <nl> - preview_description . stack_modified = dropped_functions_number ! = 0 ; <nl> - <nl> - var old_script ; <nl> - <nl> - / / Create an old script only if there are function that should be linked <nl> - / / to old version . <nl> - if ( link_to_old_script_list . length = = 0 ) { <nl> - % LiveEditReplaceScript ( script , new_source , null ) ; <nl> - old_script = UNDEFINED ; <nl> - } else { <nl> - var old_script_name = CreateNameForOldScript ( script ) ; <nl> - <nl> - / / Update the script text and create a new script representing an old <nl> - / / version of the script . <nl> - old_script = % LiveEditReplaceScript ( script , new_source , old_script_name ) ; <nl> - <nl> - var link_to_old_script_report = new GlobalArray ( ) ; <nl> - change_log . push ( { linked_to_old_script : link_to_old_script_report } ) ; <nl> - <nl> - / / We need to link to old script all former nested functions . <nl> - for ( var i = 0 ; i < link_to_old_script_list . length ; i + + ) { <nl> - LinkToOldScript ( link_to_old_script_list [ i ] , old_script , <nl> - link_to_old_script_report ) ; <nl> - } <nl> - <nl> - preview_description . created_script_name = old_script_name ; <nl> - } <nl> - <nl> - for ( var i = 0 ; i < replace_code_list . length ; i + + ) { <nl> - PatchFunctionCode ( replace_code_list [ i ] , change_log ) ; <nl> - } <nl> - <nl> - var position_patch_report = new GlobalArray ( ) ; <nl> - change_log . push ( { position_patched : position_patch_report } ) ; <nl> - <nl> - for ( var i = 0 ; i < update_positions_list . length ; i + + ) { <nl> - / / TODO ( LiveEdit ) : take into account whether it ' s source_changed or <nl> - / / unchanged and whether positions changed at all . <nl> - PatchPositions ( update_positions_list [ i ] , diff_array , <nl> - position_patch_report ) ; <nl> - <nl> - if ( update_positions_list [ i ] . live_shared_function_infos ) { <nl> - var new_function_literal_id = <nl> - update_positions_list [ i ] <nl> - . corresponding_node . info . function_literal_id ; <nl> - update_positions_list [ i ] . live_shared_function_infos . forEach ( function ( <nl> - info ) { <nl> - % LiveEditFunctionSourceUpdated ( <nl> - info . raw_array , new_function_literal_id ) ; <nl> - } ) ; <nl> - } <nl> - } <nl> - <nl> - % LiveEditFixupScript ( script , max_function_literal_id ) ; <nl> - <nl> - / / Link all the functions we ' re going to use to an actual script . <nl> - for ( var i = 0 ; i < link_to_original_script_list . length ; i + + ) { <nl> - % LiveEditFunctionSetScript ( <nl> - link_to_original_script_list [ i ] . info . shared_function_info , script ) ; <nl> - } <nl> - <nl> - preview_description . updated = true ; <nl> - return preview_description ; <nl> - } <nl> - <nl> - / / Fully compiles source string as a script . Returns Array of <nl> - / / FunctionCompileInfo - - a descriptions of all functions of the script . <nl> - / / Elements of array are ordered by start positions of functions ( from top <nl> - / / to bottom ) in the source . Fields outer_index and next_sibling_index help <nl> - / / to navigate the nesting structure of functions . <nl> - / / <nl> - / / All functions get compiled linked to script provided as parameter script . <nl> - / / TODO ( LiveEdit ) : consider not using actual scripts as script , because <nl> - / / we have to manually erase all links right after compile . <nl> - function GatherCompileInfo ( source , script ) { <nl> - / / Get function info , elements are partially sorted ( it is a tree of <nl> - / / nested functions serialized as parent followed by serialized children . <nl> - var raw_compile_info = % LiveEditGatherCompileInfo ( script , source ) ; <nl> - <nl> - / / Sort function infos by start position field . <nl> - var compile_info = new GlobalArray ( ) ; <nl> - var old_index_map = new GlobalArray ( ) ; <nl> - for ( var i = 0 ; i < raw_compile_info . length ; i + + ) { <nl> - var info = new FunctionCompileInfo ( raw_compile_info [ i ] ) ; <nl> - / / Remove all links to the actual script . Breakpoints system and <nl> - / / LiveEdit itself believe that any function in heap that points to a <nl> - / / particular script is a regular function . <nl> - / / For some functions we will restore this link later . <nl> - % LiveEditFunctionSetScript ( info . shared_function_info , UNDEFINED ) ; <nl> - compile_info . push ( info ) ; <nl> - old_index_map . push ( i ) ; <nl> - } <nl> - <nl> - for ( var i = 0 ; i < compile_info . length ; i + + ) { <nl> - var k = i ; <nl> - for ( var j = i + 1 ; j < compile_info . length ; j + + ) { <nl> - if ( compile_info [ k ] . start_position > compile_info [ j ] . start_position ) { <nl> - k = j ; <nl> - } <nl> - } <nl> - if ( k ! = i ) { <nl> - var temp_info = compile_info [ k ] ; <nl> - var temp_index = old_index_map [ k ] ; <nl> - compile_info [ k ] = compile_info [ i ] ; <nl> - old_index_map [ k ] = old_index_map [ i ] ; <nl> - compile_info [ i ] = temp_info ; <nl> - old_index_map [ i ] = temp_index ; <nl> - } <nl> - } <nl> - <nl> - / / After sorting update outer_index field using old_index_map . Also <nl> - / / set next_sibling_index field . <nl> - var current_index = 0 ; <nl> - <nl> - / / The recursive function , that goes over all children of a particular <nl> - / / node ( i . e . function info ) . <nl> - function ResetIndexes ( new_parent_index , old_parent_index ) { <nl> - var previous_sibling = - 1 ; <nl> - while ( current_index < compile_info . length & & <nl> - compile_info [ current_index ] . outer_index = = old_parent_index ) { <nl> - var saved_index = current_index ; <nl> - compile_info [ saved_index ] . outer_index = new_parent_index ; <nl> - if ( previous_sibling ! = - 1 ) { <nl> - compile_info [ previous_sibling ] . next_sibling_index = saved_index ; <nl> - } <nl> - previous_sibling = saved_index ; <nl> - current_index + + ; <nl> - ResetIndexes ( saved_index , old_index_map [ saved_index ] ) ; <nl> - } <nl> - if ( previous_sibling ! = - 1 ) { <nl> - compile_info [ previous_sibling ] . next_sibling_index = - 1 ; <nl> - } <nl> - } <nl> - <nl> - ResetIndexes ( - 1 , - 1 ) ; <nl> - Assert ( current_index = = compile_info . length ) ; <nl> - <nl> - return compile_info ; <nl> - } <nl> - <nl> - <nl> - / / Replaces function ' s Code . <nl> - function PatchFunctionCode ( old_node , change_log ) { <nl> - var new_info = old_node . corresponding_node . info ; <nl> - if ( old_node . live_shared_function_infos ) { <nl> - old_node . live_shared_function_infos . forEach ( function ( old_info ) { <nl> - % LiveEditReplaceFunctionCode ( new_info . raw_array , <nl> - old_info . raw_array ) ; <nl> - <nl> - / / The function got a new code . However , this new code brings all new <nl> - / / instances of SharedFunctionInfo for nested functions . However , <nl> - / / we want the original instances to be used wherever possible . <nl> - / / ( This is because old instances and new instances will be both <nl> - / / linked to a script and breakpoints subsystem does not really <nl> - / / expects this ; neither does LiveEdit subsystem on next call ) . <nl> - for ( var i = 0 ; i < old_node . children . length ; i + + ) { <nl> - if ( old_node . children [ i ] . corresponding_node ) { <nl> - var corresponding_child_info = <nl> - old_node . children [ i ] . corresponding_node . info . <nl> - shared_function_info ; <nl> - <nl> - if ( old_node . children [ i ] . live_shared_function_infos ) { <nl> - old_node . children [ i ] . live_shared_function_infos . <nl> - forEach ( function ( old_child_info ) { <nl> - % LiveEditReplaceRefToNestedFunction ( <nl> - old_info . info , <nl> - corresponding_child_info , <nl> - old_child_info . info ) ; <nl> - } ) ; <nl> - } <nl> - } <nl> - } <nl> - } ) ; <nl> - <nl> - change_log . push ( { function_patched : new_info . function_name } ) ; <nl> - } else { <nl> - change_log . push ( { function_patched : new_info . function_name , <nl> - function_info_not_found : true } ) ; <nl> - } <nl> - } <nl> - <nl> - <nl> - / / Makes a function associated with another instance of a script ( the <nl> - / / one representing its old version ) . This way the function still <nl> - / / may access its own text . <nl> - function LinkToOldScript ( old_info_node , old_script , report_array ) { <nl> - if ( old_info_node . live_shared_function_infos ) { <nl> - old_info_node . live_shared_function_infos . <nl> - forEach ( function ( info ) { <nl> - % LiveEditFunctionSetScript ( info . info , old_script ) ; <nl> - } ) ; <nl> - <nl> - report_array . push ( { name : old_info_node . info . function_name } ) ; <nl> - } else { <nl> - report_array . push ( <nl> - { name : old_info_node . info . function_name , not_found : true } ) ; <nl> - } <nl> - } <nl> - <nl> - function Assert ( condition , message ) { <nl> - if ( ! condition ) { <nl> - if ( message ) { <nl> - throw " Assert " + message ; <nl> - } else { <nl> - throw " Assert " ; <nl> - } <nl> - } <nl> - } <nl> - <nl> - function DiffChunk ( pos1 , pos2 , len1 , len2 ) { <nl> - this . pos1 = pos1 ; <nl> - this . pos2 = pos2 ; <nl> - this . len1 = len1 ; <nl> - this . len2 = len2 ; <nl> - } <nl> - <nl> - function PosTranslator ( diff_array ) { <nl> - var chunks = new GlobalArray ( ) ; <nl> - var current_diff = 0 ; <nl> - for ( var i = 0 ; i < diff_array . length ; i + = 3 ) { <nl> - var pos1_begin = diff_array [ i ] ; <nl> - var pos2_begin = pos1_begin + current_diff ; <nl> - var pos1_end = diff_array [ i + 1 ] ; <nl> - var pos2_end = diff_array [ i + 2 ] ; <nl> - chunks . push ( new DiffChunk ( pos1_begin , pos2_begin , pos1_end - pos1_begin , <nl> - pos2_end - pos2_begin ) ) ; <nl> - current_diff = pos2_end - pos1_end ; <nl> - } <nl> - this . chunks = chunks ; <nl> - } <nl> - PosTranslator . prototype . GetChunks = function ( ) { <nl> - return this . chunks ; <nl> - } ; <nl> - <nl> - PosTranslator . prototype . Translate = function ( pos , inside_chunk_handler ) { <nl> - var array = this . chunks ; <nl> - if ( array . length = = 0 | | pos < array [ 0 ] . pos1 ) { <nl> - return pos ; <nl> - } <nl> - var chunk_index1 = 0 ; <nl> - var chunk_index2 = array . length - 1 ; <nl> - <nl> - while ( chunk_index1 < chunk_index2 ) { <nl> - var middle_index = MathFloor ( ( chunk_index1 + chunk_index2 ) / 2 ) ; <nl> - if ( pos < array [ middle_index + 1 ] . pos1 ) { <nl> - chunk_index2 = middle_index ; <nl> - } else { <nl> - chunk_index1 = middle_index + 1 ; <nl> - } <nl> - } <nl> - var chunk = array [ chunk_index1 ] ; <nl> - if ( pos > = chunk . pos1 + chunk . len1 ) { <nl> - return pos + chunk . pos2 + chunk . len2 - chunk . pos1 - chunk . len1 ; <nl> - } <nl> - <nl> - if ( ! inside_chunk_handler ) { <nl> - inside_chunk_handler = PosTranslator . DefaultInsideChunkHandler ; <nl> - } <nl> - return inside_chunk_handler ( pos , chunk ) ; <nl> - } ; <nl> - <nl> - PosTranslator . DefaultInsideChunkHandler = function ( pos , diff_chunk ) { <nl> - Assert ( false , " Cannot translate position in changed area " ) ; <nl> - } ; <nl> - <nl> - PosTranslator . ShiftWithTopInsideChunkHandler = <nl> - function ( pos , diff_chunk ) { <nl> - / / We carelessly do not check whether we stay inside the chunk after <nl> - / / translation . <nl> - return pos - diff_chunk . pos1 + diff_chunk . pos2 ; <nl> - } ; <nl> - <nl> - var FunctionStatus = { <nl> - / / No change to function or its inner functions ; however its positions <nl> - / / in script may have been shifted . <nl> - UNCHANGED : " unchanged " , <nl> - / / The code of a function remains unchanged , but something happened inside <nl> - / / some inner functions . <nl> - SOURCE_CHANGED : " source changed " , <nl> - / / The code of a function is changed or some nested function cannot be <nl> - / / properly patched so this function must be recompiled . <nl> - CHANGED : " changed " , <nl> - / / Function is changed but cannot be patched . <nl> - DAMAGED : " damaged " <nl> - } ; <nl> - <nl> - function CodeInfoTreeNode ( code_info , children , array_index ) { <nl> - this . info = code_info ; <nl> - this . children = children ; <nl> - / / an index in array of compile_info <nl> - this . array_index = array_index ; <nl> - this . parent = UNDEFINED ; <nl> - <nl> - this . status = FunctionStatus . UNCHANGED ; <nl> - / / Status explanation is used for debugging purposes and will be shown <nl> - / / in user UI if some explanations are needed . <nl> - this . status_explanation = UNDEFINED ; <nl> - this . new_start_pos = UNDEFINED ; <nl> - this . new_end_pos = UNDEFINED ; <nl> - this . corresponding_node = UNDEFINED ; <nl> - this . unmatched_new_nodes = UNDEFINED ; <nl> - <nl> - / / ' Textual ' correspondence / matching is weaker than ' pure ' <nl> - / / correspondence / matching . We need ' textual ' level for visual presentation <nl> - / / in UI , we use ' pure ' level for actual code manipulation . <nl> - / / Sometimes only function body is changed ( functions in old and new script <nl> - / / textually correspond ) , but we cannot patch the code , so we see them <nl> - / / as an old function deleted and new function created . <nl> - this . textual_corresponding_node = UNDEFINED ; <nl> - this . textually_unmatched_new_nodes = UNDEFINED ; <nl> - <nl> - this . live_shared_function_infos = UNDEFINED ; <nl> - } <nl> - <nl> - / / From array of function infos that is implicitly a tree creates <nl> - / / an actual tree of functions in script . <nl> - function BuildCodeInfoTree ( code_info_array ) { <nl> - / / Throughtout all function we iterate over input array . <nl> - var index = 0 ; <nl> - <nl> - / / Recursive function that builds a branch of tree . <nl> - function BuildNode ( ) { <nl> - var my_index = index ; <nl> - index + + ; <nl> - var child_array = new GlobalArray ( ) ; <nl> - while ( index < code_info_array . length & & <nl> - code_info_array [ index ] . outer_index = = my_index ) { <nl> - child_array . push ( BuildNode ( ) ) ; <nl> - } <nl> - var node = new CodeInfoTreeNode ( code_info_array [ my_index ] , child_array , <nl> - my_index ) ; <nl> - for ( var i = 0 ; i < child_array . length ; i + + ) { <nl> - child_array [ i ] . parent = node ; <nl> - } <nl> - return node ; <nl> - } <nl> - <nl> - var root = BuildNode ( ) ; <nl> - Assert ( index = = code_info_array . length ) ; <nl> - return root ; <nl> - } <nl> - <nl> - / / Applies a list of the textual diff chunks onto the tree of functions . <nl> - / / Determines status of each function ( from unchanged to damaged ) . However <nl> - / / children of unchanged functions are ignored . <nl> - function MarkChangedFunctions ( code_info_tree , chunks ) { <nl> - <nl> - / / A convenient iterator over diff chunks that also translates <nl> - / / positions from old to new in a current non - changed part of script . <nl> - var chunk_it = new function ( ) { <nl> - var chunk_index = 0 ; <nl> - var pos_diff = 0 ; <nl> - this . current = function ( ) { return chunks [ chunk_index ] ; } ; <nl> - this . next = function ( ) { <nl> - var chunk = chunks [ chunk_index ] ; <nl> - pos_diff = chunk . pos2 + chunk . len2 - ( chunk . pos1 + chunk . len1 ) ; <nl> - chunk_index + + ; <nl> - } ; <nl> - this . done = function ( ) { return chunk_index > = chunks . length ; } ; <nl> - this . TranslatePos = function ( pos ) { return pos + pos_diff ; } ; <nl> - } ; <nl> - <nl> - / / A recursive function that processes internals of a function and all its <nl> - / / inner functions . Iterator chunk_it initially points to a chunk that is <nl> - / / below function start . <nl> - function ProcessInternals ( info_node ) { <nl> - info_node . new_start_pos = chunk_it . TranslatePos ( <nl> - info_node . info . start_position ) ; <nl> - var child_index = 0 ; <nl> - var code_changed = false ; <nl> - var source_changed = false ; <nl> - / / Simultaneously iterates over child functions and over chunks . <nl> - while ( ! chunk_it . done ( ) & & <nl> - chunk_it . current ( ) . pos1 < info_node . info . end_position ) { <nl> - if ( child_index < info_node . children . length ) { <nl> - var child = info_node . children [ child_index ] ; <nl> - <nl> - if ( child . info . end_position < = chunk_it . current ( ) . pos1 ) { <nl> - ProcessUnchangedChild ( child ) ; <nl> - child_index + + ; <nl> - continue ; <nl> - } else if ( child . info . start_position > = <nl> - chunk_it . current ( ) . pos1 + chunk_it . current ( ) . len1 ) { <nl> - code_changed = true ; <nl> - chunk_it . next ( ) ; <nl> - continue ; <nl> - } else if ( child . info . start_position < = chunk_it . current ( ) . pos1 & & <nl> - child . info . end_position > = chunk_it . current ( ) . pos1 + <nl> - chunk_it . current ( ) . len1 ) { <nl> - ProcessInternals ( child ) ; <nl> - source_changed = source_changed | | <nl> - ( child . status ! = FunctionStatus . UNCHANGED ) ; <nl> - code_changed = code_changed | | <nl> - ( child . status = = FunctionStatus . DAMAGED ) ; <nl> - child_index + + ; <nl> - continue ; <nl> - } else { <nl> - code_changed = true ; <nl> - child . status = FunctionStatus . DAMAGED ; <nl> - child . status_explanation = <nl> - " Text diff overlaps with function boundary " ; <nl> - child_index + + ; <nl> - continue ; <nl> - } <nl> - } else { <nl> - if ( chunk_it . current ( ) . pos1 + chunk_it . current ( ) . len1 < = <nl> - info_node . info . end_position ) { <nl> - info_node . status = FunctionStatus . CHANGED ; <nl> - chunk_it . next ( ) ; <nl> - continue ; <nl> - } else { <nl> - info_node . status = FunctionStatus . DAMAGED ; <nl> - info_node . status_explanation = <nl> - " Text diff overlaps with function boundary " ; <nl> - return ; <nl> - } <nl> - } <nl> - Assert ( " Unreachable " , false ) ; <nl> - } <nl> - while ( child_index < info_node . children . length ) { <nl> - var child = info_node . children [ child_index ] ; <nl> - ProcessUnchangedChild ( child ) ; <nl> - child_index + + ; <nl> - } <nl> - if ( code_changed ) { <nl> - info_node . status = FunctionStatus . CHANGED ; <nl> - } else if ( source_changed ) { <nl> - info_node . status = FunctionStatus . SOURCE_CHANGED ; <nl> - } <nl> - info_node . new_end_pos = <nl> - chunk_it . TranslatePos ( info_node . info . end_position ) ; <nl> - } <nl> - <nl> - function ProcessUnchangedChild ( node ) { <nl> - node . new_start_pos = chunk_it . TranslatePos ( node . info . start_position ) ; <nl> - node . new_end_pos = chunk_it . TranslatePos ( node . info . end_position ) ; <nl> - } <nl> - <nl> - ProcessInternals ( code_info_tree ) ; <nl> - } <nl> - <nl> - / / For each old function ( if it is not damaged ) tries to find a corresponding <nl> - / / function in new script . Typically it should succeed ( non - damaged functions <nl> - / / by definition may only have changes inside their bodies ) . However there are <nl> - / / reasons for correspondence not to be found ; function with unmodified text <nl> - / / in new script may become enclosed into other function ; the innocent change <nl> - / / inside function body may in fact be something like " } function B ( ) { " that <nl> - / / splits a function into 2 functions . <nl> - function FindCorrespondingFunctions ( old_code_tree , new_code_tree ) { <nl> - <nl> - / / A recursive function that tries to find a correspondence for all <nl> - / / child functions and for their inner functions . <nl> - function ProcessNode ( old_node , new_node ) { <nl> - var scope_change_description = <nl> - IsFunctionContextLocalsChanged ( old_node . info , new_node . info ) ; <nl> - if ( scope_change_description ) { <nl> - old_node . status = FunctionStatus . CHANGED ; <nl> - } <nl> - <nl> - var old_children = old_node . children ; <nl> - var new_children = new_node . children ; <nl> - <nl> - var unmatched_new_nodes_list = [ ] ; <nl> - var textually_unmatched_new_nodes_list = [ ] ; <nl> - <nl> - var old_index = 0 ; <nl> - var new_index = 0 ; <nl> - while ( old_index < old_children . length ) { <nl> - if ( old_children [ old_index ] . status = = FunctionStatus . DAMAGED ) { <nl> - old_index + + ; <nl> - } else if ( new_index < new_children . length ) { <nl> - if ( new_children [ new_index ] . info . start_position < <nl> - old_children [ old_index ] . new_start_pos ) { <nl> - unmatched_new_nodes_list . push ( new_children [ new_index ] ) ; <nl> - textually_unmatched_new_nodes_list . push ( new_children [ new_index ] ) ; <nl> - new_index + + ; <nl> - } else if ( new_children [ new_index ] . info . start_position = = <nl> - old_children [ old_index ] . new_start_pos ) { <nl> - if ( new_children [ new_index ] . info . end_position = = <nl> - old_children [ old_index ] . new_end_pos ) { <nl> - old_children [ old_index ] . corresponding_node = <nl> - new_children [ new_index ] ; <nl> - old_children [ old_index ] . textual_corresponding_node = <nl> - new_children [ new_index ] ; <nl> - if ( scope_change_description ) { <nl> - old_children [ old_index ] . status = FunctionStatus . DAMAGED ; <nl> - old_children [ old_index ] . status_explanation = <nl> - " Enclosing function is now incompatible . " + <nl> - scope_change_description ; <nl> - old_children [ old_index ] . corresponding_node = UNDEFINED ; <nl> - } else if ( old_children [ old_index ] . status ! = <nl> - FunctionStatus . UNCHANGED ) { <nl> - ProcessNode ( old_children [ old_index ] , <nl> - new_children [ new_index ] ) ; <nl> - if ( old_children [ old_index ] . status = = FunctionStatus . DAMAGED ) { <nl> - unmatched_new_nodes_list . push ( <nl> - old_children [ old_index ] . corresponding_node ) ; <nl> - old_children [ old_index ] . corresponding_node = UNDEFINED ; <nl> - old_node . status = FunctionStatus . CHANGED ; <nl> - } <nl> - } else { <nl> - ProcessNode ( old_children [ old_index ] , new_children [ new_index ] ) ; <nl> - } <nl> - } else { <nl> - old_children [ old_index ] . status = FunctionStatus . DAMAGED ; <nl> - old_children [ old_index ] . status_explanation = <nl> - " No corresponding function in new script found " ; <nl> - old_node . status = FunctionStatus . CHANGED ; <nl> - unmatched_new_nodes_list . push ( new_children [ new_index ] ) ; <nl> - textually_unmatched_new_nodes_list . push ( new_children [ new_index ] ) ; <nl> - } <nl> - new_index + + ; <nl> - old_index + + ; <nl> - } else { <nl> - old_children [ old_index ] . status = FunctionStatus . DAMAGED ; <nl> - old_children [ old_index ] . status_explanation = <nl> - " No corresponding function in new script found " ; <nl> - old_node . status = FunctionStatus . CHANGED ; <nl> - old_index + + ; <nl> - } <nl> - } else { <nl> - old_children [ old_index ] . status = FunctionStatus . DAMAGED ; <nl> - old_children [ old_index ] . status_explanation = <nl> - " No corresponding function in new script found " ; <nl> - old_node . status = FunctionStatus . CHANGED ; <nl> - old_index + + ; <nl> - } <nl> - } <nl> - <nl> - while ( new_index < new_children . length ) { <nl> - unmatched_new_nodes_list . push ( new_children [ new_index ] ) ; <nl> - textually_unmatched_new_nodes_list . push ( new_children [ new_index ] ) ; <nl> - new_index + + ; <nl> - } <nl> - <nl> - if ( old_node . status = = FunctionStatus . CHANGED ) { <nl> - if ( old_node . info . param_num ! = new_node . info . param_num ) { <nl> - old_node . status = FunctionStatus . DAMAGED ; <nl> - old_node . status_explanation = " Changed parameter number : " + <nl> - old_node . info . param_num + " and " + new_node . info . param_num ; <nl> - } <nl> - } <nl> - old_node . unmatched_new_nodes = unmatched_new_nodes_list ; <nl> - old_node . textually_unmatched_new_nodes = <nl> - textually_unmatched_new_nodes_list ; <nl> - } <nl> - <nl> - ProcessNode ( old_code_tree , new_code_tree ) ; <nl> - <nl> - old_code_tree . corresponding_node = new_code_tree ; <nl> - old_code_tree . textual_corresponding_node = new_code_tree ; <nl> - <nl> - Assert ( old_code_tree . status ! = FunctionStatus . DAMAGED , <nl> - " Script became damaged " ) ; <nl> - } <nl> - <nl> - function FindLiveSharedInfos ( old_code_tree , script ) { <nl> - var shared_raw_list = % LiveEditFindSharedFunctionInfosForScript ( script ) ; <nl> - <nl> - var shared_infos = new GlobalArray ( ) ; <nl> - <nl> - for ( var i = 0 ; i < shared_raw_list . length ; i + + ) { <nl> - shared_infos . push ( new SharedInfoWrapper ( shared_raw_list [ i ] ) ) ; <nl> - } <nl> - <nl> - / / Finds all SharedFunctionInfos that corresponds to compile info <nl> - / / in old version of the script . <nl> - function FindFunctionInfos ( compile_info ) { <nl> - var wrappers = [ ] ; <nl> - <nl> - for ( var i = 0 ; i < shared_infos . length ; i + + ) { <nl> - var wrapper = shared_infos [ i ] ; <nl> - if ( wrapper . start_position = = compile_info . start_position & & <nl> - wrapper . end_position = = compile_info . end_position ) { <nl> - wrappers . push ( wrapper ) ; <nl> - } <nl> - } <nl> - <nl> - if ( wrappers . length > 0 ) { <nl> - return wrappers ; <nl> - } <nl> - } <nl> - <nl> - function TraverseTree ( node ) { <nl> - node . live_shared_function_infos = FindFunctionInfos ( node . info ) ; <nl> - <nl> - for ( var i = 0 ; i < node . children . length ; i + + ) { <nl> - TraverseTree ( node . children [ i ] ) ; <nl> - } <nl> - } <nl> - <nl> - TraverseTree ( old_code_tree ) ; <nl> - } <nl> - <nl> - <nl> - / / An object describing function compilation details . Its index fields <nl> - / / apply to indexes inside array that stores these objects . <nl> - function FunctionCompileInfo ( raw_array ) { <nl> - this . function_name = raw_array [ 0 ] ; <nl> - this . start_position = raw_array [ 1 ] ; <nl> - this . end_position = raw_array [ 2 ] ; <nl> - this . param_num = raw_array [ 3 ] ; <nl> - this . scope_info = raw_array [ 4 ] ; <nl> - this . outer_index = raw_array [ 5 ] ; <nl> - this . shared_function_info = raw_array [ 6 ] ; <nl> - this . function_literal_id = raw_array [ 7 ] ; <nl> - this . next_sibling_index = null ; <nl> - this . raw_array = raw_array ; <nl> - } <nl> - <nl> - function SharedInfoWrapper ( raw_array ) { <nl> - this . function_name = raw_array [ 0 ] ; <nl> - this . start_position = raw_array [ 1 ] ; <nl> - this . end_position = raw_array [ 2 ] ; <nl> - this . info = raw_array [ 3 ] ; <nl> - this . raw_array = raw_array ; <nl> - } <nl> - <nl> - / / Changes positions ( including all statements ) in function . <nl> - function PatchPositions ( old_info_node , diff_array , report_array ) { <nl> - if ( old_info_node . live_shared_function_infos ) { <nl> - old_info_node . live_shared_function_infos . forEach ( function ( info ) { <nl> - % LiveEditPatchFunctionPositions ( info . raw_array , <nl> - diff_array ) ; <nl> - } ) ; <nl> - <nl> - report_array . push ( { name : old_info_node . info . function_name } ) ; <nl> - } else { <nl> - / / TODO ( LiveEdit ) : function is not compiled yet or is already collected . <nl> - report_array . push ( <nl> - { name : old_info_node . info . function_name , info_not_found : true } ) ; <nl> - } <nl> - } <nl> - <nl> - / / Adds a suffix to script name to mark that it is old version . <nl> - function CreateNameForOldScript ( script ) { <nl> - / / TODO ( 635 ) : try better than this ; support several changes . <nl> - return script . name + " ( old ) " ; <nl> - } <nl> - <nl> - / / Compares a function scope heap structure , old and new version , whether it <nl> - / / changed or not . Returns explanation if they differ . <nl> - function IsFunctionContextLocalsChanged ( function_info1 , function_info2 ) { <nl> - var scope_info1 = function_info1 . scope_info ; <nl> - var scope_info2 = function_info2 . scope_info ; <nl> - <nl> - var scope_info1_text ; <nl> - var scope_info2_text ; <nl> - <nl> - if ( scope_info1 ) { <nl> - scope_info1_text = scope_info1 . toString ( ) ; <nl> - } else { <nl> - scope_info1_text = " " ; <nl> - } <nl> - if ( scope_info2 ) { <nl> - scope_info2_text = scope_info2 . toString ( ) ; <nl> - } else { <nl> - scope_info2_text = " " ; <nl> - } <nl> - <nl> - if ( scope_info1_text ! = scope_info2_text ) { <nl> - return " Variable map changed : [ " + scope_info1_text + <nl> - " ] = > [ " + scope_info2_text + " ] " ; <nl> - } <nl> - / / No differences . Return undefined . <nl> - return ; <nl> - } <nl> - <nl> - / / Minifier forward declaration . <nl> - var FunctionPatchabilityStatus ; <nl> - <nl> - / / For array of wrapped shared function infos checks that none of them <nl> - / / have activations on stack ( of any thread ) . Throws a Failure exception <nl> - / / if this proves to be false . <nl> - function CheckStackActivations ( old_shared_wrapper_list , <nl> - new_shared_list , <nl> - change_log ) { <nl> - var old_shared_list = new GlobalArray ( ) ; <nl> - for ( var i = 0 ; i < old_shared_wrapper_list . length ; i + + ) { <nl> - old_shared_list [ i ] = old_shared_wrapper_list [ i ] . info ; <nl> - } <nl> - var result = % LiveEditCheckAndDropActivations ( <nl> - old_shared_list , new_shared_list , true ) ; <nl> - if ( result [ old_shared_wrapper_list . length ] ) { <nl> - / / Extra array element may contain error message . <nl> - throw new Failure ( result [ old_shared_wrapper_list . length ] ) ; <nl> - } <nl> - <nl> - var problems = new GlobalArray ( ) ; <nl> - var dropped = new GlobalArray ( ) ; <nl> - for ( var i = 0 ; i < old_shared_list . length ; i + + ) { <nl> - var shared = old_shared_wrapper_list [ i ] ; <nl> - if ( result [ i ] = = FunctionPatchabilityStatus . REPLACED_ON_ACTIVE_STACK ) { <nl> - dropped . push ( { name : shared . function_name } ) ; <nl> - } else if ( result [ i ] ! = FunctionPatchabilityStatus . AVAILABLE_FOR_PATCH ) { <nl> - var description = { <nl> - name : shared . function_name , <nl> - start_pos : shared . start_position , <nl> - end_pos : shared . end_position , <nl> - replace_problem : <nl> - FunctionPatchabilityStatus . SymbolName ( result [ i ] ) <nl> - } ; <nl> - problems . push ( description ) ; <nl> - } <nl> - } <nl> - if ( dropped . length > 0 ) { <nl> - change_log . push ( { dropped_from_stack : dropped } ) ; <nl> - } <nl> - if ( problems . length > 0 ) { <nl> - change_log . push ( { functions_on_stack : problems } ) ; <nl> - throw new Failure ( " Blocked by functions on stack " ) ; <nl> - } <nl> - <nl> - return dropped . length ; <nl> - } <nl> - <nl> - / / A copy of the FunctionPatchabilityStatus enum from liveedit . h <nl> - var FunctionPatchabilityStatus = { <nl> - AVAILABLE_FOR_PATCH : 1 , <nl> - BLOCKED_ON_ACTIVE_STACK : 2 , <nl> - BLOCKED_ON_OTHER_STACK : 3 , <nl> - BLOCKED_UNDER_NATIVE_CODE : 4 , <nl> - REPLACED_ON_ACTIVE_STACK : 5 , <nl> - BLOCKED_UNDER_GENERATOR : 6 , <nl> - BLOCKED_ACTIVE_GENERATOR : 7 , <nl> - BLOCKED_NO_NEW_TARGET_ON_RESTART : 8 <nl> - } ; <nl> - <nl> - FunctionPatchabilityStatus . SymbolName = function ( code ) { <nl> - var enumeration = FunctionPatchabilityStatus ; <nl> - for ( var name in enumeration ) { <nl> - if ( enumeration [ name ] = = code ) { <nl> - return name ; <nl> - } <nl> - } <nl> - } ; <nl> - <nl> - <nl> - / / A logical failure in liveedit process . This means that change_log <nl> - / / is valid and consistent description of what happened . <nl> - function Failure ( message ) { <nl> - this . message = message ; <nl> - } <nl> - <nl> - Failure . prototype . toString = function ( ) { <nl> - return " LiveEdit Failure : " + this . message ; <nl> - } ; <nl> - <nl> - function CopyErrorPositionToDetails ( e , details ) { <nl> - function createPositionStruct ( script , position ) { <nl> - if ( position = = - 1 ) return ; <nl> - var location = % ScriptPositionInfo ( script , position , true ) ; <nl> - if ( location = = null ) return ; <nl> - return { <nl> - line : location . line + 1 , <nl> - column : location . column + 1 , <nl> - position : position <nl> - } ; <nl> - } <nl> - <nl> - if ( ! ( " scriptObject " in e ) | | ! ( " startPosition " in e ) ) { <nl> - return ; <nl> - } <nl> - <nl> - var script = e . scriptObject ; <nl> - <nl> - var position_struct = { <nl> - start : createPositionStruct ( script , e . startPosition ) , <nl> - end : createPositionStruct ( script , e . endPosition ) <nl> - } ; <nl> - details . position = position_struct ; <nl> - } <nl> - <nl> - / / LiveEdit main entry point : changes a script text to a new string . <nl> - function SetScriptSource ( script , new_source , preview_only , change_log ) { <nl> - var old_source = script . source ; <nl> - var diff = CompareStrings ( old_source , new_source ) ; <nl> - return ApplyPatchMultiChunk ( script , diff , new_source , preview_only , <nl> - change_log ) ; <nl> - } <nl> - <nl> - function CompareStrings ( s1 , s2 ) { <nl> - return % LiveEditCompareStrings ( s1 , s2 ) ; <nl> - } <nl> - <nl> - / / Applies the change to the script . <nl> - / / The change is always a substring ( change_pos , change_pos + change_len ) <nl> - / / being replaced with a completely different string new_str . <nl> - / / This API is a legacy and is obsolete . <nl> - / / <nl> - / / @ param { Script } script that is being changed <nl> - / / @ param { Array } change_log a list that collects engineer - readable <nl> - / / description of what happened . <nl> - function ApplySingleChunkPatch ( script , change_pos , change_len , new_str , <nl> - change_log ) { <nl> - var old_source = script . source ; <nl> - <nl> - / / Prepare new source string . <nl> - var new_source = old_source . substring ( 0 , change_pos ) + <nl> - new_str + old_source . substring ( change_pos + change_len ) ; <nl> - <nl> - return ApplyPatchMultiChunk ( script , <nl> - [ change_pos , change_pos + change_len , change_pos + new_str . length ] , <nl> - new_source , false , change_log ) ; <nl> - } <nl> - <nl> - / / Creates JSON description for a change tree . <nl> - function DescribeChangeTree ( old_code_tree ) { <nl> - <nl> - function ProcessOldNode ( node ) { <nl> - var child_infos = [ ] ; <nl> - for ( var i = 0 ; i < node . children . length ; i + + ) { <nl> - var child = node . children [ i ] ; <nl> - if ( child . status ! = FunctionStatus . UNCHANGED ) { <nl> - child_infos . push ( ProcessOldNode ( child ) ) ; <nl> - } <nl> - } <nl> - var new_child_infos = [ ] ; <nl> - if ( node . textually_unmatched_new_nodes ) { <nl> - for ( var i = 0 ; i < node . textually_unmatched_new_nodes . length ; i + + ) { <nl> - var child = node . textually_unmatched_new_nodes [ i ] ; <nl> - new_child_infos . push ( ProcessNewNode ( child ) ) ; <nl> - } <nl> - } <nl> - var res = { <nl> - name : node . info . function_name , <nl> - positions : DescribePositions ( node ) , <nl> - status : node . status , <nl> - children : child_infos , <nl> - new_children : new_child_infos <nl> - } ; <nl> - if ( node . status_explanation ) { <nl> - res . status_explanation = node . status_explanation ; <nl> - } <nl> - if ( node . textual_corresponding_node ) { <nl> - res . new_positions = DescribePositions ( node . textual_corresponding_node ) ; <nl> - } <nl> - return res ; <nl> - } <nl> - <nl> - function ProcessNewNode ( node ) { <nl> - var child_infos = [ ] ; <nl> - / / Do not list ancestors . <nl> - if ( false ) { <nl> - for ( var i = 0 ; i < node . children . length ; i + + ) { <nl> - child_infos . push ( ProcessNewNode ( node . children [ i ] ) ) ; <nl> - } <nl> - } <nl> - var res = { <nl> - name : node . info . function_name , <nl> - positions : DescribePositions ( node ) , <nl> - children : child_infos , <nl> - } ; <nl> - return res ; <nl> - } <nl> - <nl> - function DescribePositions ( node ) { <nl> - return { <nl> - start_position : node . info . start_position , <nl> - end_position : node . info . end_position <nl> - } ; <nl> - } <nl> - <nl> - return ProcessOldNode ( old_code_tree ) ; <nl> - } <nl> - <nl> - / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - <nl> - / / Exports <nl> - <nl> - var LiveEdit = { } ; <nl> - LiveEdit . SetScriptSource = SetScriptSource ; <nl> - LiveEdit . ApplyPatchMultiChunk = ApplyPatchMultiChunk ; <nl> - LiveEdit . Failure = Failure ; <nl> - <nl> - LiveEdit . TestApi = { <nl> - PosTranslator : PosTranslator , <nl> - CompareStrings : CompareStrings , <nl> - ApplySingleChunkPatch : ApplySingleChunkPatch <nl> - } ; <nl> - <nl> - / / Functions needed by the debugger runtime . <nl> - utils . InstallConstants ( utils , [ <nl> - " SetScriptSource " , LiveEdit . SetScriptSource , <nl> - ] ) ; <nl> - utils . InstallConstants ( global , [ <nl> - " Debug " , { } , <nl> - ] ) ; <nl> - global . Debug . LiveEdit = LiveEdit ; <nl> - } ) <nl> mmm a / src / frames . cc <nl> ppp b / src / frames . cc <nl> InnerPointerToCodeCache : : InnerPointerToCodeCacheEntry * <nl> } <nl> return entry ; <nl> } <nl> - <nl> - <nl> - / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - <nl> - <nl> - <nl> - # define DEFINE_WRAPPER ( type , field ) \ <nl> - class field # # _Wrapper : public ZoneObject { \ <nl> - public : / * NOLINT * / \ <nl> - field # # _Wrapper ( const field & original ) : frame_ ( original ) { \ <nl> - } \ <nl> - field frame_ ; \ <nl> - } ; <nl> - STACK_FRAME_TYPE_LIST ( DEFINE_WRAPPER ) <nl> - # undef DEFINE_WRAPPER <nl> - <nl> - static StackFrame * AllocateFrameCopy ( StackFrame * frame , Zone * zone ) { <nl> - # define FRAME_TYPE_CASE ( type , field ) \ <nl> - case StackFrame : : type : { \ <nl> - field # # _Wrapper * wrapper = \ <nl> - new ( zone ) field # # _Wrapper ( * ( reinterpret_cast < field * > ( frame ) ) ) ; \ <nl> - return & wrapper - > frame_ ; \ <nl> - } <nl> - <nl> - switch ( frame - > type ( ) ) { <nl> - STACK_FRAME_TYPE_LIST ( FRAME_TYPE_CASE ) <nl> - default : UNREACHABLE ( ) ; <nl> - } <nl> - # undef FRAME_TYPE_CASE <nl> - return nullptr ; <nl> - } <nl> - <nl> - <nl> - Vector < StackFrame * > CreateStackMap ( Isolate * isolate , Zone * zone ) { <nl> - ZoneVector < StackFrame * > frames ( zone ) ; <nl> - for ( StackFrameIterator it ( isolate ) ; ! it . done ( ) ; it . Advance ( ) ) { <nl> - StackFrame * frame = AllocateFrameCopy ( it . frame ( ) , zone ) ; <nl> - frames . push_back ( frame ) ; <nl> - } <nl> - return Vector < StackFrame * > ( frames . data ( ) , frames . size ( ) ) ; <nl> - } <nl> - <nl> - <nl> } / / namespace internal <nl> } / / namespace v8 <nl> mmm a / src / frames . h <nl> ppp b / src / frames . h <nl> class SafeStackFrameIterator : public StackFrameIteratorBase { <nl> StackFrame : : Type top_frame_type_ ; <nl> ExternalCallbackScope * external_callback_scope_ ; <nl> } ; <nl> - <nl> - / / Reads all frames on the current stack and copies them into the current <nl> - / / zone memory . <nl> - Vector < StackFrame * > CreateStackMap ( Isolate * isolate , Zone * zone ) ; <nl> - <nl> } / / namespace internal <nl> } / / namespace v8 <nl> <nl> mmm a / src / heap / factory . cc <nl> ppp b / src / heap / factory . cc <nl> Handle < Script > Factory : : NewScriptWithId ( Handle < String > source , int script_id , <nl> return script ; <nl> } <nl> <nl> + Handle < Script > Factory : : CloneScript ( Handle < Script > script ) { <nl> + Heap * heap = isolate ( ) - > heap ( ) ; <nl> + int script_id = isolate ( ) - > heap ( ) - > NextScriptId ( ) ; <nl> + Handle < Script > new_script = <nl> + Handle < Script > : : cast ( NewStruct ( SCRIPT_TYPE , TENURED ) ) ; <nl> + new_script - > set_source ( script - > source ( ) ) ; <nl> + new_script - > set_name ( script - > name ( ) ) ; <nl> + new_script - > set_id ( script_id ) ; <nl> + new_script - > set_line_offset ( script - > line_offset ( ) ) ; <nl> + new_script - > set_column_offset ( script - > column_offset ( ) ) ; <nl> + new_script - > set_context_data ( script - > context_data ( ) ) ; <nl> + new_script - > set_type ( script - > type ( ) ) ; <nl> + new_script - > set_wrapper ( script - > wrapper ( ) ) ; <nl> + new_script - > set_line_ends ( heap - > undefined_value ( ) ) ; <nl> + new_script - > set_eval_from_shared_or_wrapped_arguments ( <nl> + script - > eval_from_shared_or_wrapped_arguments ( ) ) ; <nl> + new_script - > set_shared_function_infos ( * empty_weak_fixed_array ( ) , <nl> + SKIP_WRITE_BARRIER ) ; <nl> + new_script - > set_eval_from_position ( script - > eval_from_position ( ) ) ; <nl> + new_script - > set_flags ( script - > flags ( ) ) ; <nl> + new_script - > set_host_defined_options ( script - > host_defined_options ( ) ) ; <nl> + heap - > set_script_list ( <nl> + * FixedArrayOfWeakCells : : Add ( isolate ( ) , script_list ( ) , new_script ) ) ; <nl> + LOG ( isolate ( ) , ScriptEvent ( Logger : : ScriptEventType : : kCreate , script_id ) ) ; <nl> + return new_script ; <nl> + } <nl> + <nl> Handle < CallableTask > Factory : : NewCallableTask ( Handle < JSReceiver > callable , <nl> Handle < Context > context ) { <nl> DCHECK ( callable - > IsCallable ( ) ) ; <nl> mmm a / src / heap / factory . h <nl> ppp b / src / heap / factory . h <nl> class V8_EXPORT_PRIVATE Factory { <nl> PretenureFlag tenure = TENURED ) ; <nl> Handle < Script > NewScriptWithId ( Handle < String > source , int script_id , <nl> PretenureFlag tenure = TENURED ) ; <nl> + Handle < Script > CloneScript ( Handle < Script > script ) ; <nl> <nl> Handle < BreakPointInfo > NewBreakPointInfo ( int source_position ) ; <nl> Handle < BreakPoint > NewBreakPoint ( int id , Handle < String > condition ) ; <nl> mmm a / src / inspector / v8 - debugger - script . cc <nl> ppp b / src / inspector / v8 - debugger - script . cc <nl> class ActualScript : public V8DebuggerScript { <nl> : V8DebuggerScript ( isolate , String16 : : fromInteger ( script - > Id ( ) ) , <nl> GetNameOrSourceUrl ( script ) ) , <nl> m_isLiveEdit ( isLiveEdit ) { <nl> - v8 : : Local < v8 : : String > tmp ; <nl> - if ( script - > SourceURL ( ) . ToLocal ( & tmp ) ) m_sourceURL = toProtocolString ( tmp ) ; <nl> - if ( script - > SourceMappingURL ( ) . ToLocal ( & tmp ) ) <nl> - m_sourceMappingURL = toProtocolString ( tmp ) ; <nl> - m_startLine = script - > LineOffset ( ) ; <nl> - m_startColumn = script - > ColumnOffset ( ) ; <nl> - std : : vector < int > lineEnds = script - > LineEnds ( ) ; <nl> - CHECK ( lineEnds . size ( ) ) ; <nl> - int source_length = lineEnds [ lineEnds . size ( ) - 1 ] ; <nl> - if ( lineEnds . size ( ) ) { <nl> - m_endLine = static_cast < int > ( lineEnds . size ( ) ) + m_startLine - 1 ; <nl> - if ( lineEnds . size ( ) > 1 ) { <nl> - m_endColumn = source_length - lineEnds [ lineEnds . size ( ) - 2 ] - 1 ; <nl> - } else { <nl> - m_endColumn = source_length + m_startColumn ; <nl> - } <nl> - } else { <nl> - m_endLine = m_startLine ; <nl> - m_endColumn = m_startColumn ; <nl> - } <nl> - <nl> - USE ( script - > ContextId ( ) . To ( & m_executionContextId ) ) ; <nl> - <nl> - if ( script - > Source ( ) . ToLocal ( & tmp ) ) { <nl> - m_source = toProtocolString ( tmp ) ; <nl> - } <nl> - <nl> - m_isModule = script - > IsModule ( ) ; <nl> - <nl> - m_script . Reset ( m_isolate , script ) ; <nl> - m_script . AnnotateStrongRetainer ( kGlobalDebuggerScriptHandleLabel ) ; <nl> + Initialize ( script ) ; <nl> } <nl> <nl> bool isLiveEdit ( ) const override { return m_isLiveEdit ; } <nl> class ActualScript : public V8DebuggerScript { <nl> return ; <nl> } <nl> if ( preview ) return ; <nl> - m_source = newSource ; <nl> m_hash = String16 ( ) ; <nl> + Initialize ( scope . Escape ( result - > script ) ) ; <nl> } <nl> <nl> bool getPossibleBreakpoints ( <nl> class ActualScript : public V8DebuggerScript { <nl> return m_script . Get ( m_isolate ) ; <nl> } <nl> <nl> + void Initialize ( v8 : : Local < v8 : : debug : : Script > script ) { <nl> + v8 : : Local < v8 : : String > tmp ; <nl> + if ( script - > SourceURL ( ) . ToLocal ( & tmp ) ) m_sourceURL = toProtocolString ( tmp ) ; <nl> + if ( script - > SourceMappingURL ( ) . ToLocal ( & tmp ) ) <nl> + m_sourceMappingURL = toProtocolString ( tmp ) ; <nl> + m_startLine = script - > LineOffset ( ) ; <nl> + m_startColumn = script - > ColumnOffset ( ) ; <nl> + std : : vector < int > lineEnds = script - > LineEnds ( ) ; <nl> + CHECK ( lineEnds . size ( ) ) ; <nl> + int source_length = lineEnds [ lineEnds . size ( ) - 1 ] ; <nl> + if ( lineEnds . size ( ) ) { <nl> + m_endLine = static_cast < int > ( lineEnds . size ( ) ) + m_startLine - 1 ; <nl> + if ( lineEnds . size ( ) > 1 ) { <nl> + m_endColumn = source_length - lineEnds [ lineEnds . size ( ) - 2 ] - 1 ; <nl> + } else { <nl> + m_endColumn = source_length + m_startColumn ; <nl> + } <nl> + } else { <nl> + m_endLine = m_startLine ; <nl> + m_endColumn = m_startColumn ; <nl> + } <nl> + <nl> + USE ( script - > ContextId ( ) . To ( & m_executionContextId ) ) ; <nl> + <nl> + if ( script - > Source ( ) . ToLocal ( & tmp ) ) { <nl> + m_source = toProtocolString ( tmp ) ; <nl> + } <nl> + <nl> + m_isModule = script - > IsModule ( ) ; <nl> + <nl> + m_script . Reset ( m_isolate , script ) ; <nl> + m_script . AnnotateStrongRetainer ( kGlobalDebuggerScriptHandleLabel ) ; <nl> + } <nl> + <nl> String16 m_sourceMappingURL ; <nl> bool m_isLiveEdit = false ; <nl> bool m_isModule = false ; <nl> mmm a / src / runtime / runtime - debug . cc <nl> ppp b / src / runtime / runtime - debug . cc <nl> RUNTIME_FUNCTION ( Runtime_LiveEditPatchScript ) { <nl> Handle < Script > script ( Script : : cast ( script_function - > shared ( ) - > script ( ) ) , <nl> isolate ) ; <nl> v8 : : debug : : LiveEditResult result ; <nl> - LiveEdit : : PatchScript ( script , new_source , & result ) ; <nl> + LiveEdit : : PatchScript ( isolate , script , new_source , false , & result ) ; <nl> switch ( result . status ) { <nl> case v8 : : debug : : LiveEditResult : : COMPILE_ERROR : <nl> return isolate - > Throw ( * isolate - > factory ( ) - > NewStringFromAsciiChecked ( <nl> mmm a / src / runtime / runtime . h <nl> ppp b / src / runtime / runtime . h <nl> namespace internal { <nl> F ( CreateObjectLiteral , 4 , 1 ) \ <nl> F ( CreateRegExpLiteral , 4 , 1 ) <nl> <nl> - # define FOR_EACH_INTRINSIC_LIVEEDIT ( F ) \ <nl> - F ( LiveEditCheckAndDropActivations , 3 , 1 ) \ <nl> - F ( LiveEditCompareStrings , 2 , 1 ) \ <nl> - F ( LiveEditFindSharedFunctionInfosForScript , 1 , 1 ) \ <nl> - F ( LiveEditFixupScript , 2 , 1 ) \ <nl> - F ( LiveEditFunctionSetScript , 2 , 1 ) \ <nl> - F ( LiveEditFunctionSourceUpdated , 2 , 1 ) \ <nl> - F ( LiveEditGatherCompileInfo , 2 , 1 ) \ <nl> - F ( LiveEditPatchFunctionPositions , 2 , 1 ) \ <nl> - F ( LiveEditReplaceFunctionCode , 2 , 1 ) \ <nl> - F ( LiveEditReplaceRefToNestedFunction , 3 , 1 ) \ <nl> - F ( LiveEditReplaceScript , 3 , 1 ) <nl> - <nl> # define FOR_EACH_INTRINSIC_MATHS ( F ) F ( GenerateRandomNumbers , 0 , 1 ) <nl> <nl> # define FOR_EACH_INTRINSIC_MODULE ( F ) \ <nl> namespace internal { <nl> FOR_EACH_INTRINSIC_INTERPRETER ( F ) \ <nl> FOR_EACH_INTRINSIC_INTL ( F ) \ <nl> FOR_EACH_INTRINSIC_LITERALS ( F ) \ <nl> - FOR_EACH_INTRINSIC_LIVEEDIT ( F ) \ <nl> FOR_EACH_INTRINSIC_MATHS ( F ) \ <nl> FOR_EACH_INTRINSIC_MODULE ( F ) \ <nl> FOR_EACH_INTRINSIC_NUMBERS ( F ) \ <nl> mmm a / test / cctest / test - liveedit . cc <nl> ppp b / test / cctest / test - liveedit . cc <nl> void PatchFunctions ( v8 : : Local < v8 : : Context > context , const char * source_a , <nl> v8 : : debug : : LiveEditResult * result = nullptr ) { <nl> v8 : : Isolate * isolate = context - > GetIsolate ( ) ; <nl> i : : Isolate * i_isolate = reinterpret_cast < i : : Isolate * > ( isolate ) ; <nl> - v8 : : HandleScope scope ( isolate ) ; <nl> + v8 : : EscapableHandleScope scope ( isolate ) ; <nl> v8 : : Local < v8 : : Script > script_a = <nl> v8 : : Script : : Compile ( context , v8_str ( isolate , source_a ) ) . ToLocalChecked ( ) ; <nl> script_a - > Run ( context ) . ToLocalChecked ( ) ; <nl> void PatchFunctions ( v8 : : Local < v8 : : Context > context , const char * source_a , <nl> <nl> if ( result ) { <nl> LiveEdit : : PatchScript ( <nl> - i_script_a , i_isolate - > factory ( ) - > NewStringFromAsciiChecked ( source_b ) , <nl> + i_isolate , i_script_a , <nl> + i_isolate - > factory ( ) - > NewStringFromAsciiChecked ( source_b ) , false , <nl> result ) ; <nl> + if ( result - > status = = v8 : : debug : : LiveEditResult : : COMPILE_ERROR ) { <nl> + result - > message = scope . Escape ( result - > message ) ; <nl> + } <nl> } else { <nl> v8 : : debug : : LiveEditResult result ; <nl> LiveEdit : : PatchScript ( <nl> - i_script_a , i_isolate - > factory ( ) - > NewStringFromAsciiChecked ( source_b ) , <nl> + i_isolate , i_script_a , <nl> + i_isolate - > factory ( ) - > NewStringFromAsciiChecked ( source_b ) , false , <nl> & result ) ; <nl> CHECK_EQ ( result . status , v8 : : debug : : LiveEditResult : : OK ) ; <nl> } <nl> } <nl> } / / anonymous namespace <nl> <nl> - / / TODO ( kozyatinskiy ) : enable it with new liveedit implementation . <nl> - DISABLED_TEST ( LiveEditPatchFunctions ) { <nl> + TEST ( LiveEditPatchFunctions ) { <nl> LocalContext env ; <nl> v8 : : HandleScope scope ( env - > GetIsolate ( ) ) ; <nl> v8 : : Local < v8 : : Context > context = env . local ( ) ; <nl> DISABLED_TEST ( LiveEditPatchFunctions ) { <nl> - > ToInt32 ( env - > GetIsolate ( ) ) <nl> - > Value ( ) , <nl> 20 ) ; <nl> - <nl> / / Change inner functions . <nl> PatchFunctions ( <nl> context , <nl> DISABLED_TEST ( LiveEditPatchFunctions ) { <nl> v8 : : String : : Utf8Value new_result_utf8 ( env - > GetIsolate ( ) , result ) ; <nl> CHECK_NOT_NULL ( strstr ( * new_result_utf8 , " cb " ) ) ; <nl> } <nl> + <nl> + / / TODO ( kozyatinskiy ) : should work when we remove ( . <nl> + PatchFunctions ( context , " f = ( ) = > 2 " , " f = a = > a " ) ; <nl> + CHECK_EQ ( CompileRunChecked ( env - > GetIsolate ( ) , " f ( 3 ) " ) <nl> + - > ToInt32 ( env - > GetIsolate ( ) ) <nl> + - > Value ( ) , <nl> + 2 ) ; <nl> + <nl> + / / Replace function with not a function . <nl> + PatchFunctions ( context , " f = ( ) = > 2 " , " f = a = = 2 " ) ; <nl> + CHECK_EQ ( CompileRunChecked ( env - > GetIsolate ( ) , " f ( 3 ) " ) <nl> + - > ToInt32 ( env - > GetIsolate ( ) ) <nl> + - > Value ( ) , <nl> + 2 ) ; <nl> + <nl> + / / TODO ( kozyatinskiy ) : should work when we put function into ( . . . ) . <nl> + PatchFunctions ( context , " f = a = > 2 " , " f = ( a = > 5 ) ( ) " ) ; <nl> + CHECK_EQ ( CompileRunChecked ( env - > GetIsolate ( ) , " f ( ) " ) <nl> + - > ToInt32 ( env - > GetIsolate ( ) ) <nl> + - > Value ( ) , <nl> + 2 ) ; <nl> + <nl> + PatchFunctions ( context , <nl> + " f2 = null ; \ n " <nl> + " f = ( ) = > { \ n " <nl> + " f2 = ( ) = > 5 ; \ n " <nl> + " return f2 ( ) ; \ n " <nl> + " } \ n " <nl> + " f ( ) \ n " , <nl> + " f2 = null ; \ n " <nl> + " f = ( ) = > { \ n " <nl> + " for ( var a = ( ( ) = > 7 ) ( ) , b = 0 ; a < 10 ; + + a , + + b ) ; \ n " <nl> + " return b ; \ n " <nl> + " } \ n " <nl> + " f ( ) \ n " ) ; <nl> + / / TODO ( kozyatinskiy ) : ditto . <nl> + CHECK_EQ ( CompileRunChecked ( env - > GetIsolate ( ) , " f2 ( ) " ) <nl> + - > ToInt32 ( env - > GetIsolate ( ) ) <nl> + - > Value ( ) , <nl> + 5 ) ; <nl> + CHECK_EQ ( CompileRunChecked ( env - > GetIsolate ( ) , " f ( ) " ) <nl> + - > ToInt32 ( env - > GetIsolate ( ) ) <nl> + - > Value ( ) , <nl> + 3 ) ; <nl> } <nl> <nl> - / / TODO ( kozyatinskiy ) : enable it with new liveedit implementation . <nl> - DISABLED_TEST ( LiveEditCompileError ) { <nl> + TEST ( LiveEditCompileError ) { <nl> LocalContext env ; <nl> v8 : : HandleScope scope ( env - > GetIsolate ( ) ) ; <nl> v8 : : Local < v8 : : Context > context = env . local ( ) ; <nl> DISABLED_TEST ( LiveEditCompileError ) { <nl> PatchFunctions ( context , " function foo ( ) { } " , <nl> " function foo ( ) { return a # b ; } " , & result ) ; <nl> CHECK_EQ ( result . status , debug : : LiveEditResult : : COMPILE_ERROR ) ; <nl> - / / TODO ( kozyatinskiy ) : should be 1 . <nl> - CHECK_EQ ( result . line_number , kNoSourcePosition ) ; <nl> - / / TODO ( kozyatinskiy ) : should be 26 . <nl> - CHECK_EQ ( result . column_number , kNoSourcePosition ) ; <nl> + CHECK_EQ ( result . line_number , 1 ) ; <nl> + CHECK_EQ ( result . column_number , 26 ) ; <nl> } <nl> <nl> TEST ( LiveEditFunctionExpression ) { <nl> TEST ( LiveEditFunctionExpression ) { <nl> i_isolate ) ; <nl> debug : : LiveEditResult result ; <nl> LiveEdit : : PatchScript ( <nl> - i_script , i_isolate - > factory ( ) - > NewStringFromAsciiChecked ( updated_source ) , <nl> + i_isolate , i_script , <nl> + i_isolate - > factory ( ) - > NewStringFromAsciiChecked ( updated_source ) , false , <nl> & result ) ; <nl> CHECK_EQ ( result . status , debug : : LiveEditResult : : OK ) ; <nl> { <nl> new file mode 100644 <nl> index 00000000000 . . 6328a9b6def <nl> mmm / dev / null <nl> ppp b / test / debugger / debug / debug - live - edit - recursion . js <nl> <nl> + / / Copyright 2018 the V8 project authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . <nl> + <nl> + / / Flags : - - allow - natives - syntax <nl> + <nl> + Debug = debug . Debug ; <nl> + <nl> + function test ( i ) { <nl> + if ( i = = 3 ) { <nl> + return ( function * gen ( ) { yield test ( i - 1 ) ; } ) ( ) . next ( ) . value ; <nl> + } else if ( i > 1 ) { <nl> + return test ( i - 1 ) ; <nl> + } else { <nl> + debugger ; <nl> + return 5 ; <nl> + } <nl> + } <nl> + <nl> + let patch = null , exception = null ; <nl> + <nl> + Debug . setListener ( listener ) ; <nl> + patch = [ ' return 5 ' , ' return 3 ' ] ; <nl> + assertEquals ( 3 , test ( 2 ) ) ; / / no running generator <nl> + patch = [ ' return 3 ' , ' return - 1 ' ] ; <nl> + assertEquals ( 3 , test ( 3 ) ) ; / / there is running generator <nl> + assertEquals ( exception , <nl> + ' LiveEdit failed : BLOCKED_BY_FUNCTION_BELOW_NON_DROPPABLE_FRAME ' ) ; <nl> + Debug . setListener ( null ) ; <nl> + <nl> + function listener ( event ) { <nl> + if ( event ! = Debug . DebugEvent . Break | | ! patch ) return ; <nl> + try { <nl> + % LiveEditPatchScript ( test , <nl> + Debug . scriptSource ( test ) . replace ( patch [ 0 ] , patch [ 1 ] ) ) ; <nl> + } catch ( e ) { <nl> + exception = e ; <nl> + } <nl> + patch = null ; <nl> + } <nl> mmm a / test / debugger / debug / debug - liveedit - stepin . js <nl> ppp b / test / debugger / debug / debug - liveedit - stepin . js <nl> Debug . setListener ( null ) ; <nl> <nl> assertNull ( exception ) ; <nl> assertEquals ( [ " Emacs " , " Eclipse " , " Vim " ] , results ) ; <nl> - / / TODO ( kozyatinskiy ) : uncomment lines with new liveedit implementation . <nl> assertEquals ( [ <nl> " debugger ; " , <nl> " results . push ( BestEditor ( ) ) ; " , <nl> assertEquals ( [ <nl> " results . push ( BestEditor ( ) ) ; " , <nl> " results . push ( BestEditor ( ) ) ; " , <nl> " return ' Emacs ' ; " , <nl> - / / " return ' Eclipse ' ; " , <nl> + " return ' Eclipse ' ; " , <nl> " return ' Eclipse ' ; " , <nl> " results . push ( BestEditor ( ) ) ; " , <nl> " results . push ( BestEditor ( ) ) ; " , <nl> " return ' Eclipse ' ; " , <nl> - / / " return ' Vim ' ; " , <nl> + " return ' Vim ' ; " , <nl> " return ' Vim ' ; " , <nl> " results . push ( BestEditor ( ) ) ; " , <nl> " Debug . setListener ( null ) ; " <nl> mmm a / test / debugger / debug / es6 / debug - liveedit - new - target - 1 . js <nl> ppp b / test / debugger / debug / es6 / debug - liveedit - new - target - 1 . js <nl> function Replace ( fun , original , patch ) { <nl> try { <nl> % LiveEditPatchScript ( fun , Debug . scriptSource ( fun ) . replace ( original , patch ) ) ; <nl> } catch ( e ) { <nl> - / / TODO ( kozyatinskiy ) : message should be BLOCKED_BY_NEW_TARGET_IN_RESTART_FRAME . <nl> - assertEquals ( e , ' LiveEdit failed : BLOCKED_BY_FUNCTION_BELOW_NON_DROPPABLE_FRAME ' ) ; <nl> + assertEquals ( e , ' LiveEdit failed : BLOCKED_BY_NEW_TARGET_IN_RESTART_FRAME ' ) ; <nl> exceptions + + ; <nl> } <nl> } ) ; <nl> mmm a / test / debugger / debug / es6 / debug - liveedit - new - target - 2 . js <nl> ppp b / test / debugger / debug / es6 / debug - liveedit - new - target - 2 . js <nl> function Replace ( fun , original , patch ) { <nl> try { <nl> % LiveEditPatchScript ( fun , Debug . scriptSource ( fun ) . replace ( original , patch ) ) ; <nl> } catch ( e ) { <nl> - / / TODO ( kozyatinskiy ) : message should be BLOCKED_BY_NEW_TARGET_IN_RESTART_FRAME . <nl> - assertEquals ( e , ' LiveEdit failed : BLOCKED_BY_FUNCTION_BELOW_NON_DROPPABLE_FRAME ' ) ; <nl> + assertEquals ( e , ' LiveEdit failed : BLOCKED_BY_NEW_TARGET_IN_RESTART_FRAME ' ) ; <nl> exceptions + + ; <nl> } <nl> } ) ; <nl> mmm a / test / debugger / debug / es6 / generators - debug - liveedit . js <nl> ppp b / test / debugger / debug / es6 / generators - debug - liveedit . js <nl> function patch ( fun , from , to ) { <nl> / / Patching will fail however when a live iterator is suspended . <nl> iter = generator ( function ( ) { } ) ; <nl> assertIteratorResult ( undefined , false , iter . next ( ) ) ; <nl> - / / TODO ( kozyatinskiy ) : message should be BLOCKED_BY_RUNNING_GENERATOR . <nl> assertThrowsEquals ( function ( ) { <nl> patch ( generator , ' \ ' Capybara \ ' ' , ' \ ' Tapir \ ' ' ) <nl> - } , ' LiveEdit failed : BLOCKED_BY_FUNCTION_BELOW_NON_DROPPABLE_FRAME ' ) ; <nl> + } , ' LiveEdit failed : BLOCKED_BY_RUNNING_GENERATOR ' ) ; <nl> assertIteratorResult ( " Capybara " , true , iter . next ( ) ) ; <nl> <nl> / / Try to patch functions with activations inside and outside generator <nl> mmm a / test / debugger / debug / es8 / debug - async - liveedit . js <nl> ppp b / test / debugger / debug / es8 / debug - async - liveedit . js <nl> function patch ( fun , from , to ) { <nl> / / Patching will fail however when an async function is suspended . <nl> var resolve ; <nl> promise = asyncfn ( function ( ) { return new Promise ( function ( r ) { resolve = r } ) } ) ; <nl> - / / TODO ( kozyatinskiy ) : message should be BLOCKED_BY_RUNNING_GENERATOR . <nl> assertThrowsEquals ( function ( ) { <nl> patch ( asyncfn , ' \ ' Capybara \ ' ' , ' \ ' Tapir \ ' ' ) <nl> - } , ' LiveEdit failed : BLOCKED_BY_FUNCTION_BELOW_NON_DROPPABLE_FRAME ' ) ; <nl> + } , ' LiveEdit failed : BLOCKED_BY_RUNNING_GENERATOR ' ) ; <nl> resolve ( ) ; <nl> assertPromiseValue ( " Capybara " , promise ) ; <nl> <nl> new file mode 100644 <nl> index 00000000000 . . cd50a5358a9 <nl> mmm / dev / null <nl> ppp b / test / inspector / debugger / set - breakpoint - after - liveedit - expected . txt <nl> <nl> + Breakpoint in liveedited script <nl> + Update script source <nl> + { <nl> + callFrames : [ <nl> + ] <nl> + stackChanged : false <nl> + } <nl> + Set breakpoint <nl> + { <nl> + actualLocation : { <nl> + columnNumber : 0 <nl> + lineNumber : 3 <nl> + scriptId : < scriptId > <nl> + } <nl> + breakpointId : < breakpointId > <nl> + } <nl> + Call function foo and dump stack <nl> + foo ( : 3 : 0 ) <nl> + ( anonymous ) ( : 0 : 0 ) <nl> new file mode 100644 <nl> index 00000000000 . . 05f065b27f5 <nl> mmm / dev / null <nl> ppp b / test / inspector / debugger / set - breakpoint - after - liveedit . js <nl> <nl> + / / Copyright 2018 the V8 project authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . <nl> + <nl> + let { session , contextGroup , Protocol } = <nl> + InspectorTest . start ( ' Breakpoint in liveedited script ' ) ; <nl> + <nl> + contextGroup . addScript ( <nl> + ` function foo ( ) { <nl> + } <nl> + var f = foo ; ` ) ; <nl> + <nl> + const newSource = ` function boo ( ) { <nl> + } <nl> + function foo ( ) { <nl> + } <nl> + f = foo ; ` ; <nl> + <nl> + ( async function test ( ) { <nl> + session . setupScriptMap ( ) ; <nl> + Protocol . Debugger . enable ( ) ; <nl> + const { params : { scriptId } } = await Protocol . Debugger . onceScriptParsed ( ) ; <nl> + InspectorTest . log ( ' Update script source ' ) ; <nl> + let { result } = await Protocol . Debugger . setScriptSource ( <nl> + { scriptId , scriptSource : newSource } ) <nl> + InspectorTest . logMessage ( result ) ; <nl> + InspectorTest . log ( ' Set breakpoint ' ) ; <nl> + ( { result } = await Protocol . Debugger . setBreakpoint ( { location : { <nl> + scriptId , <nl> + lineNumber : 3 , <nl> + columnNumber : 0 <nl> + } } ) ) ; <nl> + InspectorTest . logMessage ( result ) ; <nl> + InspectorTest . log ( ' Call function foo and dump stack ' ) ; <nl> + Protocol . Runtime . evaluate ( { expression : ' foo ( ) ' } ) ; <nl> + const { params : { callFrames } } = await Protocol . Debugger . oncePaused ( ) ; <nl> + session . logCallFrames ( callFrames ) ; <nl> + InspectorTest . completeTest ( ) ; <nl> + } ) ( ) ; <nl> mmm a / test / inspector / debugger / set - script - source - exception - expected . txt <nl> ppp b / test / inspector / debugger / set - script - source - exception - expected . txt <nl> Running test : testSourceWithSyntaxError <nl> id : < messageId > <nl> result : { <nl> exceptionDetails : { <nl> - columnNumber : 0 <nl> + columnNumber : 11 <nl> exceptionId : < exceptionId > <nl> - lineNumber : 0 <nl> - text : Invalid or unexpected token <nl> + lineNumber : 1 <nl> + text : Uncaught SyntaxError : Invalid or unexpected token <nl> } <nl> } <nl> } <nl> mmm a / test / inspector / debugger / set - script - source - expected . txt <nl> ppp b / test / inspector / debugger / set - script - source - expected . txt <nl> TestExpression ( 2 , 4 ) = = = 8 <nl> Update current script source ' a * b ' - > ' a # b ' . . <nl> { <nl> exceptionDetails : { <nl> - columnNumber : 0 <nl> + columnNumber : 13 <nl> exceptionId : < exceptionId > <nl> - lineNumber : 0 <nl> - text : Invalid or unexpected token <nl> + lineNumber : 1 <nl> + text : Uncaught SyntaxError : Invalid or unexpected token <nl> } <nl> } <nl> TestExpression ( 2 , 4 ) = = = 8 <nl> mmm a / tools / presubmit . py <nl> ppp b / tools / presubmit . py <nl> def CreateRuntimeFunctionCallMatcher ( self ) : <nl> m = pattern . match ( line ) <nl> if m : <nl> runtime_functions . append ( m . group ( 1 ) ) <nl> - if len ( runtime_functions ) < 475 : <nl> + if len ( runtime_functions ) < 450 : <nl> print ( " Runtime functions list is suspiciously short . " <nl> " Consider updating the presubmit script . " ) <nl> sys . exit ( 1 ) <nl> | Reland " [ debug ] liveedit in native " | v8/v8 | 5505c66446ab5fec9752c9f1f2cae536f7a9b811 | 2018-07-03T21:01:57Z |
mmm a / src / mongo / shell / utils_sh . js <nl> ppp b / src / mongo / shell / utils_sh . js <nl> sh . _checkMongos = function ( ) { <nl> } <nl> <nl> sh . _checkFullName = function ( fullName ) { <nl> - assert ( fullName , " neeed a full name " ) <nl> + assert ( fullName , " need a full name " ) <nl> assert ( fullName . indexOf ( " . " ) > 0 , " name needs to be fully qualified < db > . < collection > ' " ) <nl> } <nl> <nl> | fix misspelling in assert | mongodb/mongo | aa84f525eb4d651b19efef35f83e884adabda4ad | 2014-03-27T18:27:40Z |
mmm a / test / IRGen / super . sil <nl> ppp b / test / IRGen / super . sil <nl> <nl> / / RUN : rm - rf % t <nl> / / RUN : mkdir % t <nl> - / / RUN : % target - swift - frontend - emit - module - enable - resilience - module - name resilient_class - o % t % S / . . / Inputs / resilient_class . swift <nl> + / / RUN : % target - swift - frontend - emit - module - enable - resilience - I % t - module - name resilient_struct - o % t % S / . . / Inputs / resilient_struct . swift <nl> + / / RUN : % target - swift - frontend - emit - module - enable - resilience - I % t - module - name resilient_class - o % t % S / . . / Inputs / resilient_class . swift <nl> / / RUN : % target - swift - frontend - use - native - super - method - enable - resilience - parse - sil - parse - as - library - emit - ir - I % t % s | FileCheck % s <nl> <nl> sil_stage canonical <nl> mmm a / test / SILGen / partial_apply_super . swift <nl> ppp b / test / SILGen / partial_apply_super . swift <nl> <nl> / / RUN : rm - rf % t <nl> / / RUN : mkdir % t <nl> - / / RUN : % target - swift - frontend - emit - module - emit - module - path = % t / resilient_class . swiftmodule - module - name resilient_class % S / . . / Inputs / resilient_class . swift <nl> + / / RUN : % target - swift - frontend - I % t - emit - module - emit - module - path = % t / resilient_struct . swiftmodule - module - name resilient_struct % S / . . / Inputs / resilient_struct . swift <nl> + / / RUN : % target - swift - frontend - I % t - emit - module - emit - module - path = % t / resilient_class . swiftmodule - module - name resilient_class % S / . . / Inputs / resilient_class . swift <nl> / / RUN : % target - swift - frontend - use - native - super - method - emit - silgen - parse - as - library - I % t % s | FileCheck % s <nl> <nl> import resilient_class <nl> mmm a / test / SILGen / super . swift <nl> ppp b / test / SILGen / super . swift <nl> <nl> / / RUN : rm - rf % t <nl> / / RUN : mkdir % t <nl> - / / RUN : % target - swift - frontend - emit - module - emit - module - path = % t / resilient_class . swiftmodule - module - name resilient_class % S / . . / Inputs / resilient_class . swift <nl> + / / RUN : % target - swift - frontend - I % t - emit - module - emit - module - path = % t / resilient_struct . swiftmodule - module - name resilient_struct % S / . . / Inputs / resilient_struct . swift <nl> + / / RUN : % target - swift - frontend - I % t - emit - module - emit - module - path = % t / resilient_class . swiftmodule - module - name resilient_class % S / . . / Inputs / resilient_class . swift <nl> / / RUN : % target - swift - frontend - use - native - super - method - emit - silgen - parse - as - library - I % t % s | FileCheck % s <nl> <nl> import resilient_class <nl> | Fix broken tests - - resilient_class module now depends on resilient_struct | apple/swift | 40867560fd4229bfac812eda2a05c279faa76753 | 2016-01-07T17:44:31Z |
mmm a / version <nl> ppp b / version <nl> @ @ - 1 + 1 @ @ <nl> - 11 . 1 . 15 <nl> + 11 . 1 . 16 <nl> | version 11 . 1 . 16 | pqrs-org/Karabiner-Elements | 51b7b6c809d6031cc391f379872ca438c9189c57 | 2017-11-07T17:00:41Z |
mmm a / validation - test / stdlib / Collection / DefaultedBidirectionalCollectionOfRef . swift <nl> ppp b / validation - test / stdlib / Collection / DefaultedBidirectionalCollectionOfRef . swift <nl> <nl> / / RUN : % target - run - simple - swift <nl> / / REQUIRES : executable_test <nl> <nl> + / / FIXME : the test is too slow when the standard library is not optimized . <nl> + / / rdar : / / problem / 46878013 <nl> + / / REQUIRES : optimized_stdlib <nl> + <nl> import StdlibUnittest <nl> import StdlibCollectionUnittest <nl> <nl> mmm a / validation - test / stdlib / Collection / DefaultedCollectionOfRef . swift <nl> ppp b / validation - test / stdlib / Collection / DefaultedCollectionOfRef . swift <nl> <nl> / / RUN : % target - run - simple - swift <nl> / / REQUIRES : executable_test <nl> <nl> + / / FIXME : the test is too slow when the standard library is not optimized . <nl> + / / rdar : / / problem / 46878013 <nl> + / / REQUIRES : optimized_stdlib <nl> + <nl> import StdlibUnittest <nl> import StdlibCollectionUnittest <nl> <nl> mmm a / validation - test / stdlib / Collection / DefaultedMutableBidirectionalCollectionOfRef . swift <nl> ppp b / validation - test / stdlib / Collection / DefaultedMutableBidirectionalCollectionOfRef . swift <nl> <nl> / / RUN : % target - run - simple - swift <nl> / / REQUIRES : executable_test <nl> <nl> + / / FIXME : the test is too slow when the standard library is not optimized . <nl> + / / rdar : / / problem / 46878013 <nl> + / / REQUIRES : optimized_stdlib <nl> + <nl> import StdlibUnittest <nl> import StdlibCollectionUnittest <nl> <nl> mmm a / validation - test / stdlib / Collection / DefaultedMutableCollectionOfRef . swift <nl> ppp b / validation - test / stdlib / Collection / DefaultedMutableCollectionOfRef . swift <nl> <nl> / / RUN : % target - run - simple - swift <nl> / / REQUIRES : executable_test <nl> <nl> + / / FIXME : the test is too slow when the standard library is not optimized . <nl> + / / rdar : / / problem / 46878013 <nl> + / / REQUIRES : optimized_stdlib <nl> + <nl> import StdlibUnittest <nl> import StdlibCollectionUnittest <nl> <nl> mmm a / validation - test / stdlib / Collection / DefaultedMutableRandomAccessCollectionOfRef . swift <nl> ppp b / validation - test / stdlib / Collection / DefaultedMutableRandomAccessCollectionOfRef . swift <nl> <nl> / / RUN : % target - run - simple - swift <nl> / / REQUIRES : executable_test <nl> <nl> + / / FIXME : the test is too slow when the standard library is not optimized . <nl> + / / rdar : / / problem / 46878013 <nl> + / / REQUIRES : optimized_stdlib <nl> + <nl> import StdlibUnittest <nl> import StdlibCollectionUnittest <nl> <nl> mmm a / validation - test / stdlib / Collection / DefaultedMutableRangeReplaceableBidirectionalCollectionOfRef . swift <nl> ppp b / validation - test / stdlib / Collection / DefaultedMutableRangeReplaceableBidirectionalCollectionOfRef . swift <nl> <nl> / / RUN : % target - run - simple - swift <nl> / / REQUIRES : executable_test <nl> <nl> + / / FIXME : the test is too slow when the standard library is not optimized . <nl> + / / rdar : / / problem / 46878013 <nl> + / / REQUIRES : optimized_stdlib <nl> + <nl> import StdlibUnittest <nl> import StdlibCollectionUnittest <nl> <nl> mmm a / validation - test / stdlib / Collection / DefaultedMutableRangeReplaceableCollectionOfRef . swift <nl> ppp b / validation - test / stdlib / Collection / DefaultedMutableRangeReplaceableCollectionOfRef . swift <nl> <nl> / / RUN : % target - run - simple - swift <nl> / / REQUIRES : executable_test <nl> <nl> + / / FIXME : the test is too slow when the standard library is not optimized . <nl> + / / rdar : / / problem / 46878013 <nl> + / / REQUIRES : optimized_stdlib <nl> + <nl> import StdlibUnittest <nl> import StdlibCollectionUnittest <nl> <nl> mmm a / validation - test / stdlib / Collection / DefaultedMutableRangeReplaceableRandomAccessCollectionOfRef . swift <nl> ppp b / validation - test / stdlib / Collection / DefaultedMutableRangeReplaceableRandomAccessCollectionOfRef . swift <nl> <nl> / / RUN : % target - run - simple - swift <nl> / / REQUIRES : executable_test <nl> <nl> + / / FIXME : the test is too slow when the standard library is not optimized . <nl> + / / rdar : / / problem / 46878013 <nl> + / / REQUIRES : optimized_stdlib <nl> + <nl> import StdlibUnittest <nl> import StdlibCollectionUnittest <nl> <nl> mmm a / validation - test / stdlib / Collection / DefaultedRandomAccessCollectionOfRef . swift <nl> ppp b / validation - test / stdlib / Collection / DefaultedRandomAccessCollectionOfRef . swift <nl> <nl> / / RUN : % target - run - simple - swift <nl> / / REQUIRES : executable_test <nl> <nl> + / / FIXME : the test is too slow when the standard library is not optimized . <nl> + / / rdar : / / problem / 46878013 <nl> + / / REQUIRES : optimized_stdlib <nl> + <nl> import StdlibUnittest <nl> import StdlibCollectionUnittest <nl> <nl> mmm a / validation - test / stdlib / Collection / DefaultedRangeReplaceableBidirectionalCollectionOfRef . swift <nl> ppp b / validation - test / stdlib / Collection / DefaultedRangeReplaceableBidirectionalCollectionOfRef . swift <nl> <nl> / / RUN : % target - run - simple - swift <nl> / / REQUIRES : executable_test <nl> <nl> + / / FIXME : the test is too slow when the standard library is not optimized . <nl> + / / rdar : / / problem / 46878013 <nl> + / / REQUIRES : optimized_stdlib <nl> + <nl> import StdlibUnittest <nl> import StdlibCollectionUnittest <nl> <nl> mmm a / validation - test / stdlib / Collection / DefaultedRangeReplaceableCollectionOfRef . swift <nl> ppp b / validation - test / stdlib / Collection / DefaultedRangeReplaceableCollectionOfRef . swift <nl> <nl> / / RUN : % target - run - simple - swift <nl> / / REQUIRES : executable_test <nl> <nl> + / / FIXME : the test is too slow when the standard library is not optimized . <nl> + / / rdar : / / problem / 46878013 <nl> + / / REQUIRES : optimized_stdlib <nl> + <nl> import StdlibUnittest <nl> import StdlibCollectionUnittest <nl> <nl> mmm a / validation - test / stdlib / Collection / DefaultedRangeReplaceableRandomAccessCollectionOfRef . swift <nl> ppp b / validation - test / stdlib / Collection / DefaultedRangeReplaceableRandomAccessCollectionOfRef . swift <nl> <nl> / / RUN : % target - run - simple - swift <nl> / / REQUIRES : executable_test <nl> <nl> + / / FIXME : the test is too slow when the standard library is not optimized . <nl> + / / rdar : / / problem / 46878013 <nl> + / / REQUIRES : optimized_stdlib <nl> + <nl> import StdlibUnittest <nl> import StdlibCollectionUnittest <nl> <nl> mmm a / validation - test / stdlib / Collection / MinimalBidirectionalCollectionOfRef . swift <nl> ppp b / validation - test / stdlib / Collection / MinimalBidirectionalCollectionOfRef . swift <nl> <nl> / / RUN : % target - run - simple - swift <nl> / / REQUIRES : executable_test <nl> <nl> + / / FIXME : the test is too slow when the standard library is not optimized . <nl> + / / rdar : / / problem / 46878013 <nl> + / / REQUIRES : optimized_stdlib <nl> + <nl> import StdlibUnittest <nl> import StdlibCollectionUnittest <nl> <nl> mmm a / validation - test / stdlib / Collection / MinimalCollectionOfRef . swift <nl> ppp b / validation - test / stdlib / Collection / MinimalCollectionOfRef . swift <nl> <nl> / / RUN : % target - run - simple - swift <nl> / / REQUIRES : executable_test <nl> <nl> + / / FIXME : the test is too slow when the standard library is not optimized . <nl> + / / rdar : / / problem / 46878013 <nl> + / / REQUIRES : optimized_stdlib <nl> + <nl> import StdlibUnittest <nl> import StdlibCollectionUnittest <nl> <nl> mmm a / validation - test / stdlib / Collection / MinimalMutableBidirectionalCollectionOfRef . swift <nl> ppp b / validation - test / stdlib / Collection / MinimalMutableBidirectionalCollectionOfRef . swift <nl> <nl> / / RUN : % target - run - simple - swift <nl> / / REQUIRES : executable_test <nl> <nl> + / / FIXME : the test is too slow when the standard library is not optimized . <nl> + / / rdar : / / problem / 46878013 <nl> + / / REQUIRES : optimized_stdlib <nl> + <nl> import StdlibUnittest <nl> import StdlibCollectionUnittest <nl> <nl> mmm a / validation - test / stdlib / Collection / MinimalMutableCollectionOfRef . swift <nl> ppp b / validation - test / stdlib / Collection / MinimalMutableCollectionOfRef . swift <nl> <nl> / / RUN : % target - run - simple - swift <nl> / / REQUIRES : executable_test <nl> <nl> + / / FIXME : the test is too slow when the standard library is not optimized . <nl> + / / rdar : / / problem / 46878013 <nl> + / / REQUIRES : optimized_stdlib <nl> + <nl> import StdlibUnittest <nl> import StdlibCollectionUnittest <nl> <nl> mmm a / validation - test / stdlib / Collection / MinimalMutableRandomAccessCollectionOfRef . swift <nl> ppp b / validation - test / stdlib / Collection / MinimalMutableRandomAccessCollectionOfRef . swift <nl> <nl> / / RUN : % target - run - simple - swift <nl> / / REQUIRES : executable_test <nl> <nl> + / / FIXME : the test is too slow when the standard library is not optimized . <nl> + / / rdar : / / problem / 46878013 <nl> + / / REQUIRES : optimized_stdlib <nl> + <nl> import StdlibUnittest <nl> import StdlibCollectionUnittest <nl> <nl> mmm a / validation - test / stdlib / Collection / MinimalMutableRangeReplaceableBidirectionalCollectionOfRef . swift <nl> ppp b / validation - test / stdlib / Collection / MinimalMutableRangeReplaceableBidirectionalCollectionOfRef . swift <nl> <nl> / / RUN : % target - run - simple - swift <nl> / / REQUIRES : executable_test <nl> <nl> + / / FIXME : the test is too slow when the standard library is not optimized . <nl> + / / rdar : / / problem / 46878013 <nl> + / / REQUIRES : optimized_stdlib <nl> + <nl> import StdlibUnittest <nl> import StdlibCollectionUnittest <nl> <nl> mmm a / validation - test / stdlib / Collection / MinimalMutableRangeReplaceableCollectionOfRef . swift <nl> ppp b / validation - test / stdlib / Collection / MinimalMutableRangeReplaceableCollectionOfRef . swift <nl> <nl> / / RUN : % target - run - simple - swift <nl> / / REQUIRES : executable_test <nl> <nl> + / / FIXME : the test is too slow when the standard library is not optimized . <nl> + / / rdar : / / problem / 46878013 <nl> + / / REQUIRES : optimized_stdlib <nl> + <nl> import StdlibUnittest <nl> import StdlibCollectionUnittest <nl> <nl> mmm a / validation - test / stdlib / Collection / MinimalMutableRangeReplaceableRandomAccessCollectionOfRef . swift <nl> ppp b / validation - test / stdlib / Collection / MinimalMutableRangeReplaceableRandomAccessCollectionOfRef . swift <nl> <nl> / / RUN : % target - run - simple - swift <nl> / / REQUIRES : executable_test <nl> <nl> + / / FIXME : the test is too slow when the standard library is not optimized . <nl> + / / rdar : / / problem / 46878013 <nl> + / / REQUIRES : optimized_stdlib <nl> + <nl> import StdlibUnittest <nl> import StdlibCollectionUnittest <nl> <nl> mmm a / validation - test / stdlib / Collection / MinimalRandomAccessCollectionOfRef . swift <nl> ppp b / validation - test / stdlib / Collection / MinimalRandomAccessCollectionOfRef . swift <nl> <nl> / / RUN : % target - run - simple - swift <nl> / / REQUIRES : executable_test <nl> <nl> + / / FIXME : the test is too slow when the standard library is not optimized . <nl> + / / rdar : / / problem / 46878013 <nl> + / / REQUIRES : optimized_stdlib <nl> + <nl> import StdlibUnittest <nl> import StdlibCollectionUnittest <nl> <nl> mmm a / validation - test / stdlib / Collection / MinimalRangeReplaceableBidirectionalCollectionOfRef . swift <nl> ppp b / validation - test / stdlib / Collection / MinimalRangeReplaceableBidirectionalCollectionOfRef . swift <nl> <nl> / / RUN : % target - run - simple - swift <nl> / / REQUIRES : executable_test <nl> <nl> + / / FIXME : the test is too slow when the standard library is not optimized . <nl> + / / rdar : / / problem / 46878013 <nl> + / / REQUIRES : optimized_stdlib <nl> + <nl> import StdlibUnittest <nl> import StdlibCollectionUnittest <nl> <nl> mmm a / validation - test / stdlib / Collection / MinimalRangeReplaceableCollectionOfRef . swift <nl> ppp b / validation - test / stdlib / Collection / MinimalRangeReplaceableCollectionOfRef . swift <nl> <nl> / / RUN : % target - run - simple - swift <nl> / / REQUIRES : executable_test <nl> <nl> + / / FIXME : the test is too slow when the standard library is not optimized . <nl> + / / rdar : / / problem / 46878013 <nl> + / / REQUIRES : optimized_stdlib <nl> + <nl> import StdlibUnittest <nl> import StdlibCollectionUnittest <nl> <nl> mmm a / validation - test / stdlib / Collection / MinimalRangeReplaceableRandomAccessCollectionOfRef . swift <nl> ppp b / validation - test / stdlib / Collection / MinimalRangeReplaceableRandomAccessCollectionOfRef . swift <nl> <nl> / / RUN : % target - run - simple - swift <nl> / / REQUIRES : executable_test <nl> <nl> + / / FIXME : the test is too slow when the standard library is not optimized . <nl> + / / rdar : / / problem / 46878013 <nl> + / / REQUIRES : optimized_stdlib <nl> + <nl> import StdlibUnittest <nl> import StdlibCollectionUnittest <nl> <nl> | [ test ] Regenerate CollectionOfRef validation tests | apple/swift | 447da103e03204f210651eca02f814566bed48de | 2019-02-08T23:01:27Z |
mmm a / tensorflow / python / ops / parallel_for / __init__ . py <nl> ppp b / tensorflow / python / ops / parallel_for / __init__ . py <nl> <nl> from tensorflow . python . ops . parallel_for . control_flow_ops import pfor <nl> from tensorflow . python . ops . parallel_for . gradients import batch_jacobian <nl> from tensorflow . python . ops . parallel_for . gradients import jacobian <nl> - from tensorflow . python . util . all_util import remove_undocumented <nl> - <nl> - _allowed_symbols = [ <nl> - ' pfor ' , <nl> - ' for_loop ' , <nl> - ' jacobian ' , <nl> - ' batch_jacobian ' , <nl> - ] <nl> - <nl> - remove_undocumented ( __name__ , _allowed_symbols ) <nl> | Remove usage of remove_undocumented from core parallel_for . | tensorflow/tensorflow | 2a0958455799601068db054c130fa9573e7c1e22 | 2018-07-18T17:37:01Z |
mmm a / xbmc / cores / VideoPlayer / VideoRenderers / BaseRenderer . cpp <nl> ppp b / xbmc / cores / VideoPlayer / VideoRenderers / BaseRenderer . cpp <nl> void CBaseRenderer : : ManageDisplay ( ) <nl> else if ( stereo_view = = RENDER_STEREO_VIEW_RIGHT ) stereo_view = RENDER_STEREO_VIEW_LEFT ; <nl> } <nl> <nl> - switch ( stereo_mode ) <nl> + if ( m_format ! = RENDER_FMT_BYPASS ) <nl> { <nl> - case CONF_FLAGS_STEREO_MODE_TAB : <nl> - / / Those are flipped in y <nl> - if ( m_format = = RENDER_FMT_CVBREF | | m_format = = RENDER_FMT_MEDIACODEC ) <nl> - { <nl> - if ( stereo_view = = RENDER_STEREO_VIEW_LEFT ) <nl> - m_sourceRect . y1 + = m_sourceRect . y2 * 0 . 5f ; <nl> - else if ( stereo_view = = RENDER_STEREO_VIEW_RIGHT ) <nl> - m_sourceRect . y2 * = 0 . 5f ; <nl> - } <nl> - else <nl> - { <nl> - if ( stereo_view = = RENDER_STEREO_VIEW_LEFT ) <nl> - m_sourceRect . y2 * = 0 . 5f ; <nl> + switch ( stereo_mode ) <nl> + { <nl> + case CONF_FLAGS_STEREO_MODE_TAB : <nl> + / / Those are flipped in y <nl> + if ( m_format = = RENDER_FMT_CVBREF | | m_format = = RENDER_FMT_MEDIACODEC ) <nl> + { <nl> + if ( stereo_view = = RENDER_STEREO_VIEW_LEFT ) <nl> + m_sourceRect . y1 + = m_sourceRect . y2 * 0 . 5f ; <nl> + else if ( stereo_view = = RENDER_STEREO_VIEW_RIGHT ) <nl> + m_sourceRect . y2 * = 0 . 5f ; <nl> + } <nl> + else <nl> + { <nl> + if ( stereo_view = = RENDER_STEREO_VIEW_LEFT ) <nl> + m_sourceRect . y2 * = 0 . 5f ; <nl> + else if ( stereo_view = = RENDER_STEREO_VIEW_RIGHT ) <nl> + m_sourceRect . y1 + = m_sourceRect . y2 * 0 . 5f ; <nl> + } <nl> + break ; <nl> + <nl> + case CONF_FLAGS_STEREO_MODE_SBS : <nl> + if ( stereo_view = = RENDER_STEREO_VIEW_LEFT ) <nl> + m_sourceRect . x2 * = 0 . 5f ; <nl> else if ( stereo_view = = RENDER_STEREO_VIEW_RIGHT ) <nl> - m_sourceRect . y1 + = m_sourceRect . y2 * 0 . 5f ; <nl> - } <nl> - break ; <nl> - <nl> - case CONF_FLAGS_STEREO_MODE_SBS : <nl> - if ( stereo_view = = RENDER_STEREO_VIEW_LEFT ) <nl> - m_sourceRect . x2 * = 0 . 5f ; <nl> - else if ( stereo_view = = RENDER_STEREO_VIEW_RIGHT ) <nl> - m_sourceRect . x1 + = m_sourceRect . x2 * 0 . 5f ; <nl> - break ; <nl> + m_sourceRect . x1 + = m_sourceRect . x2 * 0 . 5f ; <nl> + break ; <nl> <nl> - default : <nl> - break ; <nl> + default : <nl> + break ; <nl> + } <nl> } <nl> <nl> CalcNormalDisplayRect ( m_viewRect . x1 , m_viewRect . y1 , m_viewRect . Width ( ) , m_viewRect . Height ( ) , GetAspectRatio ( ) * CDisplaySettings : : GetInstance ( ) . GetPixelRatio ( ) , CDisplaySettings : : GetInstance ( ) . GetZoomAmount ( ) , CDisplaySettings : : GetInstance ( ) . GetVerticalShift ( ) ) ; <nl> | [ renderer ] Don ' t adjust 3d rectangles in bypass mode | xbmc/xbmc | c03a4a7d1410fbdbbdd59581161c203f640a2108 | 2015-12-30T12:54:26Z |
mmm a / include / swift / SIL / SILInstruction . h <nl> ppp b / include / swift / SIL / SILInstruction . h <nl> class SILInstruction : public ValueBase , public llvm : : ilist_node < SILInstruction > { <nl> / / / the basic block that MovePos lives in , right before MovePos . <nl> void moveBefore ( SILInstruction * MovePos ) ; <nl> <nl> + / / / Replace every use of a result of this instruction with the corresponding <nl> + / / / result from RHS . The method assumes that both instructions have the same <nl> + / / / number of results . To replace just one result use <nl> + / / / SILValue : : replaceAllUsesWith . <nl> + void replaceAllUsesWith ( ValueBase * RHS ) { <nl> + assert ( getNumTypes ( ) = = RHS - > getNumTypes ( ) & & <nl> + " An instruction and the value base that it is being replaced by " <nl> + " must have the same number of types . " ) ; <nl> + <nl> + for ( unsigned i = 0 , e = getNumTypes ( ) ; i ! = e ; + + i ) <nl> + SILValue ( this , i ) . replaceAllUsesWith ( SILValue ( RHS , i ) ) ; <nl> + } <nl> + <nl> / / / \ brief Drops all uses that belong to this instruction . <nl> void dropAllReferences ( ) ; <nl> <nl> mmm a / lib / SILPasses / SILCombine . cpp <nl> ppp b / lib / SILPasses / SILCombine . cpp <nl> class SILCombiner : <nl> DEBUG ( llvm : : dbgs ( ) < < " SC : Replacing " < < I < < " \ n " <nl> " with " < < * V < < ' \ n ' ) ; <nl> <nl> - assert ( I . getNumTypes ( ) = = V - > getNumTypes ( ) & & <nl> - " An instruction and the value base that it is being replaced by " <nl> - " must have the same number of types . " ) ; <nl> - <nl> - for ( unsigned i = 0 , e = I . getNumTypes ( ) ; i ! = e ; + + i ) <nl> - SILValue ( & I , i ) . replaceAllUsesWith ( SILValue ( V , i ) ) ; <nl> + I . replaceAllUsesWith ( V ) ; <nl> <nl> return & I ; <nl> } <nl> | Refactor out all result replaceAllUsesWith from SILCombine into SILInstruction : : replaceAllUsesWith . | apple/swift | 08181f9f75fd867e93b17a18dec3bdc7591b9f78 | 2013-12-03T22:24:48Z |
mmm a / tensorflow / python / BUILD <nl> ppp b / tensorflow / python / BUILD <nl> py_test ( <nl> ] , <nl> ) <nl> <nl> + py_test ( <nl> + name = " datasets_test " , <nl> + size = " small " , <nl> + srcs = [ <nl> + " grappler / datasets_test . py " , <nl> + ] , <nl> + srcs_version = " PY2AND3 " , <nl> + tags = [ " no_pip " ] , # tf_optimizer is not available in pip . <nl> + deps = [ <nl> + " : array_ops " , <nl> + " : client_testlib " , <nl> + " : framework_for_generated_wrappers " , <nl> + " : tf_item " , <nl> + " / / tensorflow / core : protos_all_py " , <nl> + " / / tensorflow / python / data " , <nl> + ] , <nl> + ) <nl> + <nl> py_library ( <nl> name = " tf_cluster " , <nl> srcs = [ <nl> new file mode 100644 <nl> index 0000000000000 . . 2d942af597c18 <nl> mmm / dev / null <nl> ppp b / tensorflow / python / grappler / datasets_test . py <nl> <nl> + # Copyright 2017 The TensorFlow Authors . All Rights Reserved . <nl> + # <nl> + # Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + # you may not use this file except in compliance with the License . <nl> + # You may obtain a copy of the License at <nl> + # <nl> + # http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + # <nl> + # Unless required by applicable law or agreed to in writing , software <nl> + # distributed under the License is distributed on an " AS IS " BASIS , <nl> + # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + # See the License for the specific language governing permissions and <nl> + # limitations under the License . <nl> + # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + " " " Tests for the datasets shape inference . " " " <nl> + <nl> + from __future__ import absolute_import <nl> + from __future__ import division <nl> + from __future__ import print_function <nl> + <nl> + import numpy as np <nl> + <nl> + from tensorflow . python . data . ops import dataset_ops <nl> + from tensorflow . python . data . ops import iterator_ops <nl> + from tensorflow . python . framework import dtypes <nl> + from tensorflow . python . framework import meta_graph <nl> + from tensorflow . python . framework import ops <nl> + from tensorflow . python . framework import tensor_shape <nl> + from tensorflow . python . grappler import item <nl> + from tensorflow . python . ops import array_ops <nl> + from tensorflow . python . platform import test <nl> + <nl> + <nl> + class GrapplerTest ( test . TestCase ) : <nl> + <nl> + def testFromTensors ( self ) : <nl> + test_cases = [ { <nl> + ' tensor ' : 0 , <nl> + ' shape ' : tensor_shape . TensorShape ( [ ] ) <nl> + } , { <nl> + ' tensor ' : np . array ( [ 1 , 2 , 3 ] ) , <nl> + ' shape ' : tensor_shape . TensorShape ( [ 3 ] ) <nl> + } , { <nl> + ' tensor ' : np . array ( [ [ 1 , 2 , 3 ] ] ) , <nl> + ' shape ' : tensor_shape . TensorShape ( [ 1 , 3 ] ) <nl> + } ] <nl> + <nl> + for test_case in test_cases : <nl> + with ops . Graph ( ) . as_default ( ) as g : <nl> + dataset = dataset_ops . Dataset . from_tensors ( test_case [ ' tensor ' ] ) <nl> + iterator = dataset . make_one_shot_iterator ( ) <nl> + get_next = iterator . get_next ( ) <nl> + train_op = ops . get_collection_ref ( ops . GraphKeys . TRAIN_OP ) <nl> + train_op . append ( get_next ) <nl> + mg = meta_graph . create_meta_graph_def ( graph = g ) <nl> + grappler_item = item . Item ( mg ) <nl> + op_properties = grappler_item . GetOpProperties ( ) <nl> + self . assertEqual ( test_case [ ' shape ' ] , <nl> + op_properties [ ' IteratorGetNext ' ] [ 0 ] . shape ) <nl> + <nl> + def testFromTensorSlices ( self ) : <nl> + test_cases = [ { <nl> + ' tensor ' : np . array ( [ 1 , 2 , 3 ] ) , <nl> + ' shape ' : tensor_shape . TensorShape ( [ ] ) <nl> + } , { <nl> + ' tensor ' : np . array ( [ [ 1 , 2 , 3 ] ] ) , <nl> + ' shape ' : tensor_shape . TensorShape ( [ 3 ] ) <nl> + } , { <nl> + ' tensor ' : np . array ( [ [ [ 1 , 2 , 3 ] ] ] ) , <nl> + ' shape ' : tensor_shape . TensorShape ( [ 1 , 3 ] ) <nl> + } ] <nl> + <nl> + for test_case in test_cases : <nl> + with ops . Graph ( ) . as_default ( ) as g : <nl> + dataset = dataset_ops . Dataset . from_tensor_slices ( test_case [ ' tensor ' ] ) <nl> + iterator = dataset . make_one_shot_iterator ( ) <nl> + get_next = iterator . get_next ( ) <nl> + train_op = ops . get_collection_ref ( ops . GraphKeys . TRAIN_OP ) <nl> + train_op . append ( get_next ) <nl> + mg = meta_graph . create_meta_graph_def ( graph = g ) <nl> + grappler_item = item . Item ( mg ) <nl> + op_properties = grappler_item . GetOpProperties ( ) <nl> + self . assertEqual ( test_case [ ' shape ' ] , <nl> + op_properties [ ' IteratorGetNext ' ] [ 0 ] . shape ) <nl> + <nl> + def testFromGenerator ( self ) : <nl> + test_cases = [ { <nl> + ' tensor ' : 0 , <nl> + ' shape ' : tensor_shape . TensorShape ( [ ] ) <nl> + } , { <nl> + ' tensor ' : np . array ( [ 1 , 2 , 3 ] ) , <nl> + ' shape ' : tensor_shape . TensorShape ( [ 3 ] ) <nl> + } , { <nl> + ' tensor ' : np . array ( [ [ 1 , 2 , 3 ] ] ) , <nl> + ' shape ' : tensor_shape . TensorShape ( [ 1 , 3 ] ) <nl> + } ] <nl> + <nl> + for test_case in test_cases : <nl> + <nl> + def make_generator ( tensor ) : <nl> + <nl> + def generator ( ) : <nl> + yield tensor <nl> + <nl> + return generator <nl> + <nl> + with ops . Graph ( ) . as_default ( ) as g : <nl> + dataset = dataset_ops . Dataset . from_generator ( <nl> + make_generator ( test_case [ ' tensor ' ] ) , <nl> + dtypes . int64 , <nl> + output_shapes = test_case [ ' shape ' ] ) <nl> + iterator = dataset . make_one_shot_iterator ( ) <nl> + get_next = iterator . get_next ( ) <nl> + train_op = ops . get_collection_ref ( ops . GraphKeys . TRAIN_OP ) <nl> + train_op . append ( get_next ) <nl> + mg = meta_graph . create_meta_graph_def ( graph = g ) <nl> + grappler_item = item . Item ( mg ) <nl> + op_properties = grappler_item . GetOpProperties ( ) <nl> + self . assertEqual ( test_case [ ' shape ' ] , <nl> + op_properties [ ' IteratorGetNext ' ] [ 0 ] . shape ) <nl> + <nl> + def testRange ( self ) : <nl> + with ops . Graph ( ) . as_default ( ) as g : <nl> + dataset = dataset_ops . Dataset . range ( 42 ) <nl> + iterator = dataset . make_one_shot_iterator ( ) <nl> + get_next = iterator . get_next ( ) <nl> + train_op = ops . get_collection_ref ( ops . GraphKeys . TRAIN_OP ) <nl> + train_op . append ( get_next ) <nl> + mg = meta_graph . create_meta_graph_def ( graph = g ) <nl> + grappler_item = item . Item ( mg ) <nl> + op_properties = grappler_item . GetOpProperties ( ) <nl> + self . assertEqual ( tensor_shape . scalar ( ) , <nl> + op_properties [ ' IteratorGetNext ' ] [ 0 ] . shape ) <nl> + <nl> + def _testTransformation ( self , fn ) : <nl> + test_cases = [ { <nl> + ' tensor ' : 0 , <nl> + ' shape ' : tensor_shape . TensorShape ( { } ) <nl> + } , { <nl> + ' tensor ' : np . array ( [ 1 , 2 , 3 ] ) , <nl> + ' shape ' : tensor_shape . TensorShape ( [ 3 ] ) <nl> + } , { <nl> + ' tensor ' : np . array ( [ [ 1 , 2 , 3 ] ] ) , <nl> + ' shape ' : tensor_shape . TensorShape ( [ 1 , 3 ] ) <nl> + } ] <nl> + <nl> + for test_case in test_cases : <nl> + with ops . Graph ( ) . as_default ( ) as g : <nl> + dataset = dataset_ops . Dataset . from_tensors ( test_case [ ' tensor ' ] ) <nl> + dataset = fn ( dataset , test_case [ ' tensor ' ] , test_case [ ' shape ' ] ) <nl> + iterator = dataset . make_one_shot_iterator ( ) <nl> + get_next = iterator . get_next ( ) <nl> + train_op = ops . get_collection_ref ( ops . GraphKeys . TRAIN_OP ) <nl> + train_op . append ( get_next ) <nl> + mg = meta_graph . create_meta_graph_def ( graph = g ) <nl> + grappler_item = item . Item ( mg ) <nl> + op_properties = grappler_item . GetOpProperties ( ) <nl> + self . assertEqual ( test_case [ ' shape ' ] , <nl> + op_properties [ ' IteratorGetNext ' ] [ 0 ] . shape ) <nl> + <nl> + def testConcatenate ( self ) : <nl> + <nl> + def fn ( dataset , tensor , shape ) : <nl> + del shape <nl> + return dataset . concatenate ( dataset_ops . Dataset . from_tensors ( tensor ) ) <nl> + <nl> + self . _testTransformation ( fn ) <nl> + <nl> + def testPrefetch ( self ) : <nl> + <nl> + def fn ( dataset , tensor , shape ) : <nl> + del tensor , shape <nl> + return dataset . prefetch ( 42 ) <nl> + <nl> + self . _testTransformation ( fn ) <nl> + <nl> + def testRepeat ( self ) : <nl> + <nl> + def fn ( dataset , tensor , shape ) : <nl> + del tensor , shape <nl> + return dataset . repeat ( 42 ) <nl> + <nl> + self . _testTransformation ( fn ) <nl> + <nl> + def testShuffle ( self ) : <nl> + <nl> + def fn ( dataset , tensor , shape ) : <nl> + del tensor , shape <nl> + return dataset . shuffle ( 42 ) <nl> + <nl> + self . _testTransformation ( fn ) <nl> + <nl> + def testCache ( self ) : <nl> + <nl> + def fn ( dataset , tensor , shape ) : <nl> + del tensor , shape <nl> + return dataset . cache ( ) <nl> + <nl> + self . _testTransformation ( fn ) <nl> + <nl> + def testTake ( self ) : <nl> + <nl> + def fn ( dataset , tensor , shape ) : <nl> + del tensor , shape <nl> + return dataset . take ( 42 ) <nl> + <nl> + self . _testTransformation ( fn ) <nl> + <nl> + def testSkip ( self ) : <nl> + <nl> + def fn ( dataset , tensor , shape ) : <nl> + del tensor , shape <nl> + return dataset . skip ( 42 ) <nl> + <nl> + self . _testTransformation ( fn ) <nl> + <nl> + def testShard ( self ) : <nl> + <nl> + def fn ( dataset , tensor , shape ) : <nl> + del tensor , shape <nl> + return dataset . shard ( 42 , 0 ) <nl> + <nl> + self . _testTransformation ( fn ) <nl> + <nl> + def testFilter ( self ) : <nl> + <nl> + def fn ( dataset , tensor , shape ) : <nl> + del tensor , shape <nl> + return dataset . filter ( lambda x : True ) <nl> + <nl> + self . _testTransformation ( fn ) <nl> + <nl> + def as_tensor_shape ( self , proto_with_symbolic_values ) : <nl> + for i in range ( len ( proto_with_symbolic_values . dim ) ) : <nl> + if proto_with_symbolic_values . dim [ i ] . size < - 1 : <nl> + proto_with_symbolic_values . dim [ i ] . size = - 1 <nl> + return tensor_shape . TensorShape ( proto_with_symbolic_values ) <nl> + <nl> + def testBatch ( self ) : <nl> + test_cases = [ { <nl> + ' tensor ' : 0 , <nl> + ' shape ' : tensor_shape . TensorShape ( [ None ] ) <nl> + } , { <nl> + ' tensor ' : np . array ( [ 1 , 2 , 3 ] ) , <nl> + ' shape ' : tensor_shape . TensorShape ( [ None , 3 ] ) <nl> + } , { <nl> + ' tensor ' : np . array ( [ [ 1 , 2 , 3 ] ] ) , <nl> + ' shape ' : tensor_shape . TensorShape ( [ None , 1 , 3 ] ) <nl> + } ] <nl> + <nl> + for test_case in test_cases : <nl> + with ops . Graph ( ) . as_default ( ) as g : <nl> + dataset = dataset_ops . Dataset . from_tensors ( test_case [ ' tensor ' ] ) <nl> + dataset = dataset . batch ( 42 ) <nl> + iterator = dataset . make_one_shot_iterator ( ) <nl> + get_next = iterator . get_next ( ) <nl> + train_op = ops . get_collection_ref ( ops . GraphKeys . TRAIN_OP ) <nl> + train_op . append ( get_next ) <nl> + mg = meta_graph . create_meta_graph_def ( graph = g ) <nl> + grappler_item = item . Item ( mg ) <nl> + op_properties = grappler_item . GetOpProperties ( ) <nl> + inferred_shape = self . as_tensor_shape ( <nl> + op_properties [ ' IteratorGetNext ' ] [ 0 ] . shape ) <nl> + self . assertTrue ( test_case [ ' shape ' ] [ 0 ] . is_compatible_with ( <nl> + inferred_shape [ 0 ] ) ) <nl> + self . assertEqual ( test_case [ ' shape ' ] [ 1 : ] , inferred_shape [ 1 : ] ) <nl> + <nl> + def testPaddedBatch ( self ) : <nl> + test_cases = [ { <nl> + ' tensor ' : 0 , <nl> + ' shape ' : tensor_shape . TensorShape ( [ None ] ) <nl> + } , { <nl> + ' tensor ' : np . array ( [ 1 , 2 , 3 ] ) , <nl> + ' shape ' : tensor_shape . TensorShape ( [ None , 4 ] ) <nl> + } , { <nl> + ' tensor ' : np . array ( [ [ 1 , 2 , 3 ] ] ) , <nl> + ' shape ' : tensor_shape . TensorShape ( [ None , 2 , 4 ] ) <nl> + } ] <nl> + <nl> + for test_case in test_cases : <nl> + with ops . Graph ( ) . as_default ( ) as g : <nl> + dataset = dataset_ops . Dataset . from_tensors ( test_case [ ' tensor ' ] ) <nl> + dataset = dataset . padded_batch ( 42 , padded_shapes = test_case [ ' shape ' ] [ 1 : ] ) <nl> + iterator = dataset . make_one_shot_iterator ( ) <nl> + get_next = iterator . get_next ( ) <nl> + train_op = ops . get_collection_ref ( ops . GraphKeys . TRAIN_OP ) <nl> + train_op . append ( get_next ) <nl> + mg = meta_graph . create_meta_graph_def ( graph = g ) <nl> + grappler_item = item . Item ( mg ) <nl> + op_properties = grappler_item . GetOpProperties ( ) <nl> + inferred_shape = self . as_tensor_shape ( <nl> + op_properties [ ' IteratorGetNext ' ] [ 0 ] . shape ) <nl> + self . assertTrue ( test_case [ ' shape ' ] [ 0 ] . is_compatible_with ( <nl> + inferred_shape [ 0 ] ) ) <nl> + self . assertEqual ( test_case [ ' shape ' ] [ 1 : ] , inferred_shape [ 1 : ] ) <nl> + <nl> + def testFlatMap ( self ) : <nl> + test_cases = [ { <nl> + ' tensor ' : 0 , <nl> + ' shape ' : tensor_shape . TensorShape ( [ ] ) <nl> + } , { <nl> + ' tensor ' : np . array ( [ 1 , 2 , 3 ] ) , <nl> + ' shape ' : tensor_shape . TensorShape ( [ 3 ] ) <nl> + } , { <nl> + ' tensor ' : np . array ( [ [ 1 , 2 , 3 ] ] ) , <nl> + ' shape ' : tensor_shape . TensorShape ( [ 1 , 3 ] ) <nl> + } ] <nl> + <nl> + for test_case in test_cases : <nl> + with ops . Graph ( ) . as_default ( ) as g : <nl> + dataset = dataset_ops . Dataset . range ( 42 ) <nl> + <nl> + def make_dataset ( tensor ) : <nl> + <nl> + def dataset_fn ( n ) : <nl> + return dataset_ops . Dataset . from_tensors ( tensor ) . repeat ( n ) <nl> + <nl> + return dataset_fn <nl> + <nl> + dataset = dataset . flat_map ( make_dataset ( test_case [ ' tensor ' ] ) ) <nl> + iterator = dataset . make_one_shot_iterator ( ) <nl> + get_next = iterator . get_next ( ) <nl> + train_op = ops . get_collection_ref ( ops . GraphKeys . TRAIN_OP ) <nl> + train_op . append ( get_next ) <nl> + mg = meta_graph . create_meta_graph_def ( graph = g ) <nl> + grappler_item = item . Item ( mg ) <nl> + op_properties = grappler_item . GetOpProperties ( ) <nl> + self . assertEqual ( test_case [ ' shape ' ] , <nl> + op_properties [ ' IteratorGetNext ' ] [ 0 ] . shape ) <nl> + <nl> + def testInterleave ( self ) : <nl> + test_cases = [ { <nl> + ' tensor ' : 0 , <nl> + ' shape ' : tensor_shape . TensorShape ( [ ] ) <nl> + } , { <nl> + ' tensor ' : np . array ( [ 1 , 2 , 3 ] ) , <nl> + ' shape ' : tensor_shape . TensorShape ( [ 3 ] ) <nl> + } , { <nl> + ' tensor ' : np . array ( [ [ 1 , 2 , 3 ] ] ) , <nl> + ' shape ' : tensor_shape . TensorShape ( [ 1 , 3 ] ) <nl> + } ] <nl> + <nl> + for test_case in test_cases : <nl> + with ops . Graph ( ) . as_default ( ) as g : <nl> + dataset = dataset_ops . Dataset . range ( 42 ) <nl> + <nl> + def make_dataset ( tensor ) : <nl> + <nl> + def dataset_fn ( n ) : <nl> + return dataset_ops . Dataset . from_tensors ( tensor ) . repeat ( n ) <nl> + <nl> + return dataset_fn <nl> + <nl> + dataset = dataset . interleave ( <nl> + make_dataset ( test_case [ ' tensor ' ] ) , cycle_length = 42 ) <nl> + iterator = dataset . make_one_shot_iterator ( ) <nl> + get_next = iterator . get_next ( ) <nl> + train_op = ops . get_collection_ref ( ops . GraphKeys . TRAIN_OP ) <nl> + train_op . append ( get_next ) <nl> + mg = meta_graph . create_meta_graph_def ( graph = g ) <nl> + grappler_item = item . Item ( mg ) <nl> + op_properties = grappler_item . GetOpProperties ( ) <nl> + self . assertEqual ( test_case [ ' shape ' ] , <nl> + op_properties [ ' IteratorGetNext ' ] [ 0 ] . shape ) <nl> + <nl> + def testMap ( self ) : <nl> + test_cases = [ { <nl> + ' tensor ' : 0 , <nl> + ' shape ' : tensor_shape . TensorShape ( [ ] ) <nl> + } , { <nl> + ' tensor ' : np . array ( [ 1 , 2 , 3 ] ) , <nl> + ' shape ' : tensor_shape . TensorShape ( [ 3 ] ) <nl> + } , { <nl> + ' tensor ' : np . array ( [ [ 1 , 2 , 3 ] ] ) , <nl> + ' shape ' : tensor_shape . TensorShape ( [ 3 , 1 ] ) <nl> + } , { <nl> + ' tensor ' : np . array ( [ [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] ] ] ) , <nl> + ' shape ' : tensor_shape . TensorShape ( [ 3 , 2 , 1 ] ) <nl> + } ] <nl> + <nl> + for test_case in test_cases : <nl> + with ops . Graph ( ) . as_default ( ) as g : <nl> + dataset = dataset_ops . Dataset . from_tensors ( test_case [ ' tensor ' ] ) <nl> + dataset = dataset . map ( array_ops . transpose ) <nl> + iterator = dataset . make_one_shot_iterator ( ) <nl> + get_next = iterator . get_next ( ) <nl> + train_op = ops . get_collection_ref ( ops . GraphKeys . TRAIN_OP ) <nl> + train_op . append ( get_next ) <nl> + mg = meta_graph . create_meta_graph_def ( graph = g ) <nl> + grappler_item = item . Item ( mg ) <nl> + op_properties = grappler_item . GetOpProperties ( ) <nl> + self . assertEqual ( test_case [ ' shape ' ] , <nl> + op_properties [ ' IteratorGetNext ' ] [ 0 ] . shape ) <nl> + <nl> + def testFromStructure ( self ) : <nl> + test_cases = [ { <nl> + ' shape ' : tensor_shape . TensorShape ( [ ] ) <nl> + } , { <nl> + ' shape ' : tensor_shape . TensorShape ( [ 3 ] ) <nl> + } , { <nl> + ' shape ' : tensor_shape . TensorShape ( [ 1 , 2 ] ) <nl> + } , { <nl> + ' shape ' : tensor_shape . TensorShape ( [ 1 , 2 , 3 ] ) <nl> + } ] <nl> + <nl> + for test_case in test_cases : <nl> + with ops . Graph ( ) . as_default ( ) as g : <nl> + iterator = iterator_ops . Iterator . from_structure ( <nl> + dtypes . int64 , output_shapes = test_case [ ' shape ' ] ) <nl> + get_next = iterator . get_next ( ) <nl> + train_op = ops . get_collection_ref ( ops . GraphKeys . TRAIN_OP ) <nl> + train_op . append ( get_next ) <nl> + mg = meta_graph . create_meta_graph_def ( graph = g ) <nl> + grappler_item = item . Item ( mg ) <nl> + op_properties = grappler_item . GetOpProperties ( ) <nl> + self . assertEqual ( test_case [ ' shape ' ] , <nl> + op_properties [ ' IteratorGetNext ' ] [ 0 ] . shape ) <nl> + <nl> + def testFromStringHandle ( self ) : <nl> + test_cases = [ { <nl> + ' shape ' : tensor_shape . TensorShape ( [ ] ) <nl> + } , { <nl> + ' shape ' : tensor_shape . TensorShape ( [ 3 ] ) <nl> + } , { <nl> + ' shape ' : tensor_shape . TensorShape ( [ 1 , 2 ] ) <nl> + } , { <nl> + ' shape ' : tensor_shape . TensorShape ( [ 1 , 2 , 3 ] ) <nl> + } ] <nl> + <nl> + for test_case in test_cases : <nl> + with ops . Graph ( ) . as_default ( ) as g : <nl> + iterator = iterator_ops . Iterator . from_structure ( dtypes . int64 ) <nl> + handle = iterator . string_handle ( ) <nl> + iterator = iterator_ops . Iterator . from_string_handle ( <nl> + handle , dtypes . int64 , output_shapes = test_case [ ' shape ' ] ) <nl> + get_next = iterator . get_next ( ) <nl> + train_op = ops . get_collection_ref ( ops . GraphKeys . TRAIN_OP ) <nl> + train_op . append ( get_next ) <nl> + mg = meta_graph . create_meta_graph_def ( graph = g ) <nl> + grappler_item = item . Item ( mg ) <nl> + op_properties = grappler_item . GetOpProperties ( ) <nl> + self . assertEqual ( test_case [ ' shape ' ] , <nl> + op_properties [ ' IteratorGetNext ' ] [ 0 ] . shape ) <nl> + <nl> + <nl> + if __name__ = = ' __main__ ' : <nl> + test . main ( ) <nl> | Adding a test that checks that Grappler is able to infer shapes for core ` tf . data ` API . | tensorflow/tensorflow | ad82d251fbf937e95f578e7980b0b10936eda62a | 2017-12-22T01:38:31Z |
mmm a / src / btree / btree_store . cc <nl> ppp b / src / btree / btree_store . cc <nl> void btree_store_t < protocol_t > : : acquire_superblock_for_write ( <nl> template < class protocol_t > <nl> void btree_store_t < protocol_t > : : new_read_token ( object_buffer_t < fifo_enforcer_sink_t : : exit_read_t > * token_out ) { <nl> assert_thread ( ) ; <nl> - fifo_enforcer_read_token_t token = token_source . enter_read ( ) ; <nl> - token_out - > create ( & token_sink , token ) ; <nl> + fifo_enforcer_read_token_t token = main_token_source . enter_read ( ) ; <nl> + token_out - > create ( & main_token_sink , token ) ; <nl> } <nl> <nl> template < class protocol_t > <nl> void btree_store_t < protocol_t > : : new_write_token ( object_buffer_t < fifo_enforcer_sink_t : : exit_write_t > * token_out ) { <nl> assert_thread ( ) ; <nl> - fifo_enforcer_write_token_t token = token_source . enter_write ( ) ; <nl> - token_out - > create ( & token_sink , token ) ; <nl> + fifo_enforcer_write_token_t token = main_token_source . enter_write ( ) ; <nl> + token_out - > create ( & main_token_sink , token ) ; <nl> } <nl> <nl> + template < class protocol_t > <nl> + void btree_store_t < protocol_t > : : new_sindex_read_token ( object_buffer_t < fifo_enforcer_sink_t : : exit_read_t > * token_out ) { <nl> + assert_thread ( ) ; <nl> + fifo_enforcer_read_token_t token = sindex_token_source . enter_read ( ) ; <nl> + token_out - > create ( & sindex_token_sink , token ) ; <nl> + } <nl> + <nl> + template < class protocol_t > <nl> + void btree_store_t < protocol_t > : : new_sindex_write_token ( object_buffer_t < fifo_enforcer_sink_t : : exit_write_t > * token_out ) { <nl> + assert_thread ( ) ; <nl> + fifo_enforcer_write_token_t token = sindex_token_source . enter_write ( ) ; <nl> + token_out - > create ( & sindex_token_sink , token ) ; <nl> + } <nl> + <nl> + template < class protocol_t > <nl> + void new_sindex_write_token ( object_buffer_t < fifo_enforcer_sink_t : : exit_write_t > * token_out ) ; <nl> + <nl> # include " memcached / protocol . hpp " <nl> template class btree_store_t < memcached_protocol_t > ; <nl> <nl> mmm a / src / btree / btree_store . hpp <nl> ppp b / src / btree / btree_store . hpp <nl> class btree_store_t : public store_view_t < protocol_t > { <nl> void new_read_token ( object_buffer_t < fifo_enforcer_sink_t : : exit_read_t > * token_out ) ; <nl> void new_write_token ( object_buffer_t < fifo_enforcer_sink_t : : exit_write_t > * token_out ) ; <nl> <nl> + void new_sindex_read_token ( object_buffer_t < fifo_enforcer_sink_t : : exit_read_t > * token_out ) ; <nl> + void new_sindex_write_token ( object_buffer_t < fifo_enforcer_sink_t : : exit_write_t > * token_out ) ; <nl> + <nl> typedef region_map_t < protocol_t , binary_blob_t > metainfo_t ; <nl> <nl> void do_get_metainfo ( <nl> class btree_store_t : public store_view_t < protocol_t > { <nl> signal_t * interruptor ) <nl> THROWS_ONLY ( interrupted_exc_t ) ; <nl> <nl> + btree_slice_t * get_sindex_slice ( uuid_t id ) { <nl> + return & ( secondary_index_slices . at ( id ) ) ; <nl> + } <nl> + <nl> protected : <nl> / / Functions to be implemented by derived ( protocol - specific ) store_t classes <nl> virtual void protocol_read ( const typename protocol_t : : read_t & read , <nl> class btree_store_t : public store_view_t < protocol_t > { <nl> mirrored_cache_config_t cache_dynamic_config ; <nl> order_source_t order_source ; <nl> <nl> - fifo_enforcer_source_t token_source ; <nl> - fifo_enforcer_sink_t token_sink ; <nl> + fifo_enforcer_source_t main_token_source , sindex_token_source ; <nl> + fifo_enforcer_sink_t main_token_sink , sindex_token_sink ; <nl> <nl> perfmon_collection_t perfmon_collection ; <nl> scoped_ptr_t < cache_t > cache ; <nl> mmm a / src / unittest / btree_sindex . cc <nl> ppp b / src / unittest / btree_sindex . cc <nl> void run_sindex_btree_store_api_test ( ) { <nl> & dummy_interuptor ) ; <nl> } <nl> <nl> + { <nl> + / / Insert a piece of data in to the btree . <nl> + object_buffer_t < fifo_enforcer_sink_t : : exit_write_t > token ; <nl> + store . new_write_token ( & token ) ; <nl> + <nl> + object_buffer_t < fifo_enforcer_sink_t : : exit_write_t > sindex_token ; <nl> + store . new_sindex_write_token ( & sindex_token ) ; <nl> + <nl> + scoped_ptr_t < transaction_t > txn ; <nl> + scoped_ptr_t < real_superblock_t > super_block ; <nl> + <nl> + store . acquire_superblock_for_write ( rwi_write , repli_timestamp_t : : invalid , <nl> + 1 , & token , & txn , & super_block , & dummy_interuptor ) ; <nl> + <nl> + scoped_ptr_t < real_superblock_t > sindex_super_block ; <nl> + <nl> + store . acquire_sindex_superblock_for_write ( id , & sindex_token , txn . get ( ) , & sindex_super_block , super_block - > get ( ) , & dummy_interuptor ) ; <nl> + <nl> + store_key_t key ( " foo " ) ; <nl> + boost : : shared_ptr < scoped_cJSON_t > data ( new scoped_cJSON_t ( cJSON_CreateNumber ( 1 ) ) ) ; <nl> + <nl> + rdb_protocol_t : : point_write_response_t response ; <nl> + <nl> + rdb_set ( key , data , true , store . get_sindex_slice ( id ) , repli_timestamp_t : : invalid , <nl> + txn . get ( ) , sindex_super_block . get ( ) , & response ) ; <nl> + } <nl> + <nl> + { <nl> + / / Read that data <nl> + object_buffer_t < fifo_enforcer_sink_t : : exit_read_t > token ; <nl> + store . new_read_token ( & token ) ; <nl> + <nl> + object_buffer_t < fifo_enforcer_sink_t : : exit_read_t > sindex_token ; <nl> + store . new_sindex_read_token ( & sindex_token ) ; <nl> + <nl> + scoped_ptr_t < transaction_t > txn ; <nl> + scoped_ptr_t < real_superblock_t > super_block ; <nl> + <nl> + store . acquire_superblock_for_read ( rwi_read , & token , & txn , & super_block , & dummy_interuptor , false ) ; <nl> + <nl> + scoped_ptr_t < real_superblock_t > sindex_super_block ; <nl> + <nl> + store . acquire_sindex_superblock_for_read ( id , & sindex_token , txn . get ( ) , & sindex_super_block , super_block - > get ( ) , & dummy_interuptor ) ; <nl> + <nl> + point_read_response_t response ; <nl> + <nl> + rdb_get ( store_key_t ( " foo " ) , store . get_sindex_slice ( id ) , txn . get ( ) , sindex_super_block . get ( ) , & response ) ; <nl> + <nl> + boost : : shared_ptr < scoped_cJSON_t > data ( new scoped_cJSON_t ( cJSON_CreateNumber ( 1 ) ) ) ; <nl> + ASSERT_EQ ( query_language : : json_cmp ( response . data - > get ( ) , data - > get ( ) ) , 0 ) ; <nl> + } <nl> + <nl> { <nl> object_buffer_t < fifo_enforcer_sink_t : : exit_write_t > token ; <nl> store . new_write_token ( & token ) ; <nl> | Adds a unittest for underlying structures . | rethinkdb/rethinkdb | 2ccd6bed5e5eda89aa5c0fd5b0be60c58ed532f8 | 2013-01-08T00:19:50Z |
mmm a / grpc . def <nl> ppp b / grpc . def <nl> EXPORTS <nl> census_resource_id <nl> census_record_values <nl> grpc_compression_algorithm_parse <nl> - grpc_stream_compression_algorithm_parse <nl> grpc_compression_algorithm_name <nl> + grpc_stream_compression_algorithm_name <nl> grpc_compression_algorithm_for_level <nl> + grpc_stream_compression_algorithm_for_level <nl> grpc_compression_options_init <nl> grpc_compression_options_enable_algorithm <nl> grpc_compression_options_disable_algorithm <nl> grpc_compression_options_is_algorithm_enabled <nl> + grpc_compression_options_is_stream_compression_algorithm_enabled <nl> grpc_metadata_array_init <nl> grpc_metadata_array_destroy <nl> grpc_call_details_init <nl> mmm a / src / ruby / ext / grpc / rb_grpc_imports . generated . c <nl> ppp b / src / ruby / ext / grpc / rb_grpc_imports . generated . c <nl> census_delete_resource_type census_delete_resource_import ; <nl> census_resource_id_type census_resource_id_import ; <nl> census_record_values_type census_record_values_import ; <nl> grpc_compression_algorithm_parse_type grpc_compression_algorithm_parse_import ; <nl> - grpc_stream_compression_algorithm_parse_type grpc_stream_compression_algorithm_parse_import ; <nl> grpc_compression_algorithm_name_type grpc_compression_algorithm_name_import ; <nl> + grpc_stream_compression_algorithm_name_type grpc_stream_compression_algorithm_name_import ; <nl> grpc_compression_algorithm_for_level_type grpc_compression_algorithm_for_level_import ; <nl> + grpc_stream_compression_algorithm_for_level_type grpc_stream_compression_algorithm_for_level_import ; <nl> grpc_compression_options_init_type grpc_compression_options_init_import ; <nl> grpc_compression_options_enable_algorithm_type grpc_compression_options_enable_algorithm_import ; <nl> grpc_compression_options_disable_algorithm_type grpc_compression_options_disable_algorithm_import ; <nl> grpc_compression_options_is_algorithm_enabled_type grpc_compression_options_is_algorithm_enabled_import ; <nl> + grpc_compression_options_is_stream_compression_algorithm_enabled_type grpc_compression_options_is_stream_compression_algorithm_enabled_import ; <nl> grpc_metadata_array_init_type grpc_metadata_array_init_import ; <nl> grpc_metadata_array_destroy_type grpc_metadata_array_destroy_import ; <nl> grpc_call_details_init_type grpc_call_details_init_import ; <nl> void grpc_rb_load_imports ( HMODULE library ) { <nl> census_resource_id_import = ( census_resource_id_type ) GetProcAddress ( library , " census_resource_id " ) ; <nl> census_record_values_import = ( census_record_values_type ) GetProcAddress ( library , " census_record_values " ) ; <nl> grpc_compression_algorithm_parse_import = ( grpc_compression_algorithm_parse_type ) GetProcAddress ( library , " grpc_compression_algorithm_parse " ) ; <nl> - grpc_stream_compression_algorithm_parse_import = ( grpc_stream_compression_algorithm_parse_type ) GetProcAddress ( library , " grpc_stream_compression_algorithm_parse " ) ; <nl> grpc_compression_algorithm_name_import = ( grpc_compression_algorithm_name_type ) GetProcAddress ( library , " grpc_compression_algorithm_name " ) ; <nl> + grpc_stream_compression_algorithm_name_import = ( grpc_stream_compression_algorithm_name_type ) GetProcAddress ( library , " grpc_stream_compression_algorithm_name " ) ; <nl> grpc_compression_algorithm_for_level_import = ( grpc_compression_algorithm_for_level_type ) GetProcAddress ( library , " grpc_compression_algorithm_for_level " ) ; <nl> + grpc_stream_compression_algorithm_for_level_import = ( grpc_stream_compression_algorithm_for_level_type ) GetProcAddress ( library , " grpc_stream_compression_algorithm_for_level " ) ; <nl> grpc_compression_options_init_import = ( grpc_compression_options_init_type ) GetProcAddress ( library , " grpc_compression_options_init " ) ; <nl> grpc_compression_options_enable_algorithm_import = ( grpc_compression_options_enable_algorithm_type ) GetProcAddress ( library , " grpc_compression_options_enable_algorithm " ) ; <nl> grpc_compression_options_disable_algorithm_import = ( grpc_compression_options_disable_algorithm_type ) GetProcAddress ( library , " grpc_compression_options_disable_algorithm " ) ; <nl> grpc_compression_options_is_algorithm_enabled_import = ( grpc_compression_options_is_algorithm_enabled_type ) GetProcAddress ( library , " grpc_compression_options_is_algorithm_enabled " ) ; <nl> + grpc_compression_options_is_stream_compression_algorithm_enabled_import = ( grpc_compression_options_is_stream_compression_algorithm_enabled_type ) GetProcAddress ( library , " grpc_compression_options_is_stream_compression_algorithm_enabled " ) ; <nl> grpc_metadata_array_init_import = ( grpc_metadata_array_init_type ) GetProcAddress ( library , " grpc_metadata_array_init " ) ; <nl> grpc_metadata_array_destroy_import = ( grpc_metadata_array_destroy_type ) GetProcAddress ( library , " grpc_metadata_array_destroy " ) ; <nl> grpc_call_details_init_import = ( grpc_call_details_init_type ) GetProcAddress ( library , " grpc_call_details_init " ) ; <nl> mmm a / src / ruby / ext / grpc / rb_grpc_imports . generated . h <nl> ppp b / src / ruby / ext / grpc / rb_grpc_imports . generated . h <nl> extern census_record_values_type census_record_values_import ; <nl> typedef int ( * grpc_compression_algorithm_parse_type ) ( grpc_slice value , grpc_compression_algorithm * algorithm ) ; <nl> extern grpc_compression_algorithm_parse_type grpc_compression_algorithm_parse_import ; <nl> # define grpc_compression_algorithm_parse grpc_compression_algorithm_parse_import <nl> - typedef int ( * grpc_stream_compression_algorithm_parse_type ) ( grpc_slice value , grpc_compression_algorithm * algorithm ) ; <nl> - extern grpc_stream_compression_algorithm_parse_type grpc_stream_compression_algorithm_parse_import ; <nl> - # define grpc_stream_compression_algorithm_parse grpc_stream_compression_algorithm_parse_import <nl> typedef int ( * grpc_compression_algorithm_name_type ) ( grpc_compression_algorithm algorithm , char * * name ) ; <nl> extern grpc_compression_algorithm_name_type grpc_compression_algorithm_name_import ; <nl> # define grpc_compression_algorithm_name grpc_compression_algorithm_name_import <nl> + typedef int ( * grpc_stream_compression_algorithm_name_type ) ( grpc_stream_compression_algorithm algorithm , char * * name ) ; <nl> + extern grpc_stream_compression_algorithm_name_type grpc_stream_compression_algorithm_name_import ; <nl> + # define grpc_stream_compression_algorithm_name grpc_stream_compression_algorithm_name_import <nl> typedef grpc_compression_algorithm ( * grpc_compression_algorithm_for_level_type ) ( grpc_compression_level level , uint32_t accepted_encodings ) ; <nl> extern grpc_compression_algorithm_for_level_type grpc_compression_algorithm_for_level_import ; <nl> # define grpc_compression_algorithm_for_level grpc_compression_algorithm_for_level_import <nl> + typedef grpc_stream_compression_algorithm ( * grpc_stream_compression_algorithm_for_level_type ) ( grpc_stream_compression_level level , uint32_t accepted_stream_encodings ) ; <nl> + extern grpc_stream_compression_algorithm_for_level_type grpc_stream_compression_algorithm_for_level_import ; <nl> + # define grpc_stream_compression_algorithm_for_level grpc_stream_compression_algorithm_for_level_import <nl> typedef void ( * grpc_compression_options_init_type ) ( grpc_compression_options * opts ) ; <nl> extern grpc_compression_options_init_type grpc_compression_options_init_import ; <nl> # define grpc_compression_options_init grpc_compression_options_init_import <nl> extern grpc_compression_options_disable_algorithm_type grpc_compression_options_ <nl> typedef int ( * grpc_compression_options_is_algorithm_enabled_type ) ( const grpc_compression_options * opts , grpc_compression_algorithm algorithm ) ; <nl> extern grpc_compression_options_is_algorithm_enabled_type grpc_compression_options_is_algorithm_enabled_import ; <nl> # define grpc_compression_options_is_algorithm_enabled grpc_compression_options_is_algorithm_enabled_import <nl> + typedef int ( * grpc_compression_options_is_stream_compression_algorithm_enabled_type ) ( const grpc_compression_options * opts , grpc_stream_compression_algorithm algorithm ) ; <nl> + extern grpc_compression_options_is_stream_compression_algorithm_enabled_type grpc_compression_options_is_stream_compression_algorithm_enabled_import ; <nl> + # define grpc_compression_options_is_stream_compression_algorithm_enabled grpc_compression_options_is_stream_compression_algorithm_enabled_import <nl> typedef void ( * grpc_metadata_array_init_type ) ( grpc_metadata_array * array ) ; <nl> extern grpc_metadata_array_init_type grpc_metadata_array_init_import ; <nl> # define grpc_metadata_array_init grpc_metadata_array_init_import <nl> | generate_project | grpc/grpc | b32c23a9e74522e377ba4f55248cb0e1de099f96 | 2017-07-26T21:49:53Z |
mmm a / src / training / stringrenderer . cpp <nl> ppp b / src / training / stringrenderer . cpp <nl> StringRenderer : : StringRenderer ( const std : : string & font_desc , int page_width , <nl> font_index_ ( 0 ) , <nl> last_offset_ ( 0 ) { <nl> set_resolution ( kDefaultOutputResolution ) ; <nl> + set_font ( font_desc ) ; <nl> } <nl> <nl> bool StringRenderer : : set_font ( const std : : string & desc ) { <nl> | Fixed access to uninitialized variable | tesseract-ocr/tesseract | a7d1402e5d9d793e5cceaf7adda6e3c16f3b5c93 | 2018-05-02T14:11:35Z |
mmm a / src / webui / webapplication . cpp <nl> ppp b / src / webui / webapplication . cpp <nl> <nl> # include " base / utils / bytearray . h " <nl> # include " base / utils / fs . h " <nl> # include " base / utils / misc . h " <nl> - # include " base / utils / net . h " <nl> # include " base / utils / random . h " <nl> # include " base / utils / string . h " <nl> # include " api / apierror . h " <nl> void WebApplication : : configure ( ) <nl> { <nl> const auto pref = Preferences : : instance ( ) ; <nl> <nl> - m_domainList = pref - > getServerDomains ( ) . split ( ' ; ' , QString : : SkipEmptyParts ) ; <nl> - std : : for_each ( m_domainList . begin ( ) , m_domainList . end ( ) , [ ] ( QString & entry ) { entry = entry . trimmed ( ) ; } ) ; <nl> - <nl> const QString rootFolder = Utils : : Fs : : expandPathAbs ( <nl> ! pref - > isAltWebUiEnabled ( ) ? WWW_FOLDER : pref - > getWebUiRootFolder ( ) ) ; <nl> if ( rootFolder ! = m_rootFolder ) { <nl> void WebApplication : : configure ( ) <nl> m_translatedFiles . clear ( ) ; <nl> } <nl> <nl> + m_isLocalAuthEnabled = pref - > isWebUiLocalAuthEnabled ( ) ; <nl> + m_isAuthSubnetWhitelistEnabled = pref - > isWebUiAuthSubnetWhitelistEnabled ( ) ; <nl> + m_authSubnetWhitelist = pref - > getWebUiAuthSubnetWhitelist ( ) ; <nl> + <nl> + m_domainList = pref - > getServerDomains ( ) . split ( ' ; ' , QString : : SkipEmptyParts ) ; <nl> + std : : for_each ( m_domainList . begin ( ) , m_domainList . end ( ) , [ ] ( QString & entry ) { entry = entry . trimmed ( ) ; } ) ; <nl> + <nl> m_isClickjackingProtectionEnabled = pref - > isWebUiClickjackingProtectionEnabled ( ) ; <nl> m_isCSRFProtectionEnabled = pref - > isWebUiCSRFProtectionEnabled ( ) ; <nl> m_isHttpsEnabled = pref - > isWebUiHttpsEnabled ( ) ; <nl> QString WebApplication : : generateSid ( ) const <nl> <nl> bool WebApplication : : isAuthNeeded ( ) <nl> { <nl> - qDebug ( " Checking auth rules against client address % s " , qPrintable ( m_env . clientAddress . toString ( ) ) ) ; <nl> - const Preferences * pref = Preferences : : instance ( ) ; <nl> - if ( ! pref - > isWebUiLocalAuthEnabled ( ) & & Utils : : Net : : isLoopbackAddress ( m_env . clientAddress ) ) <nl> + if ( ! m_isLocalAuthEnabled & & Utils : : Net : : isLoopbackAddress ( m_env . clientAddress ) ) <nl> return false ; <nl> - if ( pref - > isWebUiAuthSubnetWhitelistEnabled ( ) & & Utils : : Net : : isIPInRange ( m_env . clientAddress , pref - > getWebUiAuthSubnetWhitelist ( ) ) ) <nl> + if ( m_isAuthSubnetWhitelistEnabled & & Utils : : Net : : isIPInRange ( m_env . clientAddress , m_authSubnetWhitelist ) ) <nl> return false ; <nl> return true ; <nl> } <nl> mmm a / src / webui / webapplication . h <nl> ppp b / src / webui / webapplication . h <nl> <nl> # include " base / http / irequesthandler . h " <nl> # include " base / http / responsebuilder . h " <nl> # include " base / http / types . h " <nl> + # include " base / utils / net . h " <nl> # include " base / utils / version . h " <nl> <nl> constexpr Utils : : Version < int , 3 , 2 > API_VERSION { 2 , 0 , 1 } ; <nl> class WebApplication <nl> QSet < QString > m_publicAPIs ; <nl> bool m_isAltUIUsed = false ; <nl> QString m_rootFolder ; <nl> - QStringList m_domainList ; <nl> <nl> struct TranslatedFile <nl> { <nl> class WebApplication <nl> QMap < QString , TranslatedFile > m_translatedFiles ; <nl> QString m_currentLocale ; <nl> <nl> + bool m_isLocalAuthEnabled ; <nl> + bool m_isAuthSubnetWhitelistEnabled ; <nl> + QList < Utils : : Net : : Subnet > m_authSubnetWhitelist ; <nl> + <nl> / / security related <nl> + QStringList m_domainList ; <nl> bool m_isClickjackingProtectionEnabled ; <nl> bool m_isCSRFProtectionEnabled ; <nl> bool m_isHttpsEnabled ; <nl> | Cache more preference values | qbittorrent/qBittorrent | e04aae686ff773b2337822008a22f0d2b1c7aeb7 | 2018-07-14T07:48:18Z |
similarity index 100 % <nl> rename from js / common / tests / shell / shell - v8 - disabled . js <nl> rename to js / common / tests / shell / shell - v8 . js <nl> | Revert " Disable testcases for now , it triggers the crash on windows . " | arangodb/arangodb | 92e1580ace44daf23beaaa244fa371d9bac1f2bf | 2016-08-17T07:32:30Z |
deleted file mode 100644 <nl> index 6c9e19ca6c . . 0000000000 <nl> mmm a / change / react - native - windows - 2020 - 02 - 07 - 19 - 14 - 14 - image - rtl . json <nl> ppp / dev / null <nl> <nl> - { <nl> - " type " : " none " , <nl> - " comment " : " Flip ImageView in rtl mode " , <nl> - " packageName " : " react - native - windows " , <nl> - " email " : " guokai . ok @ gmail . com " , <nl> - " commit " : " 426f7b1af8f0f5d019cdf6d4036df4e9c0edab68 " , <nl> - " dependentChangeType " : " patch " , <nl> - " date " : " 2020 - 02 - 08T03 : 14 : 14 . 206Z " <nl> - } <nl> \ No newline at end of file <nl> mmm a / packages / E2ETest / package . json <nl> ppp b / packages / E2ETest / package . json <nl> <nl> " react " : " 16 . 9 . 0 " , <nl> " react - native " : " 0 . 61 . 5 " , <nl> " react - native - windows " : " 0 . 61 . 0 - beta . 7 " , <nl> - " react - native - windows - extended " : " 0 . 61 . 0 - beta . 11 " , <nl> + " react - native - windows - extended " : " 0 . 61 . 0 - beta . 12 " , <nl> " rnpm - plugin - windows " : " ^ 0 . 5 . 1 - 0 " <nl> } , <nl> " devDependencies " : { <nl> mmm a / packages / microsoft - reactnative - sampleapps / package . json <nl> ppp b / packages / microsoft - reactnative - sampleapps / package . json <nl> <nl> " react " : " 16 . 9 . 0 " , <nl> " react - native " : " 0 . 61 . 5 " , <nl> " react - native - windows " : " 0 . 61 . 0 - beta . 7 " , <nl> - " react - native - windows - extended " : " 0 . 61 . 0 - beta . 11 " , <nl> + " react - native - windows - extended " : " 0 . 61 . 0 - beta . 12 " , <nl> " rnpm - plugin - windows " : " ^ 0 . 5 . 1 - 0 " <nl> } , <nl> " devDependencies " : { <nl> mmm a / packages / playground / package . json <nl> ppp b / packages / playground / package . json <nl> <nl> " react " : " 16 . 9 . 0 " , <nl> " react - native " : " 0 . 61 . 5 " , <nl> " react - native - windows " : " 0 . 61 . 0 - beta . 7 " , <nl> - " react - native - windows - extended " : " 0 . 61 . 0 - beta . 11 " , <nl> + " react - native - windows - extended " : " 0 . 61 . 0 - beta . 12 " , <nl> " rnpm - plugin - windows " : " ^ 0 . 5 . 1 - 0 " <nl> } , <nl> " devDependencies " : { <nl> mmm a / packages / react - native - windows - extended / package . json <nl> ppp b / packages / react - native - windows - extended / package . json <nl> <nl> { <nl> " name " : " react - native - windows - extended " , <nl> - " version " : " 0 . 61 . 0 - beta . 11 " , <nl> + " version " : " 0 . 61 . 0 - beta . 12 " , <nl> " description " : " Additional react - native - windows components that are not part of RN lean - core . " , <nl> " main " : " lib / index . js " , <nl> " repository " : { <nl> mmm a / vnext / CHANGELOG . json <nl> ppp b / vnext / CHANGELOG . json <nl> <nl> { <nl> " name " : " react - native - windows " , <nl> " entries " : [ <nl> + { <nl> + " date " : " Thu , 13 Feb 2020 22 : 20 : 11 GMT " , <nl> + " tag " : " react - native - windows_v0 . 61 . 0 - beta . 7 " , <nl> + " version " : " 0 . 61 . 0 - beta . 7 " , <nl> + " comments " : { <nl> + " none " : [ <nl> + { <nl> + " comment " : " Flip ImageView in rtl mode " , <nl> + " author " : " guokai . ok @ gmail . com " , <nl> + " commit " : " 426f7b1af8f0f5d019cdf6d4036df4e9c0edab68 " <nl> + } <nl> + ] <nl> + } <nl> + } , <nl> { <nl> " date " : " Thu , 13 Feb 2020 21 : 30 : 14 GMT " , <nl> " tag " : " react - native - windows_v0 . 61 . 0 - beta . 7 " , <nl> | applying package updates * * * NO_CI * * * | microsoft/react-native-windows | ed8bda6fa640751d0250c542d50ead5420ca7261 | 2020-02-13T22:20:11Z |
mmm a / modules / canbus / vehicle / lincoln / protocol / accel_6b . h <nl> ppp b / modules / canbus / vehicle / lincoln / protocol / accel_6b . h <nl> namespace apollo { <nl> namespace canbus { <nl> namespace lincoln { <nl> <nl> + using : : apollo : : common : : canbus : : ProtocolData ; <nl> + <nl> / * * <nl> * @ class Accel6b <nl> * <nl> mmm a / modules / canbus / vehicle / lincoln / protocol / brake_60 . h <nl> ppp b / modules / canbus / vehicle / lincoln / protocol / brake_60 . h <nl> namespace apollo { <nl> namespace canbus { <nl> namespace lincoln { <nl> <nl> + using : : apollo : : common : : canbus : : ProtocolData ; <nl> + <nl> / * * <nl> * @ class Brake60 <nl> * <nl> mmm a / modules / canbus / vehicle / lincoln / protocol / brake_61 . h <nl> ppp b / modules / canbus / vehicle / lincoln / protocol / brake_61 . h <nl> namespace apollo { <nl> namespace canbus { <nl> namespace lincoln { <nl> <nl> + using : : apollo : : common : : canbus : : ProtocolData ; <nl> + <nl> / * * <nl> * @ class Brake61 <nl> * <nl> mmm a / modules / canbus / vehicle / lincoln / protocol / brakeinfo_74 . h <nl> ppp b / modules / canbus / vehicle / lincoln / protocol / brakeinfo_74 . h <nl> namespace apollo { <nl> namespace canbus { <nl> namespace lincoln { <nl> <nl> + using : : apollo : : common : : canbus : : ProtocolData ; <nl> + <nl> / * * <nl> * @ class Brakeinfo74 <nl> * <nl> mmm a / modules / canbus / vehicle / lincoln / protocol / fuellevel_72 . h <nl> ppp b / modules / canbus / vehicle / lincoln / protocol / fuellevel_72 . h <nl> namespace apollo { <nl> namespace canbus { <nl> namespace lincoln { <nl> <nl> + using : : apollo : : common : : canbus : : ProtocolData ; <nl> + <nl> / * * <nl> * @ class Fuellevel72 <nl> * <nl> mmm a / modules / canbus / vehicle / lincoln / protocol / gear_66 . h <nl> ppp b / modules / canbus / vehicle / lincoln / protocol / gear_66 . h <nl> namespace apollo { <nl> namespace canbus { <nl> namespace lincoln { <nl> <nl> + using : : apollo : : common : : canbus : : ProtocolData ; <nl> + <nl> / * * <nl> * @ class Gear66 <nl> * <nl> mmm a / modules / canbus / vehicle / lincoln / protocol / gear_67 . h <nl> ppp b / modules / canbus / vehicle / lincoln / protocol / gear_67 . h <nl> namespace apollo { <nl> namespace canbus { <nl> namespace lincoln { <nl> <nl> + using : : apollo : : common : : canbus : : ProtocolData ; <nl> + <nl> / * * <nl> * @ class Gear67 <nl> * <nl> mmm a / modules / canbus / vehicle / lincoln / protocol / gps_6d . h <nl> ppp b / modules / canbus / vehicle / lincoln / protocol / gps_6d . h <nl> namespace apollo { <nl> namespace canbus { <nl> namespace lincoln { <nl> <nl> + using : : apollo : : common : : canbus : : ProtocolData ; <nl> + <nl> / * * <nl> * @ class Gps6d <nl> * <nl> mmm a / modules / canbus / vehicle / lincoln / protocol / gps_6e . h <nl> ppp b / modules / canbus / vehicle / lincoln / protocol / gps_6e . h <nl> namespace apollo { <nl> namespace canbus { <nl> namespace lincoln { <nl> <nl> + using : : apollo : : common : : canbus : : ProtocolData ; <nl> + <nl> / * * <nl> * @ class Gps6e <nl> * <nl> mmm a / modules / canbus / vehicle / lincoln / protocol / gps_6f . h <nl> ppp b / modules / canbus / vehicle / lincoln / protocol / gps_6f . h <nl> namespace apollo { <nl> namespace canbus { <nl> namespace lincoln { <nl> <nl> + using : : apollo : : common : : canbus : : ProtocolData ; <nl> + <nl> / * * <nl> * @ class Gps6f <nl> * <nl> mmm a / modules / canbus / vehicle / lincoln / protocol / gyro_6c . h <nl> ppp b / modules / canbus / vehicle / lincoln / protocol / gyro_6c . h <nl> namespace apollo { <nl> namespace canbus { <nl> namespace lincoln { <nl> <nl> + using : : apollo : : common : : canbus : : ProtocolData ; <nl> + <nl> / * * <nl> * @ class Gyro6c <nl> * <nl> mmm a / modules / canbus / vehicle / lincoln / protocol / misc_69 . h <nl> ppp b / modules / canbus / vehicle / lincoln / protocol / misc_69 . h <nl> namespace apollo { <nl> namespace canbus { <nl> namespace lincoln { <nl> <nl> + using : : apollo : : common : : canbus : : ProtocolData ; <nl> + <nl> / * * <nl> * @ class Misc69 <nl> * <nl> mmm a / modules / canbus / vehicle / lincoln / protocol / steering_64 . h <nl> ppp b / modules / canbus / vehicle / lincoln / protocol / steering_64 . h <nl> namespace apollo { <nl> namespace canbus { <nl> namespace lincoln { <nl> <nl> + using : : apollo : : common : : canbus : : ProtocolData ; <nl> + <nl> / * * <nl> * @ class Steering64 <nl> * <nl> mmm a / modules / canbus / vehicle / lincoln / protocol / steering_65 . h <nl> ppp b / modules / canbus / vehicle / lincoln / protocol / steering_65 . h <nl> namespace apollo { <nl> namespace canbus { <nl> namespace lincoln { <nl> <nl> + using : : apollo : : common : : canbus : : ProtocolData ; <nl> + <nl> / * * <nl> * @ class Steering65 <nl> * <nl> mmm a / modules / canbus / vehicle / lincoln / protocol / throttle_62 . h <nl> ppp b / modules / canbus / vehicle / lincoln / protocol / throttle_62 . h <nl> namespace apollo { <nl> namespace canbus { <nl> namespace lincoln { <nl> <nl> + using : : apollo : : common : : canbus : : ProtocolData ; <nl> + <nl> / * * <nl> * @ class Throttle62 <nl> * <nl> mmm a / modules / canbus / vehicle / lincoln / protocol / throttle_63 . h <nl> ppp b / modules / canbus / vehicle / lincoln / protocol / throttle_63 . h <nl> namespace apollo { <nl> namespace canbus { <nl> namespace lincoln { <nl> <nl> + using : : apollo : : common : : canbus : : ProtocolData ; <nl> + <nl> / * * <nl> * @ class Throttle63 <nl> * <nl> mmm a / modules / canbus / vehicle / lincoln / protocol / throttleinfo_75 . h <nl> ppp b / modules / canbus / vehicle / lincoln / protocol / throttleinfo_75 . h <nl> namespace apollo { <nl> namespace canbus { <nl> namespace lincoln { <nl> <nl> + using : : apollo : : common : : canbus : : ProtocolData ; <nl> + <nl> / * * <nl> * @ class Throttleinfo75 <nl> * <nl> mmm a / modules / canbus / vehicle / lincoln / protocol / tirepressure_71 . h <nl> ppp b / modules / canbus / vehicle / lincoln / protocol / tirepressure_71 . h <nl> namespace apollo { <nl> namespace canbus { <nl> namespace lincoln { <nl> <nl> + using : : apollo : : common : : canbus : : ProtocolData ; <nl> + <nl> / * * <nl> * @ class Tirepressure71 <nl> * <nl> mmm a / modules / canbus / vehicle / lincoln / protocol / turnsignal_68 . h <nl> ppp b / modules / canbus / vehicle / lincoln / protocol / turnsignal_68 . h <nl> namespace apollo { <nl> namespace canbus { <nl> namespace lincoln { <nl> <nl> + using : : apollo : : common : : canbus : : ProtocolData ; <nl> + <nl> / * * <nl> * @ class Turnsignal68 <nl> * <nl> mmm a / modules / canbus / vehicle / lincoln / protocol / version_7f . h <nl> ppp b / modules / canbus / vehicle / lincoln / protocol / version_7f . h <nl> namespace apollo { <nl> namespace canbus { <nl> namespace lincoln { <nl> <nl> + using : : apollo : : common : : canbus : : ProtocolData ; <nl> + <nl> / * * <nl> * @ class Version7f <nl> * <nl> mmm a / modules / canbus / vehicle / lincoln / protocol / wheelspeed_6a . h <nl> ppp b / modules / canbus / vehicle / lincoln / protocol / wheelspeed_6a . h <nl> namespace apollo { <nl> namespace canbus { <nl> namespace lincoln { <nl> <nl> + using : : apollo : : common : : canbus : : ProtocolData ; <nl> + <nl> / * * <nl> * @ class Wheelspeed6a <nl> * <nl> mmm a / modules / canbus / vehicle / vehicle_controller . h <nl> ppp b / modules / canbus / vehicle / vehicle_controller . h <nl> <nl> namespace apollo { <nl> namespace canbus { <nl> <nl> - using : : apollo : : common : : canbus : : CarSender ; <nl> + using : : apollo : : common : : canbus : : CanSender ; <nl> using : : apollo : : common : : canbus : : MessageManager ; <nl> <nl> / * * <nl> | change namespace 2 | ApolloAuto/apollo | 6cd2f43d65d3d3502cf0c623c968e5d15215c781 | 2017-10-13T03:01:10Z |
mmm a / src / app / script / app_object . cpp <nl> ppp b / src / app / script / app_object . cpp <nl> int App_set_activeLayer ( lua_State * L ) <nl> <nl> int App_set_activeFrame ( lua_State * L ) <nl> { <nl> - const doc : : frame_t frame = lua_tointeger ( L , 2 ) - 1 ; <nl> + const doc : : frame_t frame = get_frame_number_from_arg ( L , 2 ) ; <nl> # ifdef ENABLE_UI <nl> app : : Context * ctx = App : : instance ( ) - > context ( ) ; <nl> if ( auto uiCtx = dynamic_cast < UIContext * > ( ctx ) ) { <nl> | lua : Add support to use app . activeFrame with a Frame object | aseprite/aseprite | ca6d038af3be57721d10ccf0ae993827084433bf | 2018-11-28T15:05:17Z |
mmm a / brightray / browser / net / devtools_network_transaction . h <nl> ppp b / brightray / browser / net / devtools_network_transaction . h <nl> <nl> # include " net / base / completion_callback . h " <nl> # include " net / base / load_states . h " <nl> # include " net / base / request_priority . h " <nl> + # include " net / http / http_raw_request_headers . h " <nl> # include " net / http / http_transaction . h " <nl> <nl> namespace brightray { <nl> class DevToolsNetworkTransaction : public net : : HttpTransaction { <nl> int ResumeNetworkStart ( ) override ; <nl> void GetConnectionAttempts ( net : : ConnectionAttempts * out ) const override ; <nl> <nl> + / / FIXME ( torycl ) Implement these methods properly <nl> + void SetRequestHeadersCallback ( net : : RequestHeadersCallback callback ) { } <nl> + void SetResponseHeadersCallback ( net : : ResponseHeadersCallback callback ) { } <nl> + <nl> private : <nl> void Fail ( ) ; <nl> bool CheckFailed ( ) ; <nl> | FIXME : Fix brightray : : DevToolsNetworkTransaction compilation | electron/electron | 0d83b69fe25a354748c60406bf82e6be7d67967b | 2018-02-23T01:21:23Z |
mmm a / benchmark / single - source / Join . swift <nl> ppp b / benchmark / single - source / Join . swift <nl> public func run_Join ( N : Int ) { <nl> for x in 0 . . < 1000 * N { <nl> array . append ( String ( x ) ) <nl> } <nl> - _ = array . joinWithSeparator ( " " ) <nl> - _ = array . joinWithSeparator ( " " ) <nl> + _ = array . join ( separator : " " ) <nl> + _ = array . join ( separator : " " ) <nl> } <nl> mmm a / stdlib / private / SwiftPrivate / SwiftPrivate . swift <nl> ppp b / stdlib / private / SwiftPrivate / SwiftPrivate . swift <nl> public func asHex < <nl> where <nl> S . Iterator . Element : Integer <nl> > ( x : S ) - > String { <nl> - return " [ " + x . lazy . map { asHex ( $ 0 ) } . joinWithSeparator ( " , " ) + " ] " <nl> + return " [ " + x . lazy . map { asHex ( $ 0 ) } . join ( separator : " , " ) + " ] " <nl> } <nl> <nl> / / / Compute the prefix sum of ` seq ` . <nl> mmm a / stdlib / public / core / Join . swift <nl> ppp b / stdlib / public / core / Join . swift <nl> extension Sequence where Iterator . Element : Sequence { <nl> / / / ` separator ` between the elements of the sequence ` self ` . <nl> / / / <nl> / / / For example , <nl> - / / / ` [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] . joinWithSeparator ( [ - 1 , - 2 ] ) ` <nl> + / / / ` [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] . join ( separator : [ - 1 , - 2 ] ) ` <nl> / / / yields ` [ 1 , 2 , 3 , - 1 , - 2 , 4 , 5 , 6 , - 1 , - 2 , 7 , 8 , 9 ] ` . <nl> @ warn_unused_result <nl> - public func joinWithSeparator < <nl> + public func join < <nl> Separator : Sequence <nl> where <nl> Separator . Iterator . Element = = Iterator . Element . Iterator . Element <nl> - > ( separator : Separator ) - > JoinSequence < Self > { <nl> + > ( separator separator : Separator ) - > JoinSequence < Self > { <nl> return JoinSequence ( base : self , separator : separator ) <nl> } <nl> } <nl> extension JoinSequence { <nl> fatalError ( " unavailable function can ' t be called " ) <nl> } <nl> } <nl> + <nl> + extension Sequence where Iterator . Element : Sequence { <nl> + @ available ( * , unavailable , renamed = " join " ) <nl> + public func joinWithSeparator < <nl> + Separator : Sequence <nl> + where <nl> + Separator . Iterator . Element = = Iterator . Element . Iterator . Element <nl> + > ( separator : Separator ) - > JoinSequence < Self > { <nl> + fatalError ( " unavailable function can ' t be called " ) <nl> + } <nl> + } <nl> + <nl> mmm a / stdlib / public / core / String . swift <nl> ppp b / stdlib / public / core / String . swift <nl> extension Sequence where Iterator . Element = = String { <nl> / / / Interpose the ` separator ` between elements of ` self ` , then concatenate <nl> / / / the result . For example : <nl> / / / <nl> - / / / [ " foo " , " bar " , " baz " ] . joinWithSeparator ( " - | - " ) / / " foo - | - bar - | - baz " <nl> + / / / [ " foo " , " bar " , " baz " ] . join ( separator : " - | - " ) / / " foo - | - bar - | - baz " <nl> @ warn_unused_result <nl> - public func joinWithSeparator ( separator : String ) - > String { <nl> + public func join ( separator separator : String ) - > String { <nl> var result = " " <nl> <nl> / / FIXME ( performance ) : this code assumes UTF - 16 in - memory representation . <nl> extension String { <nl> fatalError ( " unavailable function can ' t be called " ) <nl> } <nl> } <nl> + <nl> + extension Sequence where Iterator . Element = = String { <nl> + @ available ( * , unavailable , renamed = " join " ) <nl> + public func joinWithSeparator ( separator : String ) - > String { <nl> + fatalError ( " unavailable function can ' t be called " ) <nl> + } <nl> + } <nl> mmm a / test / 1_stdlib / Mirror . swift <nl> ppp b / test / 1_stdlib / Mirror . swift <nl> extension Mirror { <nl> return " [ " + <nl> children . lazy <nl> . map { " \ ( $ 0 . 0 ? ? nil_ ) : \ ( String ( reflecting : $ 0 . 1 ) ) " } <nl> - . joinWithSeparator ( " , " ) <nl> + . join ( separator : " , " ) <nl> + " ] " <nl> } <nl> } <nl> mmm a / test / SILOptimizer / devirt_type_subst_bug . swift <nl> ppp b / test / SILOptimizer / devirt_type_subst_bug . swift <nl> <nl> / / from ApplyInst to match what GenericSignature expects . <nl> <nl> func asHex ( a : [ UInt8 ] ) - > String { <nl> - return a . map { " 0x " + String ( $ 0 , radix : 16 ) } . joinWithSeparator ( " " ) <nl> + return a . map { " 0x " + String ( $ 0 , radix : 16 ) } . join ( separator : " " ) <nl> } <nl> mmm a / test / expr / expressions . swift <nl> ppp b / test / expr / expressions . swift <nl> func invalidDictionaryLiteral ( ) { <nl> <nl> <nl> / / FIXME : The issue here is a type compatibility problem , there is no ambiguity . <nl> - [ 4 ] . joinWithSeparator ( [ 1 ] ) / / expected - error { { type of expression is ambiguous without more context } } <nl> - [ 4 ] . joinWithSeparator ( [ [ [ 1 ] ] ] ) / / expected - error { { type of expression is ambiguous without more context } } <nl> + [ 4 ] . join ( separator : [ 1 ] ) / / expected - error { { type of expression is ambiguous without more context } } <nl> + [ 4 ] . join ( separator : [ [ [ 1 ] ] ] ) / / expected - error { { type of expression is ambiguous without more context } } <nl> <nl> / / = = = mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - = = = / / <nl> / / nil / metatype comparisons <nl> mmm a / validation - test / compiler_crashers_fixed / 00039 - string - join . script . swift <nl> ppp b / validation - test / compiler_crashers_fixed / 00039 - string - join . script . swift <nl> <nl> / / Test case submitted to project by https : / / github . com / tmu ( Teemu Kurppa ) <nl> / / rdar : / / 18174611 <nl> <nl> - [ " ab " , " cd " ] . joinWithSeparator ( " " ) <nl> + [ " ab " , " cd " ] . join ( separator : " " ) <nl> <nl> mmm a / validation - test / stdlib / Join . swift . gyb <nl> ppp b / validation - test / stdlib / Join . swift . gyb <nl> JoinTestSuite . test ( " $ { Base } . join ( ) " ) { <nl> $ { Base } ( $ { label } $ 0 ) <nl> } ) <nl> let separator = $ { Base } ( $ { label } test . separator ) <nl> - let r = Array ( elements . joinWithSeparator ( separator ) ) <nl> + let r = Array ( elements . join ( separator : separator ) ) <nl> checkSequence ( test . expected , r ) <nl> } <nl> } <nl> JoinTestSuite . test ( " $ { Base } . join ( ) / _copyToNativeArrayBuffer ( ) " ) { <nl> $ { Base } ( $ { label } $ 0 ) <nl> } ) <nl> let separator = $ { Base } ( $ { label } test . separator ) <nl> - let r = Array ( elements . joinWithSeparator ( separator ) ) <nl> + let r = Array ( elements . join ( separator : separator ) ) <nl> checkSequence ( test . expected , r ) <nl> } <nl> } <nl> JoinTestSuite . test ( " $ { Base } . join ( ) / _copyToNativeArrayBuffer ( ) " ) { <nl> % end <nl> <nl> func join ( separator : String , _ elements : [ String ] ) - > String { <nl> - return elements . joinWithSeparator ( separator ) <nl> + return elements . join ( separator : separator ) <nl> } <nl> <nl> - JoinTestSuite . test ( " String . joinWithSeparator ( ) " ) { <nl> + JoinTestSuite . test ( " String . join ( separator : ) " ) { <nl> / / <nl> / / Test the free function . <nl> / / <nl> JoinTestSuite . test ( " String . joinWithSeparator ( ) " ) { <nl> / / Test forwarding instance function . <nl> / / <nl> <nl> - expectEqual ( " abxycdxyef " , [ " ab " , " cd " , " ef " ] . joinWithSeparator ( " xy " ) ) <nl> + expectEqual ( " abxycdxyef " , [ " ab " , " cd " , " ef " ] . join ( separator : " xy " ) ) <nl> } <nl> <nl> runAllTests ( ) <nl> | stdlib : joinWithSeparator ( _ : ) = > join ( separator : ) | apple/swift | 98561f6137b1816c85532a67fbf66d3d31fd72aa | 2016-02-19T06:30:57Z |
mmm a / aten / src / ATen / core / jit_type . h <nl> ppp b / aten / src / ATen / core / jit_type . h <nl> struct CAFFE2_API ClassType : public NamedType { <nl> } <nl> <nl> Function * getMethod ( const std : : string & name ) const ; <nl> - std : : vector < Function * > methods ( ) const ; <nl> + const std : : vector < Function * > & methods ( ) const ; <nl> + void addMethod ( Function * method ) { <nl> + methods_ . push_back ( method ) ; <nl> + } <nl> <nl> std : : shared_ptr < CompilationUnit > compilation_unit ( ) ; <nl> std : : shared_ptr < const CompilationUnit > compilation_unit ( ) const ; <nl> struct CAFFE2_API ClassType : public NamedType { <nl> / / if present , this class inherits from torch . nn . Module <nl> / / and these are the indices of the attributes which are parameters <nl> std : : shared_ptr < std : : vector < bool > > parameterSlots_ ; <nl> + <nl> + / / List of methods associated with this class . <nl> + std : : vector < Function * > methods_ ; <nl> } ; <nl> } / / namespace c10 <nl> mmm a / test / expect / TestJit . test_import_method . expect <nl> ppp b / test / expect / TestJit . test_import_method . expect <nl> <nl> - def foo ( x : Tensor , <nl> + def forward ( self , <nl> + x : Tensor , <nl> y : Tensor ) - > Tensor : <nl> _0 = torch . add ( torch . mul ( x , 2 ) , y , alpha = 1 ) <nl> return _0 <nl> mmm a / test / test_jit . py <nl> ppp b / test / test_jit . py <nl> def foo ( a ) : <nl> self . assertExpected ( cu . foo . code ) <nl> <nl> def test_import_method ( self ) : <nl> - @ torch . jit . script <nl> - def foo ( x , y ) : <nl> - return 2 * x + y <nl> + with torch . jit . _disable_emit_hooks ( ) : <nl> + class Foo ( torch . jit . ScriptModule ) : <nl> + def __init__ ( self ) : <nl> + super ( Foo , self ) . __init__ ( ) <nl> <nl> - r , _ = _jit_python_print ( foo ) <nl> - cu = torch . jit . CompilationUnit ( ) . _import ( r , [ ] ) <nl> - self . assertExpected ( cu . foo . code ) <nl> + @ torch . jit . script_method <nl> + def forward ( self , x , y ) : <nl> + return 2 * x + y <nl> + <nl> + foo = Foo ( ) <nl> + buffer = io . BytesIO ( ) <nl> + torch . jit . save ( foo , buffer ) <nl> + <nl> + buffer . seek ( 0 ) <nl> + foo_loaded = torch . jit . load ( buffer ) <nl> + self . assertExpected ( foo_loaded . forward . code ) <nl> <nl> def test_import_way_too_new ( self ) : <nl> @ torch . jit . script <nl> def test_annoying_doubles ( self ) : <nl> mod . nan = float ( " nan " ) <nl> <nl> with torch . jit . _disable_emit_hooks ( ) : <nl> - @ torch . jit . script <nl> - def foo ( ) : <nl> - return math . pi , 0 . 1 , mod . inf , mod . ninf , 2 . 225073858507201e - 308 , mod . nan <nl> + class Foo ( torch . jit . ScriptModule ) : <nl> + def __init__ ( self ) : <nl> + super ( Foo , self ) . __init__ ( ) <nl> + <nl> + @ torch . jit . script_method <nl> + def forward ( self ) : <nl> + return math . pi , 0 . 1 , mod . inf , mod . ninf , 2 . 225073858507201e - 308 , mod . nan <nl> + <nl> + foo = Foo ( ) <nl> + buffer = io . BytesIO ( ) <nl> + torch . jit . save ( foo , buffer ) <nl> + <nl> + buffer . seek ( 0 ) <nl> + foo_loaded = torch . jit . load ( buffer ) <nl> <nl> - pp , table = _jit_python_print ( foo ) <nl> - sm = torch . jit . CompilationUnit ( ) . _import ( pp , table ) <nl> r = foo ( ) <nl> - r2 = sm . foo ( ) <nl> + r2 = foo_loaded ( ) <nl> # use precise assert , we are checking floating point details <nl> self . assertTrue ( r [ : - 1 ] = = r2 [ : - 1 ] ) <nl> self . assertTrue ( math . isnan ( r [ - 1 ] ) and math . isnan ( r2 [ - 1 ] ) ) <nl> def test ( ) : <nl> return x <nl> ' ' ' ) <nl> <nl> - def test_duplicate ( self ) : <nl> - with self . assertRaisesRegex ( RuntimeError , ' method \ ' test \ ' already defined ' ) : <nl> - cu = torch . jit . CompilationUnit ( ' ' ' <nl> - def test ( ) : <nl> - return 1 <nl> - <nl> - def test ( ) : <nl> - return 2 <nl> - ' ' ' ) <nl> - <nl> def test_call_ge ( self ) : <nl> with self . assertRaisesRegex ( RuntimeError , ' Expected at most 1 arguments but found 3 ' ) : <nl> @ _trace ( torch . zeros ( 1 , 2 , 3 ) ) <nl> mmm a / torch / csrc / jit / pybind_utils . h <nl> ppp b / torch / csrc / jit / pybind_utils . h <nl> namespace jit { <nl> / / locations in libtorch code rather than user code . <nl> <nl> using tracer : : TypedStack ; <nl> + <nl> + inline std : : shared_ptr < script : : CompilationUnit > get_python_cu ( ) { <nl> + return py : : module : : import ( " torch . jit " ) <nl> + . attr ( " _python_cu " ) <nl> + . cast < std : : shared_ptr < script : : CompilationUnit > > ( ) ; <nl> + } <nl> + <nl> struct TypedIValue : public std : : pair < IValue , TypePtr > { <nl> using pair : : pair ; <nl> <nl> inline py : : object toPyObject ( IValue & & ivalue ) { <nl> return std : : move ( py_dict ) ; <nl> } else if ( ivalue . isObject ( ) ) { <nl> const auto obj = std : : move ( ivalue ) . toObject ( ) ; <nl> - auto pyCu = script : : CompilationUnit : : _get_python_cu ( ) ; <nl> + auto pyCu = get_python_cu ( ) ; <nl> const auto classType = pyCu - > get_class ( c10 : : QualifiedName ( obj - > name ( ) ) ) ; <nl> AT_ASSERT ( classType ) ; <nl> auto pyClass = <nl> mmm a / torch / csrc / jit / script / class_type . cpp <nl> ppp b / torch / csrc / jit / script / class_type . cpp <nl> size_t ClassType : : addAttribute ( <nl> return slot ; <nl> } <nl> <nl> - std : : vector < Function * > ClassType : : methods ( ) const { <nl> - / / TODO : this needs to be made more efficient ! <nl> - / / This grabs all the functions in the CU and filters them by qualified name . <nl> - auto cuFunctions = compilation_unit ( ) - > get_functions ( ) ; <nl> - const auto & classname = * qualified_name_obj ( ) ; <nl> - cuFunctions . erase ( <nl> - std : : remove_if ( <nl> - cuFunctions . begin ( ) , <nl> - cuFunctions . end ( ) , <nl> - [ & ] ( Function * fn ) { return ! classname . isPrefixOf ( fn - > qualname ( ) ) ; } ) , <nl> - cuFunctions . end ( ) ) ; <nl> - return cuFunctions ; <nl> + const std : : vector < Function * > & ClassType : : methods ( ) const { <nl> + return methods_ ; <nl> } <nl> <nl> ClassType : : ClassType ( <nl> mmm a / torch / csrc / jit / script / compilation_unit . h <nl> ppp b / torch / csrc / jit / script / compilation_unit . h <nl> struct TORCH_API CompilationUnit { <nl> resolvers , / * determines how we handle free <nl> variables in each definition * / <nl> / / if non - null , the first argument to each def , is bound to this value <nl> - const Self * self ) ; <nl> + const Self * self , <nl> + / / see [ name mangling ] <nl> + bool shouldMangle = false ) ; <nl> <nl> / / same as above but parse the definitions from source <nl> / / Returns the list of Function ' s just defined . <nl> struct TORCH_API CompilationUnit { <nl> / * * <nl> * Register a class as being owned by this compilation unit . <nl> * / <nl> - void register_class ( c10 : : NamedTypePtr classType ) { <nl> - classes_ . push_back ( std : : move ( classType ) ) ; <nl> + void register_class ( c10 : : NamedTypePtr namedType ) { <nl> + if ( auto classType = namedType - > cast < c10 : : ClassType > ( ) ) { <nl> + / / TODO : class types cannot be redefined because we have no way right now <nl> + / / of invalidating their methods . NamedTuples are fine though , since they <nl> + / / don ' t have methods . <nl> + TORCH_CHECK ( <nl> + 0 = = classDict_ . count ( * classType - > qualified_name_obj ( ) ) , <nl> + " class ' " , <nl> + classType - > qualname ( ) , <nl> + " ' already defined . " ) ; <nl> + } <nl> + classes_ . push_back ( std : : move ( namedType ) ) ; <nl> + classDict_ [ * classes_ . back ( ) - > qualified_name_obj ( ) ] = classes_ . size ( ) - 1 ; <nl> } ; <nl> <nl> c10 : : ClassTypePtr get_class ( const c10 : : QualifiedName & name ) const { <nl> - for ( const auto & cls : classes_ ) { <nl> - if ( cls - > qualname ( ) = = name . qualifiedName ( ) ) { <nl> - return cls - > expect < ClassType > ( ) ; <nl> - } <nl> + auto it = classDict_ . find ( name ) ; <nl> + if ( it = = classDict_ . end ( ) ) { <nl> + return nullptr ; <nl> } <nl> - return nullptr ; <nl> + return classes_ [ it - > second ] - > cast < c10 : : ClassType > ( ) ; <nl> } <nl> <nl> c10 : : TupleTypePtr get_named_tuple ( const c10 : : QualifiedName & name ) const { <nl> struct TORCH_API CompilationUnit { <nl> } <nl> <nl> c10 : : NamedTypePtr get_type ( const c10 : : QualifiedName & name ) const { <nl> - for ( const auto & cls : classes_ ) { <nl> - if ( cls - > qualname ( ) = = name . qualifiedName ( ) ) { <nl> - return cls ; <nl> - } <nl> + auto it = classDict_ . find ( name ) ; <nl> + if ( it = = classDict_ . end ( ) ) { <nl> + return nullptr ; <nl> } <nl> - return nullptr ; <nl> + return classes_ [ it - > second ] ; <nl> } <nl> <nl> - / * * <nl> - * Python compilation unit methods <nl> - * <nl> - * Right now there is a single compilation unit that owns all ScriptClasses <nl> - * defined in Python . Below are accessors methods for it . <nl> - * / <nl> - static std : : shared_ptr < CompilationUnit > _get_python_cu_const ( ) { <nl> - return _get_python_cu ( ) ; <nl> - } <nl> - static std : : shared_ptr < CompilationUnit > _get_python_cu ( ) { <nl> - static auto pyCu = std : : make_shared < CompilationUnit > ( ) ; <nl> - return pyCu ; <nl> - } <nl> / / For testing : clear all Python - defined classes to ensure that unit tests <nl> / / have isolation . <nl> - static void _clear_python_cu ( ) { <nl> - _get_python_cu ( ) - > classes_ . clear ( ) ; <nl> - _get_python_cu ( ) - > functions_ . clear ( ) ; <nl> - _get_python_cu ( ) - > dict_ . clear ( ) ; <nl> + void _clear_python_cu ( ) { <nl> + / / Delete all the associated class methods <nl> + for ( auto type : classes_ ) { <nl> + if ( auto cls = type - > cast < ClassType > ( ) ) { <nl> + for ( auto method : cls - > methods ( ) ) { <nl> + / / Tombstone the method in the compilation unit . <nl> + / / Don ' t erase because the dict_ <nl> + auto it = dict_ . find ( method - > qualname ( ) ) ; <nl> + TORCH_INTERNAL_ASSERT ( it ! = dict_ . end ( ) ) ; <nl> + functions_ [ it - > second ] = nullptr ; <nl> + / / Erase in our big lookup table <nl> + dict_ . erase ( it ) ; <nl> + } <nl> + } <nl> + } <nl> + classes_ . clear ( ) ; <nl> + classDict_ . clear ( ) ; <nl> } <nl> <nl> private : <nl> struct TORCH_API CompilationUnit { <nl> const Def & def , <nl> const ResolverPtr & resolver , <nl> const Self * self , <nl> - const std : : unordered_map < std : : string , Function * > & function_table ) const ; <nl> + const std : : unordered_map < std : : string , Function * > & function_table , <nl> + bool shouldMangle = false ) const ; <nl> <nl> Function & register_function ( std : : unique_ptr < Function > fn ) { <nl> TORCH_CHECK ( <nl> - 0 = = dict_ . count ( fn - > qualname ( ) ) , <nl> + 0 = = dict_ . count ( fn - > qualname ( ) . qualifiedName ( ) ) , <nl> " method ' " , <nl> fn - > qualname ( ) . qualifiedName ( ) , <nl> " ' already defined . " ) ; <nl> struct TORCH_API CompilationUnit { <nl> std : : vector < std : : unique_ptr < Function > > functions_ ; <nl> / / for fast lookup <nl> std : : unordered_map < c10 : : QualifiedName , size_t > dict_ ; <nl> + std : : unordered_map < c10 : : QualifiedName , size_t > classDict_ ; <nl> bool optimized_ = true ; <nl> <nl> - / / [ class owernship ] Right now there aree two relationships between classes <nl> + <nl> + / / [ class ownership ] Right now there aree two relationships between classes <nl> / / and compilation units : <nl> / / 1 . Classes have compilation units internally that hold their methods . <nl> / / 2 . On load , the TypePtrs of any imported classes are owned by the main <nl> / / module ' s compilation unit . <nl> std : : vector < c10 : : NamedTypePtr > classes_ ; <nl> + <nl> + / / [ name mangling ] All code objects must have a unique qualified name in a <nl> + / / CompilationUnit . In Python , sometimes functions won ' t have unique qualified <nl> + / / name ( for example , nested functions ) . So we mangle Python functions to <nl> + / / ensure that they are uniquely named . <nl> + mutable size_t mangleIndex_ = 0 ; <nl> + std : : string mangle ( const std : : string & name ) const ; <nl> } ; <nl> <nl> } / / namespace script <nl> mmm a / torch / csrc / jit / script / compiler . cpp <nl> ppp b / torch / csrc / jit / script / compiler . cpp <nl> CompilationUnit : : CompilationUnit ( const std : : string & source ) <nl> define ( c10 : : nullopt , source , nativeResolver ( ) , nullptr ) ; <nl> } <nl> <nl> + / / Mangle a qualified name so that it is globally unique . <nl> + std : : string CompilationUnit : : mangle ( const std : : string & name ) const { <nl> + static const std : : string manglePrefix = " ___torch_mangle_ " ; <nl> + <nl> + std : : string mangledName ; <nl> + auto pos = name . find ( manglePrefix ) ; <nl> + if ( pos ! = std : : string : : npos ) { <nl> + / / If the name is already mangled , avoid re - appending the prefix . <nl> + mangledName . reserve ( name . size ( ) ) ; <nl> + / / Append the part of the name up to the end of the prefix <nl> + mangledName . append ( name , 0 , pos ) ; <nl> + mangledName . append ( std : : to_string ( mangleIndex_ + + ) ) ; <nl> + } else { <nl> + mangledName = c10 : : str ( name , manglePrefix , std : : to_string ( mangleIndex_ + + ) ) ; <nl> + } <nl> + return mangledName ; <nl> + } <nl> + <nl> std : : unique_ptr < Function > CompilationUnit : : define ( <nl> const c10 : : optional < QualifiedName > & prefix , <nl> const Def & def , <nl> const ResolverPtr & resolver , <nl> const Self * self , <nl> - const std : : unordered_map < std : : string , Function * > & function_table ) const { <nl> + const std : : unordered_map < std : : string , Function * > & function_table , <nl> + bool shouldMangle ) const { <nl> TORCH_INTERNAL_ASSERT ( resolver ) ; <nl> auto _resolver = resolver ; <nl> if ( ! self ) { <nl> std : : unique_ptr < Function > CompilationUnit : : define ( <nl> } ; <nl> auto name = prefix ? QualifiedName ( * prefix , def . name ( ) . name ( ) ) <nl> : QualifiedName ( def . name ( ) . name ( ) ) ; <nl> - return torch : : make_unique < Function > ( <nl> + if ( shouldMangle ) { <nl> + / / If ` shouldMangle ` is set , we should generate a unique name for this <nl> + / / function if there is already an existing one . <nl> + if ( auto fn = find_function ( name ) ) { <nl> + auto newBase = mangle ( name . name ( ) ) ; <nl> + name = QualifiedName ( name . prefix ( ) , newBase ) ; <nl> + } <nl> + } <nl> + auto fn = torch : : make_unique < Function > ( <nl> std : : move ( name ) , is_optimized ( ) , std : : make_shared < Graph > ( ) , creator ) ; <nl> + if ( self ) { <nl> + / / Register this as a method on ` self ` ' s type <nl> + self - > getClassType ( ) - > addMethod ( fn . get ( ) ) ; <nl> + } <nl> + return fn ; <nl> } <nl> <nl> std : : vector < Function * > CompilationUnit : : define ( <nl> const c10 : : optional < QualifiedName > & prefix , <nl> const std : : vector < Def > & definitions , <nl> const std : : vector < ResolverPtr > & resolvers , <nl> - const Self * self ) { <nl> + const Self * self , <nl> + bool shouldMangle ) { <nl> TORCH_INTERNAL_ASSERT ( definitions . size ( ) = = resolvers . size ( ) ) ; <nl> / / We need to compile ` __init__ ` first , since it can determine what attributes <nl> / / are available to other methods . So reorder the definitions accordingly . <nl> std : : vector < Function * > CompilationUnit : : define ( <nl> definitions [ * init_idx ] , <nl> resolvers [ * init_idx ] , <nl> self , <nl> - function_table ) ; <nl> + function_table , <nl> + shouldMangle ) ; <nl> const auto & name = fn - > name ( ) ; <nl> function_table [ name ] = fn . get ( ) ; <nl> functions . push_back ( fn . get ( ) ) ; <nl> std : : vector < Function * > CompilationUnit : : define ( <nl> continue ; <nl> } <nl> <nl> - auto fn = <nl> - define ( prefix , definitions [ i ] , resolvers [ i ] , self , function_table ) ; <nl> + auto fn = define ( <nl> + prefix , <nl> + definitions [ i ] , <nl> + resolvers [ i ] , <nl> + self , <nl> + function_table , <nl> + shouldMangle ) ; <nl> const auto & name = fn - > name ( ) ; <nl> function_table [ name ] = fn . get ( ) ; <nl> functions . push_back ( fn . get ( ) ) ; <nl> mmm a / torch / csrc / jit / script / init . cpp <nl> ppp b / torch / csrc / jit / script / init . cpp <nl> struct PythonResolver : public Resolver { <nl> annotations , <nl> qualifiedName , <nl> TupleType : : namedTupleSchemaFromNamesAndTypes ( qualifiedName , fields , annotations ) ) ; <nl> - CompilationUnit : : _get_python_cu ( ) - > register_class ( tt ) ; <nl> + get_python_cu ( ) - > register_class ( tt ) ; <nl> return tt ; <nl> } <nl> <nl> - return CompilationUnit : : _get_python_cu ( ) - > get_class ( qualifiedName ) ; <nl> + return get_python_cu ( ) - > get_class ( qualifiedName ) ; <nl> } <nl> <nl> private : <nl> void initJitScriptBindings ( PyObject * module ) { <nl> ResolutionCallback rcb , <nl> FunctionDefaults defaults ) { <nl> C10_LOG_API_USAGE_ONCE ( " torch . script . compile " ) ; <nl> - / / TODO this should be the global python CU <nl> const auto name = c10 : : QualifiedName ( qualname ) ; <nl> TORCH_INTERNAL_ASSERT ( name . name ( ) = = def . name ( ) . name ( ) ) ; <nl> - auto cu = std : : make_shared < CompilationUnit > ( ) ; <nl> - cu - > define ( <nl> + auto cu = get_python_cu ( ) ; <nl> + auto defined_functions = cu - > define ( <nl> QualifiedName ( name . prefix ( ) ) , <nl> { def } , <nl> { pythonResolver ( std : : move ( rcb ) ) } , <nl> - nullptr ) ; <nl> - auto defined = cu - > get_functions ( ) . at ( 0 ) ; <nl> + nullptr , <nl> + true ) ; <nl> + TORCH_INTERNAL_ASSERT ( defined_functions . size ( ) = = 1 ) ; <nl> + auto & defined = defined_functions [ 0 ] ; <nl> defined - > setSchema ( getSchemaWithNameAndDefaults ( <nl> def . range ( ) , defined - > getSchema ( ) , def . name ( ) . name ( ) , defaults ) ) ; <nl> StrongFunctionPtr ret ( std : : move ( cu ) , defined ) ; <nl> void initJitScriptBindings ( PyObject * module ) { <nl> const ClassDef & classDef , <nl> ResolutionCallback rcb ) { <nl> C10_LOG_API_USAGE_ONCE ( " torch . script . class " ) ; <nl> - auto cu = CompilationUnit : : _get_python_cu ( ) ; <nl> + auto cu = get_python_cu ( ) ; <nl> const auto classname = c10 : : QualifiedName ( qualifiedName ) ; <nl> auto classType = ClassType : : create ( classname , cu ) ; <nl> cu - > register_class ( classType ) ; <nl> void initJitScriptBindings ( PyObject * module ) { <nl> const std : : vector < at : : Tensor > & constant_table ) { <nl> import_functions ( <nl> c10 : : nullopt , <nl> - * CompilationUnit : : _get_python_cu_const ( ) , <nl> + * get_python_cu ( ) , <nl> cu , <nl> std : : make_shared < Source > ( src ) , <nl> constant_table , <nl> void initJitScriptBindings ( PyObject * module ) { <nl> <nl> m . def ( " _jit_set_emit_hooks " , setEmitHooks ) ; <nl> m . def ( " _jit_get_emit_hooks " , getEmitHooks ) ; <nl> - m . def ( " _jit_clear_class_registry " , CompilationUnit : : _clear_python_cu ) ; <nl> + m . def ( " _jit_clear_class_registry " , [ ] ( ) { <nl> + get_python_cu ( ) - > _clear_python_cu ( ) ; <nl> + } ) ; <nl> m . def ( <nl> " _debug_set_autodiff_subgraph_inlining " , <nl> debugSetAutodiffSubgraphInlining ) ; <nl> mmm a / torch / csrc / jit / script / python_sugared_value . cpp <nl> ppp b / torch / csrc / jit / script / python_sugared_value . cpp <nl> std : : shared_ptr < SugaredValue > toSugaredValue ( <nl> if ( py : : cast < bool > ( isClass ) ) { <nl> py : : str qualifiedName = <nl> py : : module : : import ( " torch . jit " ) . attr ( " _qualified_name " ) ( obj ) ; <nl> - auto pyCu = CompilationUnit : : _get_python_cu ( ) ; <nl> + auto pyCu = get_python_cu ( ) ; <nl> if ( auto classType = pyCu - > get_class ( c10 : : QualifiedName ( qualifiedName ) ) ) { <nl> return std : : make_shared < ClassValue > ( classType ) ; <nl> } <nl> mmm a / torch / jit / __init__ . py <nl> ppp b / torch / jit / __init__ . py <nl> def _parse_env ( name , default , true_message , false_message ) : <nl> _unflatten = torch . _C . _jit_unflatten <nl> _jit_script_class_compile = torch . _C . _jit_script_class_compile <nl> <nl> + # The Python CompilationUnit . All functions and modules defined in Python will <nl> + # live in here . It ' s defined in Python because doing in cpp creates static <nl> + # destruction order issues . <nl> + _python_cu = torch . _C . CompilationUnit ( ) <nl> + <nl> Future = torch . _C . Future <nl> _fork = torch . _C . fork <nl> _wait = torch . _C . wait <nl> def _make_strong_submodule ( field , module , parent ) : <nl> return new_strong_submodule <nl> <nl> <nl> - # TODO : we are leaking these things because they don ' t have a distinct owner <nl> - # right now . <nl> - _delete_me_recursive_compile_holder = [ ] <nl> def _try_compile_fn ( fn , loc ) : <nl> - global _delete_me_recursive_compile_holder <nl> if _jit_internal . is_ignored_fn ( fn ) : <nl> # Don ' t do anything for @ ignore ' d functions <nl> return None <nl> def _try_compile_fn ( fn , loc ) : <nl> # extract the necessary info from the closed over variables on the function <nl> # object <nl> rcb = _jit_internal . createResolutionCallbackFromClosure ( fn ) <nl> - _delete_me_recursive_compile_holder . append ( torch . jit . script ( fn , _rcb = rcb ) ) <nl> - return _delete_me_recursive_compile_holder [ - 1 ] <nl> + return torch . jit . script ( fn , _rcb = rcb ) <nl> <nl> <nl> @ contextlib . contextmanager <nl> | _script_compile and _script_class_compile add to the python CU | pytorch/pytorch | 16aa235f4318ca5f5e072be41d32ce04a10531d8 | 2019-07-15T20:13:08Z |
mmm a / src / python / grpcio_tests / commands . py <nl> ppp b / src / python / grpcio_tests / commands . py <nl> class TestGevent ( setuptools . Command ) : <nl> # This test will stuck while running higher version of gevent <nl> ' unit . _auth_context_test . AuthContextTest . testSessionResumption ' , <nl> # TODO ( https : / / github . com / grpc / grpc / issues / 15411 ) enable these tests <nl> - ' unit . _metadata_flags_test ' , <nl> + ' unit . _channel_ready_future_test . ChannelReadyFutureTest . test_immediately_connectable_channel_connectivity ' , <nl> + " unit . _cython . _channel_test . ChannelTest . test_single_channel_lonely_connectivity " , <nl> ' unit . _exit_test . ExitTest . test_in_flight_unary_unary_call ' , <nl> ' unit . _exit_test . ExitTest . test_in_flight_unary_stream_call ' , <nl> ' unit . _exit_test . ExitTest . test_in_flight_stream_unary_call ' , <nl> class TestGevent ( setuptools . Command ) : <nl> ' unit . _exit_test . ExitTest . test_in_flight_partial_unary_stream_call ' , <nl> ' unit . _exit_test . ExitTest . test_in_flight_partial_stream_unary_call ' , <nl> ' unit . _exit_test . ExitTest . test_in_flight_partial_stream_stream_call ' , <nl> + ' unit . _metadata_flags_test ' , <nl> ' health_check . _health_servicer_test . HealthServicerTest . test_cancelled_watch_removed_from_watch_list ' , <nl> # TODO ( https : / / github . com / grpc / grpc / issues / 17330 ) enable these three tests <nl> ' channelz . _channelz_servicer_test . ChannelzServicerTest . test_many_subchannels ' , <nl> | Disable two flaky gevent tests | grpc/grpc | 4966adaeaef20531f85c00236d4cb63aab2e30c1 | 2019-03-07T23:19:16Z |
mmm a / stdlib / public / core / StaticString . swift <nl> ppp b / stdlib / public / core / StaticString . swift <nl> public struct StaticString { <nl> return body ( UnsafeBufferPointer ( <nl> start : utf8Start , count : utf8CodeUnitCount ) ) <nl> } else { <nl> - var buffer : UInt64 = 0 <nl> - var i = 0 <nl> - let sink : ( UInt8 ) - > Void = { <nl> - # if _endian ( little ) <nl> - buffer = buffer | ( UInt64 ( $ 0 ) < < ( UInt64 ( i ) * 8 ) ) <nl> - # else <nl> - buffer = buffer | ( UInt64 ( $ 0 ) < < ( UInt64 ( 7 - i ) * 8 ) ) <nl> - # endif <nl> - i + = 1 <nl> - } <nl> - UTF8 . encode ( unicodeScalar , into : sink ) <nl> - return body ( UnsafeBufferPointer ( <nl> - start : UnsafePointer ( Builtin . addressof ( & buffer ) ) , <nl> - count : i ) ) <nl> + return unicodeScalar . withUTF8CodeUnits { body ( $ 0 ) } <nl> } <nl> } <nl> <nl> mmm a / test / IRGen / objc_super . swift <nl> ppp b / test / IRGen / objc_super . swift <nl> class GenericRuncer < T > : Gizmo { <nl> } <nl> <nl> / / CHECK : define internal swiftcc void [ [ PARTIAL_FORWARDING_THUNK ] ] ( % swift . refcounted * swiftself % 0 ) { { . * } } { <nl> - / / CHECK : @ " $ ss12StaticStringV14withUTF8BufferyxxSRys5UInt8VGXElFyAEcfU_ " <nl> + / / CHECK : @ " $ ss12StaticStringV14withUTF8BufferyxxSRys5UInt8VGXElFxAFXEfU_ " <nl> / / CHECK : } <nl> | Merge remote - tracking branch ' origin / master ' into master - rebranch | apple/swift | a4cac465883cdfd427ed7d23f6c52d2398de1acc | 2020-08-06T23:03:49Z |
mmm a / test / test_jit . py <nl> ppp b / test / test_jit . py <nl> def test ( x ) : <nl> <nl> test_resize_as ( ) <nl> <nl> + def test_requires_grad_loop ( self ) : <nl> + @ torch . jit . script <nl> + def test ( x , y , z ) : <nl> + # type : ( Tensor , Tensor , int ) - > Tensor <nl> + for _ in range ( z ) : <nl> + x = y <nl> + return x <nl> + <nl> + # x requires grad , y does not <nl> + # testing that requires grad analysis correctly exits , with its input <nl> + # to the loop ( x ) requiring grad and its output to the loop not requiring grad <nl> + # and the output of the node conservatively setting grad to true <nl> + <nl> + inps = ( torch . tensor ( 1 . 0 , requires_grad = True ) , torch . tensor ( 1 ) , 10 ) <nl> + test ( * inps ) <nl> + <nl> + graph = test . graph_for ( * inps ) <nl> + loop = graph . findNode ( " prim : : Loop " ) <nl> + loop_body = next ( loop . blocks ( ) ) <nl> + loop_inputs = list ( loop_body . inputs ( ) ) <nl> + loop_outputs = list ( loop_body . outputs ( ) ) <nl> + <nl> + self . assertTrue ( loop_inputs [ 1 ] . requires_grad ( ) ) <nl> + self . assertFalse ( loop_outputs [ 1 ] . requires_grad ( ) ) <nl> + self . assertTrue ( loop . output ( ) . requires_grad ( ) ) <nl> + <nl> def test_view_shape_prop ( self ) : <nl> cu = torch . jit . CompilationUnit ( ' ' ' <nl> def test_view_shape_prop ( a ) : <nl> mmm a / torch / csrc / jit / passes / requires_grad_analysis . cpp <nl> ppp b / torch / csrc / jit / passes / requires_grad_analysis . cpp <nl> <nl> + # include < ATen / core / jit_type . h > <nl> # include < torch / csrc / jit / argument_spec . h > <nl> # include < torch / csrc / jit / ir . h > <nl> # include < torch / csrc / jit / operator . h > <nl> - # include < ATen / core / jit_type . h > <nl> <nl> # include < vector > <nl> <nl> void PropagateRequiresGrad ( Node * node ) { <nl> fmap ( node - > inputs ( ) . slice ( 2 ) , getRequiresGrad ) ; <nl> std : : vector < bool > body_outputs_require ( node - > outputs ( ) . size ( ) , false ) ; <nl> <nl> - while ( body_inputs_require ! = body_outputs_require ) { <nl> - body_inputs_require = <nl> + std : : vector < bool > new_body_inputs_require = body_inputs_require ; <nl> + std : : vector < bool > new_body_outputs_require = body_outputs_require ; <nl> + <nl> + / / continue iterating until the results have converged <nl> + do { <nl> + body_inputs_require = new_body_inputs_require ; <nl> + body_outputs_require = new_body_outputs_require ; <nl> + <nl> + new_body_inputs_require = <nl> bitwiseOr ( body_inputs_require , body_outputs_require ) ; <nl> setRequiresGrad ( <nl> - body - > param_node ( ) - > outputs ( ) . slice ( 1 ) , body_inputs_require ) ; <nl> + body - > param_node ( ) - > outputs ( ) . slice ( 1 ) , new_body_inputs_require ) ; <nl> PropagateRequiresGrad ( body ) ; <nl> - body_outputs_require = <nl> + new_body_outputs_require = <nl> fmap ( body - > return_node ( ) - > inputs ( ) . slice ( 1 ) , getRequiresGrad ) ; <nl> - } <nl> + } while ( new_body_inputs_require ! = body_inputs_require & & <nl> + new_body_outputs_require ! = body_outputs_require ) ; <nl> <nl> setRequiresGrad ( node , body_outputs_require ) ; <nl> } else { <nl> void PropagateRequiresGrad ( Block * block ) { <nl> PropagateRequiresGrad ( node ) ; <nl> } <nl> } <nl> - <nl> } / / anonymous namespace <nl> <nl> void PropagateRequiresGrad ( std : : shared_ptr < Graph > & graph ) { <nl> PropagateRequiresGrad ( graph - > block ( ) ) ; <nl> } <nl> - <nl> } / / namespace jit <nl> } / / namespace torch <nl> mmm a / torch / csrc / jit / python_ir . cpp <nl> ppp b / torch / csrc / jit / python_ir . cpp <nl> void initPythonIRBindings ( PyObject * module_ ) { <nl> } ) <nl> . VS ( copyMetadata ) <nl> . VS ( isTensor ) <nl> + . VS ( requires_grad ) <nl> . def ( " toIValue " , [ ] ( Value & n ) { return toIValue ( & n ) ; } ) <nl> . def ( " type " , [ ] ( Value & v ) { return v . type ( ) ; } ) ; <nl> # undef VS <nl> | Fix For Requires Grad Infinite Loop ( ) | pytorch/pytorch | ca962f0f95185e76b1f43a4423d28986ee0da191 | 2019-03-24T21:34:50Z |
mmm a / project / BuildDependencies / DownloadBuildDeps . bat <nl> ppp b / project / BuildDependencies / DownloadBuildDeps . bat <nl> IF NOT EXIST % FORMED_OK_FLAG % ( <nl> cd % CUR_PATH % <nl> <nl> rmdir % TMP_PATH % / S / Q <nl> + EXIT / B 0 <nl> | [ win32 ] explicitly set zero exit code on success | xbmc/xbmc | 17f6b89ccee19fa5a1c61b879879dc3d5dadfa23 | 2013-11-01T13:38:24Z |
mmm a / CMakeLists . txt <nl> ppp b / CMakeLists . txt <nl> if ( gRPC_BUILD_TESTS ) <nl> add_dependencies ( buildtests_cxx google_mesh_ca_certificate_provider_factory_test ) <nl> add_dependencies ( buildtests_cxx grpc_cli ) <nl> add_dependencies ( buildtests_cxx grpc_tls_certificate_distributor_test ) <nl> + add_dependencies ( buildtests_cxx grpc_tls_certificate_provider_test ) <nl> add_dependencies ( buildtests_cxx grpc_tls_credentials_options_test ) <nl> if ( _gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX ) <nl> add_dependencies ( buildtests_cxx grpc_tool_test ) <nl> if ( gRPC_BUILD_TESTS ) <nl> <nl> add_executable ( grpc_tls_certificate_distributor_test <nl> test / core / security / grpc_tls_certificate_distributor_test . cc <nl> + test / core / security / tls_utils . cc <nl> third_party / googletest / googletest / src / gtest - all . cc <nl> third_party / googletest / googlemock / src / gmock - all . cc <nl> ) <nl> target_link_libraries ( grpc_tls_certificate_distributor_test <nl> ) <nl> <nl> <nl> + endif ( ) <nl> + if ( gRPC_BUILD_TESTS ) <nl> + <nl> + add_executable ( grpc_tls_certificate_provider_test <nl> + test / core / security / grpc_tls_certificate_provider_test . cc <nl> + test / core / security / tls_utils . cc <nl> + third_party / googletest / googletest / src / gtest - all . cc <nl> + third_party / googletest / googlemock / src / gmock - all . cc <nl> + ) <nl> + <nl> + target_include_directories ( grpc_tls_certificate_provider_test <nl> + PRIVATE <nl> + $ { CMAKE_CURRENT_SOURCE_DIR } <nl> + $ { CMAKE_CURRENT_SOURCE_DIR } / include <nl> + $ { _gRPC_ADDRESS_SORTING_INCLUDE_DIR } <nl> + $ { _gRPC_RE2_INCLUDE_DIR } <nl> + $ { _gRPC_SSL_INCLUDE_DIR } <nl> + $ { _gRPC_UPB_GENERATED_DIR } <nl> + $ { _gRPC_UPB_GRPC_GENERATED_DIR } <nl> + $ { _gRPC_UPB_INCLUDE_DIR } <nl> + $ { _gRPC_ZLIB_INCLUDE_DIR } <nl> + third_party / googletest / googletest / include <nl> + third_party / googletest / googletest <nl> + third_party / googletest / googlemock / include <nl> + third_party / googletest / googlemock <nl> + $ { _gRPC_PROTO_GENS_DIR } <nl> + ) <nl> + <nl> + target_link_libraries ( grpc_tls_certificate_provider_test <nl> + $ { _gRPC_PROTOBUF_LIBRARIES } <nl> + $ { _gRPC_ALLTARGETS_LIBRARIES } <nl> + grpc_test_util <nl> + grpc <nl> + gpr <nl> + address_sorting <nl> + upb <nl> + ) <nl> + <nl> + <nl> endif ( ) <nl> if ( gRPC_BUILD_TESTS ) <nl> <nl> add_executable ( grpc_tls_credentials_options_test <nl> test / core / security / grpc_tls_credentials_options_test . cc <nl> + test / core / security / tls_utils . cc <nl> third_party / googletest / googletest / src / gtest - all . cc <nl> third_party / googletest / googlemock / src / gmock - all . cc <nl> ) <nl> mmm a / build_autogenerated . yaml <nl> ppp b / build_autogenerated . yaml <nl> targets : <nl> gtest : true <nl> build : test <nl> language : c + + <nl> - headers : [ ] <nl> + headers : <nl> + - test / core / security / tls_utils . h <nl> src : <nl> - test / core / security / grpc_tls_certificate_distributor_test . cc <nl> + - test / core / security / tls_utils . cc <nl> + deps : <nl> + - grpc_test_util <nl> + - grpc <nl> + - gpr <nl> + - address_sorting <nl> + - upb <nl> + - name : grpc_tls_certificate_provider_test <nl> + gtest : true <nl> + build : test <nl> + language : c + + <nl> + headers : <nl> + - test / core / security / tls_utils . h <nl> + src : <nl> + - test / core / security / grpc_tls_certificate_provider_test . cc <nl> + - test / core / security / tls_utils . cc <nl> deps : <nl> - grpc_test_util <nl> - grpc <nl> targets : <nl> gtest : true <nl> build : test <nl> language : c + + <nl> - headers : [ ] <nl> + headers : <nl> + - test / core / security / tls_utils . h <nl> src : <nl> - test / core / security / grpc_tls_credentials_options_test . cc <nl> + - test / core / security / tls_utils . cc <nl> deps : <nl> - grpc_test_util <nl> - grpc <nl> mmm a / grpc . def <nl> ppp b / grpc . def <nl> EXPORTS <nl> grpc_tls_identity_pairs_add_pair <nl> grpc_tls_identity_pairs_destroy <nl> grpc_tls_certificate_provider_static_data_create <nl> + grpc_tls_certificate_provider_file_watcher_create <nl> grpc_tls_certificate_provider_release <nl> grpc_tls_credentials_options_create <nl> grpc_tls_credentials_options_set_cert_request_type <nl> mmm a / include / grpc / grpc_security . h <nl> ppp b / include / grpc / grpc_security . h <nl> GRPCAPI grpc_tls_certificate_provider * <nl> grpc_tls_certificate_provider_static_data_create ( <nl> const char * root_certificate , grpc_tls_identity_pairs * pem_key_cert_pairs ) ; <nl> <nl> + / * * <nl> + * Creates a grpc_tls_certificate_provider that will watch the credential <nl> + * changes on the file system . This provider will always return the up - to - date <nl> + * cert data for all the cert names callers set through <nl> + * | grpc_tls_credentials_options | . Note that this API only supports one key - cert <nl> + * file and hence one set of identity key - cert pair , so SNI ( Server Name <nl> + * Indication ) is not supported . <nl> + * - private_key_path is the file path of the private key . This must be set if <nl> + * | identity_certificate_path | is set . Otherwise , it could be null if no <nl> + * identity credentials are needed . <nl> + * - identity_certificate_path is the file path of the identity certificate <nl> + * chain . This must be set if | private_key_path | is set . Otherwise , it could <nl> + * be null if no identity credentials are needed . <nl> + * - root_cert_path is the file path to the root certificate bundle . This <nl> + * may be null if no root certs are needed . <nl> + * - refresh_interval_sec is the refreshing interval that we will check the <nl> + * files for updates . <nl> + * It does not take ownership of parameters . <nl> + * It is used for experimental purpose for now and subject to change . <nl> + * / <nl> + GRPCAPI grpc_tls_certificate_provider * <nl> + grpc_tls_certificate_provider_file_watcher_create ( <nl> + const char * private_key_path , const char * identity_certificate_path , <nl> + const char * root_cert_path , unsigned int refresh_interval_sec ) ; <nl> + <nl> / * * <nl> * Releases a grpc_tls_certificate_provider object . The creator of the <nl> * grpc_tls_certificate_provider object is responsible for its release . It is <nl> mmm a / include / grpcpp / security / tls_certificate_provider . h <nl> ppp b / include / grpcpp / security / tls_certificate_provider . h <nl> class StaticDataCertificateProvider : public CertificateProviderInterface { <nl> const std : : vector < IdentityKeyCertPair > & identity_key_cert_pairs ) <nl> : StaticDataCertificateProvider ( " " , identity_key_cert_pairs ) { } <nl> <nl> - ~ StaticDataCertificateProvider ( ) ; <nl> + ~ StaticDataCertificateProvider ( ) override ; <nl> + <nl> + grpc_tls_certificate_provider * c_provider ( ) override { return c_provider_ ; } <nl> + <nl> + private : <nl> + grpc_tls_certificate_provider * c_provider_ = nullptr ; <nl> + } ; <nl> + <nl> + / / A CertificateProviderInterface implementation that will watch the credential <nl> + / / changes on the file system . This provider will always return the up - to - date <nl> + / / cert data for all the cert names callers set through | TlsCredentialsOptions | . <nl> + / / Several things to note : <nl> + / / 1 . This API only supports one key - cert file and hence one set of identity <nl> + / / key - cert pair , so SNI ( Server Name Indication ) is not supported . <nl> + / / 2 . The private key and identity certificate should always match . This API <nl> + / / guarantees atomic read , and it is the callers ' responsibility to do atomic <nl> + / / updates . There are many ways to atomically update the key and certs in the <nl> + / / file system . To name a few : <nl> + / / 1 ) creating a new directory , renaming the old directory to a new name , and <nl> + / / then renaming the new directory to the original name of the old directory . <nl> + / / 2 ) using a symlink for the directory . When need to change , put new <nl> + / / credential data in a new directory , and change symlink . <nl> + class FileWatcherCertificateProvider final <nl> + : public CertificateProviderInterface { <nl> + public : <nl> + / / Constructor to get credential updates from root and identity file paths . <nl> + / / <nl> + / / @ param private_key_path is the file path of the private key . <nl> + / / @ param identity_certificate_path is the file path of the identity <nl> + / / certificate chain . <nl> + / / @ param root_cert_path is the file path to the root certificate bundle . <nl> + / / @ param refresh_interval_sec is the refreshing interval that we will check <nl> + / / the files for updates . <nl> + FileWatcherCertificateProvider ( const std : : string & private_key_path , <nl> + const std : : string & identity_certificate_path , <nl> + const std : : string & root_cert_path , <nl> + unsigned int refresh_interval_sec ) ; <nl> + / / Constructor to get credential updates from identity file paths only . <nl> + FileWatcherCertificateProvider ( const std : : string & private_key_path , <nl> + const std : : string & identity_certificate_path , <nl> + unsigned int refresh_interval_sec ) <nl> + : FileWatcherCertificateProvider ( private_key_path , <nl> + identity_certificate_path , " " , <nl> + refresh_interval_sec ) { } <nl> + / / Constructor to get credential updates from root file path only . <nl> + FileWatcherCertificateProvider ( const std : : string & root_cert_path , <nl> + unsigned int refresh_interval_sec ) <nl> + : FileWatcherCertificateProvider ( " " , " " , root_cert_path , <nl> + refresh_interval_sec ) { } <nl> + <nl> + ~ FileWatcherCertificateProvider ( ) override ; <nl> <nl> grpc_tls_certificate_provider * c_provider ( ) override { return c_provider_ ; } <nl> <nl> mmm a / src / core / lib / security / credentials / tls / grpc_tls_certificate_distributor . h <nl> ppp b / src / core / lib / security / credentials / tls / grpc_tls_certificate_distributor . h <nl> struct grpc_tls_certificate_distributor <nl> grpc_error * identity_cert_error ) = 0 ; <nl> } ; <nl> <nl> - / / Sets the key materials based on their certificate name . Note that we are <nl> - / / not doing any copies for pem_root_certs and pem_key_cert_pairs . For <nl> - / / pem_root_certs , the original string contents need to outlive the <nl> - / / distributor ; for pem_key_cert_pairs , internally it is taking two <nl> - / / unique_ptr ( s ) to the credential string , so the ownership is actually <nl> - / / transferred . <nl> + / / Sets the key materials based on their certificate name . <nl> / / <nl> / / @ param cert_name The name of the certificates being updated . <nl> / / @ param pem_root_certs The content of root certificates . <nl> mmm a / src / core / lib / security / credentials / tls / grpc_tls_certificate_provider . cc <nl> ppp b / src / core / lib / security / credentials / tls / grpc_tls_certificate_provider . cc <nl> <nl> # include < grpc / support / log . h > <nl> # include < grpc / support / string_util . h > <nl> <nl> + # include " src / core / lib / gprpp / stat . h " <nl> + # include " src / core / lib / slice / slice_internal . h " <nl> # include " src / core / lib / surface / api_trace . h " <nl> <nl> namespace grpc_core { <nl> StaticDataCertificateProvider : : StaticDataCertificateProvider ( <nl> distributor_ - > SetWatchStatusCallback ( [ this ] ( std : : string cert_name , <nl> bool root_being_watched , <nl> bool identity_being_watched ) { <nl> - if ( ! root_being_watched & & ! identity_being_watched ) return ; <nl> + grpc_core : : MutexLock lock ( & mu_ ) ; <nl> absl : : optional < std : : string > root_certificate ; <nl> absl : : optional < grpc_core : : PemKeyCertPairList > pem_key_cert_pairs ; <nl> - if ( root_being_watched ) { <nl> + StaticDataCertificateProvider : : WatcherInfo & info = watcher_info_ [ cert_name ] ; <nl> + if ( ! info . root_being_watched & & root_being_watched & & <nl> + ! root_certificate_ . empty ( ) ) { <nl> root_certificate = root_certificate_ ; <nl> } <nl> - if ( identity_being_watched ) { <nl> + info . root_being_watched = root_being_watched ; <nl> + if ( ! info . identity_being_watched & & identity_being_watched & & <nl> + ! pem_key_cert_pairs_ . empty ( ) ) { <nl> pem_key_cert_pairs = pem_key_cert_pairs_ ; <nl> } <nl> - distributor_ - > SetKeyMaterials ( cert_name , std : : move ( root_certificate ) , <nl> - std : : move ( pem_key_cert_pairs ) ) ; <nl> + info . identity_being_watched = identity_being_watched ; <nl> + if ( ! info . root_being_watched & & ! info . identity_being_watched ) { <nl> + watcher_info_ . erase ( cert_name ) ; <nl> + } <nl> + const bool root_has_update = root_certificate . has_value ( ) ; <nl> + const bool identity_has_update = pem_key_cert_pairs . has_value ( ) ; <nl> + if ( root_has_update | | identity_has_update ) { <nl> + distributor_ - > SetKeyMaterials ( cert_name , std : : move ( root_certificate ) , <nl> + std : : move ( pem_key_cert_pairs ) ) ; <nl> + } <nl> + grpc_error * root_cert_error = GRPC_ERROR_NONE ; <nl> + grpc_error * identity_cert_error = GRPC_ERROR_NONE ; <nl> + if ( root_being_watched & & ! root_has_update ) { <nl> + root_cert_error = GRPC_ERROR_CREATE_FROM_STATIC_STRING ( <nl> + " Unable to get latest root certificates . " ) ; <nl> + } <nl> + if ( identity_being_watched & & ! identity_has_update ) { <nl> + identity_cert_error = GRPC_ERROR_CREATE_FROM_STATIC_STRING ( <nl> + " Unable to get latest identity certificates . " ) ; <nl> + } <nl> + if ( root_cert_error ! = GRPC_ERROR_NONE | | <nl> + identity_cert_error ! = GRPC_ERROR_NONE ) { <nl> + distributor_ - > SetErrorForCert ( cert_name , root_cert_error , <nl> + identity_cert_error ) ; <nl> + } <nl> + } ) ; <nl> + } <nl> + <nl> + StaticDataCertificateProvider : : ~ StaticDataCertificateProvider ( ) { <nl> + / / Reset distributor ' s callback to make sure the callback won ' t be invoked <nl> + / / again after this object ( provider ) is destroyed . <nl> + distributor_ - > SetWatchStatusCallback ( nullptr ) ; <nl> + } <nl> + <nl> + namespace { <nl> + <nl> + gpr_timespec TimeoutSecondsToDeadline ( int64_t seconds ) { <nl> + return gpr_time_add ( gpr_now ( GPR_CLOCK_MONOTONIC ) , <nl> + gpr_time_from_seconds ( seconds , GPR_TIMESPAN ) ) ; <nl> + } <nl> + <nl> + } / / namespace <nl> + <nl> + FileWatcherCertificateProvider : : FileWatcherCertificateProvider ( <nl> + std : : string private_key_path , std : : string identity_certificate_path , <nl> + std : : string root_cert_path , unsigned int refresh_interval_sec ) <nl> + : private_key_path_ ( std : : move ( private_key_path ) ) , <nl> + identity_certificate_path_ ( std : : move ( identity_certificate_path ) ) , <nl> + root_cert_path_ ( std : : move ( root_cert_path ) ) , <nl> + refresh_interval_sec_ ( refresh_interval_sec ) , <nl> + distributor_ ( MakeRefCounted < grpc_tls_certificate_distributor > ( ) ) { <nl> + / / Private key and identity cert files must be both set or both unset . <nl> + GPR_ASSERT ( private_key_path_ . empty ( ) = = identity_certificate_path_ . empty ( ) ) ; <nl> + / / Must be watching either root or identity certs . <nl> + GPR_ASSERT ( ! private_key_path_ . empty ( ) | | ! root_cert_path_ . empty ( ) ) ; <nl> + gpr_event_init ( & shutdown_event_ ) ; <nl> + ForceUpdate ( ) ; <nl> + auto thread_lambda = [ ] ( void * arg ) { <nl> + FileWatcherCertificateProvider * provider = <nl> + static_cast < FileWatcherCertificateProvider * > ( arg ) ; <nl> + GPR_ASSERT ( provider ! = nullptr ) ; <nl> + while ( true ) { <nl> + void * value = gpr_event_wait ( <nl> + & provider - > shutdown_event_ , <nl> + TimeoutSecondsToDeadline ( provider - > refresh_interval_sec_ ) ) ; <nl> + if ( value ! = nullptr ) { <nl> + return ; <nl> + } ; <nl> + provider - > ForceUpdate ( ) ; <nl> + } <nl> + } ; <nl> + refresh_thread_ = grpc_core : : Thread ( <nl> + " FileWatcherCertificateProvider_refreshing_thread " , thread_lambda , this ) ; <nl> + refresh_thread_ . Start ( ) ; <nl> + distributor_ - > SetWatchStatusCallback ( [ this ] ( std : : string cert_name , <nl> + bool root_being_watched , <nl> + bool identity_being_watched ) { <nl> + grpc_core : : MutexLock lock ( & mu_ ) ; <nl> + absl : : optional < std : : string > root_certificate ; <nl> + absl : : optional < grpc_core : : PemKeyCertPairList > pem_key_cert_pairs ; <nl> + FileWatcherCertificateProvider : : WatcherInfo & info = <nl> + watcher_info_ [ cert_name ] ; <nl> + if ( ! info . root_being_watched & & root_being_watched & & <nl> + ! root_certificate_ . empty ( ) ) { <nl> + root_certificate = root_certificate_ ; <nl> + } <nl> + info . root_being_watched = root_being_watched ; <nl> + if ( ! info . identity_being_watched & & identity_being_watched & & <nl> + ! pem_key_cert_pairs_ . empty ( ) ) { <nl> + pem_key_cert_pairs = pem_key_cert_pairs_ ; <nl> + } <nl> + info . identity_being_watched = identity_being_watched ; <nl> + if ( ! info . root_being_watched & & ! info . identity_being_watched ) { <nl> + watcher_info_ . erase ( cert_name ) ; <nl> + } <nl> + ExecCtx exec_ctx ; <nl> + if ( root_certificate . has_value ( ) | | pem_key_cert_pairs . has_value ( ) ) { <nl> + distributor_ - > SetKeyMaterials ( cert_name , root_certificate , <nl> + pem_key_cert_pairs ) ; <nl> + } <nl> + grpc_error * root_cert_error = GRPC_ERROR_NONE ; <nl> + grpc_error * identity_cert_error = GRPC_ERROR_NONE ; <nl> + if ( root_being_watched & & ! root_certificate . has_value ( ) ) { <nl> + root_cert_error = GRPC_ERROR_CREATE_FROM_STATIC_STRING ( <nl> + " Unable to get latest root certificates . " ) ; <nl> + } <nl> + if ( identity_being_watched & & ! pem_key_cert_pairs . has_value ( ) ) { <nl> + identity_cert_error = GRPC_ERROR_CREATE_FROM_STATIC_STRING ( <nl> + " Unable to get latest identity certificates . " ) ; <nl> + } <nl> + if ( root_cert_error ! = GRPC_ERROR_NONE | | <nl> + identity_cert_error ! = GRPC_ERROR_NONE ) { <nl> + distributor_ - > SetErrorForCert ( cert_name , root_cert_error , <nl> + identity_cert_error ) ; <nl> + } <nl> } ) ; <nl> } <nl> <nl> + FileWatcherCertificateProvider : : ~ FileWatcherCertificateProvider ( ) { <nl> + / / Reset distributor ' s callback to make sure the callback won ' t be invoked <nl> + / / again after this object ( provider ) is destroyed . <nl> + distributor_ - > SetWatchStatusCallback ( nullptr ) ; <nl> + gpr_event_set ( & shutdown_event_ , ( void * ) ( 1 ) ) ; <nl> + refresh_thread_ . Join ( ) ; <nl> + } <nl> + <nl> + void FileWatcherCertificateProvider : : ForceUpdate ( ) { <nl> + absl : : optional < std : : string > root_certificate ; <nl> + absl : : optional < grpc_core : : PemKeyCertPairList > pem_key_cert_pairs ; <nl> + if ( ! root_cert_path_ . empty ( ) ) { <nl> + root_certificate = ReadRootCertificatesFromFile ( root_cert_path_ ) ; <nl> + } <nl> + if ( ! private_key_path_ . empty ( ) ) { <nl> + pem_key_cert_pairs = ReadIdentityKeyCertPairFromFiles ( <nl> + private_key_path_ , identity_certificate_path_ ) ; <nl> + } <nl> + grpc_core : : MutexLock lock ( & mu_ ) ; <nl> + const bool root_cert_changed = <nl> + ( ! root_certificate . has_value ( ) & & ! root_certificate_ . empty ( ) ) | | <nl> + ( root_certificate . has_value ( ) & & root_certificate_ ! = * root_certificate ) ; <nl> + if ( root_cert_changed ) { <nl> + if ( root_certificate . has_value ( ) ) { <nl> + root_certificate_ = std : : move ( * root_certificate ) ; <nl> + } else { <nl> + root_certificate_ = " " ; <nl> + } <nl> + } <nl> + const bool identity_cert_changed = <nl> + ( ! pem_key_cert_pairs . has_value ( ) & & ! pem_key_cert_pairs_ . empty ( ) ) | | <nl> + ( pem_key_cert_pairs . has_value ( ) & & <nl> + pem_key_cert_pairs_ ! = * pem_key_cert_pairs ) ; <nl> + if ( identity_cert_changed ) { <nl> + if ( pem_key_cert_pairs . has_value ( ) ) { <nl> + pem_key_cert_pairs_ = std : : move ( * pem_key_cert_pairs ) ; <nl> + } else { <nl> + pem_key_cert_pairs_ = { } ; <nl> + } <nl> + } <nl> + if ( root_cert_changed | | identity_cert_changed ) { <nl> + ExecCtx exec_ctx ; <nl> + grpc_error * root_cert_error = GRPC_ERROR_CREATE_FROM_STATIC_STRING ( <nl> + " Unable to get latest root certificates . " ) ; <nl> + grpc_error * identity_cert_error = GRPC_ERROR_CREATE_FROM_STATIC_STRING ( <nl> + " Unable to get latest identity certificates . " ) ; <nl> + for ( const auto & p : watcher_info_ ) { <nl> + const std : : string & cert_name = p . first ; <nl> + const WatcherInfo & info = p . second ; <nl> + absl : : optional < std : : string > root_to_report ; <nl> + absl : : optional < grpc_core : : PemKeyCertPairList > identity_to_report ; <nl> + / / Set key materials to the distributor if their contents changed . <nl> + if ( info . root_being_watched & & ! root_certificate_ . empty ( ) & & <nl> + root_cert_changed ) { <nl> + root_to_report = root_certificate_ ; <nl> + } <nl> + if ( info . identity_being_watched & & ! pem_key_cert_pairs_ . empty ( ) & & <nl> + identity_cert_changed ) { <nl> + identity_to_report = pem_key_cert_pairs_ ; <nl> + } <nl> + if ( root_to_report . has_value ( ) | | identity_to_report . has_value ( ) ) { <nl> + distributor_ - > SetKeyMaterials ( cert_name , std : : move ( root_to_report ) , <nl> + std : : move ( identity_to_report ) ) ; <nl> + } <nl> + / / Report errors to the distributor if the contents are empty . <nl> + const bool report_root_error = <nl> + info . root_being_watched & & root_certificate_ . empty ( ) ; <nl> + const bool report_identity_error = <nl> + info . identity_being_watched & & pem_key_cert_pairs_ . empty ( ) ; <nl> + if ( report_root_error | | report_identity_error ) { <nl> + distributor_ - > SetErrorForCert ( <nl> + cert_name , <nl> + report_root_error ? GRPC_ERROR_REF ( root_cert_error ) <nl> + : GRPC_ERROR_NONE , <nl> + report_identity_error ? GRPC_ERROR_REF ( identity_cert_error ) <nl> + : GRPC_ERROR_NONE ) ; <nl> + } <nl> + } <nl> + GRPC_ERROR_UNREF ( root_cert_error ) ; <nl> + GRPC_ERROR_UNREF ( identity_cert_error ) ; <nl> + } <nl> + } <nl> + <nl> + absl : : optional < std : : string > <nl> + FileWatcherCertificateProvider : : ReadRootCertificatesFromFile ( <nl> + const std : : string & root_cert_full_path ) { <nl> + / / Read the root file . <nl> + grpc_slice root_slice = grpc_empty_slice ( ) ; <nl> + grpc_error * root_error = <nl> + grpc_load_file ( root_cert_full_path . c_str ( ) , 0 , & root_slice ) ; <nl> + if ( root_error ! = GRPC_ERROR_NONE ) { <nl> + gpr_log ( GPR_ERROR , " Reading file % s failed : % s " , <nl> + root_cert_full_path . c_str ( ) , grpc_error_string ( root_error ) ) ; <nl> + GRPC_ERROR_UNREF ( root_error ) ; <nl> + return absl : : nullopt ; <nl> + } <nl> + std : : string root_cert ( StringViewFromSlice ( root_slice ) ) ; <nl> + grpc_slice_unref_internal ( root_slice ) ; <nl> + return root_cert ; <nl> + } <nl> + <nl> + namespace { <nl> + <nl> + / / This helper function gets the last - modified time of | filename | . When failed , <nl> + / / it logs the error and returns 0 . <nl> + time_t GetModificationTime ( const char * filename ) { <nl> + time_t ts = 0 ; <nl> + absl : : Status status = grpc_core : : GetFileModificationTime ( filename , & ts ) ; <nl> + return ts ; <nl> + } <nl> + <nl> + } / / namespace <nl> + <nl> + absl : : optional < PemKeyCertPairList > <nl> + FileWatcherCertificateProvider : : ReadIdentityKeyCertPairFromFiles ( <nl> + const std : : string & private_key_path , <nl> + const std : : string & identity_certificate_path ) { <nl> + struct SliceWrapper { <nl> + grpc_slice slice = grpc_empty_slice ( ) ; <nl> + ~ SliceWrapper ( ) { grpc_slice_unref_internal ( slice ) ; } <nl> + } ; <nl> + const int kNumRetryAttempts = 3 ; <nl> + for ( int i = 0 ; i < kNumRetryAttempts ; + + i ) { <nl> + / / TODO ( ZhenLian ) : replace the timestamp approach with key - match approach <nl> + / / once the latter is implemented . <nl> + / / Checking the last modification of identity files before reading . <nl> + time_t identity_key_ts_before = <nl> + GetModificationTime ( private_key_path . c_str ( ) ) ; <nl> + if ( identity_key_ts_before = = 0 ) { <nl> + gpr_log ( <nl> + GPR_ERROR , <nl> + " Failed to get the file ' s modification time of % s . Start retrying . . . " , <nl> + private_key_path . c_str ( ) ) ; <nl> + continue ; <nl> + } <nl> + time_t identity_cert_ts_before = <nl> + GetModificationTime ( identity_certificate_path . c_str ( ) ) ; <nl> + if ( identity_cert_ts_before = = 0 ) { <nl> + gpr_log ( <nl> + GPR_ERROR , <nl> + " Failed to get the file ' s modification time of % s . Start retrying . . . " , <nl> + identity_certificate_path . c_str ( ) ) ; <nl> + continue ; <nl> + } <nl> + / / Read the identity files . <nl> + SliceWrapper key_slice , cert_slice ; <nl> + grpc_error * key_error = <nl> + grpc_load_file ( private_key_path . c_str ( ) , 0 , & key_slice . slice ) ; <nl> + if ( key_error ! = GRPC_ERROR_NONE ) { <nl> + gpr_log ( GPR_ERROR , " Reading file % s failed : % s . Start retrying . . . " , <nl> + private_key_path . c_str ( ) , grpc_error_string ( key_error ) ) ; <nl> + GRPC_ERROR_UNREF ( key_error ) ; <nl> + continue ; <nl> + } <nl> + grpc_error * cert_error = <nl> + grpc_load_file ( identity_certificate_path . c_str ( ) , 0 , & cert_slice . slice ) ; <nl> + if ( cert_error ! = GRPC_ERROR_NONE ) { <nl> + gpr_log ( GPR_ERROR , " Reading file % s failed : % s . Start retrying . . . " , <nl> + identity_certificate_path . c_str ( ) , grpc_error_string ( cert_error ) ) ; <nl> + GRPC_ERROR_UNREF ( cert_error ) ; <nl> + continue ; <nl> + } <nl> + std : : string private_key ( StringViewFromSlice ( key_slice . slice ) ) ; <nl> + std : : string cert_chain ( StringViewFromSlice ( cert_slice . slice ) ) ; <nl> + grpc_ssl_pem_key_cert_pair * ssl_pair = <nl> + static_cast < grpc_ssl_pem_key_cert_pair * > ( <nl> + gpr_malloc ( sizeof ( grpc_ssl_pem_key_cert_pair ) ) ) ; <nl> + ssl_pair - > private_key = gpr_strdup ( private_key . c_str ( ) ) ; <nl> + ssl_pair - > cert_chain = gpr_strdup ( cert_chain . c_str ( ) ) ; <nl> + PemKeyCertPairList identity_pairs ; <nl> + identity_pairs . emplace_back ( ssl_pair ) ; <nl> + / / Checking the last modification of identity files before reading . <nl> + time_t identity_key_ts_after = <nl> + GetModificationTime ( private_key_path . c_str ( ) ) ; <nl> + if ( identity_key_ts_before ! = identity_key_ts_after ) { <nl> + gpr_log ( GPR_ERROR , <nl> + " Last modified time before and after reading % s is not the same . " <nl> + " Start retrying . . . " , <nl> + private_key_path . c_str ( ) ) ; <nl> + continue ; <nl> + } <nl> + time_t identity_cert_ts_after = <nl> + GetModificationTime ( identity_certificate_path . c_str ( ) ) ; <nl> + if ( identity_cert_ts_before ! = identity_cert_ts_after ) { <nl> + gpr_log ( GPR_ERROR , <nl> + " Last modified time before and after reading % s is not the same . " <nl> + " Start retrying . . . " , <nl> + identity_certificate_path . c_str ( ) ) ; <nl> + continue ; <nl> + } <nl> + return identity_pairs ; <nl> + } <nl> + gpr_log ( GPR_ERROR , <nl> + " All retry attempts failed . Will try again after the next interval . " ) ; <nl> + return absl : : nullopt ; <nl> + } <nl> + <nl> } / / namespace grpc_core <nl> <nl> / * * - - Wrapper APIs declared in grpc_security . h - - * * / <nl> grpc_tls_certificate_provider * grpc_tls_certificate_provider_static_data_create ( <nl> std : : move ( root_cert_core ) , std : : move ( identity_pairs_core ) ) ; <nl> } <nl> <nl> + grpc_tls_certificate_provider * <nl> + grpc_tls_certificate_provider_file_watcher_create ( <nl> + const char * private_key_path , const char * identity_certificate_path , <nl> + const char * root_cert_path , unsigned int refresh_interval_sec ) { <nl> + return new grpc_core : : FileWatcherCertificateProvider ( <nl> + private_key_path = = nullptr ? " " : private_key_path , <nl> + identity_certificate_path = = nullptr ? " " : identity_certificate_path , <nl> + root_cert_path = = nullptr ? " " : root_cert_path , refresh_interval_sec ) ; <nl> + } <nl> + <nl> void grpc_tls_certificate_provider_release ( <nl> grpc_tls_certificate_provider * provider ) { <nl> GRPC_API_TRACE ( " grpc_tls_certificate_provider_release ( provider = % p ) " , 1 , <nl> mmm a / src / core / lib / security / credentials / tls / grpc_tls_certificate_provider . h <nl> ppp b / src / core / lib / security / credentials / tls / grpc_tls_certificate_provider . h <nl> <nl> <nl> # include " src / core / lib / gprpp / ref_counted . h " <nl> # include " src / core / lib / gprpp / ref_counted_ptr . h " <nl> + # include " src / core / lib / gprpp / thd . h " <nl> + # include " src / core / lib / iomgr / load_file . h " <nl> # include " src / core / lib / iomgr / pollset_set . h " <nl> # include " src / core / lib / security / credentials / tls / grpc_tls_certificate_distributor . h " <nl> # include " src / core / lib / security / security_connector / ssl_utils . h " <nl> class StaticDataCertificateProvider final <nl> std : : string root_certificate , <nl> grpc_core : : PemKeyCertPairList pem_key_cert_pairs ) ; <nl> <nl> + ~ StaticDataCertificateProvider ( ) override ; <nl> + <nl> + RefCountedPtr < grpc_tls_certificate_distributor > distributor ( ) const override { <nl> + return distributor_ ; <nl> + } <nl> + <nl> + private : <nl> + struct WatcherInfo { <nl> + bool root_being_watched = false ; <nl> + bool identity_being_watched = false ; <nl> + } ; <nl> + RefCountedPtr < grpc_tls_certificate_distributor > distributor_ ; <nl> + std : : string root_certificate_ ; <nl> + grpc_core : : PemKeyCertPairList pem_key_cert_pairs_ ; <nl> + / / Guards members below . <nl> + grpc_core : : Mutex mu_ ; <nl> + / / Stores each cert_name we get from the distributor callback and its watcher <nl> + / / information . <nl> + std : : map < std : : string , WatcherInfo > watcher_info_ ; <nl> + } ; <nl> + <nl> + / / A provider class that will watch the credential changes on the file system . <nl> + class FileWatcherCertificateProvider final <nl> + : public grpc_tls_certificate_provider { <nl> + public : <nl> + FileWatcherCertificateProvider ( std : : string private_key_path , <nl> + std : : string identity_certificate_path , <nl> + std : : string root_cert_path , <nl> + unsigned int refresh_interval_sec ) ; <nl> + <nl> + ~ FileWatcherCertificateProvider ( ) override ; <nl> + <nl> RefCountedPtr < grpc_tls_certificate_distributor > distributor ( ) const override { <nl> return distributor_ ; <nl> } <nl> <nl> private : <nl> + struct WatcherInfo { <nl> + bool root_being_watched = false ; <nl> + bool identity_being_watched = false ; <nl> + } ; <nl> + / / Force an update from the file system regardless of the interval . <nl> + void ForceUpdate ( ) ; <nl> + / / Read the root certificates from files and update the distributor . <nl> + absl : : optional < std : : string > ReadRootCertificatesFromFile ( <nl> + const std : : string & root_cert_full_path ) ; <nl> + / / Read the root certificates from files and update the distributor . <nl> + absl : : optional < PemKeyCertPairList > ReadIdentityKeyCertPairFromFiles ( <nl> + const std : : string & private_key_file_name , <nl> + const std : : string & identity_certificate_file_name ) ; <nl> + <nl> + / / Information that is used by the refreshing thread . <nl> + std : : string private_key_path_ ; <nl> + std : : string identity_certificate_path_ ; <nl> + std : : string root_cert_path_ ; <nl> + unsigned int refresh_interval_sec_ = 0 ; <nl> + <nl> RefCountedPtr < grpc_tls_certificate_distributor > distributor_ ; <nl> + grpc_core : : Thread refresh_thread_ ; <nl> + gpr_event shutdown_event_ ; <nl> + <nl> + / / Guards members below . <nl> + grpc_core : : Mutex mu_ ; <nl> + / / The most - recent credential data . It will be empty if the most recent read <nl> + / / attempt failed . <nl> std : : string root_certificate_ ; <nl> grpc_core : : PemKeyCertPairList pem_key_cert_pairs_ ; <nl> + / / Stores each cert_name we get from the distributor callback and its watcher <nl> + / / information . <nl> + std : : map < std : : string , WatcherInfo > watcher_info_ ; <nl> } ; <nl> <nl> } / / namespace grpc_core <nl> mmm a / src / core / lib / security / credentials / tls / grpc_tls_credentials_options . h <nl> ppp b / src / core / lib / security / credentials / tls / grpc_tls_credentials_options . h <nl> struct grpc_tls_credentials_options <nl> server_authorization_check_config_ = std : : move ( config ) ; <nl> } <nl> / / Sets the provider in the options . <nl> - / / This should only be used by C - core API for Tls * Creds case . <nl> void set_certificate_provider ( <nl> grpc_core : : RefCountedPtr < grpc_tls_certificate_provider > provider ) { <nl> provider_ = std : : move ( provider ) ; <nl> mmm a / src / core / lib / security / security_connector / tls / tls_security_connector . h <nl> ppp b / src / core / lib / security / security_connector / tls / tls_security_connector . h <nl> class TlsChannelSecurityConnector final <nl> return client_handshaker_factory_ ; <nl> } ; <nl> <nl> - const absl : : optional < absl : : string_view > & RootCertsForTesting ( ) { <nl> + absl : : optional < absl : : string_view > RootCertsForTesting ( ) { <nl> grpc_core : : MutexLock lock ( & mu_ ) ; <nl> return pem_root_certs_ ; <nl> } <nl> <nl> - const absl : : optional < grpc_core : : PemKeyCertPairList > & <nl> - KeyCertPairListForTesting ( ) { <nl> + absl : : optional < grpc_core : : PemKeyCertPairList > KeyCertPairListForTesting ( ) { <nl> grpc_core : : MutexLock lock ( & mu_ ) ; <nl> return pem_key_cert_pair_list_ ; <nl> } <nl> mmm a / src / cpp / common / tls_certificate_provider . cc <nl> ppp b / src / cpp / common / tls_certificate_provider . cc <nl> StaticDataCertificateProvider : : ~ StaticDataCertificateProvider ( ) { <nl> grpc_tls_certificate_provider_release ( c_provider_ ) ; <nl> } ; <nl> <nl> + FileWatcherCertificateProvider : : FileWatcherCertificateProvider ( <nl> + const std : : string & private_key_path , <nl> + const std : : string & identity_certificate_path , <nl> + const std : : string & root_cert_path , unsigned int refresh_interval_sec ) { <nl> + c_provider_ = grpc_tls_certificate_provider_file_watcher_create ( <nl> + private_key_path . c_str ( ) , identity_certificate_path . c_str ( ) , <nl> + root_cert_path . c_str ( ) , refresh_interval_sec ) ; <nl> + GPR_ASSERT ( c_provider_ ! = nullptr ) ; <nl> + } ; <nl> + <nl> + FileWatcherCertificateProvider : : ~ FileWatcherCertificateProvider ( ) { <nl> + grpc_tls_certificate_provider_release ( c_provider_ ) ; <nl> + } ; <nl> + <nl> } / / namespace experimental <nl> } / / namespace grpc <nl> mmm a / src / ruby / ext / grpc / rb_grpc_imports . generated . c <nl> ppp b / src / ruby / ext / grpc / rb_grpc_imports . generated . c <nl> grpc_tls_identity_pairs_create_type grpc_tls_identity_pairs_create_import ; <nl> grpc_tls_identity_pairs_add_pair_type grpc_tls_identity_pairs_add_pair_import ; <nl> grpc_tls_identity_pairs_destroy_type grpc_tls_identity_pairs_destroy_import ; <nl> grpc_tls_certificate_provider_static_data_create_type grpc_tls_certificate_provider_static_data_create_import ; <nl> + grpc_tls_certificate_provider_file_watcher_create_type grpc_tls_certificate_provider_file_watcher_create_import ; <nl> grpc_tls_certificate_provider_release_type grpc_tls_certificate_provider_release_import ; <nl> grpc_tls_credentials_options_create_type grpc_tls_credentials_options_create_import ; <nl> grpc_tls_credentials_options_set_cert_request_type_type grpc_tls_credentials_options_set_cert_request_type_import ; <nl> void grpc_rb_load_imports ( HMODULE library ) { <nl> grpc_tls_identity_pairs_add_pair_import = ( grpc_tls_identity_pairs_add_pair_type ) GetProcAddress ( library , " grpc_tls_identity_pairs_add_pair " ) ; <nl> grpc_tls_identity_pairs_destroy_import = ( grpc_tls_identity_pairs_destroy_type ) GetProcAddress ( library , " grpc_tls_identity_pairs_destroy " ) ; <nl> grpc_tls_certificate_provider_static_data_create_import = ( grpc_tls_certificate_provider_static_data_create_type ) GetProcAddress ( library , " grpc_tls_certificate_provider_static_data_create " ) ; <nl> + grpc_tls_certificate_provider_file_watcher_create_import = ( grpc_tls_certificate_provider_file_watcher_create_type ) GetProcAddress ( library , " grpc_tls_certificate_provider_file_watcher_create " ) ; <nl> grpc_tls_certificate_provider_release_import = ( grpc_tls_certificate_provider_release_type ) GetProcAddress ( library , " grpc_tls_certificate_provider_release " ) ; <nl> grpc_tls_credentials_options_create_import = ( grpc_tls_credentials_options_create_type ) GetProcAddress ( library , " grpc_tls_credentials_options_create " ) ; <nl> grpc_tls_credentials_options_set_cert_request_type_import = ( grpc_tls_credentials_options_set_cert_request_type_type ) GetProcAddress ( library , " grpc_tls_credentials_options_set_cert_request_type " ) ; <nl> mmm a / src / ruby / ext / grpc / rb_grpc_imports . generated . h <nl> ppp b / src / ruby / ext / grpc / rb_grpc_imports . generated . h <nl> extern grpc_tls_identity_pairs_destroy_type grpc_tls_identity_pairs_destroy_impo <nl> typedef grpc_tls_certificate_provider * ( * grpc_tls_certificate_provider_static_data_create_type ) ( const char * root_certificate , grpc_tls_identity_pairs * pem_key_cert_pairs ) ; <nl> extern grpc_tls_certificate_provider_static_data_create_type grpc_tls_certificate_provider_static_data_create_import ; <nl> # define grpc_tls_certificate_provider_static_data_create grpc_tls_certificate_provider_static_data_create_import <nl> + typedef grpc_tls_certificate_provider * ( * grpc_tls_certificate_provider_file_watcher_create_type ) ( const char * private_key_path , const char * identity_certificate_path , const char * root_cert_path , unsigned int refresh_interval_sec ) ; <nl> + extern grpc_tls_certificate_provider_file_watcher_create_type grpc_tls_certificate_provider_file_watcher_create_import ; <nl> + # define grpc_tls_certificate_provider_file_watcher_create grpc_tls_certificate_provider_file_watcher_create_import <nl> typedef void ( * grpc_tls_certificate_provider_release_type ) ( grpc_tls_certificate_provider * provider ) ; <nl> extern grpc_tls_certificate_provider_release_type grpc_tls_certificate_provider_release_import ; <nl> # define grpc_tls_certificate_provider_release grpc_tls_certificate_provider_release_import <nl> mmm a / test / core / end2end / fixtures / h2_tls . cc <nl> ppp b / test / core / end2end / fixtures / h2_tls . cc <nl> <nl> # include " test / core / util / port . h " <nl> # include " test / core / util / test_config . h " <nl> <nl> + / / For normal TLS connections . <nl> # define CA_CERT_PATH " src / core / tsi / test_creds / ca . pem " <nl> # define SERVER_CERT_PATH " src / core / tsi / test_creds / server1 . pem " <nl> # define SERVER_KEY_PATH " src / core / tsi / test_creds / server1 . key " <nl> struct fullstack_secure_fixture_data { <nl> grpc_tls_certificate_provider * server_provider = nullptr ; <nl> } ; <nl> <nl> - static grpc_end2end_test_fixture chttp2_create_fixture_secure_fullstack ( <nl> + static grpc_end2end_test_fixture chttp2_create_fixture_static_data ( <nl> grpc_channel_args * / * client_args * / , grpc_channel_args * / * server_args * / , <nl> grpc_tls_version tls_version ) { <nl> grpc_end2end_test_fixture f ; <nl> static grpc_end2end_test_fixture chttp2_create_fixture_secure_fullstack ( <nl> return f ; <nl> } <nl> <nl> - static grpc_end2end_test_fixture chttp2_create_fixture_secure_fullstack_tls1_2 ( <nl> + static grpc_end2end_test_fixture chttp2_create_fixture_cert_watcher ( <nl> + grpc_channel_args * / * client_args * / , grpc_channel_args * / * server_args * / , <nl> + grpc_tls_version tls_version ) { <nl> + grpc_end2end_test_fixture f ; <nl> + int port = grpc_pick_unused_port_or_die ( ) ; <nl> + fullstack_secure_fixture_data * ffd = new fullstack_secure_fixture_data ( ) ; <nl> + memset ( & f , 0 , sizeof ( f ) ) ; <nl> + ffd - > localaddr = grpc_core : : JoinHostPort ( " localhost " , port ) ; <nl> + ffd - > tls_version = tls_version ; <nl> + ffd - > client_provider = grpc_tls_certificate_provider_file_watcher_create ( <nl> + SERVER_KEY_PATH , SERVER_CERT_PATH , CA_CERT_PATH , 1 ) ; <nl> + ffd - > server_provider = grpc_tls_certificate_provider_file_watcher_create ( <nl> + SERVER_KEY_PATH , SERVER_CERT_PATH , CA_CERT_PATH , 1 ) ; <nl> + f . fixture_data = ffd ; <nl> + f . cq = grpc_completion_queue_create_for_next ( nullptr ) ; <nl> + f . shutdown_cq = grpc_completion_queue_create_for_pluck ( nullptr ) ; <nl> + return f ; <nl> + } <nl> + <nl> + static grpc_end2end_test_fixture chttp2_create_fixture_static_data_tls1_2 ( <nl> grpc_channel_args * client_args , grpc_channel_args * server_args ) { <nl> - return chttp2_create_fixture_secure_fullstack ( client_args , server_args , <nl> - grpc_tls_version : : TLS1_2 ) ; <nl> + return chttp2_create_fixture_static_data ( client_args , server_args , <nl> + grpc_tls_version : : TLS1_2 ) ; <nl> } <nl> <nl> - static grpc_end2end_test_fixture chttp2_create_fixture_secure_fullstack_tls1_3 ( <nl> + static grpc_end2end_test_fixture chttp2_create_fixture_static_data_tls1_3 ( <nl> grpc_channel_args * client_args , grpc_channel_args * server_args ) { <nl> - return chttp2_create_fixture_secure_fullstack ( client_args , server_args , <nl> - grpc_tls_version : : TLS1_3 ) ; <nl> + return chttp2_create_fixture_static_data ( client_args , server_args , <nl> + grpc_tls_version : : TLS1_3 ) ; <nl> + } <nl> + <nl> + static grpc_end2end_test_fixture chttp2_create_fixture_cert_watcher_tls1_2 ( <nl> + grpc_channel_args * client_args , grpc_channel_args * server_args ) { <nl> + return chttp2_create_fixture_cert_watcher ( client_args , server_args , <nl> + grpc_tls_version : : TLS1_2 ) ; <nl> + } <nl> + <nl> + static grpc_end2end_test_fixture chttp2_create_fixture_cert_watcher_tls1_3 ( <nl> + grpc_channel_args * client_args , grpc_channel_args * server_args ) { <nl> + return chttp2_create_fixture_cert_watcher ( client_args , server_args , <nl> + grpc_tls_version : : TLS1_3 ) ; <nl> } <nl> <nl> static void process_auth_failure ( void * state , grpc_auth_context * / * ctx * / , <nl> static void chttp2_init_server ( grpc_end2end_test_fixture * f , <nl> } <nl> <nl> static grpc_end2end_test_config configs [ ] = { <nl> - / * client sync reload async authz + server sync reload . * / <nl> + / / client : static data provider + async custom verification <nl> + / / server : static data provider <nl> + / / extra : TLS 1 . 2 <nl> { " chttp2 / simple_ssl_fullstack_tls1_2 " , <nl> FEATURE_MASK_SUPPORTS_DELAYED_CONNECTION | <nl> FEATURE_MASK_SUPPORTS_PER_CALL_CREDENTIALS | <nl> FEATURE_MASK_SUPPORTS_CLIENT_CHANNEL | <nl> FEATURE_MASK_SUPPORTS_AUTHORITY_HEADER , <nl> - " foo . test . google . fr " , chttp2_create_fixture_secure_fullstack_tls1_2 , <nl> + " foo . test . google . fr " , chttp2_create_fixture_static_data_tls1_2 , <nl> chttp2_init_client , chttp2_init_server , chttp2_tear_down_secure_fullstack } , <nl> + / / client : static data provider + async custom verification <nl> + / / server : static data provider <nl> + / / extra : TLS 1 . 3 <nl> { " chttp2 / simple_ssl_fullstack_tls1_3 " , <nl> FEATURE_MASK_SUPPORTS_DELAYED_CONNECTION | <nl> FEATURE_MASK_SUPPORTS_PER_CALL_CREDENTIALS | <nl> FEATURE_MASK_SUPPORTS_CLIENT_CHANNEL | <nl> FEATURE_MASK_SUPPORTS_AUTHORITY_HEADER , <nl> - " foo . test . google . fr " , chttp2_create_fixture_secure_fullstack_tls1_3 , <nl> + " foo . test . google . fr " , chttp2_create_fixture_static_data_tls1_3 , <nl> chttp2_init_client , chttp2_init_server , chttp2_tear_down_secure_fullstack } , <nl> + / / client : certificate watcher provider + async custom verification <nl> + / / server : certificate watcher provider <nl> + / / extra : TLS 1 . 2 <nl> + { " chttp2 / reloading_from_files_ssl_fullstack_tls1_2 " , <nl> + FEATURE_MASK_SUPPORTS_DELAYED_CONNECTION | <nl> + FEATURE_MASK_SUPPORTS_PER_CALL_CREDENTIALS | <nl> + FEATURE_MASK_SUPPORTS_CLIENT_CHANNEL | <nl> + FEATURE_MASK_SUPPORTS_AUTHORITY_HEADER , <nl> + " foo . test . google . fr " , chttp2_create_fixture_cert_watcher_tls1_2 , <nl> + chttp2_init_client , chttp2_init_server , chttp2_tear_down_secure_fullstack } , <nl> + / / client : certificate watcher provider + async custom verification <nl> + / / server : certificate watcher provider <nl> + / / extra : TLS 1 . 3 <nl> + { " chttp2 / reloading_from_files_ssl_fullstack_tls1_3 " , <nl> + FEATURE_MASK_SUPPORTS_DELAYED_CONNECTION | <nl> + FEATURE_MASK_SUPPORTS_PER_CALL_CREDENTIALS | <nl> + FEATURE_MASK_SUPPORTS_CLIENT_CHANNEL | <nl> + FEATURE_MASK_SUPPORTS_AUTHORITY_HEADER , <nl> + " foo . test . google . fr " , chttp2_create_fixture_cert_watcher_tls1_3 , <nl> + chttp2_init_client , chttp2_init_server , chttp2_tear_down_secure_fullstack } , <nl> + <nl> } ; <nl> <nl> int main ( int argc , char * * argv ) { <nl> mmm a / test / core / security / BUILD <nl> ppp b / test / core / security / BUILD <nl> grpc_cc_test ( <nl> ] , <nl> ) <nl> <nl> + grpc_cc_library ( <nl> + name = " tls_utils " , <nl> + srcs = [ " tls_utils . cc " ] , <nl> + hdrs = [ " tls_utils . h " ] , <nl> + language = " C + + " , <nl> + visibility = [ " / / test / cpp : __subpackages__ " ] , <nl> + deps = [ " / / : grpc " ] , <nl> + ) <nl> + <nl> grpc_cc_test ( <nl> name = " tls_security_connector_test " , <nl> srcs = [ " tls_security_connector_test . cc " ] , <nl> grpc_cc_test ( <nl> srcs = [ " grpc_tls_credentials_options_test . cc " ] , <nl> data = [ <nl> " / / src / core / tsi / test_creds : ca . pem " , <nl> + " / / src / core / tsi / test_creds : multi - domain . key " , <nl> + " / / src / core / tsi / test_creds : multi - domain . pem " , <nl> + " / / src / core / tsi / test_creds : server0 . key " , <nl> + " / / src / core / tsi / test_creds : server0 . pem " , <nl> " / / src / core / tsi / test_creds : server1 . key " , <nl> " / / src / core / tsi / test_creds : server1 . pem " , <nl> ] , <nl> external_deps = [ " gtest " ] , <nl> language = " C + + " , <nl> deps = [ <nl> + " : tls_utils " , <nl> " / / : gpr " , <nl> " / / : grpc " , <nl> " / / : grpc_secure " , <nl> grpc_cc_test ( <nl> external_deps = [ " gtest " ] , <nl> language = " C + + " , <nl> deps = [ <nl> + " : tls_utils " , <nl> + " / / : gpr " , <nl> + " / / : grpc " , <nl> + " / / : grpc_secure " , <nl> + " / / test / core / util : grpc_test_util " , <nl> + ] , <nl> + ) <nl> + <nl> + grpc_cc_test ( <nl> + name = " grpc_tls_certificate_provider_test " , <nl> + srcs = [ " grpc_tls_certificate_provider_test . cc " ] , <nl> + data = [ <nl> + " / / src / core / tsi / test_creds : ca . pem " , <nl> + " / / src / core / tsi / test_creds : multi - domain . key " , <nl> + " / / src / core / tsi / test_creds : multi - domain . pem " , <nl> + " / / src / core / tsi / test_creds : server0 . key " , <nl> + " / / src / core / tsi / test_creds : server0 . pem " , <nl> + " / / src / core / tsi / test_creds : server1 . key " , <nl> + " / / src / core / tsi / test_creds : server1 . pem " , <nl> + ] , <nl> + external_deps = [ " gtest " ] , <nl> + language = " C + + " , <nl> + deps = [ <nl> + " : tls_utils " , <nl> " / / : gpr " , <nl> " / / : grpc " , <nl> " / / : grpc_secure " , <nl> mmm a / test / core / security / grpc_tls_certificate_distributor_test . cc <nl> ppp b / test / core / security / grpc_tls_certificate_distributor_test . cc <nl> <nl> # include < thread > <nl> <nl> # include " src / core / lib / slice / slice_internal . h " <nl> + # include " test / core / security / tls_utils . h " <nl> # include " test / core / util / test_config . h " <nl> <nl> + namespace grpc_core { <nl> + <nl> namespace testing { <nl> <nl> constexpr const char * kCertName1 = " cert_1_name " ; <nl> class GrpcTlsCertificateDistributorTest : public : : testing : : Test { <nl> / / Forward declaration . <nl> class TlsCertificatesTestWatcher ; <nl> <nl> - static grpc_core : : PemKeyCertPairList MakeCertKeyPairs ( const char * private_key , <nl> - const char * certs ) { <nl> - if ( strcmp ( private_key , " " ) = = 0 & & strcmp ( certs , " " ) = = 0 ) { <nl> - return { } ; <nl> - } <nl> - grpc_ssl_pem_key_cert_pair * ssl_pair = <nl> - static_cast < grpc_ssl_pem_key_cert_pair * > ( <nl> - gpr_malloc ( sizeof ( grpc_ssl_pem_key_cert_pair ) ) ) ; <nl> - ssl_pair - > private_key = gpr_strdup ( private_key ) ; <nl> - ssl_pair - > cert_chain = gpr_strdup ( certs ) ; <nl> - grpc_core : : PemKeyCertPairList pem_key_cert_pairs ; <nl> - pem_key_cert_pairs . emplace_back ( ssl_pair ) ; <nl> - return pem_key_cert_pairs ; <nl> - } <nl> - <nl> / / CredentialInfo contains the parameters when calling OnCertificatesChanged <nl> / / of a watcher . When OnCertificatesChanged is invoked , we will push a <nl> / / CredentialInfo to the cert_update_queue of state_ , and check in each test <nl> / / if the status updates are correct . <nl> struct CredentialInfo { <nl> std : : string root_certs ; <nl> - grpc_core : : PemKeyCertPairList key_cert_pairs ; <nl> - CredentialInfo ( std : : string root , grpc_core : : PemKeyCertPairList key_cert ) <nl> + PemKeyCertPairList key_cert_pairs ; <nl> + CredentialInfo ( std : : string root , PemKeyCertPairList key_cert ) <nl> : root_certs ( std : : move ( root ) ) , key_cert_pairs ( std : : move ( key_cert ) ) { } <nl> bool operator = = ( const CredentialInfo & other ) const { <nl> return root_certs = = other . root_certs & & <nl> class GrpcTlsCertificateDistributorTest : public : : testing : : Test { <nl> <nl> void OnCertificatesChanged ( <nl> absl : : optional < absl : : string_view > root_certs , <nl> - absl : : optional < grpc_core : : PemKeyCertPairList > key_cert_pairs ) override { <nl> + absl : : optional < PemKeyCertPairList > key_cert_pairs ) override { <nl> std : : string updated_root ; <nl> if ( root_certs . has_value ( ) ) { <nl> updated_root = std : : string ( * root_certs ) ; <nl> } <nl> - grpc_core : : PemKeyCertPairList updated_identity ; <nl> + PemKeyCertPairList updated_identity ; <nl> if ( key_cert_pairs . has_value ( ) ) { <nl> updated_identity = std : : move ( * key_cert_pairs ) ; <nl> } <nl> class GrpcTlsCertificateDistributorTest : public : : testing : : Test { <nl> grpc_slice root_error_slice ; <nl> GPR_ASSERT ( grpc_error_get_str ( <nl> root_cert_error , GRPC_ERROR_STR_DESCRIPTION , & root_error_slice ) ) ; <nl> - root_error_str = <nl> - std : : string ( grpc_core : : StringViewFromSlice ( root_error_slice ) ) ; <nl> + root_error_str = std : : string ( StringViewFromSlice ( root_error_slice ) ) ; <nl> } <nl> if ( identity_cert_error ! = GRPC_ERROR_NONE ) { <nl> grpc_slice identity_error_slice ; <nl> class GrpcTlsCertificateDistributorTest : public : : testing : : Test { <nl> GRPC_ERROR_STR_DESCRIPTION , <nl> & identity_error_slice ) ) ; <nl> identity_error_str = <nl> - std : : string ( grpc_core : : StringViewFromSlice ( identity_error_slice ) ) ; <nl> + std : : string ( StringViewFromSlice ( identity_error_slice ) ) ; <nl> } <nl> state_ - > error_queue . emplace_back ( std : : move ( root_error_str ) , <nl> std : : move ( identity_error_str ) ) ; <nl> class GrpcTlsCertificateDistributorTest : public : : testing : : Test { <nl> <nl> WatcherState * MakeWatcher ( absl : : optional < std : : string > root_cert_name , <nl> absl : : optional < std : : string > identity_cert_name ) { <nl> - grpc_core : : MutexLock lock ( & mu_ ) ; <nl> + MutexLock lock ( & mu_ ) ; <nl> watchers_ . emplace_back ( ) ; <nl> / / TlsCertificatesTestWatcher ctor takes a pointer to the WatcherState . <nl> / / It sets WatcherState : : watcher to point to itself . <nl> class GrpcTlsCertificateDistributorTest : public : : testing : : Test { <nl> } <nl> <nl> void CancelWatch ( WatcherState * state ) { <nl> - grpc_core : : MutexLock lock ( & mu_ ) ; <nl> + MutexLock lock ( & mu_ ) ; <nl> distributor_ . CancelTlsCertificatesWatch ( state - > watcher ) ; <nl> EXPECT_EQ ( state - > watcher , nullptr ) ; <nl> } <nl> class GrpcTlsCertificateDistributorTest : public : : testing : : Test { <nl> std : : list < WatcherState > watchers_ ; <nl> std : : deque < CallbackStatus > callback_queue_ ; <nl> / / This is to make watchers_ and callback_queue_ thread - safe . <nl> - grpc_core : : Mutex mu_ ; <nl> + Mutex mu_ ; <nl> } ; <nl> <nl> TEST_F ( GrpcTlsCertificateDistributorTest , BasicCredentialBehaviors ) { <nl> TEST_F ( GrpcTlsCertificateDistributorTest , BasicCredentialBehaviors ) { <nl> TEST_F ( GrpcTlsCertificateDistributorTest , UpdateCredentialsOnAnySide ) { <nl> WatcherState * watcher_state_1 = MakeWatcher ( kCertName1 , kCertName1 ) ; <nl> EXPECT_THAT ( GetCallbackQueue ( ) , <nl> - testing : : ElementsAre ( CallbackStatus ( kCertName1 , true , true ) ) ) ; <nl> + : : testing : : ElementsAre ( CallbackStatus ( kCertName1 , true , true ) ) ) ; <nl> / / SetKeyMaterials should trigger watcher ' s OnCertificatesChanged method . <nl> distributor_ . SetKeyMaterials ( <nl> kCertName1 , kRootCert1Contents , <nl> MakeCertKeyPairs ( kIdentityCert1PrivateKey , kIdentityCert1Contents ) ) ; <nl> EXPECT_THAT ( <nl> watcher_state_1 - > GetCredentialQueue ( ) , <nl> - testing : : ElementsAre ( CredentialInfo ( <nl> + : : testing : : ElementsAre ( CredentialInfo ( <nl> kRootCert1Contents , <nl> MakeCertKeyPairs ( kIdentityCert1PrivateKey , kIdentityCert1Contents ) ) ) ) ; <nl> / / Set root certs should trigger watcher ' s OnCertificatesChanged again . <nl> distributor_ . SetKeyMaterials ( kCertName1 , kRootCert2Contents , absl : : nullopt ) ; <nl> EXPECT_THAT ( <nl> watcher_state_1 - > GetCredentialQueue ( ) , <nl> - testing : : ElementsAre ( CredentialInfo ( <nl> + : : testing : : ElementsAre ( CredentialInfo ( <nl> kRootCert2Contents , <nl> MakeCertKeyPairs ( kIdentityCert1PrivateKey , kIdentityCert1Contents ) ) ) ) ; <nl> / / Set identity certs should trigger watcher ' s OnCertificatesChanged again . <nl> TEST_F ( GrpcTlsCertificateDistributorTest , UpdateCredentialsOnAnySide ) { <nl> MakeCertKeyPairs ( kIdentityCert2PrivateKey , kIdentityCert2Contents ) ) ; <nl> EXPECT_THAT ( <nl> watcher_state_1 - > GetCredentialQueue ( ) , <nl> - testing : : ElementsAre ( CredentialInfo ( <nl> + : : testing : : ElementsAre ( CredentialInfo ( <nl> kRootCert2Contents , <nl> MakeCertKeyPairs ( kIdentityCert2PrivateKey , kIdentityCert2Contents ) ) ) ) ; <nl> CancelWatch ( watcher_state_1 ) ; <nl> TEST_F ( GrpcTlsCertificateDistributorTest , SameIdentityNameDiffRootName ) { <nl> MakeWatcher ( kRootCert1Name , kIdentityCert1Name ) ; <nl> EXPECT_THAT ( <nl> GetCallbackQueue ( ) , <nl> - testing : : ElementsAre ( CallbackStatus ( kRootCert1Name , true , false ) , <nl> - CallbackStatus ( kIdentityCert1Name , false , true ) ) ) ; <nl> + : : testing : : ElementsAre ( CallbackStatus ( kRootCert1Name , true , false ) , <nl> + CallbackStatus ( kIdentityCert1Name , false , true ) ) ) ; <nl> / / Register watcher 2 . <nl> WatcherState * watcher_state_2 = <nl> MakeWatcher ( kRootCert2Name , kIdentityCert1Name ) ; <nl> - EXPECT_THAT ( GetCallbackQueue ( ) , testing : : ElementsAre ( CallbackStatus ( <nl> + EXPECT_THAT ( GetCallbackQueue ( ) , : : testing : : ElementsAre ( CallbackStatus ( <nl> kRootCert2Name , true , false ) ) ) ; <nl> / / Push credential updates to kRootCert1Name and check if the status works as <nl> / / expected . <nl> TEST_F ( GrpcTlsCertificateDistributorTest , SameIdentityNameDiffRootName ) { <nl> absl : : nullopt ) ; <nl> / / Check the updates are delivered to watcher 1 . <nl> EXPECT_THAT ( watcher_state_1 - > GetCredentialQueue ( ) , <nl> - testing : : ElementsAre ( CredentialInfo ( kRootCert1Contents , { } ) ) ) ; <nl> + : : testing : : ElementsAre ( CredentialInfo ( kRootCert1Contents , { } ) ) ) ; <nl> / / Push credential updates to kRootCert2Name . <nl> distributor_ . SetKeyMaterials ( kRootCert2Name , kRootCert2Contents , <nl> absl : : nullopt ) ; <nl> / / Check the updates are delivered to watcher 2 . <nl> EXPECT_THAT ( watcher_state_2 - > GetCredentialQueue ( ) , <nl> - testing : : ElementsAre ( CredentialInfo ( kRootCert2Contents , { } ) ) ) ; <nl> + : : testing : : ElementsAre ( CredentialInfo ( kRootCert2Contents , { } ) ) ) ; <nl> / / Push credential updates to kIdentityCert1Name and check if the status works <nl> / / as expected . <nl> distributor_ . SetKeyMaterials ( <nl> TEST_F ( GrpcTlsCertificateDistributorTest , SameIdentityNameDiffRootName ) { <nl> / / Check the updates are delivered to watcher 1 and watcher 2 . <nl> EXPECT_THAT ( <nl> watcher_state_1 - > GetCredentialQueue ( ) , <nl> - testing : : ElementsAre ( CredentialInfo ( <nl> + : : testing : : ElementsAre ( CredentialInfo ( <nl> kRootCert1Contents , <nl> MakeCertKeyPairs ( kIdentityCert1PrivateKey , kIdentityCert1Contents ) ) ) ) ; <nl> EXPECT_THAT ( <nl> watcher_state_2 - > GetCredentialQueue ( ) , <nl> - testing : : ElementsAre ( CredentialInfo ( <nl> + : : testing : : ElementsAre ( CredentialInfo ( <nl> kRootCert2Contents , <nl> MakeCertKeyPairs ( kIdentityCert1PrivateKey , kIdentityCert1Contents ) ) ) ) ; <nl> / / Cancel watcher 1 . <nl> CancelWatch ( watcher_state_1 ) ; <nl> - EXPECT_THAT ( GetCallbackQueue ( ) , testing : : ElementsAre ( CallbackStatus ( <nl> + EXPECT_THAT ( GetCallbackQueue ( ) , : : testing : : ElementsAre ( CallbackStatus ( <nl> kRootCert1Name , false , false ) ) ) ; <nl> / / Cancel watcher 2 . <nl> CancelWatch ( watcher_state_2 ) ; <nl> EXPECT_THAT ( <nl> GetCallbackQueue ( ) , <nl> - testing : : ElementsAre ( CallbackStatus ( kRootCert2Name , false , false ) , <nl> - CallbackStatus ( kIdentityCert1Name , false , false ) ) ) ; <nl> + : : testing : : ElementsAre ( CallbackStatus ( kRootCert2Name , false , false ) , <nl> + CallbackStatus ( kIdentityCert1Name , false , false ) ) ) ; <nl> } <nl> <nl> TEST_F ( GrpcTlsCertificateDistributorTest , SameRootNameDiffIdentityName ) { <nl> TEST_F ( GrpcTlsCertificateDistributorTest , SameRootNameDiffIdentityName ) { <nl> MakeWatcher ( kRootCert1Name , kIdentityCert1Name ) ; <nl> EXPECT_THAT ( <nl> GetCallbackQueue ( ) , <nl> - testing : : ElementsAre ( CallbackStatus ( kRootCert1Name , true , false ) , <nl> - CallbackStatus ( kIdentityCert1Name , false , true ) ) ) ; <nl> + : : testing : : ElementsAre ( CallbackStatus ( kRootCert1Name , true , false ) , <nl> + CallbackStatus ( kIdentityCert1Name , false , true ) ) ) ; <nl> / / Register watcher 2 . <nl> WatcherState * watcher_state_2 = <nl> MakeWatcher ( kRootCert1Name , kIdentityCert2Name ) ; <nl> - EXPECT_THAT ( GetCallbackQueue ( ) , testing : : ElementsAre ( CallbackStatus ( <nl> + EXPECT_THAT ( GetCallbackQueue ( ) , : : testing : : ElementsAre ( CallbackStatus ( <nl> kIdentityCert2Name , false , true ) ) ) ; <nl> / / Push credential updates to kRootCert1Name and check if the status works as <nl> / / expected . <nl> TEST_F ( GrpcTlsCertificateDistributorTest , SameRootNameDiffIdentityName ) { <nl> absl : : nullopt ) ; <nl> / / Check the updates are delivered to watcher 1 . <nl> EXPECT_THAT ( watcher_state_1 - > GetCredentialQueue ( ) , <nl> - testing : : ElementsAre ( CredentialInfo ( kRootCert1Contents , { } ) ) ) ; <nl> + : : testing : : ElementsAre ( CredentialInfo ( kRootCert1Contents , { } ) ) ) ; <nl> / / Check the updates are delivered to watcher 2 . <nl> EXPECT_THAT ( watcher_state_2 - > GetCredentialQueue ( ) , <nl> - testing : : ElementsAre ( CredentialInfo ( kRootCert1Contents , { } ) ) ) ; <nl> + : : testing : : ElementsAre ( CredentialInfo ( kRootCert1Contents , { } ) ) ) ; <nl> / / Push credential updates to SetKeyMaterials . <nl> distributor_ . SetKeyMaterials ( <nl> kIdentityCert1Name , absl : : nullopt , <nl> TEST_F ( GrpcTlsCertificateDistributorTest , SameRootNameDiffIdentityName ) { <nl> / / Check the updates are delivered to watcher 1 . <nl> EXPECT_THAT ( <nl> watcher_state_1 - > GetCredentialQueue ( ) , <nl> - testing : : ElementsAre ( CredentialInfo ( <nl> + : : testing : : ElementsAre ( CredentialInfo ( <nl> kRootCert1Contents , <nl> MakeCertKeyPairs ( kIdentityCert1PrivateKey , kIdentityCert1Contents ) ) ) ) ; <nl> / / Push credential updates to kIdentityCert2Name . <nl> TEST_F ( GrpcTlsCertificateDistributorTest , SameRootNameDiffIdentityName ) { <nl> / / Check the updates are delivered to watcher 2 . <nl> EXPECT_THAT ( <nl> watcher_state_2 - > GetCredentialQueue ( ) , <nl> - testing : : ElementsAre ( CredentialInfo ( <nl> + : : testing : : ElementsAre ( CredentialInfo ( <nl> kRootCert1Contents , <nl> MakeCertKeyPairs ( kIdentityCert2PrivateKey , kIdentityCert2Contents ) ) ) ) ; <nl> / / Cancel watcher 1 . <nl> CancelWatch ( watcher_state_1 ) ; <nl> - EXPECT_THAT ( GetCallbackQueue ( ) , testing : : ElementsAre ( CallbackStatus ( <nl> + EXPECT_THAT ( GetCallbackQueue ( ) , : : testing : : ElementsAre ( CallbackStatus ( <nl> kIdentityCert1Name , false , false ) ) ) ; <nl> / / Cancel watcher 2 . <nl> CancelWatch ( watcher_state_2 ) ; <nl> EXPECT_THAT ( <nl> GetCallbackQueue ( ) , <nl> - testing : : ElementsAre ( CallbackStatus ( kRootCert1Name , false , false ) , <nl> - CallbackStatus ( kIdentityCert2Name , false , false ) ) ) ; <nl> + : : testing : : ElementsAre ( CallbackStatus ( kRootCert1Name , false , false ) , <nl> + CallbackStatus ( kIdentityCert2Name , false , false ) ) ) ; <nl> } <nl> <nl> TEST_F ( GrpcTlsCertificateDistributorTest , <nl> TEST_F ( GrpcTlsCertificateDistributorTest , <nl> / / Register watcher 1 watching kCertName1 for both root and identity certs . <nl> WatcherState * watcher_state_1 = MakeWatcher ( kCertName1 , kCertName1 ) ; <nl> EXPECT_THAT ( GetCallbackQueue ( ) , <nl> - testing : : ElementsAre ( CallbackStatus ( kCertName1 , true , true ) ) ) ; <nl> + : : testing : : ElementsAre ( CallbackStatus ( kCertName1 , true , true ) ) ) ; <nl> / / Push credential updates to kCertName1 and check if the status works as <nl> / / expected . <nl> distributor_ . SetKeyMaterials ( <nl> TEST_F ( GrpcTlsCertificateDistributorTest , <nl> / / Check the updates are delivered to watcher 1 . <nl> EXPECT_THAT ( <nl> watcher_state_1 - > GetCredentialQueue ( ) , <nl> - testing : : ElementsAre ( CredentialInfo ( <nl> + : : testing : : ElementsAre ( CredentialInfo ( <nl> kRootCert1Contents , <nl> MakeCertKeyPairs ( kIdentityCert1PrivateKey , kIdentityCert1Contents ) ) ) ) ; <nl> / / Cancel watcher 1 . <nl> CancelWatch ( watcher_state_1 ) ; <nl> EXPECT_THAT ( GetCallbackQueue ( ) , <nl> - testing : : ElementsAre ( CallbackStatus ( kCertName1 , false , false ) ) ) ; <nl> + : : testing : : ElementsAre ( CallbackStatus ( kCertName1 , false , false ) ) ) ; <nl> } <nl> <nl> TEST_F ( GrpcTlsCertificateDistributorTest , <nl> TEST_F ( GrpcTlsCertificateDistributorTest , <nl> / / Register watcher 1 watching kCertName1 for root certs . <nl> WatcherState * watcher_state_1 = MakeWatcher ( kCertName1 , absl : : nullopt ) ; <nl> EXPECT_THAT ( GetCallbackQueue ( ) , <nl> - testing : : ElementsAre ( CallbackStatus ( kCertName1 , true , false ) ) ) ; <nl> + : : testing : : ElementsAre ( CallbackStatus ( kCertName1 , true , false ) ) ) ; <nl> / / Register watcher 2 watching kCertName1 for identity certs . <nl> WatcherState * watcher_state_2 = MakeWatcher ( absl : : nullopt , kCertName1 ) ; <nl> EXPECT_THAT ( GetCallbackQueue ( ) , <nl> - testing : : ElementsAre ( CallbackStatus ( kCertName1 , true , true ) ) ) ; <nl> + : : testing : : ElementsAre ( CallbackStatus ( kCertName1 , true , true ) ) ) ; <nl> / / Push credential updates to kCertName1 and check if the status works as <nl> / / expected . <nl> distributor_ . SetKeyMaterials ( <nl> TEST_F ( GrpcTlsCertificateDistributorTest , <nl> MakeCertKeyPairs ( kIdentityCert1PrivateKey , kIdentityCert1Contents ) ) ; <nl> / / Check the updates are delivered to watcher 1 . <nl> EXPECT_THAT ( watcher_state_1 - > GetCredentialQueue ( ) , <nl> - testing : : ElementsAre ( CredentialInfo ( kRootCert1Contents , { } ) ) ) ; <nl> + : : testing : : ElementsAre ( CredentialInfo ( kRootCert1Contents , { } ) ) ) ; <nl> / / Check the updates are delivered to watcher 2 . <nl> EXPECT_THAT ( watcher_state_2 - > GetCredentialQueue ( ) , <nl> - testing : : ElementsAre ( CredentialInfo ( <nl> + : : testing : : ElementsAre ( CredentialInfo ( <nl> " " , MakeCertKeyPairs ( kIdentityCert1PrivateKey , <nl> kIdentityCert1Contents ) ) ) ) ; <nl> / / Push root cert updates to kCertName1 . <nl> distributor_ . SetKeyMaterials ( kCertName1 , kRootCert2Contents , absl : : nullopt ) ; <nl> / / Check the updates are delivered to watcher 1 . <nl> EXPECT_THAT ( watcher_state_1 - > GetCredentialQueue ( ) , <nl> - testing : : ElementsAre ( CredentialInfo ( kRootCert2Contents , { } ) ) ) ; <nl> + : : testing : : ElementsAre ( CredentialInfo ( kRootCert2Contents , { } ) ) ) ; <nl> / / Check the updates are not delivered to watcher 2 . <nl> - EXPECT_THAT ( watcher_state_2 - > GetCredentialQueue ( ) , testing : : ElementsAre ( ) ) ; <nl> + EXPECT_THAT ( watcher_state_2 - > GetCredentialQueue ( ) , : : testing : : ElementsAre ( ) ) ; <nl> / / Push identity cert updates to kCertName1 . <nl> distributor_ . SetKeyMaterials ( <nl> kCertName1 , absl : : nullopt , <nl> MakeCertKeyPairs ( kIdentityCert2PrivateKey , kIdentityCert2Contents ) ) ; <nl> / / Check the updates are not delivered to watcher 1 . <nl> - EXPECT_THAT ( watcher_state_1 - > GetCredentialQueue ( ) , testing : : ElementsAre ( ) ) ; <nl> + EXPECT_THAT ( watcher_state_1 - > GetCredentialQueue ( ) , : : testing : : ElementsAre ( ) ) ; <nl> / / Check the updates are delivered to watcher 2 . <nl> EXPECT_THAT ( watcher_state_2 - > GetCredentialQueue ( ) , <nl> - testing : : ElementsAre ( CredentialInfo ( <nl> + : : testing : : ElementsAre ( CredentialInfo ( <nl> " " , MakeCertKeyPairs ( kIdentityCert2PrivateKey , <nl> kIdentityCert2Contents ) ) ) ) ; <nl> watcher_state_2 - > cert_update_queue . clear ( ) ; <nl> / / Cancel watcher 2 . <nl> CancelWatch ( watcher_state_2 ) ; <nl> EXPECT_THAT ( GetCallbackQueue ( ) , <nl> - testing : : ElementsAre ( CallbackStatus ( kCertName1 , true , false ) ) ) ; <nl> + : : testing : : ElementsAre ( CallbackStatus ( kCertName1 , true , false ) ) ) ; <nl> / / Cancel watcher 1 . <nl> CancelWatch ( watcher_state_1 ) ; <nl> EXPECT_THAT ( GetCallbackQueue ( ) , <nl> - testing : : ElementsAre ( CallbackStatus ( kCertName1 , false , false ) ) ) ; <nl> + : : testing : : ElementsAre ( CallbackStatus ( kCertName1 , false , false ) ) ) ; <nl> } <nl> <nl> TEST_F ( GrpcTlsCertificateDistributorTest , <nl> TEST_F ( GrpcTlsCertificateDistributorTest , <nl> / / Register watcher 1 watching kCertName1 for identity certs . <nl> WatcherState * watcher_state_1 = MakeWatcher ( absl : : nullopt , kCertName1 ) ; <nl> EXPECT_THAT ( GetCallbackQueue ( ) , <nl> - testing : : ElementsAre ( CallbackStatus ( kCertName1 , false , true ) ) ) ; <nl> + : : testing : : ElementsAre ( CallbackStatus ( kCertName1 , false , true ) ) ) ; <nl> / / Register watcher 2 watching kCertName1 for root certs . <nl> WatcherState * watcher_state_2 = MakeWatcher ( kCertName1 , absl : : nullopt ) ; <nl> EXPECT_THAT ( GetCallbackQueue ( ) , <nl> - testing : : ElementsAre ( CallbackStatus ( kCertName1 , true , true ) ) ) ; <nl> + : : testing : : ElementsAre ( CallbackStatus ( kCertName1 , true , true ) ) ) ; <nl> / / Push credential updates to kCertName1 and check if the status works as <nl> / / expected . <nl> distributor_ . SetKeyMaterials ( <nl> TEST_F ( GrpcTlsCertificateDistributorTest , <nl> MakeCertKeyPairs ( kIdentityCert1PrivateKey , kIdentityCert1Contents ) ) ; <nl> / / Check the updates are delivered to watcher 1 . <nl> EXPECT_THAT ( watcher_state_1 - > GetCredentialQueue ( ) , <nl> - testing : : ElementsAre ( CredentialInfo ( <nl> + : : testing : : ElementsAre ( CredentialInfo ( <nl> " " , MakeCertKeyPairs ( kIdentityCert1PrivateKey , <nl> kIdentityCert1Contents ) ) ) ) ; <nl> / / Check the updates are delivered to watcher 2 . <nl> EXPECT_THAT ( watcher_state_2 - > GetCredentialQueue ( ) , <nl> - testing : : ElementsAre ( CredentialInfo ( kRootCert1Contents , { } ) ) ) ; <nl> + : : testing : : ElementsAre ( CredentialInfo ( kRootCert1Contents , { } ) ) ) ; <nl> / / Push root cert updates to kCertName1 . <nl> distributor_ . SetKeyMaterials ( kCertName1 , kRootCert2Contents , absl : : nullopt ) ; <nl> / / Check the updates are delivered to watcher 2 . <nl> EXPECT_THAT ( watcher_state_2 - > GetCredentialQueue ( ) , <nl> - testing : : ElementsAre ( CredentialInfo ( kRootCert2Contents , { } ) ) ) ; <nl> + : : testing : : ElementsAre ( CredentialInfo ( kRootCert2Contents , { } ) ) ) ; <nl> / / Check the updates are not delivered to watcher 1 . <nl> - EXPECT_THAT ( watcher_state_1 - > GetCredentialQueue ( ) , testing : : ElementsAre ( ) ) ; <nl> + EXPECT_THAT ( watcher_state_1 - > GetCredentialQueue ( ) , : : testing : : ElementsAre ( ) ) ; <nl> / / Push identity cert updates to kCertName1 . <nl> distributor_ . SetKeyMaterials ( <nl> kCertName1 , absl : : nullopt , <nl> MakeCertKeyPairs ( kIdentityCert2PrivateKey , kIdentityCert2Contents ) ) ; <nl> / / Check the updates are not delivered to watcher 2 . <nl> - EXPECT_THAT ( watcher_state_2 - > GetCredentialQueue ( ) , testing : : ElementsAre ( ) ) ; <nl> + EXPECT_THAT ( watcher_state_2 - > GetCredentialQueue ( ) , : : testing : : ElementsAre ( ) ) ; <nl> / / Check the updates are delivered to watcher 1 . <nl> EXPECT_THAT ( watcher_state_1 - > GetCredentialQueue ( ) , <nl> - testing : : ElementsAre ( CredentialInfo ( <nl> + : : testing : : ElementsAre ( CredentialInfo ( <nl> " " , MakeCertKeyPairs ( kIdentityCert2PrivateKey , <nl> kIdentityCert2Contents ) ) ) ) ; <nl> / / Cancel watcher 2 . <nl> CancelWatch ( watcher_state_2 ) ; <nl> EXPECT_THAT ( GetCallbackQueue ( ) , <nl> - testing : : ElementsAre ( CallbackStatus ( kCertName1 , false , true ) ) ) ; <nl> + : : testing : : ElementsAre ( CallbackStatus ( kCertName1 , false , true ) ) ) ; <nl> / / Cancel watcher 1 . <nl> CancelWatch ( watcher_state_1 ) ; <nl> EXPECT_THAT ( GetCallbackQueue ( ) , <nl> - testing : : ElementsAre ( CallbackStatus ( kCertName1 , false , false ) ) ) ; <nl> + : : testing : : ElementsAre ( CallbackStatus ( kCertName1 , false , false ) ) ) ; <nl> } <nl> <nl> TEST_F ( GrpcTlsCertificateDistributorTest , <nl> TEST_F ( GrpcTlsCertificateDistributorTest , <nl> / / certs . <nl> WatcherState * watcher_state_1 = MakeWatcher ( kCertName1 , kCertName1 ) ; <nl> EXPECT_THAT ( GetCallbackQueue ( ) , <nl> - testing : : ElementsAre ( CallbackStatus ( kCertName1 , true , true ) ) ) ; <nl> + : : testing : : ElementsAre ( CallbackStatus ( kCertName1 , true , true ) ) ) ; <nl> WatcherState * watcher_state_2 = MakeWatcher ( kCertName1 , kCertName1 ) ; <nl> - EXPECT_THAT ( GetCallbackQueue ( ) , testing : : ElementsAre ( ) ) ; <nl> + EXPECT_THAT ( GetCallbackQueue ( ) , : : testing : : ElementsAre ( ) ) ; <nl> / / Push credential updates to kCertName1 . <nl> distributor_ . SetKeyMaterials ( <nl> kCertName1 , kRootCert1Contents , <nl> MakeCertKeyPairs ( kIdentityCert1PrivateKey , kIdentityCert1Contents ) ) ; <nl> / / Cancel watcher 2 . <nl> CancelWatch ( watcher_state_2 ) ; <nl> - EXPECT_THAT ( GetCallbackQueue ( ) , testing : : ElementsAre ( ) ) ; <nl> + EXPECT_THAT ( GetCallbackQueue ( ) , : : testing : : ElementsAre ( ) ) ; <nl> / / Cancel watcher 1 . <nl> CancelWatch ( watcher_state_1 ) ; <nl> EXPECT_THAT ( GetCallbackQueue ( ) , <nl> - testing : : ElementsAre ( CallbackStatus ( kCertName1 , false , false ) ) ) ; <nl> + : : testing : : ElementsAre ( CallbackStatus ( kCertName1 , false , false ) ) ) ; <nl> / / Register watcher 3 watching kCertName for root and identity certs . <nl> WatcherState * watcher_state_3 = MakeWatcher ( kCertName1 , kCertName1 ) ; <nl> EXPECT_THAT ( GetCallbackQueue ( ) , <nl> - testing : : ElementsAre ( CallbackStatus ( kCertName1 , true , true ) ) ) ; <nl> + : : testing : : ElementsAre ( CallbackStatus ( kCertName1 , true , true ) ) ) ; <nl> / / Push credential updates to kCertName1 . <nl> distributor_ . SetKeyMaterials ( <nl> kCertName1 , kRootCert2Contents , <nl> TEST_F ( GrpcTlsCertificateDistributorTest , <nl> / / Check the updates are delivered to watcher 3 . <nl> EXPECT_THAT ( <nl> watcher_state_3 - > GetCredentialQueue ( ) , <nl> - testing : : ElementsAre ( CredentialInfo ( <nl> + : : testing : : ElementsAre ( CredentialInfo ( <nl> kRootCert2Contents , <nl> MakeCertKeyPairs ( kIdentityCert2PrivateKey , kIdentityCert2Contents ) ) ) ) ; <nl> / / Cancel watcher 3 . <nl> CancelWatch ( watcher_state_3 ) ; <nl> EXPECT_THAT ( GetCallbackQueue ( ) , <nl> - testing : : ElementsAre ( CallbackStatus ( kCertName1 , false , false ) ) ) ; <nl> + : : testing : : ElementsAre ( CallbackStatus ( kCertName1 , false , false ) ) ) ; <nl> } <nl> <nl> TEST_F ( GrpcTlsCertificateDistributorTest , ResetCallbackToNull ) { <nl> / / Register watcher 1 watching kCertName1 for root and identity certs . <nl> WatcherState * watcher_state_1 = MakeWatcher ( kCertName1 , kCertName1 ) ; <nl> EXPECT_THAT ( GetCallbackQueue ( ) , <nl> - testing : : ElementsAre ( CallbackStatus ( kCertName1 , true , true ) ) ) ; <nl> + : : testing : : ElementsAre ( CallbackStatus ( kCertName1 , true , true ) ) ) ; <nl> / / Reset callback to nullptr . <nl> distributor_ . SetWatchStatusCallback ( nullptr ) ; <nl> / / Cancel watcher 1 shouldn ' t trigger any callback . <nl> CancelWatch ( watcher_state_1 ) ; <nl> - EXPECT_THAT ( GetCallbackQueue ( ) , testing : : ElementsAre ( ) ) ; <nl> + EXPECT_THAT ( GetCallbackQueue ( ) , : : testing : : ElementsAre ( ) ) ; <nl> } <nl> <nl> TEST_F ( GrpcTlsCertificateDistributorTest , SetKeyMaterialsInCallback ) { <nl> TEST_F ( GrpcTlsCertificateDistributorTest , SetKeyMaterialsInCallback ) { <nl> / / Check the updates are delivered to watcher 1 . <nl> EXPECT_THAT ( <nl> watcher_state_1 - > GetCredentialQueue ( ) , <nl> - testing : : ElementsAre ( CredentialInfo ( <nl> + : : testing : : ElementsAre ( CredentialInfo ( <nl> kRootCert1Contents , MakeCertKeyPairs ( kIdentityCert1PrivateKey , <nl> kIdentityCert1Contents ) ) ) ) ; <nl> CancelWatch ( watcher_state_1 ) ; <nl> TEST_F ( GrpcTlsCertificateDistributorTest , WatchACertInfoWithValidCredentials ) { <nl> / / watcher 1 should receive the credentials right away . <nl> EXPECT_THAT ( <nl> watcher_state_1 - > GetCredentialQueue ( ) , <nl> - testing : : ElementsAre ( CredentialInfo ( <nl> + : : testing : : ElementsAre ( CredentialInfo ( <nl> kRootCert1Contents , <nl> MakeCertKeyPairs ( kIdentityCert1PrivateKey , kIdentityCert1Contents ) ) ) ) ; <nl> CancelWatch ( watcher_state_1 ) ; <nl> TEST_F ( GrpcTlsCertificateDistributorTest , WatchACertInfoWithValidCredentials ) { <nl> WatcherState * watcher_state_2 = MakeWatcher ( kRootCert2Name , absl : : nullopt ) ; <nl> / / watcher 2 should receive the root credentials right away . <nl> EXPECT_THAT ( watcher_state_2 - > GetCredentialQueue ( ) , <nl> - testing : : ElementsAre ( CredentialInfo ( kRootCert2Contents , { } ) ) ) ; <nl> + : : testing : : ElementsAre ( CredentialInfo ( kRootCert2Contents , { } ) ) ) ; <nl> / / Register watcher 3 . <nl> WatcherState * watcher_state_3 = <nl> MakeWatcher ( absl : : nullopt , kIdentityCert2Name ) ; <nl> / / watcher 3 should received the identity credentials right away . <nl> EXPECT_THAT ( watcher_state_3 - > GetCredentialQueue ( ) , <nl> - testing : : ElementsAre ( CredentialInfo ( <nl> + : : testing : : ElementsAre ( CredentialInfo ( <nl> " " , MakeCertKeyPairs ( kIdentityCert2PrivateKey , <nl> kIdentityCert2Contents ) ) ) ) ; <nl> CancelWatch ( watcher_state_2 ) ; <nl> TEST_F ( GrpcTlsCertificateDistributorTest , <nl> kCertName1 , GRPC_ERROR_CREATE_FROM_STATIC_STRING ( kRootErrorMessage ) , <nl> GRPC_ERROR_CREATE_FROM_STATIC_STRING ( kIdentityErrorMessage ) ) ; <nl> EXPECT_THAT ( watcher_state_1 - > GetErrorQueue ( ) , <nl> - testing : : ElementsAre ( <nl> + : : testing : : ElementsAre ( <nl> ErrorInfo ( kRootErrorMessage , kIdentityErrorMessage ) ) ) ; <nl> / / Calling SetErrorForCert on root cert name should call OnError <nl> / / on watcher 1 again . <nl> TEST_F ( GrpcTlsCertificateDistributorTest , <nl> absl : : nullopt ) ; <nl> EXPECT_THAT ( <nl> watcher_state_1 - > GetErrorQueue ( ) , <nl> - testing : : ElementsAre ( ErrorInfo ( kErrorMessage , kIdentityErrorMessage ) ) ) ; <nl> + : : testing : : ElementsAre ( ErrorInfo ( kErrorMessage , kIdentityErrorMessage ) ) ) ; <nl> / / Calling SetErrorForCert on identity cert name should call OnError <nl> / / on watcher 1 again . <nl> distributor_ . SetErrorForCert ( <nl> kCertName1 , absl : : nullopt , <nl> GRPC_ERROR_CREATE_FROM_STATIC_STRING ( kErrorMessage ) ) ; <nl> EXPECT_THAT ( watcher_state_1 - > GetErrorQueue ( ) , <nl> - testing : : ElementsAre ( ErrorInfo ( kErrorMessage , kErrorMessage ) ) ) ; <nl> + : : testing : : ElementsAre ( ErrorInfo ( kErrorMessage , kErrorMessage ) ) ) ; <nl> distributor_ . CancelTlsCertificatesWatch ( watcher_state_1 - > watcher ) ; <nl> EXPECT_EQ ( watcher_state_1 - > watcher , nullptr ) ; <nl> } <nl> TEST_F ( GrpcTlsCertificateDistributorTest , SetErrorForCertForRootOrIdentity ) { <nl> kCertName1 , GRPC_ERROR_CREATE_FROM_STATIC_STRING ( kRootErrorMessage ) , <nl> absl : : nullopt ) ; <nl> EXPECT_THAT ( watcher_state_1 - > GetErrorQueue ( ) , <nl> - testing : : ElementsAre ( ErrorInfo ( kRootErrorMessage , " " ) ) ) ; <nl> + : : testing : : ElementsAre ( ErrorInfo ( kRootErrorMessage , " " ) ) ) ; <nl> / / Calling SetErrorForCert on identity name should do nothing . <nl> distributor_ . SetErrorForCert ( <nl> kCertName1 , absl : : nullopt , <nl> GRPC_ERROR_CREATE_FROM_STATIC_STRING ( kIdentityErrorMessage ) ) ; <nl> - EXPECT_THAT ( watcher_state_1 - > GetErrorQueue ( ) , testing : : ElementsAre ( ) ) ; <nl> + EXPECT_THAT ( watcher_state_1 - > GetErrorQueue ( ) , : : testing : : ElementsAre ( ) ) ; <nl> / / Calling SetErrorForCert on both names should still get one OnError call . <nl> distributor_ . SetErrorForCert ( <nl> kCertName1 , GRPC_ERROR_CREATE_FROM_STATIC_STRING ( kRootErrorMessage ) , <nl> GRPC_ERROR_CREATE_FROM_STATIC_STRING ( kIdentityErrorMessage ) ) ; <nl> EXPECT_THAT ( watcher_state_1 - > GetErrorQueue ( ) , <nl> - testing : : ElementsAre ( ErrorInfo ( kRootErrorMessage , " " ) ) ) ; <nl> + : : testing : : ElementsAre ( ErrorInfo ( kRootErrorMessage , " " ) ) ) ; <nl> CancelWatch ( watcher_state_1 ) ; <nl> / / Register watcher 2 . <nl> WatcherState * watcher_state_2 = MakeWatcher ( absl : : nullopt , kCertName1 ) ; <nl> TEST_F ( GrpcTlsCertificateDistributorTest , SetErrorForCertForRootOrIdentity ) { <nl> kCertName1 , absl : : nullopt , <nl> GRPC_ERROR_CREATE_FROM_STATIC_STRING ( kIdentityErrorMessage ) ) ; <nl> EXPECT_THAT ( watcher_state_2 - > GetErrorQueue ( ) , <nl> - testing : : ElementsAre ( ErrorInfo ( " " , kIdentityErrorMessage ) ) ) ; <nl> + : : testing : : ElementsAre ( ErrorInfo ( " " , kIdentityErrorMessage ) ) ) ; <nl> / / Calling SetErrorForCert on root name should do nothing . <nl> distributor_ . SetErrorForCert ( <nl> kCertName1 , GRPC_ERROR_CREATE_FROM_STATIC_STRING ( kRootErrorMessage ) , <nl> absl : : nullopt ) ; <nl> - EXPECT_THAT ( watcher_state_2 - > GetErrorQueue ( ) , testing : : ElementsAre ( ) ) ; <nl> + EXPECT_THAT ( watcher_state_2 - > GetErrorQueue ( ) , : : testing : : ElementsAre ( ) ) ; <nl> / / Calling SetErrorForCert on both names should still get one OnError call . <nl> distributor_ . SetErrorForCert ( <nl> kCertName1 , GRPC_ERROR_CREATE_FROM_STATIC_STRING ( kRootErrorMessage ) , <nl> GRPC_ERROR_CREATE_FROM_STATIC_STRING ( kIdentityErrorMessage ) ) ; <nl> EXPECT_THAT ( watcher_state_2 - > GetErrorQueue ( ) , <nl> - testing : : ElementsAre ( ErrorInfo ( " " , kIdentityErrorMessage ) ) ) ; <nl> + : : testing : : ElementsAre ( ErrorInfo ( " " , kIdentityErrorMessage ) ) ) ; <nl> CancelWatch ( watcher_state_2 ) ; <nl> } <nl> <nl> TEST_F ( GrpcTlsCertificateDistributorTest , <nl> WatcherState * watcher_state_1 = MakeWatcher ( kCertName1 , kCertName2 ) ; <nl> / / Should trigger OnError call right away since kCertName1 has error . <nl> EXPECT_THAT ( watcher_state_1 - > GetErrorQueue ( ) , <nl> - testing : : ElementsAre ( ErrorInfo ( kRootErrorMessage , " " ) ) ) ; <nl> + : : testing : : ElementsAre ( ErrorInfo ( kRootErrorMessage , " " ) ) ) ; <nl> / / Calling SetErrorForCert on kCertName2 should trigger OnError with both <nl> / / errors , because kCertName1 also has error . <nl> distributor_ . SetErrorForCert ( <nl> kCertName2 , absl : : nullopt , <nl> GRPC_ERROR_CREATE_FROM_STATIC_STRING ( kIdentityErrorMessage ) ) ; <nl> EXPECT_THAT ( watcher_state_1 - > GetErrorQueue ( ) , <nl> - testing : : ElementsAre ( <nl> + : : testing : : ElementsAre ( <nl> ErrorInfo ( kRootErrorMessage , kIdentityErrorMessage ) ) ) ; <nl> CancelWatch ( watcher_state_1 ) ; <nl> } <nl> TEST_F ( GrpcTlsCertificateDistributorTest , <nl> WatcherState * watcher_state_1 = MakeWatcher ( kCertName2 , kCertName1 ) ; <nl> / / Should trigger OnError call right away since kCertName2 has error . <nl> EXPECT_THAT ( watcher_state_1 - > GetErrorQueue ( ) , <nl> - testing : : ElementsAre ( ErrorInfo ( " " , kIdentityErrorMessage ) ) ) ; <nl> + : : testing : : ElementsAre ( ErrorInfo ( " " , kIdentityErrorMessage ) ) ) ; <nl> / / Calling SetErrorForCert on kCertName2 should trigger OnError with both <nl> / / errors , because kCertName1 also has error . <nl> distributor_ . SetErrorForCert ( <nl> kCertName2 , GRPC_ERROR_CREATE_FROM_STATIC_STRING ( kRootErrorMessage ) , <nl> absl : : nullopt ) ; <nl> EXPECT_THAT ( watcher_state_1 - > GetErrorQueue ( ) , <nl> - testing : : ElementsAre ( <nl> + : : testing : : ElementsAre ( <nl> ErrorInfo ( kRootErrorMessage , kIdentityErrorMessage ) ) ) ; <nl> CancelWatch ( watcher_state_1 ) ; <nl> } <nl> TEST_F ( GrpcTlsCertificateDistributorTest , <nl> / / Register watcher 1 for kCertName1 as root and kCertName2 as identity . <nl> WatcherState * watcher_state_1 = MakeWatcher ( kCertName1 , kCertName2 ) ; <nl> / / Should not trigger OnError . <nl> - EXPECT_THAT ( watcher_state_1 - > GetErrorQueue ( ) , testing : : ElementsAre ( ) ) ; <nl> + EXPECT_THAT ( watcher_state_1 - > GetErrorQueue ( ) , : : testing : : ElementsAre ( ) ) ; <nl> / / Calling SetErrorForCert on kCertName2 should trigger OnError . <nl> distributor_ . SetErrorForCert ( <nl> kCertName2 , absl : : nullopt , <nl> GRPC_ERROR_CREATE_FROM_STATIC_STRING ( kIdentityErrorMessage ) ) ; <nl> EXPECT_THAT ( watcher_state_1 - > GetErrorQueue ( ) , <nl> - testing : : ElementsAre ( ErrorInfo ( " " , kIdentityErrorMessage ) ) ) ; <nl> + : : testing : : ElementsAre ( ErrorInfo ( " " , kIdentityErrorMessage ) ) ) ; <nl> CancelWatch ( watcher_state_1 ) ; <nl> / / Register watcher 2 for kCertName2 as identity and a non - existing name <nl> / / kRootCert1Name as root . <nl> WatcherState * watcher_state_2 = MakeWatcher ( kRootCert1Name , kCertName2 ) ; <nl> / / Should not trigger OnError . <nl> - EXPECT_THAT ( watcher_state_2 - > GetErrorQueue ( ) , testing : : ElementsAre ( ) ) ; <nl> + EXPECT_THAT ( watcher_state_2 - > GetErrorQueue ( ) , : : testing : : ElementsAre ( ) ) ; <nl> / / Calling SetErrorForCert on kCertName2 should trigger OnError . <nl> distributor_ . SetErrorForCert ( <nl> kCertName2 , absl : : nullopt , <nl> GRPC_ERROR_CREATE_FROM_STATIC_STRING ( kIdentityErrorMessage ) ) ; <nl> EXPECT_THAT ( watcher_state_2 - > error_queue , <nl> - testing : : ElementsAre ( ErrorInfo ( " " , kIdentityErrorMessage ) ) ) ; <nl> + : : testing : : ElementsAre ( ErrorInfo ( " " , kIdentityErrorMessage ) ) ) ; <nl> CancelWatch ( watcher_state_2 ) ; <nl> } <nl> <nl> TEST_F ( GrpcTlsCertificateDistributorTest , <nl> SetErrorForRootNameWithPreexistingErrorForIdentityName ) { <nl> WatcherState * watcher_state_1 = MakeWatcher ( kCertName2 , kCertName1 ) ; <nl> / / Should not trigger OnError . <nl> - EXPECT_THAT ( watcher_state_1 - > GetErrorQueue ( ) , testing : : ElementsAre ( ) ) ; <nl> + EXPECT_THAT ( watcher_state_1 - > GetErrorQueue ( ) , : : testing : : ElementsAre ( ) ) ; <nl> / / Calling SetErrorForCert on kCertName2 should trigger OnError . <nl> distributor_ . SetErrorForCert ( <nl> kCertName2 , GRPC_ERROR_CREATE_FROM_STATIC_STRING ( kRootErrorMessage ) , <nl> absl : : nullopt ) ; <nl> EXPECT_THAT ( watcher_state_1 - > GetErrorQueue ( ) , <nl> - testing : : ElementsAre ( ErrorInfo ( kRootErrorMessage , " " ) ) ) ; <nl> + : : testing : : ElementsAre ( ErrorInfo ( kRootErrorMessage , " " ) ) ) ; <nl> CancelWatch ( watcher_state_1 ) ; <nl> / / Register watcher 2 for kCertName2 as root and a non - existing name <nl> / / kIdentityCert1Name as identity . <nl> WatcherState * watcher_state_2 = MakeWatcher ( kCertName2 , kIdentityCert1Name ) ; <nl> / / Should not trigger OnError . <nl> - EXPECT_THAT ( watcher_state_2 - > GetErrorQueue ( ) , testing : : ElementsAre ( ) ) ; <nl> + EXPECT_THAT ( watcher_state_2 - > GetErrorQueue ( ) , : : testing : : ElementsAre ( ) ) ; <nl> / / Calling SetErrorForCert on kCertName2 should trigger OnError . <nl> distributor_ . SetErrorForCert ( <nl> kCertName2 , GRPC_ERROR_CREATE_FROM_STATIC_STRING ( kRootErrorMessage ) , <nl> absl : : nullopt ) ; <nl> EXPECT_THAT ( watcher_state_2 - > GetErrorQueue ( ) , <nl> - testing : : ElementsAre ( ErrorInfo ( kRootErrorMessage , " " ) ) ) ; <nl> + : : testing : : ElementsAre ( ErrorInfo ( kRootErrorMessage , " " ) ) ) ; <nl> CancelWatch ( watcher_state_2 ) ; <nl> } <nl> <nl> TEST_F ( GrpcTlsCertificateDistributorTest , <nl> kCertName1 , GRPC_ERROR_CREATE_FROM_STATIC_STRING ( kRootErrorMessage ) , <nl> GRPC_ERROR_CREATE_FROM_STATIC_STRING ( kIdentityErrorMessage ) ) ; <nl> EXPECT_THAT ( watcher_state_1 - > GetErrorQueue ( ) , <nl> - testing : : ElementsAre ( <nl> + : : testing : : ElementsAre ( <nl> ErrorInfo ( kRootErrorMessage , kIdentityErrorMessage ) ) ) ; <nl> / / When watcher 1 is removed , the cert info entry should be removed . <nl> CancelWatch ( watcher_state_1 ) ; <nl> / / Register watcher 2 on the same cert name . <nl> WatcherState * watcher_state_2 = MakeWatcher ( kCertName1 , kCertName1 ) ; <nl> / / Should not trigger OnError call on watcher 2 right away . <nl> - EXPECT_THAT ( watcher_state_2 - > GetErrorQueue ( ) , testing : : ElementsAre ( ) ) ; <nl> + EXPECT_THAT ( watcher_state_2 - > GetErrorQueue ( ) , : : testing : : ElementsAre ( ) ) ; <nl> CancelWatch ( watcher_state_2 ) ; <nl> } <nl> <nl> TEST_F ( GrpcTlsCertificateDistributorTest , <nl> / / watcher 1 should receive both the old credentials and the error right away . <nl> EXPECT_THAT ( <nl> watcher_state_1 - > GetCredentialQueue ( ) , <nl> - testing : : ElementsAre ( CredentialInfo ( <nl> + : : testing : : ElementsAre ( CredentialInfo ( <nl> kRootCert1Contents , <nl> MakeCertKeyPairs ( kIdentityCert1PrivateKey , kIdentityCert1Contents ) ) ) ) ; <nl> EXPECT_THAT ( watcher_state_1 - > GetErrorQueue ( ) , <nl> - testing : : ElementsAre ( <nl> + : : testing : : ElementsAre ( <nl> ErrorInfo ( kRootErrorMessage , kIdentityErrorMessage ) ) ) ; <nl> CancelWatch ( watcher_state_1 ) ; <nl> } <nl> TEST_F ( GrpcTlsCertificateDistributorTest , <nl> / / the previous error is wiped out by a successful update . <nl> EXPECT_THAT ( <nl> watcher_state_1 - > GetCredentialQueue ( ) , <nl> - testing : : ElementsAre ( CredentialInfo ( <nl> + : : testing : : ElementsAre ( CredentialInfo ( <nl> kRootCert1Contents , <nl> MakeCertKeyPairs ( kIdentityCert1PrivateKey , kIdentityCert1Contents ) ) ) ) ; <nl> - EXPECT_THAT ( watcher_state_1 - > GetErrorQueue ( ) , testing : : ElementsAre ( ) ) ; <nl> + EXPECT_THAT ( watcher_state_1 - > GetErrorQueue ( ) , : : testing : : ElementsAre ( ) ) ; <nl> CancelWatch ( watcher_state_1 ) ; <nl> } <nl> <nl> TEST_F ( GrpcTlsCertificateDistributorTest , WatchCertInfoThenInvokeSetError ) { <nl> MakeWatcher ( absl : : nullopt , kIdentityCert1Name ) ; <nl> distributor_ . SetError ( GRPC_ERROR_CREATE_FROM_STATIC_STRING ( kErrorMessage ) ) ; <nl> EXPECT_THAT ( watcher_state_1 - > GetErrorQueue ( ) , <nl> - testing : : ElementsAre ( ErrorInfo ( kErrorMessage , kErrorMessage ) ) ) ; <nl> + : : testing : : ElementsAre ( ErrorInfo ( kErrorMessage , kErrorMessage ) ) ) ; <nl> EXPECT_THAT ( watcher_state_2 - > GetErrorQueue ( ) , <nl> - testing : : ElementsAre ( ErrorInfo ( kErrorMessage , " " ) ) ) ; <nl> + : : testing : : ElementsAre ( ErrorInfo ( kErrorMessage , " " ) ) ) ; <nl> EXPECT_THAT ( watcher_state_3 - > GetErrorQueue ( ) , <nl> - testing : : ElementsAre ( ErrorInfo ( " " , kErrorMessage ) ) ) ; <nl> + : : testing : : ElementsAre ( ErrorInfo ( " " , kErrorMessage ) ) ) ; <nl> CancelWatch ( watcher_state_1 ) ; <nl> CancelWatch ( watcher_state_2 ) ; <nl> CancelWatch ( watcher_state_3 ) ; <nl> TEST_F ( GrpcTlsCertificateDistributorTest , WatchErroredCertInfoBySetError ) { <nl> / / Register watcher 3 watching kCertName1 as root and kCertName2 as identity <nl> / / should not get the error updates . <nl> WatcherState * watcher_state_3 = MakeWatcher ( kCertName1 , kCertName2 ) ; <nl> - EXPECT_THAT ( watcher_state_3 - > GetErrorQueue ( ) , testing : : ElementsAre ( ) ) ; <nl> + EXPECT_THAT ( watcher_state_3 - > GetErrorQueue ( ) , : : testing : : ElementsAre ( ) ) ; <nl> CancelWatch ( watcher_state_3 ) ; <nl> / / Register watcher 4 watching kCertName2 as root and kCertName1 as identity <nl> / / should not get the error updates . <nl> WatcherState * watcher_state_4 = MakeWatcher ( kCertName2 , kCertName1 ) ; <nl> - EXPECT_THAT ( watcher_state_4 - > GetErrorQueue ( ) , testing : : ElementsAre ( ) ) ; <nl> + EXPECT_THAT ( watcher_state_4 - > GetErrorQueue ( ) , : : testing : : ElementsAre ( ) ) ; <nl> CancelWatch ( watcher_state_4 ) ; <nl> } <nl> <nl> TEST_F ( GrpcTlsCertificateDistributorTest , SetErrorForCertInCallback ) { <nl> WatcherState * watcher_state_1 = MakeWatcher ( cert_name , cert_name ) ; <nl> / / Check the errors are delivered to watcher 1 . <nl> EXPECT_THAT ( watcher_state_1 - > GetErrorQueue ( ) , <nl> - testing : : ElementsAre ( <nl> + : : testing : : ElementsAre ( <nl> ErrorInfo ( kRootErrorMessage , kIdentityErrorMessage ) ) ) ; <nl> CancelWatch ( watcher_state_1 ) ; <nl> } ; <nl> TEST_F ( GrpcTlsCertificateDistributorTest , SetErrorForCertInCallback ) { <nl> <nl> } / / namespace testing <nl> <nl> + } / / namespace grpc_core <nl> + <nl> int main ( int argc , char * * argv ) { <nl> grpc : : testing : : TestEnvironment env ( argc , argv ) ; <nl> : : testing : : InitGoogleTest ( & argc , argv ) ; <nl> new file mode 100644 <nl> index 00000000000 . . b8bebf7ac20 <nl> mmm / dev / null <nl> ppp b / test / core / security / grpc_tls_certificate_provider_test . cc <nl> <nl> + / / <nl> + / / Copyright 2020 gRPC authors . <nl> + / / <nl> + / / Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + / / you may not use this file except in compliance with the License . <nl> + / / You may obtain a copy of the License at <nl> + / / <nl> + / / http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + / / <nl> + / / Unless required by applicable law or agreed to in writing , software <nl> + / / distributed under the License is distributed on an " AS IS " BASIS , <nl> + / / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + / / See the License for the specific language governing permissions and <nl> + / / limitations under the License . <nl> + / / <nl> + <nl> + # include " src / core / lib / security / credentials / tls / grpc_tls_certificate_provider . h " <nl> + <nl> + # include < gmock / gmock . h > <nl> + <nl> + # include < grpc / support / alloc . h > <nl> + # include < grpc / support / log . h > <nl> + # include < grpc / support / string_util . h > <nl> + # include < gtest / gtest . h > <nl> + <nl> + # include < deque > <nl> + # include < list > <nl> + <nl> + # include " src / core / lib / gpr / tmpfile . h " <nl> + # include " src / core / lib / iomgr / load_file . h " <nl> + # include " src / core / lib / slice / slice_internal . h " <nl> + # include " test / core / security / tls_utils . h " <nl> + # include " test / core / util / test_config . h " <nl> + <nl> + # define CA_CERT_PATH " src / core / tsi / test_creds / ca . pem " <nl> + # define SERVER_CERT_PATH " src / core / tsi / test_creds / server1 . pem " <nl> + # define SERVER_KEY_PATH " src / core / tsi / test_creds / server1 . key " <nl> + # define CA_CERT_PATH_2 " src / core / tsi / test_creds / multi - domain . pem " <nl> + # define SERVER_CERT_PATH_2 " src / core / tsi / test_creds / server0 . pem " <nl> + # define SERVER_KEY_PATH_2 " src / core / tsi / test_creds / server0 . key " <nl> + # define INVALID_PATH " invalid / path " <nl> + <nl> + namespace grpc_core { <nl> + <nl> + namespace testing { <nl> + <nl> + constexpr const char * kCertName = " cert_name " ; <nl> + constexpr const char * kRootError = " Unable to get latest root certificates . " ; <nl> + constexpr const char * kIdentityError = <nl> + " Unable to get latest identity certificates . " ; <nl> + <nl> + class GrpcTlsCertificateProviderTest : public : : testing : : Test { <nl> + protected : <nl> + / / Forward declaration . <nl> + class TlsCertificatesTestWatcher ; <nl> + <nl> + / / CredentialInfo contains the parameters when calling OnCertificatesChanged <nl> + / / of a watcher . When OnCertificatesChanged is invoked , we will push a <nl> + / / CredentialInfo to the cert_update_queue of state_ , and check in each test <nl> + / / if the status updates are correct . <nl> + struct CredentialInfo { <nl> + std : : string root_certs ; <nl> + PemKeyCertPairList key_cert_pairs ; <nl> + CredentialInfo ( std : : string root , PemKeyCertPairList key_cert ) <nl> + : root_certs ( std : : move ( root ) ) , key_cert_pairs ( std : : move ( key_cert ) ) { } <nl> + bool operator = = ( const CredentialInfo & other ) const { <nl> + return root_certs = = other . root_certs & & <nl> + key_cert_pairs = = other . key_cert_pairs ; <nl> + } <nl> + } ; <nl> + <nl> + / / ErrorInfo contains the parameters when calling OnError of a watcher . When <nl> + / / OnError is invoked , we will push a ErrorInfo to the error_queue of state_ , <nl> + / / and check in each test if the status updates are correct . <nl> + struct ErrorInfo { <nl> + std : : string root_cert_str ; <nl> + std : : string identity_cert_str ; <nl> + ErrorInfo ( std : : string root , std : : string identity ) <nl> + : root_cert_str ( std : : move ( root ) ) , <nl> + identity_cert_str ( std : : move ( identity ) ) { } <nl> + bool operator = = ( const ErrorInfo & other ) const { <nl> + return root_cert_str = = other . root_cert_str & & <nl> + identity_cert_str = = other . identity_cert_str ; <nl> + } <nl> + } ; <nl> + <nl> + struct WatcherState { <nl> + TlsCertificatesTestWatcher * watcher = nullptr ; <nl> + std : : deque < CredentialInfo > cert_update_queue ; <nl> + std : : deque < ErrorInfo > error_queue ; <nl> + Mutex mu ; <nl> + <nl> + std : : deque < CredentialInfo > GetCredentialQueue ( ) { <nl> + / / We move the data member value so the data member will be re - initiated <nl> + / / with size 0 , and ready for the next check . <nl> + MutexLock lock ( & mu ) ; <nl> + return std : : move ( cert_update_queue ) ; <nl> + } <nl> + std : : deque < ErrorInfo > GetErrorQueue ( ) { <nl> + / / We move the data member value so the data member will be re - initiated <nl> + / / with size 0 , and ready for the next check . <nl> + MutexLock lock ( & mu ) ; <nl> + return std : : move ( error_queue ) ; <nl> + } <nl> + } ; <nl> + <nl> + class TlsCertificatesTestWatcher : public grpc_tls_certificate_distributor : : <nl> + TlsCertificatesWatcherInterface { <nl> + public : <nl> + / / ctor sets state - > watcher to this . <nl> + explicit TlsCertificatesTestWatcher ( WatcherState * state ) : state_ ( state ) { <nl> + state_ - > watcher = this ; <nl> + } <nl> + <nl> + / / dtor sets state - > watcher to nullptr . <nl> + ~ TlsCertificatesTestWatcher ( ) override { state_ - > watcher = nullptr ; } <nl> + <nl> + void OnCertificatesChanged ( <nl> + absl : : optional < absl : : string_view > root_certs , <nl> + absl : : optional < PemKeyCertPairList > key_cert_pairs ) override { <nl> + MutexLock lock ( & state_ - > mu ) ; <nl> + std : : string updated_root ; <nl> + if ( root_certs . has_value ( ) ) { <nl> + updated_root = std : : string ( * root_certs ) ; <nl> + } <nl> + PemKeyCertPairList updated_identity ; <nl> + if ( key_cert_pairs . has_value ( ) ) { <nl> + updated_identity = std : : move ( * key_cert_pairs ) ; <nl> + } <nl> + state_ - > cert_update_queue . emplace_back ( std : : move ( updated_root ) , <nl> + std : : move ( updated_identity ) ) ; <nl> + } <nl> + <nl> + void OnError ( grpc_error * root_cert_error , <nl> + grpc_error * identity_cert_error ) override { <nl> + MutexLock lock ( & state_ - > mu ) ; <nl> + GPR_ASSERT ( root_cert_error ! = GRPC_ERROR_NONE | | <nl> + identity_cert_error ! = GRPC_ERROR_NONE ) ; <nl> + std : : string root_error_str ; <nl> + std : : string identity_error_str ; <nl> + if ( root_cert_error ! = GRPC_ERROR_NONE ) { <nl> + grpc_slice root_error_slice ; <nl> + GPR_ASSERT ( grpc_error_get_str ( <nl> + root_cert_error , GRPC_ERROR_STR_DESCRIPTION , & root_error_slice ) ) ; <nl> + root_error_str = std : : string ( StringViewFromSlice ( root_error_slice ) ) ; <nl> + } <nl> + if ( identity_cert_error ! = GRPC_ERROR_NONE ) { <nl> + grpc_slice identity_error_slice ; <nl> + GPR_ASSERT ( grpc_error_get_str ( identity_cert_error , <nl> + GRPC_ERROR_STR_DESCRIPTION , <nl> + & identity_error_slice ) ) ; <nl> + identity_error_str = <nl> + std : : string ( StringViewFromSlice ( identity_error_slice ) ) ; <nl> + } <nl> + state_ - > error_queue . emplace_back ( std : : move ( root_error_str ) , <nl> + std : : move ( identity_error_str ) ) ; <nl> + GRPC_ERROR_UNREF ( root_cert_error ) ; <nl> + GRPC_ERROR_UNREF ( identity_cert_error ) ; <nl> + } <nl> + <nl> + private : <nl> + WatcherState * state_ ; <nl> + } ; <nl> + <nl> + void SetUp ( ) override { <nl> + root_cert_ = GetFileContents ( CA_CERT_PATH ) ; <nl> + cert_chain_ = GetFileContents ( SERVER_CERT_PATH ) ; <nl> + private_key_ = GetFileContents ( SERVER_KEY_PATH ) ; <nl> + root_cert_2_ = GetFileContents ( CA_CERT_PATH_2 ) ; <nl> + cert_chain_2_ = GetFileContents ( SERVER_CERT_PATH_2 ) ; <nl> + private_key_2_ = GetFileContents ( SERVER_KEY_PATH_2 ) ; <nl> + } <nl> + <nl> + WatcherState * MakeWatcher ( <nl> + RefCountedPtr < grpc_tls_certificate_distributor > distributor , <nl> + absl : : optional < std : : string > root_cert_name , <nl> + absl : : optional < std : : string > identity_cert_name ) { <nl> + MutexLock lock ( & mu_ ) ; <nl> + distributor_ = distributor ; <nl> + watchers_ . emplace_back ( ) ; <nl> + / / TlsCertificatesTestWatcher ctor takes a pointer to the WatcherState . <nl> + / / It sets WatcherState : : watcher to point to itself . <nl> + / / The TlsCertificatesTestWatcher dtor will set WatcherState : : watcher back <nl> + / / to nullptr to indicate that it ' s been destroyed . <nl> + auto watcher = <nl> + absl : : make_unique < TlsCertificatesTestWatcher > ( & watchers_ . back ( ) ) ; <nl> + distributor_ - > WatchTlsCertificates ( std : : move ( watcher ) , <nl> + std : : move ( root_cert_name ) , <nl> + std : : move ( identity_cert_name ) ) ; <nl> + return & watchers_ . back ( ) ; <nl> + } <nl> + <nl> + void CancelWatch ( WatcherState * state ) { <nl> + MutexLock lock ( & mu_ ) ; <nl> + distributor_ - > CancelTlsCertificatesWatch ( state - > watcher ) ; <nl> + EXPECT_EQ ( state - > watcher , nullptr ) ; <nl> + } <nl> + <nl> + std : : string root_cert_ ; <nl> + std : : string private_key_ ; <nl> + std : : string cert_chain_ ; <nl> + std : : string root_cert_2_ ; <nl> + std : : string private_key_2_ ; <nl> + std : : string cert_chain_2_ ; <nl> + RefCountedPtr < grpc_tls_certificate_distributor > distributor_ ; <nl> + / / Use a std : : list < > here to avoid the address invalidation caused by internal <nl> + / / reallocation of std : : vector < > . <nl> + std : : list < WatcherState > watchers_ ; <nl> + / / This is to make watchers_ thread - safe . <nl> + Mutex mu_ ; <nl> + } ; <nl> + <nl> + TEST_F ( GrpcTlsCertificateProviderTest , StaticDataCertificateProviderCreation ) { <nl> + StaticDataCertificateProvider provider ( <nl> + root_cert_ , MakeCertKeyPairs ( private_key_ . c_str ( ) , cert_chain_ . c_str ( ) ) ) ; <nl> + / / Watcher watching both root and identity certs . <nl> + WatcherState * watcher_state_1 = <nl> + MakeWatcher ( provider . distributor ( ) , kCertName , kCertName ) ; <nl> + EXPECT_THAT ( watcher_state_1 - > GetCredentialQueue ( ) , <nl> + : : testing : : ElementsAre ( CredentialInfo ( <nl> + root_cert_ , MakeCertKeyPairs ( private_key_ . c_str ( ) , <nl> + cert_chain_ . c_str ( ) ) ) ) ) ; <nl> + CancelWatch ( watcher_state_1 ) ; <nl> + / / Watcher watching only root certs . <nl> + WatcherState * watcher_state_2 = <nl> + MakeWatcher ( provider . distributor ( ) , kCertName , absl : : nullopt ) ; <nl> + EXPECT_THAT ( watcher_state_2 - > GetCredentialQueue ( ) , <nl> + : : testing : : ElementsAre ( CredentialInfo ( root_cert_ , { } ) ) ) ; <nl> + CancelWatch ( watcher_state_2 ) ; <nl> + / / Watcher watching only identity certs . <nl> + WatcherState * watcher_state_3 = <nl> + MakeWatcher ( provider . distributor ( ) , absl : : nullopt , kCertName ) ; <nl> + EXPECT_THAT ( <nl> + watcher_state_3 - > GetCredentialQueue ( ) , <nl> + : : testing : : ElementsAre ( CredentialInfo ( <nl> + " " , MakeCertKeyPairs ( private_key_ . c_str ( ) , cert_chain_ . c_str ( ) ) ) ) ) ; <nl> + CancelWatch ( watcher_state_3 ) ; <nl> + } <nl> + <nl> + TEST_F ( GrpcTlsCertificateProviderTest , <nl> + FileWatcherCertificateProviderWithGoodPaths ) { <nl> + FileWatcherCertificateProvider provider ( SERVER_KEY_PATH , SERVER_CERT_PATH , <nl> + CA_CERT_PATH , 1 ) ; <nl> + / / Watcher watching both root and identity certs . <nl> + WatcherState * watcher_state_1 = <nl> + MakeWatcher ( provider . distributor ( ) , kCertName , kCertName ) ; <nl> + EXPECT_THAT ( watcher_state_1 - > GetCredentialQueue ( ) , <nl> + : : testing : : ElementsAre ( CredentialInfo ( <nl> + root_cert_ , MakeCertKeyPairs ( private_key_ . c_str ( ) , <nl> + cert_chain_ . c_str ( ) ) ) ) ) ; <nl> + CancelWatch ( watcher_state_1 ) ; <nl> + / / Watcher watching only root certs . <nl> + WatcherState * watcher_state_2 = <nl> + MakeWatcher ( provider . distributor ( ) , kCertName , absl : : nullopt ) ; <nl> + EXPECT_THAT ( watcher_state_2 - > GetCredentialQueue ( ) , <nl> + : : testing : : ElementsAre ( CredentialInfo ( root_cert_ , { } ) ) ) ; <nl> + CancelWatch ( watcher_state_2 ) ; <nl> + / / Watcher watching only identity certs . <nl> + WatcherState * watcher_state_3 = <nl> + MakeWatcher ( provider . distributor ( ) , absl : : nullopt , kCertName ) ; <nl> + EXPECT_THAT ( <nl> + watcher_state_3 - > GetCredentialQueue ( ) , <nl> + : : testing : : ElementsAre ( CredentialInfo ( <nl> + " " , MakeCertKeyPairs ( private_key_ . c_str ( ) , cert_chain_ . c_str ( ) ) ) ) ) ; <nl> + CancelWatch ( watcher_state_3 ) ; <nl> + } <nl> + <nl> + TEST_F ( GrpcTlsCertificateProviderTest , <nl> + FileWatcherCertificateProviderWithBadPaths ) { <nl> + FileWatcherCertificateProvider provider ( INVALID_PATH , INVALID_PATH , <nl> + INVALID_PATH , 1 ) ; <nl> + / / Watcher watching both root and identity certs . <nl> + WatcherState * watcher_state_1 = <nl> + MakeWatcher ( provider . distributor ( ) , kCertName , kCertName ) ; <nl> + EXPECT_THAT ( watcher_state_1 - > GetErrorQueue ( ) , <nl> + : : testing : : ElementsAre ( ErrorInfo ( kRootError , kIdentityError ) ) ) ; <nl> + EXPECT_THAT ( watcher_state_1 - > GetCredentialQueue ( ) , : : testing : : ElementsAre ( ) ) ; <nl> + CancelWatch ( watcher_state_1 ) ; <nl> + / / Watcher watching only root certs . <nl> + WatcherState * watcher_state_2 = <nl> + MakeWatcher ( provider . distributor ( ) , kCertName , absl : : nullopt ) ; <nl> + EXPECT_THAT ( watcher_state_2 - > GetErrorQueue ( ) , <nl> + : : testing : : ElementsAre ( ErrorInfo ( kRootError , " " ) ) ) ; <nl> + EXPECT_THAT ( watcher_state_2 - > GetCredentialQueue ( ) , : : testing : : ElementsAre ( ) ) ; <nl> + CancelWatch ( watcher_state_2 ) ; <nl> + / / Watcher watching only identity certs . <nl> + WatcherState * watcher_state_3 = <nl> + MakeWatcher ( provider . distributor ( ) , absl : : nullopt , kCertName ) ; <nl> + EXPECT_THAT ( watcher_state_3 - > GetErrorQueue ( ) , <nl> + : : testing : : ElementsAre ( ErrorInfo ( " " , kIdentityError ) ) ) ; <nl> + EXPECT_THAT ( watcher_state_3 - > GetCredentialQueue ( ) , : : testing : : ElementsAre ( ) ) ; <nl> + CancelWatch ( watcher_state_3 ) ; <nl> + } <nl> + <nl> + / / The following tests write credential data to temporary files to test the <nl> + / / transition behavior of the provider . <nl> + TEST_F ( GrpcTlsCertificateProviderTest , <nl> + FileWatcherCertificateProviderOnBothCertsRefreshed ) { <nl> + / / Create temporary files and copy cert data into them . <nl> + TmpFile tmp_root_cert ( root_cert_ ) ; <nl> + TmpFile tmp_identity_key ( private_key_ ) ; <nl> + TmpFile tmp_identity_cert ( cert_chain_ ) ; <nl> + / / Create FileWatcherCertificateProvider . <nl> + FileWatcherCertificateProvider provider ( tmp_identity_key . name ( ) , <nl> + tmp_identity_cert . name ( ) , <nl> + tmp_root_cert . name ( ) , 1 ) ; <nl> + WatcherState * watcher_state_1 = <nl> + MakeWatcher ( provider . distributor ( ) , kCertName , kCertName ) ; <nl> + / / Expect to see the credential data . <nl> + EXPECT_THAT ( watcher_state_1 - > GetCredentialQueue ( ) , <nl> + : : testing : : ElementsAre ( CredentialInfo ( <nl> + root_cert_ , MakeCertKeyPairs ( private_key_ . c_str ( ) , <nl> + cert_chain_ . c_str ( ) ) ) ) ) ; <nl> + / / Copy new data to files . <nl> + / / TODO ( ZhenLian ) : right now it is not completely atomic . Use the real atomic <nl> + / / update when the directory renaming is added in gpr . <nl> + tmp_root_cert . RewriteFile ( root_cert_2_ ) ; <nl> + tmp_identity_key . RewriteFile ( private_key_2_ ) ; <nl> + tmp_identity_cert . RewriteFile ( cert_chain_2_ ) ; <nl> + / / Wait 2 seconds for the provider ' s refresh thread to read the updated files . <nl> + gpr_sleep_until ( gpr_time_add ( gpr_now ( GPR_CLOCK_MONOTONIC ) , <nl> + gpr_time_from_seconds ( 2 , GPR_TIMESPAN ) ) ) ; <nl> + / / Expect to see the new credential data . <nl> + EXPECT_THAT ( watcher_state_1 - > GetCredentialQueue ( ) , <nl> + : : testing : : ElementsAre ( CredentialInfo ( <nl> + root_cert_2_ , MakeCertKeyPairs ( private_key_2_ . c_str ( ) , <nl> + cert_chain_2_ . c_str ( ) ) ) ) ) ; <nl> + / / Clean up . <nl> + CancelWatch ( watcher_state_1 ) ; <nl> + } <nl> + <nl> + TEST_F ( GrpcTlsCertificateProviderTest , <nl> + FileWatcherCertificateProviderOnRootCertsRefreshed ) { <nl> + / / Create temporary files and copy cert data into them . <nl> + TmpFile tmp_root_cert ( root_cert_ ) ; <nl> + TmpFile tmp_identity_key ( private_key_ ) ; <nl> + TmpFile tmp_identity_cert ( cert_chain_ ) ; <nl> + / / Create FileWatcherCertificateProvider . <nl> + FileWatcherCertificateProvider provider ( tmp_identity_key . name ( ) , <nl> + tmp_identity_cert . name ( ) , <nl> + tmp_root_cert . name ( ) , 1 ) ; <nl> + WatcherState * watcher_state_1 = <nl> + MakeWatcher ( provider . distributor ( ) , kCertName , kCertName ) ; <nl> + / / Expect to see the credential data . <nl> + EXPECT_THAT ( watcher_state_1 - > GetCredentialQueue ( ) , <nl> + : : testing : : ElementsAre ( CredentialInfo ( <nl> + root_cert_ , MakeCertKeyPairs ( private_key_ . c_str ( ) , <nl> + cert_chain_ . c_str ( ) ) ) ) ) ; <nl> + / / Copy new data to files . <nl> + / / TODO ( ZhenLian ) : right now it is not completely atomic . Use the real atomic <nl> + / / update when the directory renaming is added in gpr . <nl> + tmp_root_cert . RewriteFile ( root_cert_2_ ) ; <nl> + / / Wait 2 seconds for the provider ' s refresh thread to read the updated files . <nl> + gpr_sleep_until ( gpr_time_add ( gpr_now ( GPR_CLOCK_MONOTONIC ) , <nl> + gpr_time_from_seconds ( 2 , GPR_TIMESPAN ) ) ) ; <nl> + / / Expect to see the new credential data . <nl> + EXPECT_THAT ( watcher_state_1 - > GetCredentialQueue ( ) , <nl> + : : testing : : ElementsAre ( CredentialInfo ( <nl> + root_cert_2_ , MakeCertKeyPairs ( private_key_ . c_str ( ) , <nl> + cert_chain_ . c_str ( ) ) ) ) ) ; <nl> + / / Clean up . <nl> + CancelWatch ( watcher_state_1 ) ; <nl> + } <nl> + <nl> + TEST_F ( GrpcTlsCertificateProviderTest , <nl> + FileWatcherCertificateProviderOnIdentityCertsRefreshed ) { <nl> + / / Create temporary files and copy cert data into them . <nl> + TmpFile tmp_root_cert ( root_cert_ ) ; <nl> + TmpFile tmp_identity_key ( private_key_ ) ; <nl> + TmpFile tmp_identity_cert ( cert_chain_ ) ; <nl> + / / Create FileWatcherCertificateProvider . <nl> + FileWatcherCertificateProvider provider ( tmp_identity_key . name ( ) , <nl> + tmp_identity_cert . name ( ) , <nl> + tmp_root_cert . name ( ) , 1 ) ; <nl> + WatcherState * watcher_state_1 = <nl> + MakeWatcher ( provider . distributor ( ) , kCertName , kCertName ) ; <nl> + / / Expect to see the credential data . <nl> + EXPECT_THAT ( watcher_state_1 - > GetCredentialQueue ( ) , <nl> + : : testing : : ElementsAre ( CredentialInfo ( <nl> + root_cert_ , MakeCertKeyPairs ( private_key_ . c_str ( ) , <nl> + cert_chain_ . c_str ( ) ) ) ) ) ; <nl> + / / Copy new data to files . <nl> + / / TODO ( ZhenLian ) : right now it is not completely atomic . Use the real atomic <nl> + / / update when the directory renaming is added in gpr . <nl> + tmp_identity_key . RewriteFile ( private_key_2_ ) ; <nl> + tmp_identity_cert . RewriteFile ( cert_chain_2_ ) ; <nl> + / / Wait 2 seconds for the provider ' s refresh thread to read the updated files . <nl> + gpr_sleep_until ( gpr_time_add ( gpr_now ( GPR_CLOCK_MONOTONIC ) , <nl> + gpr_time_from_seconds ( 2 , GPR_TIMESPAN ) ) ) ; <nl> + / / Expect to see the new credential data . <nl> + EXPECT_THAT ( watcher_state_1 - > GetCredentialQueue ( ) , <nl> + : : testing : : ElementsAre ( CredentialInfo ( <nl> + root_cert_ , MakeCertKeyPairs ( private_key_2_ . c_str ( ) , <nl> + cert_chain_2_ . c_str ( ) ) ) ) ) ; <nl> + / / Clean up . <nl> + CancelWatch ( watcher_state_1 ) ; <nl> + } <nl> + <nl> + TEST_F ( GrpcTlsCertificateProviderTest , <nl> + FileWatcherCertificateProviderWithGoodAtFirstThenDeletedBothCerts ) { <nl> + / / Create temporary files and copy cert data into it . <nl> + auto tmp_root_cert = absl : : make_unique < TmpFile > ( root_cert_ ) ; <nl> + auto tmp_identity_key = absl : : make_unique < TmpFile > ( private_key_ ) ; <nl> + auto tmp_identity_cert = absl : : make_unique < TmpFile > ( cert_chain_ ) ; <nl> + / / Create FileWatcherCertificateProvider . <nl> + FileWatcherCertificateProvider provider ( tmp_identity_key - > name ( ) , <nl> + tmp_identity_cert - > name ( ) , <nl> + tmp_root_cert - > name ( ) , 1 ) ; <nl> + WatcherState * watcher_state_1 = <nl> + MakeWatcher ( provider . distributor ( ) , kCertName , kCertName ) ; <nl> + / / The initial data is all good , so we expect to have successful credential <nl> + / / updates . <nl> + EXPECT_THAT ( watcher_state_1 - > GetCredentialQueue ( ) , <nl> + : : testing : : ElementsAre ( CredentialInfo ( <nl> + root_cert_ , MakeCertKeyPairs ( private_key_ . c_str ( ) , <nl> + cert_chain_ . c_str ( ) ) ) ) ) ; <nl> + / / Delete TmpFile objects , which will remove the corresponding files . <nl> + tmp_root_cert . reset ( ) ; <nl> + tmp_identity_key . reset ( ) ; <nl> + tmp_identity_cert . reset ( ) ; <nl> + / / Wait 2 seconds for the provider ' s refresh thread to read the deleted files . <nl> + gpr_sleep_until ( gpr_time_add ( gpr_now ( GPR_CLOCK_MONOTONIC ) , <nl> + gpr_time_from_seconds ( 2 , GPR_TIMESPAN ) ) ) ; <nl> + / / Expect to see errors sent to watchers , and no credential updates . <nl> + / / We have no ideas on how many errors we will receive , so we only check once . <nl> + EXPECT_THAT ( watcher_state_1 - > GetErrorQueue ( ) , <nl> + : : testing : : Contains ( ErrorInfo ( kRootError , kIdentityError ) ) ) ; <nl> + EXPECT_THAT ( watcher_state_1 - > GetCredentialQueue ( ) , : : testing : : ElementsAre ( ) ) ; <nl> + / / Clean up . <nl> + CancelWatch ( watcher_state_1 ) ; <nl> + } <nl> + <nl> + TEST_F ( GrpcTlsCertificateProviderTest , <nl> + FileWatcherCertificateProviderWithGoodAtFirstThenDeletedRootCerts ) { <nl> + / / Create temporary files and copy cert data into it . <nl> + auto tmp_root_cert = absl : : make_unique < TmpFile > ( root_cert_ ) ; <nl> + TmpFile tmp_identity_key ( private_key_ ) ; <nl> + TmpFile tmp_identity_cert ( cert_chain_ ) ; <nl> + / / Create FileWatcherCertificateProvider . <nl> + FileWatcherCertificateProvider provider ( tmp_identity_key . name ( ) , <nl> + tmp_identity_cert . name ( ) , <nl> + tmp_root_cert - > name ( ) , 1 ) ; <nl> + WatcherState * watcher_state_1 = <nl> + MakeWatcher ( provider . distributor ( ) , kCertName , kCertName ) ; <nl> + / / The initial data is all good , so we expect to have successful credential <nl> + / / updates . <nl> + EXPECT_THAT ( watcher_state_1 - > GetCredentialQueue ( ) , <nl> + : : testing : : ElementsAre ( CredentialInfo ( <nl> + root_cert_ , MakeCertKeyPairs ( private_key_ . c_str ( ) , <nl> + cert_chain_ . c_str ( ) ) ) ) ) ; <nl> + / / Delete root TmpFile object , which will remove the corresponding file . <nl> + tmp_root_cert . reset ( ) ; <nl> + / / Wait 2 seconds for the provider ' s refresh thread to read the deleted files . <nl> + gpr_sleep_until ( gpr_time_add ( gpr_now ( GPR_CLOCK_MONOTONIC ) , <nl> + gpr_time_from_seconds ( 2 , GPR_TIMESPAN ) ) ) ; <nl> + / / Expect to see errors sent to watchers , and no credential updates . <nl> + / / We have no ideas on how many errors we will receive , so we only check once . <nl> + EXPECT_THAT ( watcher_state_1 - > GetErrorQueue ( ) , <nl> + : : testing : : Contains ( ErrorInfo ( kRootError , " " ) ) ) ; <nl> + EXPECT_THAT ( watcher_state_1 - > GetCredentialQueue ( ) , : : testing : : ElementsAre ( ) ) ; <nl> + / / Clean up . <nl> + CancelWatch ( watcher_state_1 ) ; <nl> + } <nl> + <nl> + TEST_F ( GrpcTlsCertificateProviderTest , <nl> + FileWatcherCertificateProviderWithGoodAtFirstThenDeletedIdentityCerts ) { <nl> + / / Create temporary files and copy cert data into it . <nl> + TmpFile tmp_root_cert ( root_cert_ ) ; <nl> + auto tmp_identity_key = absl : : make_unique < TmpFile > ( private_key_ ) ; <nl> + auto tmp_identity_cert = absl : : make_unique < TmpFile > ( cert_chain_ ) ; <nl> + / / Create FileWatcherCertificateProvider . <nl> + FileWatcherCertificateProvider provider ( tmp_identity_key - > name ( ) , <nl> + tmp_identity_cert - > name ( ) , <nl> + tmp_root_cert . name ( ) , 1 ) ; <nl> + WatcherState * watcher_state_1 = <nl> + MakeWatcher ( provider . distributor ( ) , kCertName , kCertName ) ; <nl> + / / The initial data is all good , so we expect to have successful credential <nl> + / / updates . <nl> + EXPECT_THAT ( watcher_state_1 - > GetCredentialQueue ( ) , <nl> + : : testing : : ElementsAre ( CredentialInfo ( <nl> + root_cert_ , MakeCertKeyPairs ( private_key_ . c_str ( ) , <nl> + cert_chain_ . c_str ( ) ) ) ) ) ; <nl> + / / Delete identity TmpFile objects , which will remove the corresponding files . <nl> + tmp_identity_key . reset ( ) ; <nl> + tmp_identity_cert . reset ( ) ; <nl> + / / Wait 2 seconds for the provider ' s refresh thread to read the deleted files . <nl> + gpr_sleep_until ( gpr_time_add ( gpr_now ( GPR_CLOCK_MONOTONIC ) , <nl> + gpr_time_from_seconds ( 2 , GPR_TIMESPAN ) ) ) ; <nl> + / / Expect to see errors sent to watchers , and no credential updates . <nl> + / / We have no ideas on how many errors we will receive , so we only check once . <nl> + EXPECT_THAT ( watcher_state_1 - > GetErrorQueue ( ) , <nl> + : : testing : : Contains ( ErrorInfo ( " " , kIdentityError ) ) ) ; <nl> + EXPECT_THAT ( watcher_state_1 - > GetCredentialQueue ( ) , : : testing : : ElementsAre ( ) ) ; <nl> + / / Clean up . <nl> + CancelWatch ( watcher_state_1 ) ; <nl> + } <nl> + <nl> + } / / namespace testing <nl> + <nl> + } / / namespace grpc_core <nl> + <nl> + int main ( int argc , char * * argv ) { <nl> + grpc : : testing : : TestEnvironment env ( argc , argv ) ; <nl> + : : testing : : InitGoogleTest ( & argc , argv ) ; <nl> + grpc_init ( ) ; <nl> + int ret = RUN_ALL_TESTS ( ) ; <nl> + grpc_shutdown ( ) ; <nl> + return ret ; <nl> + } <nl> mmm a / test / core / security / grpc_tls_credentials_options_test . cc <nl> ppp b / test / core / security / grpc_tls_credentials_options_test . cc <nl> <nl> # include < grpc / support / string_util . h > <nl> # include < gtest / gtest . h > <nl> <nl> + # include " src / core / lib / gpr / tmpfile . h " <nl> # include " src / core / lib / iomgr / load_file . h " <nl> + # include " src / core / lib / security / credentials / tls / tls_credentials . h " <nl> + # include " src / core / lib / security / security_connector / tls / tls_security_connector . h " <nl> + # include " test / core / security / tls_utils . h " <nl> # include " test / core / util / test_config . h " <nl> <nl> # define CA_CERT_PATH " src / core / tsi / test_creds / ca . pem " <nl> # define SERVER_CERT_PATH " src / core / tsi / test_creds / server1 . pem " <nl> # define SERVER_KEY_PATH " src / core / tsi / test_creds / server1 . key " <nl> + # define CA_CERT_PATH_2 " src / core / tsi / test_creds / multi - domain . pem " <nl> + # define SERVER_CERT_PATH_2 " src / core / tsi / test_creds / server0 . pem " <nl> + # define SERVER_KEY_PATH_2 " src / core / tsi / test_creds / server0 . key " <nl> + # define INVALID_PATH " invalid / path " <nl> + <nl> + namespace grpc_core { <nl> <nl> namespace testing { <nl> <nl> - TEST ( GrpcTlsCredentialsOptionsTest , ErrorDetails ) { <nl> + class GrpcTlsCredentialsOptionsTest : public : : testing : : Test { <nl> + protected : <nl> + void SetUp ( ) override { <nl> + root_cert_ = GetFileContents ( CA_CERT_PATH ) ; <nl> + cert_chain_ = GetFileContents ( SERVER_CERT_PATH ) ; <nl> + private_key_ = GetFileContents ( SERVER_KEY_PATH ) ; <nl> + root_cert_2_ = GetFileContents ( CA_CERT_PATH_2 ) ; <nl> + cert_chain_2_ = GetFileContents ( SERVER_CERT_PATH_2 ) ; <nl> + private_key_2_ = GetFileContents ( SERVER_KEY_PATH_2 ) ; <nl> + } <nl> + <nl> + std : : string root_cert_ ; <nl> + std : : string private_key_ ; <nl> + std : : string cert_chain_ ; <nl> + std : : string root_cert_2_ ; <nl> + std : : string private_key_2_ ; <nl> + std : : string cert_chain_2_ ; <nl> + } ; <nl> + <nl> + TEST_F ( GrpcTlsCredentialsOptionsTest , ErrorDetails ) { <nl> grpc_tls_error_details error_details ; <nl> EXPECT_STREQ ( error_details . error_details ( ) . c_str ( ) , " " ) ; <nl> error_details . set_error_details ( " test error details " ) ; <nl> EXPECT_STREQ ( error_details . error_details ( ) . c_str ( ) , " test error details " ) ; <nl> } <nl> <nl> + / / Tests for StaticDataCertificateProvider . <nl> + TEST_F ( GrpcTlsCredentialsOptionsTest , <nl> + ClientOptionsWithStaticDataProviderOnBothCerts ) { <nl> + auto options = MakeRefCounted < grpc_tls_credentials_options > ( ) ; <nl> + auto provider = MakeRefCounted < StaticDataCertificateProvider > ( <nl> + root_cert_ , MakeCertKeyPairs ( private_key_ . c_str ( ) , cert_chain_ . c_str ( ) ) ) ; <nl> + options - > set_certificate_provider ( std : : move ( provider ) ) ; <nl> + options - > set_watch_root_cert ( true ) ; <nl> + options - > set_watch_identity_pair ( true ) ; <nl> + options - > set_server_verification_option ( GRPC_TLS_SERVER_VERIFICATION ) ; <nl> + auto credentials = MakeRefCounted < TlsCredentials > ( options ) ; <nl> + ASSERT_NE ( credentials , nullptr ) ; <nl> + grpc_channel_args * new_args = nullptr ; <nl> + auto connector = credentials - > create_security_connector ( <nl> + nullptr , " random targets " , nullptr , & new_args ) ; <nl> + grpc_channel_args_destroy ( new_args ) ; <nl> + ASSERT_NE ( connector , nullptr ) ; <nl> + TlsChannelSecurityConnector * tls_connector = <nl> + static_cast < TlsChannelSecurityConnector * > ( connector . get ( ) ) ; <nl> + EXPECT_NE ( tls_connector - > ClientHandshakerFactoryForTesting ( ) , nullptr ) ; <nl> + EXPECT_TRUE ( tls_connector - > RootCertsForTesting ( ) . has_value ( ) ) ; <nl> + EXPECT_TRUE ( tls_connector - > KeyCertPairListForTesting ( ) . has_value ( ) ) ; <nl> + } <nl> + <nl> + TEST_F ( GrpcTlsCredentialsOptionsTest , <nl> + ClientOptionsWithStaticDataProviderOnRootCerts ) { <nl> + auto options = MakeRefCounted < grpc_tls_credentials_options > ( ) ; <nl> + auto provider = MakeRefCounted < StaticDataCertificateProvider > ( <nl> + root_cert_ , PemKeyCertPairList ( ) ) ; <nl> + options - > set_certificate_provider ( std : : move ( provider ) ) ; <nl> + options - > set_watch_root_cert ( true ) ; <nl> + options - > set_server_verification_option ( GRPC_TLS_SERVER_VERIFICATION ) ; <nl> + auto credentials = MakeRefCounted < TlsCredentials > ( options ) ; <nl> + ASSERT_NE ( credentials , nullptr ) ; <nl> + grpc_channel_args * new_args = nullptr ; <nl> + auto connector = credentials - > create_security_connector ( <nl> + nullptr , " random targets " , nullptr , & new_args ) ; <nl> + grpc_channel_args_destroy ( new_args ) ; <nl> + ASSERT_NE ( connector , nullptr ) ; <nl> + TlsChannelSecurityConnector * tls_connector = <nl> + static_cast < TlsChannelSecurityConnector * > ( connector . get ( ) ) ; <nl> + EXPECT_NE ( tls_connector - > ClientHandshakerFactoryForTesting ( ) , nullptr ) ; <nl> + EXPECT_TRUE ( tls_connector - > RootCertsForTesting ( ) . has_value ( ) ) ; <nl> + EXPECT_FALSE ( tls_connector - > KeyCertPairListForTesting ( ) . has_value ( ) ) ; <nl> + } <nl> + <nl> + TEST_F ( GrpcTlsCredentialsOptionsTest , <nl> + ClientOptionsWithStaticDataProviderOnNotProvidedCerts ) { <nl> + auto options = MakeRefCounted < grpc_tls_credentials_options > ( ) ; <nl> + auto provider = MakeRefCounted < StaticDataCertificateProvider > ( <nl> + " " , MakeCertKeyPairs ( private_key_ . c_str ( ) , cert_chain_ . c_str ( ) ) ) ; <nl> + options - > set_certificate_provider ( std : : move ( provider ) ) ; <nl> + options - > set_watch_root_cert ( true ) ; <nl> + options - > set_server_verification_option ( GRPC_TLS_SERVER_VERIFICATION ) ; <nl> + auto credentials = MakeRefCounted < TlsCredentials > ( options ) ; <nl> + ASSERT_NE ( credentials , nullptr ) ; <nl> + grpc_channel_args * new_args = nullptr ; <nl> + auto connector = credentials - > create_security_connector ( <nl> + nullptr , " random targets " , nullptr , & new_args ) ; <nl> + grpc_channel_args_destroy ( new_args ) ; <nl> + ASSERT_NE ( connector , nullptr ) ; <nl> + TlsChannelSecurityConnector * tls_connector = <nl> + static_cast < TlsChannelSecurityConnector * > ( connector . get ( ) ) ; <nl> + EXPECT_EQ ( tls_connector - > ClientHandshakerFactoryForTesting ( ) , nullptr ) ; <nl> + } <nl> + <nl> + TEST_F ( GrpcTlsCredentialsOptionsTest , <nl> + ServerOptionsWithStaticDataProviderOnBothCerts ) { <nl> + auto options = MakeRefCounted < grpc_tls_credentials_options > ( ) ; <nl> + auto provider = MakeRefCounted < StaticDataCertificateProvider > ( <nl> + root_cert_ , MakeCertKeyPairs ( private_key_ . c_str ( ) , cert_chain_ . c_str ( ) ) ) ; <nl> + options - > set_certificate_provider ( std : : move ( provider ) ) ; <nl> + options - > set_watch_root_cert ( true ) ; <nl> + options - > set_watch_identity_pair ( true ) ; <nl> + options - > set_cert_request_type ( <nl> + GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY ) ; <nl> + auto credentials = MakeRefCounted < TlsServerCredentials > ( options ) ; <nl> + ASSERT_NE ( credentials , nullptr ) ; <nl> + auto connector = credentials - > create_security_connector ( ) ; <nl> + ASSERT_NE ( connector , nullptr ) ; <nl> + TlsServerSecurityConnector * tls_connector = <nl> + static_cast < TlsServerSecurityConnector * > ( connector . get ( ) ) ; <nl> + EXPECT_NE ( tls_connector - > ServerHandshakerFactoryForTesting ( ) , nullptr ) ; <nl> + EXPECT_TRUE ( tls_connector - > RootCertsForTesting ( ) . has_value ( ) ) ; <nl> + EXPECT_TRUE ( tls_connector - > KeyCertPairListForTesting ( ) . has_value ( ) ) ; <nl> + } <nl> + <nl> + TEST_F ( GrpcTlsCredentialsOptionsTest , <nl> + ServerOptionsWithStaticDataProviderOnIdentityCerts ) { <nl> + auto options = MakeRefCounted < grpc_tls_credentials_options > ( ) ; <nl> + auto provider = MakeRefCounted < StaticDataCertificateProvider > ( <nl> + " " , MakeCertKeyPairs ( private_key_ . c_str ( ) , cert_chain_ . c_str ( ) ) ) ; <nl> + options - > set_certificate_provider ( std : : move ( provider ) ) ; <nl> + options - > set_watch_identity_pair ( true ) ; <nl> + options - > set_cert_request_type ( GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE ) ; <nl> + auto credentials = MakeRefCounted < TlsServerCredentials > ( options ) ; <nl> + ASSERT_NE ( credentials , nullptr ) ; <nl> + auto connector = credentials - > create_security_connector ( ) ; <nl> + ASSERT_NE ( connector , nullptr ) ; <nl> + TlsServerSecurityConnector * tls_connector = <nl> + static_cast < TlsServerSecurityConnector * > ( connector . get ( ) ) ; <nl> + EXPECT_NE ( tls_connector - > ServerHandshakerFactoryForTesting ( ) , nullptr ) ; <nl> + EXPECT_FALSE ( tls_connector - > RootCertsForTesting ( ) . has_value ( ) ) ; <nl> + EXPECT_TRUE ( tls_connector - > KeyCertPairListForTesting ( ) . has_value ( ) ) ; <nl> + } <nl> + <nl> + TEST_F ( GrpcTlsCredentialsOptionsTest , <nl> + ServerOptionsWithStaticDataProviderOnNotProvidedCerts ) { <nl> + auto options = MakeRefCounted < grpc_tls_credentials_options > ( ) ; <nl> + auto provider = MakeRefCounted < StaticDataCertificateProvider > ( <nl> + root_cert_ , PemKeyCertPairList ( ) ) ; <nl> + options - > set_certificate_provider ( std : : move ( provider ) ) ; <nl> + options - > set_watch_identity_pair ( true ) ; <nl> + options - > set_cert_request_type ( GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE ) ; <nl> + auto credentials = MakeRefCounted < TlsServerCredentials > ( options ) ; <nl> + ASSERT_NE ( credentials , nullptr ) ; <nl> + auto connector = credentials - > create_security_connector ( ) ; <nl> + ASSERT_NE ( connector , nullptr ) ; <nl> + TlsServerSecurityConnector * tls_connector = <nl> + static_cast < TlsServerSecurityConnector * > ( connector . get ( ) ) ; <nl> + EXPECT_EQ ( tls_connector - > ServerHandshakerFactoryForTesting ( ) , nullptr ) ; <nl> + } <nl> + <nl> + / / / / Tests for FileWatcherCertificateProvider . <nl> + TEST_F ( GrpcTlsCredentialsOptionsTest , <nl> + ClientOptionsWithCertWatcherProviderOnBothCerts ) { <nl> + auto options = MakeRefCounted < grpc_tls_credentials_options > ( ) ; <nl> + auto provider = MakeRefCounted < FileWatcherCertificateProvider > ( <nl> + SERVER_KEY_PATH , SERVER_CERT_PATH , CA_CERT_PATH , 1 ) ; <nl> + options - > set_certificate_provider ( std : : move ( provider ) ) ; <nl> + options - > set_watch_root_cert ( true ) ; <nl> + options - > set_watch_identity_pair ( true ) ; <nl> + options - > set_server_verification_option ( GRPC_TLS_SERVER_VERIFICATION ) ; <nl> + auto credentials = MakeRefCounted < TlsCredentials > ( options ) ; <nl> + ASSERT_NE ( credentials , nullptr ) ; <nl> + grpc_channel_args * new_args = nullptr ; <nl> + auto connector = credentials - > create_security_connector ( <nl> + nullptr , " random targets " , nullptr , & new_args ) ; <nl> + grpc_channel_args_destroy ( new_args ) ; <nl> + ASSERT_NE ( connector , nullptr ) ; <nl> + TlsChannelSecurityConnector * tls_connector = <nl> + static_cast < TlsChannelSecurityConnector * > ( connector . get ( ) ) ; <nl> + EXPECT_NE ( tls_connector - > ClientHandshakerFactoryForTesting ( ) , nullptr ) ; <nl> + EXPECT_TRUE ( tls_connector - > RootCertsForTesting ( ) . has_value ( ) ) ; <nl> + EXPECT_TRUE ( tls_connector - > KeyCertPairListForTesting ( ) . has_value ( ) ) ; <nl> + } <nl> + <nl> + TEST_F ( GrpcTlsCredentialsOptionsTest , <nl> + ClientOptionsWithCertWatcherProviderOnRootCerts ) { <nl> + auto options = MakeRefCounted < grpc_tls_credentials_options > ( ) ; <nl> + auto provider = <nl> + MakeRefCounted < FileWatcherCertificateProvider > ( " " , " " , CA_CERT_PATH , 1 ) ; <nl> + options - > set_certificate_provider ( std : : move ( provider ) ) ; <nl> + options - > set_watch_root_cert ( true ) ; <nl> + options - > set_server_verification_option ( GRPC_TLS_SERVER_VERIFICATION ) ; <nl> + auto credentials = MakeRefCounted < TlsCredentials > ( options ) ; <nl> + ASSERT_NE ( credentials , nullptr ) ; <nl> + grpc_channel_args * new_args = nullptr ; <nl> + auto connector = credentials - > create_security_connector ( <nl> + nullptr , " random targets " , nullptr , & new_args ) ; <nl> + grpc_channel_args_destroy ( new_args ) ; <nl> + ASSERT_NE ( connector , nullptr ) ; <nl> + TlsChannelSecurityConnector * tls_connector = <nl> + static_cast < TlsChannelSecurityConnector * > ( connector . get ( ) ) ; <nl> + EXPECT_NE ( tls_connector - > ClientHandshakerFactoryForTesting ( ) , nullptr ) ; <nl> + EXPECT_TRUE ( tls_connector - > RootCertsForTesting ( ) . has_value ( ) ) ; <nl> + EXPECT_FALSE ( tls_connector - > KeyCertPairListForTesting ( ) . has_value ( ) ) ; <nl> + } <nl> + <nl> + TEST_F ( GrpcTlsCredentialsOptionsTest , <nl> + ClientOptionsWithCertWatcherProviderOnNotProvidedCerts ) { <nl> + auto options = MakeRefCounted < grpc_tls_credentials_options > ( ) ; <nl> + auto provider = MakeRefCounted < FileWatcherCertificateProvider > ( <nl> + SERVER_KEY_PATH , SERVER_CERT_PATH , " " , 1 ) ; <nl> + options - > set_certificate_provider ( std : : move ( provider ) ) ; <nl> + options - > set_watch_root_cert ( true ) ; <nl> + options - > set_server_verification_option ( GRPC_TLS_SERVER_VERIFICATION ) ; <nl> + auto credentials = MakeRefCounted < TlsCredentials > ( options ) ; <nl> + ASSERT_NE ( credentials , nullptr ) ; <nl> + grpc_channel_args * new_args = nullptr ; <nl> + auto connector = credentials - > create_security_connector ( <nl> + nullptr , " random targets " , nullptr , & new_args ) ; <nl> + grpc_channel_args_destroy ( new_args ) ; <nl> + ASSERT_NE ( connector , nullptr ) ; <nl> + TlsChannelSecurityConnector * tls_connector = <nl> + static_cast < TlsChannelSecurityConnector * > ( connector . get ( ) ) ; <nl> + EXPECT_EQ ( tls_connector - > ClientHandshakerFactoryForTesting ( ) , nullptr ) ; <nl> + } <nl> + <nl> + TEST_F ( GrpcTlsCredentialsOptionsTest , <nl> + ClientOptionsWithCertWatcherProviderOnBadTrustCerts ) { <nl> + auto options = MakeRefCounted < grpc_tls_credentials_options > ( ) ; <nl> + auto provider = <nl> + MakeRefCounted < FileWatcherCertificateProvider > ( " " , " " , INVALID_PATH , 1 ) ; <nl> + options - > set_certificate_provider ( std : : move ( provider ) ) ; <nl> + options - > set_watch_root_cert ( true ) ; <nl> + options - > set_server_verification_option ( GRPC_TLS_SERVER_VERIFICATION ) ; <nl> + auto credentials = MakeRefCounted < TlsCredentials > ( options ) ; <nl> + ASSERT_NE ( credentials , nullptr ) ; <nl> + grpc_channel_args * new_args = nullptr ; <nl> + auto connector = credentials - > create_security_connector ( <nl> + nullptr , " random targets " , nullptr , & new_args ) ; <nl> + grpc_channel_args_destroy ( new_args ) ; <nl> + ASSERT_NE ( connector , nullptr ) ; <nl> + TlsChannelSecurityConnector * tls_connector = <nl> + static_cast < TlsChannelSecurityConnector * > ( connector . get ( ) ) ; <nl> + EXPECT_EQ ( tls_connector - > ClientHandshakerFactoryForTesting ( ) , nullptr ) ; <nl> + } <nl> + <nl> + TEST_F ( GrpcTlsCredentialsOptionsTest , <nl> + ServerOptionsWithCertWatcherProviderOnBothCerts ) { <nl> + auto options = MakeRefCounted < grpc_tls_credentials_options > ( ) ; <nl> + auto provider = MakeRefCounted < FileWatcherCertificateProvider > ( <nl> + SERVER_KEY_PATH , SERVER_CERT_PATH , CA_CERT_PATH , 1 ) ; <nl> + options - > set_certificate_provider ( std : : move ( provider ) ) ; <nl> + options - > set_watch_root_cert ( true ) ; <nl> + options - > set_watch_identity_pair ( true ) ; <nl> + options - > set_cert_request_type ( <nl> + GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY ) ; <nl> + auto credentials = MakeRefCounted < TlsServerCredentials > ( options ) ; <nl> + ASSERT_NE ( credentials , nullptr ) ; <nl> + auto connector = credentials - > create_security_connector ( ) ; <nl> + ASSERT_NE ( connector , nullptr ) ; <nl> + TlsServerSecurityConnector * tls_connector = <nl> + static_cast < TlsServerSecurityConnector * > ( connector . get ( ) ) ; <nl> + EXPECT_NE ( tls_connector - > ServerHandshakerFactoryForTesting ( ) , nullptr ) ; <nl> + EXPECT_TRUE ( tls_connector - > RootCertsForTesting ( ) . has_value ( ) ) ; <nl> + EXPECT_TRUE ( tls_connector - > KeyCertPairListForTesting ( ) . has_value ( ) ) ; <nl> + } <nl> + <nl> + TEST_F ( GrpcTlsCredentialsOptionsTest , <nl> + ServerOptionsWithCertWatcherProviderOnIdentityCerts ) { <nl> + auto options = MakeRefCounted < grpc_tls_credentials_options > ( ) ; <nl> + auto provider = MakeRefCounted < FileWatcherCertificateProvider > ( <nl> + SERVER_KEY_PATH , SERVER_CERT_PATH , " " , 1 ) ; <nl> + options - > set_certificate_provider ( std : : move ( provider ) ) ; <nl> + options - > set_watch_identity_pair ( true ) ; <nl> + options - > set_cert_request_type ( GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE ) ; <nl> + auto credentials = MakeRefCounted < TlsServerCredentials > ( options ) ; <nl> + ASSERT_NE ( credentials , nullptr ) ; <nl> + auto connector = credentials - > create_security_connector ( ) ; <nl> + ASSERT_NE ( connector , nullptr ) ; <nl> + TlsServerSecurityConnector * tls_connector = <nl> + static_cast < TlsServerSecurityConnector * > ( connector . get ( ) ) ; <nl> + EXPECT_NE ( tls_connector - > ServerHandshakerFactoryForTesting ( ) , nullptr ) ; <nl> + EXPECT_FALSE ( tls_connector - > RootCertsForTesting ( ) . has_value ( ) ) ; <nl> + EXPECT_TRUE ( tls_connector - > KeyCertPairListForTesting ( ) . has_value ( ) ) ; <nl> + } <nl> + <nl> + TEST_F ( GrpcTlsCredentialsOptionsTest , <nl> + ServerOptionsWithCertWatcherProviderOnNotProvidedCerts ) { <nl> + auto options = MakeRefCounted < grpc_tls_credentials_options > ( ) ; <nl> + auto provider = <nl> + MakeRefCounted < FileWatcherCertificateProvider > ( " " , " " , CA_CERT_PATH , 1 ) ; <nl> + options - > set_certificate_provider ( std : : move ( provider ) ) ; <nl> + options - > set_watch_identity_pair ( true ) ; <nl> + options - > set_cert_request_type ( GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE ) ; <nl> + auto credentials = MakeRefCounted < TlsServerCredentials > ( options ) ; <nl> + ASSERT_NE ( credentials , nullptr ) ; <nl> + auto connector = credentials - > create_security_connector ( ) ; <nl> + ASSERT_NE ( connector , nullptr ) ; <nl> + TlsServerSecurityConnector * tls_connector = <nl> + static_cast < TlsServerSecurityConnector * > ( connector . get ( ) ) ; <nl> + EXPECT_EQ ( tls_connector - > ServerHandshakerFactoryForTesting ( ) , nullptr ) ; <nl> + } <nl> + <nl> + TEST_F ( GrpcTlsCredentialsOptionsTest , <nl> + ServerOptionsWithCertWatcherProviderOnBadIdentityCerts ) { <nl> + auto options = MakeRefCounted < grpc_tls_credentials_options > ( ) ; <nl> + auto provider = MakeRefCounted < FileWatcherCertificateProvider > ( <nl> + INVALID_PATH , INVALID_PATH , " " , 1 ) ; <nl> + options - > set_certificate_provider ( std : : move ( provider ) ) ; <nl> + options - > set_watch_identity_pair ( true ) ; <nl> + options - > set_cert_request_type ( GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE ) ; <nl> + auto credentials = MakeRefCounted < TlsServerCredentials > ( options ) ; <nl> + ASSERT_NE ( credentials , nullptr ) ; <nl> + auto connector = credentials - > create_security_connector ( ) ; <nl> + ASSERT_NE ( connector , nullptr ) ; <nl> + TlsServerSecurityConnector * tls_connector = <nl> + static_cast < TlsServerSecurityConnector * > ( connector . get ( ) ) ; <nl> + EXPECT_EQ ( tls_connector - > ServerHandshakerFactoryForTesting ( ) , nullptr ) ; <nl> + } <nl> + <nl> + / / The following tests write credential data to temporary files to test the <nl> + / / transition behavior of the provider . <nl> + TEST_F ( GrpcTlsCredentialsOptionsTest , <nl> + ClientOptionsWithCertWatcherProviderOnCertificateRefreshed ) { <nl> + / / Create temporary files and copy cert data into them . <nl> + TmpFile tmp_root_cert ( root_cert_ ) ; <nl> + TmpFile tmp_identity_key ( private_key_ ) ; <nl> + TmpFile tmp_identity_cert ( cert_chain_ ) ; <nl> + / / Create ClientOptions using FileWatcherCertificateProvider . <nl> + auto options = MakeRefCounted < grpc_tls_credentials_options > ( ) ; <nl> + auto provider = MakeRefCounted < FileWatcherCertificateProvider > ( <nl> + tmp_identity_key . name ( ) , tmp_identity_cert . name ( ) , tmp_root_cert . name ( ) , <nl> + 1 ) ; <nl> + options - > set_certificate_provider ( std : : move ( provider ) ) ; <nl> + options - > set_watch_root_cert ( true ) ; <nl> + options - > set_watch_identity_pair ( true ) ; <nl> + options - > set_server_verification_option ( GRPC_TLS_SERVER_VERIFICATION ) ; <nl> + auto credentials = MakeRefCounted < TlsCredentials > ( options ) ; <nl> + ASSERT_NE ( credentials , nullptr ) ; <nl> + grpc_channel_args * new_args = nullptr ; <nl> + auto connector = credentials - > create_security_connector ( <nl> + nullptr , " random targets " , nullptr , & new_args ) ; <nl> + grpc_channel_args_destroy ( new_args ) ; <nl> + ASSERT_NE ( connector , nullptr ) ; <nl> + TlsChannelSecurityConnector * tls_connector = <nl> + static_cast < TlsChannelSecurityConnector * > ( connector . get ( ) ) ; <nl> + / / Expect to see the credential data . <nl> + EXPECT_NE ( tls_connector - > ClientHandshakerFactoryForTesting ( ) , nullptr ) ; <nl> + ASSERT_TRUE ( tls_connector - > RootCertsForTesting ( ) . has_value ( ) ) ; <nl> + EXPECT_EQ ( tls_connector - > RootCertsForTesting ( ) , root_cert_ ) ; <nl> + ASSERT_TRUE ( tls_connector - > KeyCertPairListForTesting ( ) . has_value ( ) ) ; <nl> + EXPECT_EQ ( tls_connector - > KeyCertPairListForTesting ( ) , <nl> + MakeCertKeyPairs ( private_key_ . c_str ( ) , cert_chain_ . c_str ( ) ) ) ; <nl> + / / Copy new data to files . <nl> + / / TODO ( ZhenLian ) : right now it is not completely atomic . Use the real atomic <nl> + / / update when the directory renaming is added in gpr . <nl> + tmp_root_cert . RewriteFile ( root_cert_2_ ) ; <nl> + tmp_identity_key . RewriteFile ( private_key_2_ ) ; <nl> + tmp_identity_cert . RewriteFile ( cert_chain_2_ ) ; <nl> + / / Wait 2 seconds for the provider ' s refresh thread to read the updated files . <nl> + gpr_sleep_until ( gpr_time_add ( gpr_now ( GPR_CLOCK_MONOTONIC ) , <nl> + gpr_time_from_seconds ( 2 , GPR_TIMESPAN ) ) ) ; <nl> + / / Expect to see new credential data loaded by the security connector . <nl> + EXPECT_NE ( tls_connector - > ClientHandshakerFactoryForTesting ( ) , nullptr ) ; <nl> + ASSERT_TRUE ( tls_connector - > RootCertsForTesting ( ) . has_value ( ) ) ; <nl> + EXPECT_EQ ( tls_connector - > RootCertsForTesting ( ) , root_cert_2_ ) ; <nl> + ASSERT_TRUE ( tls_connector - > KeyCertPairListForTesting ( ) . has_value ( ) ) ; <nl> + EXPECT_EQ ( tls_connector - > KeyCertPairListForTesting ( ) , <nl> + MakeCertKeyPairs ( private_key_2_ . c_str ( ) , cert_chain_2_ . c_str ( ) ) ) ; <nl> + } <nl> + <nl> + TEST_F ( GrpcTlsCredentialsOptionsTest , <nl> + ClientOptionsWithCertWatcherProviderOnDeletedFiles ) { <nl> + / / Create temporary files and copy cert data into it . <nl> + auto tmp_root_cert = absl : : make_unique < TmpFile > ( root_cert_ ) ; <nl> + auto tmp_identity_key = absl : : make_unique < TmpFile > ( private_key_ ) ; <nl> + auto tmp_identity_cert = absl : : make_unique < TmpFile > ( cert_chain_ ) ; <nl> + / / Create ClientOptions using FileWatcherCertificateProvider . <nl> + auto options = MakeRefCounted < grpc_tls_credentials_options > ( ) ; <nl> + auto provider = MakeRefCounted < FileWatcherCertificateProvider > ( <nl> + tmp_identity_key - > name ( ) , tmp_identity_cert - > name ( ) , <nl> + tmp_root_cert - > name ( ) , 1 ) ; <nl> + options - > set_certificate_provider ( std : : move ( provider ) ) ; <nl> + options - > set_watch_root_cert ( true ) ; <nl> + options - > set_watch_identity_pair ( true ) ; <nl> + options - > set_server_verification_option ( GRPC_TLS_SERVER_VERIFICATION ) ; <nl> + auto credentials = MakeRefCounted < TlsCredentials > ( options ) ; <nl> + ASSERT_NE ( credentials , nullptr ) ; <nl> + grpc_channel_args * new_args = nullptr ; <nl> + auto connector = credentials - > create_security_connector ( <nl> + nullptr , " random targets " , nullptr , & new_args ) ; <nl> + grpc_channel_args_destroy ( new_args ) ; <nl> + ASSERT_NE ( connector , nullptr ) ; <nl> + TlsChannelSecurityConnector * tls_connector = <nl> + static_cast < TlsChannelSecurityConnector * > ( connector . get ( ) ) ; <nl> + / / The initial data is all good , so we expect to have successful credential <nl> + / / updates . <nl> + EXPECT_NE ( tls_connector - > ClientHandshakerFactoryForTesting ( ) , nullptr ) ; <nl> + ASSERT_TRUE ( tls_connector - > RootCertsForTesting ( ) . has_value ( ) ) ; <nl> + EXPECT_EQ ( tls_connector - > RootCertsForTesting ( ) , root_cert_ ) ; <nl> + ASSERT_TRUE ( tls_connector - > KeyCertPairListForTesting ( ) . has_value ( ) ) ; <nl> + EXPECT_EQ ( tls_connector - > KeyCertPairListForTesting ( ) , <nl> + MakeCertKeyPairs ( private_key_ . c_str ( ) , cert_chain_ . c_str ( ) ) ) ; <nl> + / / Delete TmpFile objects , which will remove the corresponding files . <nl> + tmp_root_cert . reset ( ) ; <nl> + tmp_identity_key . reset ( ) ; <nl> + tmp_identity_cert . reset ( ) ; <nl> + / / Wait 2 seconds for the provider ' s refresh thread to read the deleted files . <nl> + gpr_sleep_until ( gpr_time_add ( gpr_now ( GPR_CLOCK_MONOTONIC ) , <nl> + gpr_time_from_seconds ( 2 , GPR_TIMESPAN ) ) ) ; <nl> + / / It ' s a bit hard to test if errors are sent to the security connector , <nl> + / / because the security connector simply logs the error . We will see the err <nl> + / / messages if we open the log . <nl> + / / The old certs should still being used . <nl> + EXPECT_NE ( tls_connector - > ClientHandshakerFactoryForTesting ( ) , nullptr ) ; <nl> + ASSERT_TRUE ( tls_connector - > RootCertsForTesting ( ) . has_value ( ) ) ; <nl> + EXPECT_EQ ( tls_connector - > RootCertsForTesting ( ) , root_cert_ ) ; <nl> + ASSERT_TRUE ( tls_connector - > KeyCertPairListForTesting ( ) . has_value ( ) ) ; <nl> + EXPECT_EQ ( tls_connector - > KeyCertPairListForTesting ( ) , <nl> + MakeCertKeyPairs ( private_key_ . c_str ( ) , cert_chain_ . c_str ( ) ) ) ; <nl> + } <nl> + <nl> } / / namespace testing <nl> <nl> + } / / namespace grpc_core <nl> + <nl> int main ( int argc , char * * argv ) { <nl> grpc : : testing : : TestEnvironment env ( argc , argv ) ; <nl> : : testing : : InitGoogleTest ( & argc , argv ) ; <nl> new file mode 100644 <nl> index 00000000000 . . 4f56ed21cf8 <nl> mmm / dev / null <nl> ppp b / test / core / security / tls_utils . cc <nl> <nl> + / / <nl> + / / Copyright 2020 gRPC authors . <nl> + / / <nl> + / / Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + / / you may not use this file except in compliance with the License . <nl> + / / You may obtain a copy of the License at <nl> + / / <nl> + / / http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + / / <nl> + / / Unless required by applicable law or agreed to in writing , software <nl> + / / distributed under the License is distributed on an " AS IS " BASIS , <nl> + / / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + / / See the License for the specific language governing permissions and <nl> + / / limitations under the License . <nl> + / / <nl> + <nl> + # include " test / core / security / tls_utils . h " <nl> + <nl> + # include " src / core / lib / gpr / tmpfile . h " <nl> + # include " src / core / lib / iomgr / load_file . h " <nl> + # include " src / core / lib / slice / slice_internal . h " <nl> + <nl> + namespace grpc_core { <nl> + <nl> + namespace testing { <nl> + <nl> + TmpFile : : TmpFile ( absl : : string_view credential_data ) { <nl> + name_ = CreateTmpFileAndWriteData ( credential_data ) ; <nl> + GPR_ASSERT ( ! name_ . empty ( ) ) ; <nl> + } <nl> + <nl> + TmpFile : : ~ TmpFile ( ) { GPR_ASSERT ( remove ( name_ . c_str ( ) ) = = 0 ) ; } <nl> + <nl> + void TmpFile : : RewriteFile ( absl : : string_view credential_data ) { <nl> + / / Create a new file containing new data . <nl> + std : : string new_name = CreateTmpFileAndWriteData ( credential_data ) ; <nl> + GPR_ASSERT ( ! new_name . empty ( ) ) ; <nl> + / / Remove the old file . <nl> + GPR_ASSERT ( remove ( name_ . c_str ( ) ) = = 0 ) ; <nl> + / / Rename the new file to the original name . <nl> + GPR_ASSERT ( rename ( new_name . c_str ( ) , name_ . c_str ( ) ) = = 0 ) ; <nl> + } <nl> + <nl> + std : : string TmpFile : : CreateTmpFileAndWriteData ( <nl> + absl : : string_view credential_data ) { <nl> + char * name = nullptr ; <nl> + FILE * file_descriptor = gpr_tmpfile ( " GrpcTlsCertificateProviderTest " , & name ) ; <nl> + GPR_ASSERT ( fwrite ( credential_data . data ( ) , 1 , credential_data . size ( ) , <nl> + file_descriptor ) = = credential_data . size ( ) ) ; <nl> + GPR_ASSERT ( fclose ( file_descriptor ) = = 0 ) ; <nl> + GPR_ASSERT ( file_descriptor ! = nullptr ) ; <nl> + GPR_ASSERT ( name ! = nullptr ) ; <nl> + std : : string name_to_return = name ; <nl> + gpr_free ( name ) ; <nl> + return name_to_return ; <nl> + } <nl> + <nl> + PemKeyCertPairList MakeCertKeyPairs ( const char * private_key , <nl> + const char * certs ) { <nl> + if ( strcmp ( private_key , " " ) = = 0 & & strcmp ( certs , " " ) = = 0 ) { <nl> + return { } ; <nl> + } <nl> + grpc_ssl_pem_key_cert_pair * ssl_pair = <nl> + static_cast < grpc_ssl_pem_key_cert_pair * > ( <nl> + gpr_malloc ( sizeof ( grpc_ssl_pem_key_cert_pair ) ) ) ; <nl> + ssl_pair - > private_key = gpr_strdup ( private_key ) ; <nl> + ssl_pair - > cert_chain = gpr_strdup ( certs ) ; <nl> + PemKeyCertPairList pem_key_cert_pairs ; <nl> + pem_key_cert_pairs . emplace_back ( ssl_pair ) ; <nl> + return pem_key_cert_pairs ; <nl> + } <nl> + <nl> + std : : string GetFileContents ( const char * path ) { <nl> + grpc_slice slice = grpc_empty_slice ( ) ; <nl> + GPR_ASSERT ( GRPC_LOG_IF_ERROR ( " load_file " , grpc_load_file ( path , 0 , & slice ) ) ) ; <nl> + std : : string credential = std : : string ( StringViewFromSlice ( slice ) ) ; <nl> + grpc_slice_unref ( slice ) ; <nl> + return credential ; <nl> + } <nl> + <nl> + } / / namespace testing <nl> + <nl> + } / / namespace grpc_core <nl> new file mode 100644 <nl> index 00000000000 . . 94d29efa713 <nl> mmm / dev / null <nl> ppp b / test / core / security / tls_utils . h <nl> <nl> + / / <nl> + / / Copyright 2020 gRPC authors . <nl> + / / <nl> + / / Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + / / you may not use this file except in compliance with the License . <nl> + / / You may obtain a copy of the License at <nl> + / / <nl> + / / http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + / / <nl> + / / Unless required by applicable law or agreed to in writing , software <nl> + / / distributed under the License is distributed on an " AS IS " BASIS , <nl> + / / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + / / See the License for the specific language governing permissions and <nl> + / / limitations under the License . <nl> + / / <nl> + <nl> + # include " src / core / lib / security / security_connector / ssl_utils . h " <nl> + <nl> + namespace grpc_core { <nl> + <nl> + namespace testing { <nl> + <nl> + class TmpFile { <nl> + public : <nl> + / / Create a temporary file with | credential_data | written in . <nl> + explicit TmpFile ( absl : : string_view credential_data ) ; <nl> + <nl> + ~ TmpFile ( ) ; <nl> + <nl> + const std : : string & name ( ) { return name_ ; } <nl> + <nl> + / / Rewrite | credential_data | to the temporary file , in an atomic way . <nl> + void RewriteFile ( absl : : string_view credential_data ) ; <nl> + <nl> + private : <nl> + std : : string CreateTmpFileAndWriteData ( absl : : string_view credential_data ) ; <nl> + <nl> + std : : string name_ ; <nl> + } ; <nl> + <nl> + PemKeyCertPairList MakeCertKeyPairs ( const char * private_key , const char * certs ) ; <nl> + <nl> + std : : string GetFileContents ( const char * path ) ; <nl> + <nl> + } / / namespace testing <nl> + <nl> + } / / namespace grpc_core <nl> mmm a / test / core / surface / public_headers_must_be_c89 . c <nl> ppp b / test / core / surface / public_headers_must_be_c89 . c <nl> int main ( int argc , char * * argv ) { <nl> printf ( " % lx " , ( unsigned long ) grpc_tls_identity_pairs_add_pair ) ; <nl> printf ( " % lx " , ( unsigned long ) grpc_tls_identity_pairs_destroy ) ; <nl> printf ( " % lx " , ( unsigned long ) grpc_tls_certificate_provider_static_data_create ) ; <nl> + printf ( " % lx " , ( unsigned long ) grpc_tls_certificate_provider_file_watcher_create ) ; <nl> printf ( " % lx " , ( unsigned long ) grpc_tls_certificate_provider_release ) ; <nl> printf ( " % lx " , ( unsigned long ) grpc_tls_credentials_options_create ) ; <nl> printf ( " % lx " , ( unsigned long ) grpc_tls_credentials_options_set_cert_request_type ) ; <nl> mmm a / test / cpp / client / BUILD <nl> ppp b / test / cpp / client / BUILD <nl> grpc_package ( name = " test / cpp / client " ) <nl> grpc_cc_test ( <nl> name = " credentials_test " , <nl> srcs = [ " credentials_test . cc " ] , <nl> + data = [ <nl> + " / / src / core / tsi / test_creds : ca . pem " , <nl> + " / / src / core / tsi / test_creds : server1 . key " , <nl> + " / / src / core / tsi / test_creds : server1 . pem " , <nl> + ] , <nl> external_deps = [ <nl> " gtest " , <nl> ] , <nl> mmm a / test / cpp / client / credentials_test . cc <nl> ppp b / test / cpp / client / credentials_test . cc <nl> <nl> # include " src / cpp / client / secure_credentials . h " <nl> # include " src / cpp / common / tls_credentials_options_util . h " <nl> <nl> + # define CA_CERT_PATH " src / core / tsi / test_creds / ca . pem " <nl> + # define SERVER_CERT_PATH " src / core / tsi / test_creds / server1 . pem " <nl> + # define SERVER_KEY_PATH " src / core / tsi / test_creds / server1 . key " <nl> + <nl> namespace { <nl> <nl> constexpr const char * kRootCertName = " root_cert_name " ; <nl> constexpr const char * kIdentityCertName = " identity_cert_name " ; <nl> constexpr const char * kIdentityCertPrivateKey = " identity_private_key " ; <nl> constexpr const char * kIdentityCertContents = " identity_cert_contents " ; <nl> <nl> + using : : grpc : : experimental : : FileWatcherCertificateProvider ; <nl> using : : grpc : : experimental : : StaticDataCertificateProvider ; <nl> using : : grpc : : experimental : : TlsServerAuthorizationCheckArg ; <nl> using : : grpc : : experimental : : TlsServerAuthorizationCheckConfig ; <nl> TEST ( CredentialsTest , <nl> GPR_ASSERT ( channel_credentials . get ( ) ! = nullptr ) ; <nl> } <nl> <nl> + TEST ( <nl> + CredentialsTest , <nl> + TlsChannelCredentialsWithFileWatcherCertificateProviderLoadingRootAndIdentity ) { <nl> + auto certificate_provider = std : : make_shared < FileWatcherCertificateProvider > ( <nl> + SERVER_KEY_PATH , SERVER_CERT_PATH , CA_CERT_PATH , 1 ) ; <nl> + grpc : : experimental : : TlsChannelCredentialsOptions options ( <nl> + certificate_provider ) ; <nl> + options . watch_root_certs ( ) ; <nl> + options . set_root_cert_name ( kRootCertName ) ; <nl> + options . watch_identity_key_cert_pairs ( ) ; <nl> + options . set_identity_cert_name ( kIdentityCertName ) ; <nl> + options . set_server_verification_option ( GRPC_TLS_SERVER_VERIFICATION ) ; <nl> + auto test_server_authorization_check = <nl> + std : : make_shared < TestTlsServerAuthorizationCheck > ( ) ; <nl> + auto server_authorization_check_config = <nl> + std : : make_shared < TlsServerAuthorizationCheckConfig > ( <nl> + test_server_authorization_check ) ; <nl> + options . set_server_authorization_check_config ( <nl> + server_authorization_check_config ) ; <nl> + auto channel_credentials = grpc : : experimental : : TlsCredentials ( options ) ; <nl> + GPR_ASSERT ( channel_credentials . get ( ) ! = nullptr ) ; <nl> + } <nl> + <nl> + / / ChannelCredentials should always have root credential presented . <nl> + / / Otherwise the system root certificates will be loaded , which will cause <nl> + / / failure in some tests under MacOS / Windows . <nl> + TEST ( CredentialsTest , <nl> + TlsChannelCredentialsWithFileWatcherCertificateProviderLoadingRootOnly ) { <nl> + auto certificate_provider = <nl> + std : : make_shared < FileWatcherCertificateProvider > ( CA_CERT_PATH , 1 ) ; <nl> + grpc : : experimental : : TlsChannelCredentialsOptions options ( <nl> + certificate_provider ) ; <nl> + options . watch_root_certs ( ) ; <nl> + options . set_root_cert_name ( kRootCertName ) ; <nl> + options . set_server_verification_option ( GRPC_TLS_SERVER_VERIFICATION ) ; <nl> + auto test_server_authorization_check = <nl> + std : : make_shared < TestTlsServerAuthorizationCheck > ( ) ; <nl> + auto server_authorization_check_config = <nl> + std : : make_shared < TlsServerAuthorizationCheckConfig > ( <nl> + test_server_authorization_check ) ; <nl> + options . set_server_authorization_check_config ( <nl> + server_authorization_check_config ) ; <nl> + auto channel_credentials = grpc : : experimental : : TlsCredentials ( options ) ; <nl> + GPR_ASSERT ( channel_credentials . get ( ) ! = nullptr ) ; <nl> + } <nl> + <nl> TEST ( CredentialsTest , TlsServerAuthorizationCheckConfigErrorMessages ) { <nl> std : : shared_ptr < TlsServerAuthorizationCheckConfig > config ( <nl> new TlsServerAuthorizationCheckConfig ( nullptr ) ) ; <nl> mmm a / test / cpp / server / BUILD <nl> ppp b / test / cpp / server / BUILD <nl> grpc_cc_test ( <nl> grpc_cc_test ( <nl> name = " credentials_test " , <nl> srcs = [ " credentials_test . cc " ] , <nl> + data = [ <nl> + " / / src / core / tsi / test_creds : ca . pem " , <nl> + " / / src / core / tsi / test_creds : server1 . key " , <nl> + " / / src / core / tsi / test_creds : server1 . pem " , <nl> + ] , <nl> external_deps = [ <nl> " gtest " , <nl> ] , <nl> mmm a / test / cpp / server / credentials_test . cc <nl> ppp b / test / cpp / server / credentials_test . cc <nl> <nl> # include " test / core / util / port . h " <nl> # include " test / core / util / test_config . h " <nl> <nl> + # define CA_CERT_PATH " src / core / tsi / test_creds / ca . pem " <nl> + # define SERVER_CERT_PATH " src / core / tsi / test_creds / server1 . pem " <nl> + # define SERVER_KEY_PATH " src / core / tsi / test_creds / server1 . key " <nl> + <nl> namespace { <nl> <nl> constexpr const char * kRootCertName = " root_cert_name " ; <nl> constexpr const char * kIdentityCertName = " identity_cert_name " ; <nl> constexpr const char * kIdentityCertPrivateKey = " identity_private_key " ; <nl> constexpr const char * kIdentityCertContents = " identity_cert_contents " ; <nl> <nl> + using : : grpc : : experimental : : FileWatcherCertificateProvider ; <nl> using : : grpc : : experimental : : StaticDataCertificateProvider ; <nl> <nl> } / / namespace <nl> TEST ( CredentialsTest , <nl> GPR_ASSERT ( server_credentials . get ( ) ! = nullptr ) ; <nl> } <nl> <nl> + TEST ( <nl> + CredentialsTest , <nl> + TlsServerCredentialsWithFileWatcherCertificateProviderLoadingRootAndIdentity ) { <nl> + auto certificate_provider = std : : make_shared < FileWatcherCertificateProvider > ( <nl> + SERVER_KEY_PATH , SERVER_CERT_PATH , CA_CERT_PATH , 1 ) ; <nl> + grpc : : experimental : : TlsServerCredentialsOptions options ( certificate_provider ) ; <nl> + options . watch_root_certs ( ) ; <nl> + options . set_root_cert_name ( kRootCertName ) ; <nl> + options . watch_identity_key_cert_pairs ( ) ; <nl> + options . set_identity_cert_name ( kIdentityCertName ) ; <nl> + options . set_cert_request_type ( <nl> + GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY ) ; <nl> + auto server_credentials = grpc : : experimental : : TlsServerCredentials ( options ) ; <nl> + GPR_ASSERT ( server_credentials . get ( ) ! = nullptr ) ; <nl> + } <nl> + <nl> + / / ServerCredentials should always have identity credential presented . <nl> + / / Otherwise gRPC stack will fail . <nl> + TEST ( <nl> + CredentialsTest , <nl> + TlsServerCredentialsWithFileWatcherCertificateProviderLoadingIdentityOnly ) { <nl> + auto certificate_provider = std : : make_shared < FileWatcherCertificateProvider > ( <nl> + SERVER_KEY_PATH , SERVER_CERT_PATH , 1 ) ; <nl> + grpc : : experimental : : TlsServerCredentialsOptions options ( certificate_provider ) ; <nl> + options . watch_identity_key_cert_pairs ( ) ; <nl> + options . set_identity_cert_name ( kIdentityCertName ) ; <nl> + options . set_cert_request_type ( <nl> + GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY ) ; <nl> + auto server_credentials = grpc : : experimental : : TlsServerCredentials ( options ) ; <nl> + GPR_ASSERT ( server_credentials . get ( ) ! = nullptr ) ; <nl> + } <nl> + <nl> } / / namespace <nl> } / / namespace testing <nl> } / / namespace grpc <nl> mmm a / tools / run_tests / generated / tests . json <nl> ppp b / tools / run_tests / generated / tests . json <nl> <nl> ] , <nl> " uses_polling " : true <nl> } , <nl> + { <nl> + " args " : [ ] , <nl> + " benchmark " : false , <nl> + " ci_platforms " : [ <nl> + " linux " , <nl> + " mac " , <nl> + " posix " , <nl> + " windows " <nl> + ] , <nl> + " cpu_cost " : 1 . 0 , <nl> + " exclude_configs " : [ ] , <nl> + " exclude_iomgrs " : [ ] , <nl> + " flaky " : false , <nl> + " gtest " : true , <nl> + " language " : " c + + " , <nl> + " name " : " grpc_tls_certificate_provider_test " , <nl> + " platforms " : [ <nl> + " linux " , <nl> + " mac " , <nl> + " posix " , <nl> + " windows " <nl> + ] , <nl> + " uses_polling " : true <nl> + } , <nl> { <nl> " args " : [ ] , <nl> " benchmark " : false , <nl> | Add File Watcher Certificate Provider API | grpc/grpc | d74e43da9591febb2d7fa64c0a3a57cde8a8174e | 2020-11-19T21:36:13Z |
mmm a / lib / AST / Module . cpp <nl> ppp b / lib / AST / Module . cpp <nl> ArrayRef < Substitution > BoundGenericType : : getSubstitutions ( <nl> return * known ; <nl> <nl> / / Compute the set of substitutions . <nl> - llvm : : SmallPtrSet < ArchetypeType * , 8 > knownArchetypes ; <nl> - SmallVector < ArchetypeType * , 8 > archetypeStack ; <nl> TypeSubstitutionMap substitutions ; <nl> auto genericParams = gpContext - > getGenericParamsOfContext ( ) ; <nl> unsigned index = 0 ; <nl> mmm a / lib / Parse / ParseSIL . cpp <nl> ppp b / lib / Parse / ParseSIL . cpp <nl> bool SILParser : : parseSILInstruction ( SILBasicBlock * BB ) { <nl> } <nl> case ValueKind : : TupleElementAddrInst : <nl> case ValueKind : : TupleExtractInst : { <nl> - Identifier ElemId ; <nl> SourceLoc NameLoc ; <nl> if ( parseTypedValueRef ( Val , B ) | | <nl> P . parseToken ( tok : : comma , diag : : expected_tok_in_sil_instr , " , " ) ) <nl> bool SILParser : : parseSILInstruction ( SILBasicBlock * BB ) { <nl> Identifier invoke , type ; <nl> SourceLoc invokeLoc , typeLoc ; <nl> <nl> - SILValue invokeVal , invokeValLoc ; <nl> + SILValue invokeVal ; <nl> <nl> SILType blockType ; <nl> <nl> mmm a / lib / Parse / Parser . cpp <nl> ppp b / lib / Parse / Parser . cpp <nl> StringRef swift : : parseDeclName ( StringRef name , <nl> <nl> if ( ! Lexer : : isIdentifier ( NextParam ) ) <nl> return " " ; <nl> - Identifier NextParamID ; <nl> if ( NextParam = = " _ " ) <nl> argumentLabels . push_back ( " " ) ; <nl> else <nl> mmm a / lib / PrintAsObjC / PrintAsObjC . cpp <nl> ppp b / lib / PrintAsObjC / PrintAsObjC . cpp <nl> class ObjCPrinter : private DeclVisitor < ObjCPrinter > , <nl> auto paramLists = AFD - > getParameterLists ( ) ; <nl> assert ( paramLists . size ( ) = = 2 & & " not an ObjC - compatible method " ) ; <nl> <nl> - llvm : : SmallString < 128 > selectorBuf ; <nl> ArrayRef < Identifier > selectorPieces <nl> = AFD - > getObjCSelector ( ) . getSelectorPieces ( ) ; <nl> <nl> mmm a / lib / SILGen / SILGenApply . cpp <nl> ppp b / lib / SILGen / SILGenApply . cpp <nl> class SILGenApply : public Lowering : : ExprVisitor < SILGenApply > { <nl> setSelfParam ( ArgumentSource ( arg , RValue ( SGF , apply , superFormalType , super ) ) , <nl> apply ) ; <nl> <nl> - SILValue superMethod ; <nl> if ( constant . isForeign | | ! canUseStaticDispatch ( SGF , constant ) ) { <nl> / / All Objective - C methods and <nl> / / non - final native Swift methods use dynamic dispatch . <nl> mmm a / lib / SILGen / SILGenDynamicCast . cpp <nl> ppp b / lib / SILGen / SILGenDynamicCast . cpp <nl> namespace { <nl> <nl> / / If we ' re using checked_cast_addr , take the operand ( which <nl> / / should be an address ) and build into the destination buffer . <nl> - ManagedValue abstractResult ; <nl> if ( Strategy = = CastStrategy : : Address ) { <nl> SILValue resultBuffer = <nl> createAbstractResultBuffer ( hasAbstraction , origTargetTL , ctx ) ; <nl> mmm a / lib / SILGen / SILGenMaterializeForSet . cpp <nl> ppp b / lib / SILGen / SILGenMaterializeForSet . cpp <nl> collectIndicesFromParameters ( SILGenFunction & gen , SILLocation loc , <nl> <nl> / / Translate and reabstract the index values by recursively walking <nl> / / the abstracted index type . <nl> - SmallVector < ManagedValue , 4 > translatedIndices ; <nl> translateIndices ( gen , loc , pattern , substIndicesType , <nl> sourceIndices , result ) ; <nl> assert ( sourceIndices . empty ( ) & & " index value not claimed ! " ) ; <nl> mmm a / lib / SILOptimizer / Analysis / LoopRegionAnalysis . cpp <nl> ppp b / lib / SILOptimizer / Analysis / LoopRegionAnalysis . cpp <nl> LoopRegionFunctionInfo : : ~ LoopRegionFunctionInfo ( ) { <nl> void LoopRegionFunctionInfo : : verify ( ) { <nl> # ifndef NDEBUG <nl> llvm : : SmallVector < unsigned , 8 > UniquePredList ; <nl> - llvm : : SmallVector < LoopRegion : : SuccessorID , 8 > UniqueSuccList ; <nl> for ( auto * R : IDToRegionMap ) { <nl> / / Make sure that our region has a pred list without duplicates . We do not <nl> / / care if the predecessor list is sorted , just that it is unique . <nl> mmm a / lib / SILOptimizer / Transforms / RedundantLoadElimination . cpp <nl> ppp b / lib / SILOptimizer / Transforms / RedundantLoadElimination . cpp <nl> class RLEContext { <nl> / / / A map from each BasicBlock to its BlockState . <nl> llvm : : SmallDenseMap < SILBasicBlock * , BlockState , 4 > BBToLocState ; <nl> <nl> - / / / A map for each basic block and whether its predecessors have forwardable <nl> - / / / edges . <nl> - llvm : : DenseMap < SILBasicBlock * , bool > ForwardableEdge ; <nl> - <nl> public : <nl> RLEContext ( SILFunction * F , AliasAnalysis * AA , TypeExpansionAnalysis * TE , <nl> PostOrderFunctionInfo * PO ) ; <nl> mmm a / lib / SILOptimizer / Transforms / SILSROA . cpp <nl> ppp b / lib / SILOptimizer / Transforms / SILSROA . cpp <nl> class SROAMemoryUseAnalyzer { <nl> llvm : : SmallVector < LoadInst * , 4 > Loads ; <nl> / / Stores to AI . <nl> llvm : : SmallVector < StoreInst * , 4 > Stores ; <nl> - / / Dealloc instructions for AI . <nl> - llvm : : SmallVector < DeallocStackInst * , 4 > Deallocs ; <nl> / / Instructions which extract from aggregates . <nl> llvm : : SmallVector < SILInstruction * , 4 > ExtractInsts ; <nl> <nl> mmm a / lib / SILOptimizer / Utils / Devirtualize . cpp <nl> ppp b / lib / SILOptimizer / Utils / Devirtualize . cpp <nl> getSubstitutionsForCallee ( SILModule & M , CanSILFunctionType GenCalleeType , <nl> / / Class F belongs to . <nl> CanType FSelfClass = GenCalleeType - > getSelfParameter ( ) . getType ( ) ; <nl> <nl> - SILType FSelfSubstType ; <nl> auto * Module = M . getSwiftModule ( ) ; <nl> <nl> ArrayRef < Substitution > ClassSubs ; <nl> mmm a / lib / Serialization / DeserializeSIL . cpp <nl> ppp b / lib / Serialization / DeserializeSIL . cpp <nl> bool SILDeserializer : : readSILInstruction ( SILFunction * Fn , SILBasicBlock * BB , <nl> ValueID ValID , ValID2 , ValID3 ; <nl> TypeID TyID , TyID2 , TyID3 ; <nl> TypeID ConcreteTyID ; <nl> - DeclID ProtoID ; <nl> ModuleID OwningModuleID ; <nl> SourceLoc SLoc ; <nl> ArrayRef < uint64_t > ListOfValues ; <nl> mmm a / lib / Serialization / Serialization . cpp <nl> ppp b / lib / Serialization / Serialization . cpp <nl> Serializer : : writeSubstitutions ( ArrayRef < Substitution > substitutions , <nl> using namespace decls_block ; <nl> auto abbrCode = abbrCodes [ BoundGenericSubstitutionLayout : : Code ] ; <nl> for ( auto & sub : substitutions ) { <nl> - SmallVector < DeclID , 16 > conformanceData ; <nl> - SmallVector < const ProtocolConformance * , 8 > conformancesToWrite ; <nl> - <nl> BoundGenericSubstitutionLayout : : emitRecord ( <nl> Out , ScratchRecord , abbrCode , <nl> addTypeRef ( sub . getReplacement ( ) ) , <nl> | Remove unused variables . | apple/swift | 6d0eee9b8c070e1b849a4f7894d923033e8d2e63 | 2016-01-21T09:33:17Z |
mmm a / src / base / bittorrent / session . cpp <nl> ppp b / src / base / bittorrent / session . cpp <nl> void Session : : setSessionSettings ( ) <nl> sessionSettings . force_proxy = false ; <nl> sessionSettings . no_connect_privileged_ports = false ; <nl> sessionSettings . seed_choking_algorithm = libt : : session_settings : : fastest_upload ; <nl> + <nl> + sessionSettings . apply_ip_filter_to_trackers = pref - > isFilteringTrackerEnabled ( ) ; <nl> qDebug ( ) < < " Set session settings " ; <nl> m_nativeSession - > set_settings ( sessionSettings ) ; <nl> } <nl> mmm a / src / gui / options_imp . cpp <nl> ppp b / src / gui / options_imp . cpp <nl> void options_imp : : saveOptions ( ) <nl> pref - > setGlobalMaxRatio ( getMaxRatio ( ) ) ; <nl> session - > setMaxRatioAction ( static_cast < MaxRatioAction > ( comboRatioLimitAct - > currentIndex ( ) ) ) ; <nl> / / End Bittorrent preferences <nl> + <nl> / / Misc preferences <nl> / / * IPFilter <nl> pref - > setFilteringEnabled ( isFilteringEnabled ( ) ) ; <nl> - if ( isFilteringEnabled ( ) ) { <nl> - pref - > setFilteringTrackerEnabled ( checkIpFilterTrackers - > isChecked ( ) ) ; <nl> - pref - > setFilter ( textFilterPath - > text ( ) ) ; <nl> - } <nl> + pref - > setFilteringTrackerEnabled ( checkIpFilterTrackers - > isChecked ( ) ) ; <nl> + pref - > setFilter ( textFilterPath - > text ( ) ) ; <nl> / / End IPFilter preferences <nl> / / Queueing system <nl> pref - > setQueueingSystemEnabled ( isQueueingSystemEnabled ( ) ) ; <nl> | Fix " IP Filtering - Apply to trackers " wasn ' t being applied . Closes . | qbittorrent/qBittorrent | a81cf1ea16e0d4a148830594d0501761a24a0649 | 2016-05-08T12:46:58Z |
mmm a / modules / ml / src / knearest . cpp <nl> ppp b / modules / ml / src / knearest . cpp <nl> bool CvKNearest : : train ( const CvMat * _train_data , const CvMat * _responses , <nl> ok = true ; <nl> <nl> __END__ ; <nl> + <nl> + if ( responses & & responses - > data . ptr ! = _responses - > data . ptr ) <nl> + cvReleaseMat ( & responses ) ; <nl> <nl> return ok ; <nl> } <nl> | fixed memory leak in CvKNearest : : train ( ) and the constructor . | opencv/opencv | 4e099d2e5c3cac4ad9f40ec73932b0613f49a87c | 2011-07-08T06:48:18Z |
mmm a / scripts / record_bag . py <nl> ppp b / scripts / record_bag . py <nl> <nl> - . . . <nl> <nl> 1 . If we have NVME disk , it will be used to record all data . <nl> - 2 . If we have Non - NVME disk , it will only record SMALL_TOPICS , unless ' - - all ' is <nl> + 2 . If we have Non - NVME disk , it will only record smaller topics ( blacklist LARGE_TOPICS ) , unless ' - - all ' is <nl> specified . <nl> 3 . If no external disks are available , we will take ' / apollo ' as a <nl> ' Non - NVME disk ' and follow the rule above . <nl> <nl> import psutil <nl> <nl> <nl> - SMALL_TOPICS = [ <nl> - ' / apollo / audio_detection ' , <nl> - ' / apollo / audio_event ' , <nl> - ' / apollo / canbus / chassis ' , <nl> - ' / apollo / canbus / chassis_detail ' , <nl> - ' / apollo / common / latency_records ' , <nl> - ' / apollo / common / latency_reports ' , <nl> - ' / apollo / control ' , <nl> - ' / apollo / control / pad ' , <nl> - ' / apollo / drive_event ' , <nl> - ' / apollo / guardian ' , <nl> - ' / apollo / hmi / status ' , <nl> - ' / apollo / localization / pose ' , <nl> - ' / apollo / localization / msf_gnss ' , <nl> - ' / apollo / localization / msf_lidar ' , <nl> - ' / apollo / localization / msf_status ' , <nl> - ' / apollo / monitor ' , <nl> - ' / apollo / monitor / system_status ' , <nl> - ' / apollo / navigation ' , <nl> - ' / apollo / perception / obstacles ' , <nl> - ' / apollo / perception / traffic_light ' , <nl> - ' / apollo / planning ' , <nl> - ' / apollo / prediction ' , <nl> - ' / apollo / relative_map ' , <nl> - ' / apollo / routing_request ' , <nl> - ' / apollo / routing_response ' , <nl> - ' / apollo / routing_response_history ' , <nl> - ' / apollo / sensor / conti_radar ' , <nl> - ' / apollo / sensor / delphi_esr ' , <nl> - ' / apollo / sensor / gnss / best_pose ' , <nl> - ' / apollo / sensor / gnss / corrected_imu ' , <nl> - ' / apollo / sensor / gnss / gnss_status ' , <nl> - ' / apollo / sensor / gnss / imu ' , <nl> - ' / apollo / sensor / gnss / ins_stat ' , <nl> - ' / apollo / sensor / gnss / odometry ' , <nl> - ' / apollo / sensor / gnss / raw_data ' , <nl> - ' / apollo / sensor / gnss / rtcm_data ' , <nl> - ' / apollo / sensor / gnss / rtk_eph ' , <nl> - ' / apollo / sensor / gnss / rtk_obs ' , <nl> - ' / apollo / sensor / gnss / heading ' , <nl> - ' / apollo / sensor / mobileye ' , <nl> - ' / apollo / storytelling ' , <nl> - ' / tf ' , <nl> - ' / tf_static ' , <nl> - ] <nl> - <nl> LARGE_TOPICS = [ <nl> ' / apollo / sensor / camera / front_6mm / image ' , <nl> ' / apollo / sensor / camera / front_12mm / image ' , <nl> def __init__ ( self ) : <nl> help = ' Stop recorder . ' ) <nl> self . parser . add_argument ( ' - - stop_signal ' , default = " SIGTERM " , <nl> help = ' Signal to stop the recorder . ' ) <nl> - self . parser . add_argument ( ' - - additional_topics ' , action = ' append ' , <nl> - help = ' Record additional topics . ' ) <nl> self . parser . add_argument ( ' - - all ' , default = False , action = " store_true " , <nl> help = ' Record all topics even without high ' <nl> ' performance disks . ' ) <nl> self . parser . add_argument ( ' - - small ' , default = False , action = " store_true " , <nl> - help = ' Record samll topics only . ' ) <nl> + help = ' Record small topics only . ' ) <nl> self . parser . add_argument ( ' - - split_duration ' , default = " 1m " , <nl> help = ' Duration to split bags , will be applied ' <nl> ' as parameter to " rosbag record - - duration " . ' ) <nl> def start ( self ) : <nl> # Use the best disk , or fallback ' / apollo ' if none available . <nl> disk_to_use = disks [ 0 ] [ ' mountpoint ' ] if len ( disks ) > 0 else ' / apollo ' <nl> <nl> - topics = list ( SMALL_TOPICS ) <nl> - if record_all : <nl> - topics . extend ( LARGE_TOPICS ) <nl> - if self . args . additional_topics : <nl> - topics . extend ( self . args . additional_topics ) <nl> - self . record_task ( disk_to_use , SMALL_TOPICS , True ) <nl> - self . record_task ( disk_to_use , topics ) <nl> + self . record_task ( disk_to_use , record_all ) <nl> <nl> def stop ( self ) : <nl> " " " Stop recording . " " " <nl> shell_cmd ( ' pkill - - signal { } - f " cyber_recorder record " ' . format ( <nl> self . args . stop_signal ) ) <nl> <nl> - def record_task ( self , disk , topics , is_small_topic = False ) : <nl> + def record_task ( self , disk , record_all ) : <nl> " " " Record tasks into the < disk > / data / bag / < task_id > directory . " " " <nl> task_id = datetime . datetime . now ( ) . strftime ( ' % Y - % m - % d - % H - % M - % S ' ) <nl> - if is_small_topic : <nl> + if not record_all : <nl> task_id + = " _s " <nl> task_dir = os . path . join ( disk , ' data / bag ' , task_id ) <nl> print ( ' Recording bag to { } ' . format ( task_dir ) ) <nl> <nl> + topics_str = " - - all " <nl> + <nl> log_file = ' / apollo / data / log / apollo_record . out ' <nl> - if is_small_topic : <nl> + if not record_all : <nl> log_file + = " _s " <nl> - topics_str = ' - c ' . join ( topics ) <nl> + topics_str + = " - k { } " . format ( ' - k ' . join ( list ( LARGE_TOPICS ) ) ) <nl> <nl> if not os . path . exists ( task_dir ) : <nl> os . makedirs ( task_dir ) <nl> def record_task ( self , disk , topics , is_small_topic = False ) : <nl> cd " { } " <nl> source / apollo / scripts / apollo_base . sh <nl> source / apollo / cyber / setup . bash <nl> - nohup cyber_recorder record - c { } > { } 2 > & 1 & <nl> + nohup cyber_recorder record { } > { } 2 > & 1 & <nl> ' ' ' . format ( task_dir , topics_str , log_file ) <nl> shell_cmd ( cmd ) <nl> <nl> | record_bag . py : use blacklist for large topics | ApolloAuto/apollo | 384fb9f3df0bf33bef6c3ea87cca55b4aee6f936 | 2020-10-29T01:11:13Z |
mmm a / js / apps / system / _admin / aardvark / APP / frontend / js / views / loginView . js <nl> ppp b / js / apps / system / _admin / aardvark / APP / frontend / js / views / loginView . js <nl> <nl> $ ( ' . login - window # databases ' ) . show ( ) ; <nl> <nl> $ . ajax ( url ) . success ( function ( permissions ) { <nl> - / / enable db select and login button <nl> - $ ( ' # loginDatabase ' ) . html ( ' ' ) ; <nl> - / / fill select with allowed dbs <nl> - _ . each ( permissions . result , function ( rule , db ) { <nl> - if ( errCallback ) { <nl> - $ ( ' # loginDatabase ' ) . append ( <nl> - ' < option > ' + db + ' < / option > ' <nl> - ) ; <nl> - } else { <nl> - $ ( ' # loginDatabase ' ) . append ( <nl> - ' < option > ' + rule + ' < / option > ' <nl> - ) ; <nl> - } <nl> - } ) ; <nl> + var successFunc = function ( availableDbs ) { <nl> + / / enable db select and login button <nl> + $ ( ' # loginDatabase ' ) . html ( ' ' ) ; <nl> + / / fill select with allowed dbs <nl> + _ . each ( permissions . result , function ( rule , db ) { <nl> + if ( errCallback ) { <nl> + if ( availableDbs ) { <nl> + if ( availableDbs . indexOf ( db ) > - 1 ) { <nl> + $ ( ' # loginDatabase ' ) . append ( <nl> + ' < option > ' + db + ' < / option > ' <nl> + ) ; <nl> + } <nl> + } else { <nl> + $ ( ' # loginDatabase ' ) . append ( <nl> + ' < option > ' + db + ' < / option > ' <nl> + ) ; <nl> + } <nl> + } else { <nl> + if ( availableDbs ) { <nl> + if ( availableDbs . indexOf ( db ) > - 1 ) { <nl> + $ ( ' # loginDatabase ' ) . append ( <nl> + ' < option > ' + rule + ' < / option > ' <nl> + ) ; <nl> + } <nl> + } else { <nl> + $ ( ' # loginDatabase ' ) . append ( <nl> + ' < option > ' + rule + ' < / option > ' <nl> + ) ; <nl> + } <nl> + } <nl> + } ) ; <nl> + <nl> + self . renderDBS ( ) ; <nl> + } ; <nl> <nl> - self . renderDBS ( ) ; <nl> + / / fetch available dbs <nl> + var availableDbs ; <nl> + try { <nl> + $ . ajax ( arangoHelper . databaseUrl ( ' / _api / database / user ' ) ) . success ( function ( dbs ) { <nl> + availableDbs = dbs . result ; <nl> + successFunc ( availableDbs ) ; <nl> + } ) ; <nl> + } catch ( ignore ) { <nl> + console . log ( ignore ) ; <nl> + successFunc ( ) ; <nl> + } <nl> } ) . error ( function ( ) { <nl> if ( errCallback ) { <nl> errCallback ( ) ; <nl> <nl> / / enable db select and login button <nl> $ ( ' # loginDatabase ' ) . html ( ' ' ) ; <nl> <nl> - / / fill select with allowed dbs <nl> - _ . each ( permissions . result , function ( db , key ) { <nl> - $ ( ' # loginDatabase ' ) . append ( <nl> - ' < option > ' + key + ' < / option > ' <nl> - ) ; <nl> - } ) ; <nl> + var successFunc = function ( availableDbs ) { <nl> + if ( availableDbs ) { <nl> + _ . each ( permissions . result , function ( db , key ) { <nl> + if ( availableDbs . indexOf ( key ) > - 1 ) { <nl> + $ ( ' # loginDatabase ' ) . append ( <nl> + ' < option > ' + key + ' < / option > ' <nl> + ) ; <nl> + } <nl> + } ) ; <nl> + } else { <nl> + / / fill select with allowed dbs <nl> + _ . each ( permissions . result , function ( db , key ) { <nl> + $ ( ' # loginDatabase ' ) . append ( <nl> + ' < option > ' + key + ' < / option > ' <nl> + ) ; <nl> + } ) ; <nl> + } <nl> <nl> - self . renderDBS ( ) ; <nl> + self . renderDBS ( ) ; <nl> + } ; <nl> + <nl> + / / fetch available dbs <nl> + try { <nl> + $ . ajax ( arangoHelper . databaseUrl ( ' / _api / database / user ' ) ) . success ( function ( dbs ) { <nl> + successFunc ( dbs . result ) ; <nl> + } ) ; <nl> + } catch ( ignore ) { <nl> + successFunc ( ) ; <nl> + } <nl> } ) . error ( function ( ) { <nl> $ ( ' . wrong - credentials ' ) . show ( ) ; <nl> } ) ; <nl> | ui : fixed login windows showing wrong available dbs | arangodb/arangodb | 31e4aa1a7d2a78f2d09ff61b38718969b15784d1 | 2017-04-25T07:27:36Z |
mmm a / lib / Sema / CSGen . cpp <nl> ppp b / lib / Sema / CSGen . cpp <nl> namespace { <nl> return false ; <nl> <nl> / / Figure out the parameter type . <nl> - if ( value - > getDeclContext ( ) - > isTypeContext ( ) ) { <nl> + if ( value - > getDeclContext ( ) - > isTypeContext ( ) & & <nl> + isa < FuncDecl > ( value ) & & ! value - > isStatic ( ) ) { <nl> fnTy = fnTy - > getResult ( ) - > castTo < AnyFunctionType > ( ) ; <nl> } <nl> <nl> mmm a / test / Constraints / overload . swift <nl> ppp b / test / Constraints / overload . swift <nl> func availTest ( x : Any ) { markUsed ( " this one " ) } <nl> func doAvailTest ( x : Int ) { <nl> availTest ( x ) <nl> } <nl> + <nl> + / / rdar : / / problem / 20886179 <nl> + func test20886179 ( handlers : [ ( Int ) - > Void ] , buttonIndex : Int ) { <nl> + handlers [ buttonIndex ] ( buttonIndex ) <nl> + } <nl> | Don ' t assume that a ValueDecl in a type DeclContext with function type | apple/swift | fd5812be506fa3e952ae4dfa2541583692b868a1 | 2015-06-26T05:39:38Z |
mmm a / src / idl_gen_php . cpp <nl> ppp b / src / idl_gen_php . cpp <nl> namespace php { <nl> it ! = parser_ . structs_ . vec . end ( ) ; + + it ) { <nl> auto & struct_def = * * it ; <nl> std : : string declcode ; <nl> - GenStruct ( parser_ , struct_def , & declcode ) ; <nl> + GenStruct ( struct_def , & declcode ) ; <nl> if ( ! SaveType ( struct_def , declcode , true ) ) return false ; <nl> } <nl> return true ; <nl> namespace php { <nl> <nl> / / Ensure that a type is prefixed with its namespace whenever it is used <nl> / / outside of its namespace . <nl> - static std : : string WrapInNameSpace ( const Namespace * ns , <nl> - const std : : string & name ) { <nl> + std : : string WrapInNameSpace ( const Namespace * ns , const std : : string & name ) { <nl> std : : string qualified_name = " \ \ " ; <nl> for ( auto it = ns - > components . begin ( ) ; <nl> it ! = ns - > components . end ( ) ; + + it ) { <nl> namespace php { <nl> return qualified_name + name ; <nl> } <nl> <nl> - static std : : string WrapInNameSpace ( const Definition & def ) { <nl> + std : : string WrapInNameSpace ( const Definition & def ) { <nl> return WrapInNameSpace ( def . defined_namespace , def . name ) ; <nl> } <nl> <nl> namespace php { <nl> } <nl> <nl> / / Get the value of a table ' s scalar . <nl> - static void GetScalarFieldOfTable ( const FieldDef & field , <nl> - std : : string * code_ptr ) { <nl> + void GetScalarFieldOfTable ( const FieldDef & field , std : : string * code_ptr ) { <nl> std : : string & code = * code_ptr ; <nl> std : : string getter = GenGetter ( field . value . type ) ; <nl> <nl> namespace php { <nl> <nl> / / Get a struct by initializing an existing struct . <nl> / / Specific to Struct . <nl> - static void GetStructFieldOfStruct ( const FieldDef & field , <nl> - std : : string * code_ptr ) { <nl> + void GetStructFieldOfStruct ( const FieldDef & field , std : : string * code_ptr ) { <nl> std : : string & code = * code_ptr ; <nl> <nl> code + = Indent + " / * * \ n " ; <nl> namespace php { <nl> <nl> / / Get a struct by initializing an existing struct . <nl> / / Specific to Table . <nl> - static void GetStructFieldOfTable ( const FieldDef & field , <nl> - std : : string * code_ptr ) { <nl> + void GetStructFieldOfTable ( const FieldDef & field , std : : string * code_ptr ) { <nl> std : : string & code = * code_ptr ; <nl> <nl> code + = Indent + " public function get " ; <nl> namespace php { <nl> } <nl> <nl> / / Get the value of a string . <nl> - static void GetStringField ( const FieldDef & field , <nl> - std : : string * code_ptr ) { <nl> + void GetStringField ( const FieldDef & field , std : : string * code_ptr ) { <nl> std : : string & code = * code_ptr ; <nl> code + = Indent + " public function get " ; <nl> code + = MakeCamel ( field . name ) ; <nl> namespace php { <nl> } <nl> <nl> / / Get the value of a union from an object . <nl> - static void GetUnionField ( const FieldDef & field , <nl> - std : : string * code_ptr ) { <nl> + void GetUnionField ( const FieldDef & field , std : : string * code_ptr ) { <nl> std : : string & code = * code_ptr ; <nl> <nl> code + = Indent + " / * * \ n " ; <nl> namespace php { <nl> } <nl> <nl> / / Get the value of a vector ' s struct member . <nl> - static void GetMemberOfVectorOfStruct ( const StructDef & struct_def , <nl> - const FieldDef & field , <nl> - std : : string * code_ptr ) { <nl> + void GetMemberOfVectorOfStruct ( const StructDef & struct_def , <nl> + const FieldDef & field , std : : string * code_ptr ) { <nl> std : : string & code = * code_ptr ; <nl> auto vectortype = field . value . type . VectorType ( ) ; <nl> <nl> namespace php { <nl> <nl> / / Get the value of a vector ' s non - struct member . Uses a named return <nl> / / argument to conveniently set the zero value for the result . <nl> - static void GetMemberOfVectorOfNonStruct ( const FieldDef & field , <nl> + void GetMemberOfVectorOfNonStruct ( const FieldDef & field , <nl> std : : string * code_ptr ) { <nl> std : : string & code = * code_ptr ; <nl> auto vectortype = field . value . type . VectorType ( ) ; <nl> namespace php { <nl> } <nl> <nl> / / Get the offset of the end of a table . <nl> - static void GetEndOffsetOnTable ( const Parser & parser , <nl> - const StructDef & struct_def , <nl> - std : : string * code_ptr ) { <nl> + void GetEndOffsetOnTable ( const StructDef & struct_def , std : : string * code_ptr ) { <nl> std : : string & code = * code_ptr ; <nl> <nl> <nl> namespace php { <nl> code + = Indent + Indent + " return $ o ; \ n " ; <nl> code + = Indent + " } \ n " ; <nl> <nl> - if ( parser . root_struct_def_ = = & struct_def ) { <nl> + if ( parser_ . root_struct_def_ = = & struct_def ) { <nl> code + = " \ n " ; <nl> code + = Indent + " public static function finish " ; <nl> code + = struct_def . name ; <nl> namespace php { <nl> code + = Indent + " { \ n " ; <nl> code + = Indent + Indent + " $ builder - > finish ( $ offset " ; <nl> <nl> - if ( parser . file_identifier_ . length ( ) ) <nl> - code + = " , \ " " + parser . file_identifier_ + " \ " " ; <nl> + if ( parser_ . file_identifier_ . length ( ) ) <nl> + code + = " , \ " " + parser_ . file_identifier_ + " \ " " ; <nl> code + = " ) ; \ n " ; <nl> code + = Indent + " } \ n " ; <nl> } <nl> } <nl> <nl> / / Generate a struct field , conditioned on its child type ( s ) . <nl> - static void GenStructAccessor ( const StructDef & struct_def , <nl> - const FieldDef & field , <nl> + void GenStructAccessor ( const StructDef & struct_def , const FieldDef & field , <nl> std : : string * code_ptr ) { <nl> GenComment ( field . doc_comment , code_ptr , nullptr ) ; <nl> <nl> namespace php { <nl> } <nl> <nl> / / Generate table constructors , conditioned on its members ' types . <nl> - static void GenTableBuilders ( const Parser & parser , <nl> - const StructDef & struct_def , <nl> - std : : string * code_ptr ) { <nl> + void GenTableBuilders ( const StructDef & struct_def , std : : string * code_ptr ) { <nl> GetStartOfTable ( struct_def , code_ptr ) ; <nl> <nl> for ( auto it = struct_def . fields . vec . begin ( ) ; <nl> namespace php { <nl> } <nl> } <nl> <nl> - GetEndOffsetOnTable ( parser , struct_def , code_ptr ) ; <nl> + GetEndOffsetOnTable ( struct_def , code_ptr ) ; <nl> } <nl> <nl> / / Generate struct or table methods . <nl> - static void GenStruct ( const Parser & parser , const StructDef & struct_def , <nl> + void GenStruct ( const StructDef & struct_def , <nl> std : : string * code_ptr ) { <nl> if ( struct_def . generated ) return ; <nl> <nl> namespace php { <nl> <nl> std : : string & code = * code_ptr ; <nl> if ( ! struct_def . fixed ) { <nl> - if ( parser . file_identifier_ . length ( ) ) { <nl> + if ( parser_ . file_identifier_ . length ( ) ) { <nl> / / Return the identifier <nl> code + = Indent + " public static function " + struct_def . name ; <nl> code + = " Identifier ( ) \ n " ; <nl> code + = Indent + " { \ n " ; <nl> code + = Indent + Indent + " return \ " " ; <nl> - code + = parser . file_identifier_ + " \ " ; \ n " ; <nl> + code + = parser_ . file_identifier_ + " \ " ; \ n " ; <nl> code + = Indent + " } \ n \ n " ; <nl> <nl> / / Check if a buffer has the identifier . <nl> namespace php { <nl> code + = Indent + " } \ n \ n " ; <nl> } <nl> <nl> - if ( parser . file_extension_ . length ( ) ) { <nl> + if ( parser_ . file_extension_ . length ( ) ) { <nl> / / Return the extension <nl> code + = Indent + " public static function " + struct_def . name ; <nl> code + = " Extension ( ) \ n " ; <nl> code + = Indent + " { \ n " ; <nl> - code + = Indent + Indent + " return \ " " + parser . file_extension_ ; <nl> + code + = Indent + Indent + " return \ " " + parser_ . file_extension_ ; <nl> code + = " \ " ; \ n " ; <nl> code + = Indent + " } \ n \ n " ; <nl> } <nl> namespace php { <nl> GenStructBuilder ( struct_def , code_ptr ) ; <nl> } else { <nl> / / Create a set of functions that allow table construction . <nl> - GenTableBuilders ( parser , struct_def , code_ptr ) ; <nl> + GenTableBuilders ( struct_def , code_ptr ) ; <nl> } <nl> EndClass ( code_ptr ) ; <nl> } <nl> namespace php { <nl> return ctypename [ type . base_type ] ; <nl> } <nl> <nl> - static std : : string GenDefaultValue ( const Value & value ) { <nl> + std : : string GenDefaultValue ( const Value & value ) { <nl> if ( value . type . enum_def ) { <nl> if ( auto val = value . type . enum_def - > ReverseLookup ( <nl> atoi ( value . constant . c_str ( ) ) , false ) ) { <nl> | php : removed parser from method signatures | google/flatbuffers | cb6cc3dfb6bac954d2bd29bdccccb9ed10bf30b9 | 2016-06-22T22:36:33Z |
mmm a / tools / provision . ps1 <nl> ppp b / tools / provision . ps1 <nl> function Install - ThirdParty { <nl> # List of our third party packages , hosted in our AWS S3 bucket <nl> $ packages = @ ( <nl> " aws - sdk - cpp . 1 . 0 . 107 - r1 " , <nl> - " boost - msvc14 . 1 . 63 . 0 - r2 " , <nl> + " boost - msvc14 . 1 . 65 . 0 " , <nl> " bzip2 . 1 . 0 . 6 " , <nl> " cpp - netlib . 0 . 12 . 0 - r4 " , <nl> " doxygen . 1 . 8 . 11 " , <nl> function Main { <nl> } <nl> $ out = Install - ChocoPackage ' cppcheck ' <nl> $ out = Install - ChocoPackage ' 7zip . commandline ' <nl> + $ out = Install - ChocoPackage ' vswhere ' <nl> $ out = Install - ChocoPackage ' cmake . portable ' ' 3 . 6 . 1 ' <nl> $ chocoParams = @ ( " - - params = ` " / InstallDir : C : \ tools \ python2 ` " " ) <nl> $ out = Install - ChocoPackage ' python2 ' ' ' $ { chocoParams } <nl> mmm a / tools / provision / chocolatey / boost - msvc14 . ps1 <nl> ppp b / tools / provision / chocolatey / boost - msvc14 . ps1 <nl> <nl> # $ version - The version of the software package to build <nl> # $ chocoVersion - The chocolatey package version , used for incremental bumps <nl> # without changing the version of the software package <nl> - $ version = ' 1 . 63 . 0 ' <nl> - $ chocoVersion = ' 1 . 63 . 0 - r2 ' <nl> + $ version = ' 1 . 65 . 0 ' <nl> + $ chocoVersion = ' 1 . 65 . 0 ' <nl> + $ versionUnderscores = $ version - replace ' \ . ' , ' _ ' <nl> $ packageName = ' boost - msvc14 ' <nl> - $ projectSource = ' http : / / www . boost . org / users / history / version_1_63_0 . html ' <nl> - $ packageSourceUrl = ' http : / / www . boost . org / users / history / version_1_63_0 . html ' <nl> + $ projectSource = ` <nl> + " http : / / www . boost . org / users / history / version_ $ versionUnderscores . html " <nl> + $ packageSourceUrl = ` <nl> + " http : / / www . boost . org / users / history / version_ $ versionUnderscores . html " <nl> $ authors = ' boost - msvc14 ' <nl> $ owners = ' boost - msvc14 ' <nl> $ copyright = ' http : / / www . boost . org / users / license . html ' <nl> $ license = ' http : / / www . boost . org / users / license . html ' <nl> - $ versionUnderscores = $ version - replace ' \ . ' , ' _ ' <nl> $ timestamp = [ int ] [ double ] : : Parse ( ( Get - Date - UFormat % s ) ) <nl> $ url = " http : / / downloads . sourceforge . net / project / boost / boost / " + <nl> " $ version / boost_ $ versionUnderscores . 7z ? r = & ts = $ timestamp " + <nl> " & use_mirror = pilotfiber " <nl> $ numJobs = 2 <nl> <nl> + $ currentLoc = Get - Location <nl> + <nl> # Invoke our utilities file <nl> . " $ ( Split - Path - Parent $ MyInvocation . MyCommand . Definition ) \ osquery_utils . ps1 " <nl> <nl> if ( - not ( Test - Path $ sourceDir ) ) { <nl> Set - Location $ sourceDir <nl> <nl> # Build the b2 binary <nl> + if ( $ ( Get - Command ' vswhere ' - ErrorAction SilentlyContinue ) - eq $ null ) { <nl> + Write - Host ' [ - ] Did not find vswhere in PATH . ' - foregroundcolor red <nl> + exit <nl> + } <nl> $ b2 = Join - Path $ ( Get - Location ) ' b2 . exe ' <nl> if ( - not ( Test - Path $ b2 ) ) { <nl> + Write - Debug ' [ * ] Boost build engine not found , building ' <nl> Invoke - BatchFile ' . / bootstrap . bat ' <nl> } <nl> <nl> choco pack <nl> Write - Host " [ * ] Build took $ ( $ sw . ElapsedMilliseconds ) ms " ` <nl> - ForegroundColor DarkGreen <nl> if ( Test - Path " $ packageName . $ chocoVersion . nupkg " ) { <nl> + $ package = " $ ( Get - Location ) \ $ packageName . $ chocoVersion . nupkg " <nl> Write - Host ` <nl> - " [ + ] Finished building $ packageName v $ chocoVersion . " ` <nl> - - ForegroundColor Green <nl> + " [ + ] Finished building . Package written to $ package " - ForegroundColor Green <nl> } <nl> else { <nl> Write - Host ` <nl> " [ - ] Failed to build $ packageName v $ chocoVersion . " ` <nl> - ForegroundColor Red <nl> } <nl> + Set - Location $ currentLoc <nl> | deps : bumping boost for Windows to 1 . 65 . 0 ( ) | osquery/osquery | 6445e987c133eb09f7db976168d0f518185c4d6e | 2017-08-25T14:43:38Z |
mmm a / include / swift / AST / Types . h <nl> ppp b / include / swift / AST / Types . h <nl> class ParameterTypeFlags { <nl> : value - ParameterTypeFlags : : Shared ) ; <nl> } <nl> <nl> - ParameterTypeFlags withAutoClosure ( bool isAutoClosure ) const { <nl> - return ParameterTypeFlags ( isAutoClosure <nl> - ? value | ParameterTypeFlags : : AutoClosure <nl> - : value - ParameterTypeFlags : : AutoClosure ) ; <nl> - } <nl> - <nl> bool operator = = ( const ParameterTypeFlags & other ) const { <nl> return value . toRaw ( ) = = other . value . toRaw ( ) ; <nl> } <nl> <nl> uint8_t toRaw ( ) const { return value . toRaw ( ) ; } <nl> - <nl> - static ParameterTypeFlags fromRaw ( uint8_t value ) { <nl> - return ParameterTypeFlags ( ) <nl> - . withVariadic ( value & Variadic ) <nl> - . withAutoClosure ( value & AutoClosure ) <nl> - . withEscaping ( value & Escaping ) <nl> - . withInOut ( value & InOut ) <nl> - . withShared ( value & Shared ) ; <nl> - } <nl> } ; <nl> <nl> / / / ParenType - A paren type is a type that ' s been written in parentheses . <nl> mmm a / include / swift / Remote / MetadataReader . h <nl> ppp b / include / swift / Remote / MetadataReader . h <nl> template < typename BuiltType > class FunctionParam { <nl> void setVariadic ( ) { Flags = Flags . withVariadic ( true ) ; } <nl> void setShared ( ) { Flags = Flags . withShared ( true ) ; } <nl> void setInOut ( ) { Flags = Flags . withInOut ( true ) ; } <nl> - void setFlags ( ParameterTypeFlags flags ) { Flags = flags ; } ; <nl> <nl> FunctionParam withLabel ( StringRef label ) const { <nl> return FunctionParam ( label , Type , Flags ) ; <nl> class MetadataReader { <nl> sizeof ( TargetFunctionTypeMetadata < Runtime > ) ; <nl> for ( StoredPointer i = 0 ; i < Function - > getNumArguments ( ) ; + + i , <nl> ArgumentAddress + = sizeof ( StoredPointer ) ) { <nl> - StoredPointer ParameterAddress ; <nl> + StoredPointer FlaggedArgumentAddress ; <nl> if ( ! Reader - > readInteger ( RemoteAddress ( ArgumentAddress ) , <nl> - & ParameterAddress ) ) <nl> + & FlaggedArgumentAddress ) ) <nl> return BuiltType ( ) ; <nl> <nl> FunctionParam < BuiltType > Param ; <nl> - if ( auto ParamTypeRef = readTypeFromMetadata ( ParameterAddress ) ) { <nl> - auto ParameterFlags = Function - > getParameterFlags ( i ) ; <nl> <nl> + / / TODO : Use target - agnostic FlaggedPointer to mask this ! <nl> + const auto InOutMask = ( StoredPointer ) 1 ; <nl> + / / FIXME : Add import parameter related flags from metadata <nl> + if ( ( FlaggedArgumentAddress & InOutMask ) ! = 0 ) <nl> + Param . setInOut ( ) ; <nl> + <nl> + FlaggedArgumentAddress & = ~ InOutMask ; <nl> + if ( auto ParamTypeRef = readTypeFromMetadata ( FlaggedArgumentAddress ) ) { <nl> Param . setType ( ParamTypeRef ) ; <nl> - Param . setFlags ( ParameterTypeFlags : : fromRaw ( ParameterFlags ) ) ; <nl> Parameters . push_back ( std : : move ( Param ) ) ; <nl> } else { <nl> return BuiltType ( ) ; <nl> mmm a / include / swift / Runtime / Metadata . h <nl> ppp b / include / swift / Runtime / Metadata . h <nl> using EnumMetadata = TargetEnumMetadata < InProcess > ; <nl> template < typename Runtime > <nl> struct TargetFunctionTypeMetadata : public TargetMetadata < Runtime > { <nl> using StoredSize = typename Runtime : : StoredSize ; <nl> - using Argument = const TargetMetadata < Runtime > * ; <nl> + <nl> + / / TODO : Make this target agnostic <nl> + using Argument = FlaggedPointer < const TargetMetadata < Runtime > * , 0 > ; <nl> <nl> TargetFunctionTypeFlags < StoredSize > Flags ; <nl> <nl> struct TargetFunctionTypeMetadata : public TargetMetadata < Runtime > { <nl> TargetPointer < Runtime , const Argument > getArguments ( ) const { <nl> return reinterpret_cast < TargetPointer < Runtime , const Argument > > ( this + 1 ) ; <nl> } <nl> - <nl> - uint32_t getParameterFlags ( unsigned index ) const { <nl> - auto numParams = getNumArguments ( ) ; <nl> - assert ( index < numParams ) ; <nl> - auto * flags = reinterpret_cast < const uint32_t * > ( this + 1 + <nl> - numParams * sizeof ( Argument ) ) ; <nl> - return flags [ index ] ; <nl> - } <nl> - <nl> + <nl> StoredSize getNumArguments ( ) const { <nl> return Flags . getNumArguments ( ) ; <nl> } <nl> swift_getFunctionTypeMetadata1 ( FunctionTypeFlags flags , <nl> const void * arg0 , <nl> const Metadata * resultMetadata ) ; <nl> <nl> - SWIFT_RUNTIME_EXPORT <nl> - const FunctionTypeMetadata * <nl> - swift_getFunctionTypeMetadata1WithFlags ( FunctionTypeFlags flags , <nl> - const void * arg0 , <nl> - const uint32_t * paramFlags , <nl> - const Metadata * resultMetadata ) ; <nl> - <nl> SWIFT_RUNTIME_EXPORT <nl> const FunctionTypeMetadata * <nl> swift_getFunctionTypeMetadata2 ( FunctionTypeFlags flags , <nl> swift_getFunctionTypeMetadata2 ( FunctionTypeFlags flags , <nl> <nl> SWIFT_RUNTIME_EXPORT <nl> const FunctionTypeMetadata * <nl> - swift_getFunctionTypeMetadata2WithFlags ( FunctionTypeFlags flags , <nl> - const void * arg0 , <nl> - const void * arg1 , <nl> - const uint32_t * paramFlags , <nl> - const Metadata * resultMetadata ) ; <nl> - <nl> - SWIFT_RUNTIME_EXPORT <nl> - const FunctionTypeMetadata * swift_getFunctionTypeMetadata3 ( <nl> - FunctionTypeFlags flags , <nl> - const void * arg0 , <nl> - const void * arg1 , <nl> - const void * arg2 , <nl> - const Metadata * resultMetadata ) ; <nl> - <nl> - SWIFT_RUNTIME_EXPORT <nl> - const FunctionTypeMetadata * swift_getFunctionTypeMetadata3WithFlags ( <nl> - FunctionTypeFlags flags , <nl> - const void * arg0 , <nl> - const void * arg1 , <nl> - const void * arg2 , <nl> - const uint32_t * paramFlags , <nl> - const Metadata * resultMetadata ) ; <nl> + swift_getFunctionTypeMetadata3 ( FunctionTypeFlags flags , <nl> + const void * arg0 , <nl> + const void * arg1 , <nl> + const void * arg2 , <nl> + const Metadata * resultMetadata ) ; <nl> <nl> / / / \ brief Fetch a uniqued metadata for a thin function type . <nl> SWIFT_RUNTIME_EXPORT <nl> mmm a / include / swift / Runtime / RuntimeFunctions . def <nl> ppp b / include / swift / Runtime / RuntimeFunctions . def <nl> FUNCTION ( GetFunctionMetadata , swift_getFunctionTypeMetadata , DefaultCC , <nl> ARGS ( Int8PtrTy - > getPointerTo ( 0 ) ) , <nl> ATTRS ( NoUnwind , ReadNone ) ) <nl> <nl> - / / Metadata * swift_getFunctionTypeMetadata1 ( unsigned long flags , <nl> - / / const void * arg0 , <nl> - / / const Metadata * resultMetadata ) ; <nl> + / / Metadata * swift_getFunctionTypeMetadata1 ( unsigned long flags , const void * arg0 , const Metadata * resultMetadata ) ; <nl> FUNCTION ( GetFunctionMetadata1 , swift_getFunctionTypeMetadata1 , DefaultCC , <nl> - RETURNS ( TypeMetadataPtrTy ) , <nl> - ARGS ( SizeTy , Int8PtrTy , TypeMetadataPtrTy ) , <nl> - ATTRS ( NoUnwind , ReadNone ) ) <nl> - <nl> - / / Metadata * swift_getFunctionTypeMetadata1WithFlags ( unsigned long flags , <nl> - / / const void * arg0 , <nl> - / / const uint32_t * paramFlags , <nl> - / / const Metadata * resultMetadata ) ; <nl> - FUNCTION ( GetFunctionMetadata1WithFlags , swift_getFunctionTypeMetadata1WithFlags , <nl> - DefaultCC , <nl> RETURNS ( TypeMetadataPtrTy ) , <nl> - ARGS ( SizeTy , Int8PtrTy , Int32Ty - > getPointerTo ( ) , TypeMetadataPtrTy ) , <nl> + ARGS ( SizeTy , Int8PtrTy , TypeMetadataPtrTy ) , <nl> ATTRS ( NoUnwind , ReadNone ) ) <nl> <nl> - / / Metadata * swift_getFunctionTypeMetadata2 ( unsigned long flags , <nl> - / / const void * arg0 , <nl> - / / const void * arg1 , <nl> - / / const Metadata * resultMetadata ) ; <nl> - FUNCTION ( GetFunctionMetadata2 , swift_getFunctionTypeMetadata2 , <nl> - DefaultCC , <nl> - RETURNS ( TypeMetadataPtrTy ) , <nl> - ARGS ( SizeTy , Int8PtrTy , Int8PtrTy , TypeMetadataPtrTy ) , <nl> - ATTRS ( NoUnwind , ReadNone ) ) <nl> - <nl> - / / Metadata * swift_getFunctionTypeMetadata2WithFlags ( unsigned long flags , <nl> - / / const void * arg0 , <nl> - / / const void * arg1 , <nl> - / / const uint32_t * paramFlags , <nl> - / / const Metadata * resultMetadata ) ; <nl> - FUNCTION ( GetFunctionMetadata2WithFlags , swift_getFunctionTypeMetadata2WithFlags , <nl> - DefaultCC , <nl> + / / Metadata * swift_getFunctionTypeMetadata2 ( unsigned long flags , const void * arg0 , const void * arg1 , const Metadata * resultMetadata ) ; <nl> + FUNCTION ( GetFunctionMetadata2 , swift_getFunctionTypeMetadata2 , DefaultCC , <nl> RETURNS ( TypeMetadataPtrTy ) , <nl> - ARGS ( SizeTy , Int8PtrTy , Int8PtrTy , Int32Ty - > getPointerTo ( ) , TypeMetadataPtrTy ) , <nl> + ARGS ( SizeTy , Int8PtrTy , Int8PtrTy , TypeMetadataPtrTy ) , <nl> ATTRS ( NoUnwind , ReadNone ) ) <nl> <nl> - / / Metadata * swift_getFunctionTypeMetadata3 ( unsigned long flags , <nl> - / / const void * arg0 , <nl> - / / const void * arg1 , <nl> - / / const void * arg2 , <nl> - / / const Metadata * resultMetadata ) ; <nl> - FUNCTION ( GetFunctionMetadata3 , swift_getFunctionTypeMetadata3 , <nl> - DefaultCC , <nl> - RETURNS ( TypeMetadataPtrTy ) , <nl> - ARGS ( SizeTy , Int8PtrTy , Int8PtrTy , Int8PtrTy , TypeMetadataPtrTy ) , <nl> - ATTRS ( NoUnwind , ReadNone ) ) <nl> - <nl> - / / Metadata * swift_getFunctionTypeMetadata3WithFlags ( unsigned long flags , <nl> - / / const void * arg0 , <nl> - / / const void * arg1 , <nl> - / / const void * arg2 , <nl> - / / const uint32_t * paramFlags , <nl> - / / const Metadata * resultMetadata ) ; <nl> - FUNCTION ( GetFunctionMetadata3WithFlags , swift_getFunctionTypeMetadata3WithFlags , <nl> - DefaultCC , <nl> + / / Metadata * swift_getFunctionTypeMetadata3 ( unsigned long flags , const void * arg0 , const void * arg1 , const void * arg2 , const Metadata * resultMetadata ) ; <nl> + FUNCTION ( GetFunctionMetadata3 , swift_getFunctionTypeMetadata3 , DefaultCC , <nl> RETURNS ( TypeMetadataPtrTy ) , <nl> - ARGS ( SizeTy , Int8PtrTy , Int8PtrTy , Int8PtrTy , Int32Ty - > getPointerTo ( ) , TypeMetadataPtrTy ) , <nl> + ARGS ( SizeTy , Int8PtrTy , Int8PtrTy , Int8PtrTy , TypeMetadataPtrTy ) , <nl> ATTRS ( NoUnwind , ReadNone ) ) <nl> <nl> / / Metadata * swift_getForeignTypeMetadata ( Metadata * nonUnique ) ; <nl> mmm a / lib / IRGen / GenMeta . cpp <nl> ppp b / lib / IRGen / GenMeta . cpp <nl> namespace { <nl> " metadata ref for generic function type " ) ; <nl> return llvm : : UndefValue : : get ( IGF . IGM . TypeMetadataPtrTy ) ; <nl> } <nl> + <nl> + llvm : : Value * extractAndMarkResultType ( CanFunctionType type ) { <nl> + / / If the function type throws , set the lower bit of the return type <nl> + / / address , so that we can carry this information over to the function <nl> + / / type metadata . <nl> + auto metadata = IGF . emitTypeMetadataRef ( type - > getResult ( ) - > <nl> + getCanonicalType ( ) ) ; <nl> + return metadata ; <nl> + } <nl> <nl> - llvm : : Value * getFunctionParameterRef ( AnyFunctionType : : CanParam param ) { <nl> + llvm : : Value * extractAndMarkInOut ( AnyFunctionType : : CanParam param ) { <nl> + / / If the type is inout , get the metadata for its inner object type <nl> + / / instead , and then set the lowest bit to help the runtime unique <nl> + / / the metadata type for this function . <nl> auto type = param . getType ( ) ; <nl> - if ( param . getParameterFlags ( ) . isInOut ( ) ) <nl> - type = type - > getInOutObjectType ( ) - > getCanonicalType ( ) ; <nl> - <nl> + if ( param . getParameterFlags ( ) . isInOut ( ) ) { <nl> + auto objectType = type - > getInOutObjectType ( ) - > getCanonicalType ( ) ; <nl> + auto metadata = IGF . emitTypeMetadataRef ( objectType ) ; <nl> + auto metadataInt = IGF . Builder . CreatePtrToInt ( metadata , IGF . IGM . SizeTy ) ; <nl> + auto inoutFlag = llvm : : ConstantInt : : get ( IGF . IGM . SizeTy , 1 ) ; <nl> + auto marked = IGF . Builder . CreateOr ( metadataInt , inoutFlag ) ; <nl> + return IGF . Builder . CreateIntToPtr ( marked , IGF . IGM . Int8PtrTy ) ; <nl> + } <nl> + <nl> auto metadata = IGF . emitTypeMetadataRef ( type ) ; <nl> return IGF . Builder . CreateBitCast ( metadata , IGF . IGM . Int8PtrTy ) ; <nl> } <nl> namespace { <nl> if ( auto metatype = tryGetLocal ( type ) ) <nl> return metatype ; <nl> <nl> - auto resultMetadata = <nl> - IGF . emitTypeMetadataRef ( type - > getResult ( ) - > getCanonicalType ( ) ) ; <nl> + auto resultMetadata = extractAndMarkResultType ( type ) ; <nl> <nl> auto params = type . getParams ( ) ; <nl> auto numParams = params . size ( ) ; <nl> namespace { <nl> auto flags = llvm : : ConstantInt : : get ( IGF . IGM . SizeTy , <nl> flagsVal . getIntValue ( ) ) ; <nl> <nl> - auto collectParameters = <nl> - [ & ] ( llvm : : function_ref < void ( unsigned , llvm : : Value * , uint8_t ) > <nl> - processor ) { <nl> - for ( auto index : indices ( params ) ) { <nl> - auto param = params [ index ] ; <nl> - auto flags = param . getParameterFlags ( ) ; <nl> - processor ( index , getFunctionParameterRef ( param ) , flags . toRaw ( ) ) ; <nl> - } <nl> - } ; <nl> - <nl> - auto processParameterFlags = <nl> - [ & ] ( ConstantArrayBuilder & flags , <nl> - llvm : : PointerType * castTo ) - > llvm : : Value * { <nl> - auto * flagsVar = flags . finishAndCreateGlobal ( <nl> - " parameter - flags " , IGF . IGM . getPointerAlignment ( ) , <nl> - / * constant * / true ) ; <nl> - return IGF . Builder . CreateBitCast ( flagsVar , castTo ) ; <nl> - } ; <nl> - <nl> - auto constructSimpleCall = <nl> - [ & ] ( llvm : : SmallVectorImpl < llvm : : Value * > & arguments ) <nl> - - > llvm : : Constant * { <nl> - arguments . push_back ( flags ) ; <nl> - <nl> - ConstantInitBuilder paramFlags ( IGF . IGM ) ; <nl> - auto flagsArr = paramFlags . beginArray ( ) ; <nl> - <nl> - bool hasFlags = false ; <nl> - collectParameters ( [ & ] ( unsigned i , llvm : : Value * typeRef , uint8_t flags ) { <nl> - hasFlags | = flags ; <nl> - flagsArr . addInt32 ( flags ) ; <nl> - arguments . push_back ( typeRef ) ; <nl> - } ) ; <nl> - <nl> - if ( hasFlags ) <nl> - arguments . push_back ( <nl> - processParameterFlags ( flagsArr , IGF . IGM . Int32Ty - > getPointerTo ( ) ) ) ; <nl> - else <nl> - flagsArr . abandon ( ) ; <nl> - <nl> - arguments . push_back ( resultMetadata ) ; <nl> - <nl> - switch ( params . size ( ) ) { <nl> - case 1 : <nl> - return hasFlags ? IGF . IGM . getGetFunctionMetadata1WithFlagsFn ( ) <nl> - : IGF . IGM . getGetFunctionMetadata1Fn ( ) ; <nl> - <nl> - case 2 : <nl> - return hasFlags ? IGF . IGM . getGetFunctionMetadata2WithFlagsFn ( ) <nl> - : IGF . IGM . getGetFunctionMetadata2Fn ( ) ; <nl> - <nl> - case 3 : <nl> - return hasFlags ? IGF . IGM . getGetFunctionMetadata3WithFlagsFn ( ) <nl> - : IGF . IGM . getGetFunctionMetadata3Fn ( ) ; <nl> - <nl> - default : <nl> - llvm_unreachable ( " supports only 1 / 2 / 3 parameter functions " ) ; <nl> - } <nl> - } ; <nl> - <nl> switch ( numParams ) { <nl> - case 1 : <nl> - case 2 : <nl> - case 3 : { <nl> - llvm : : SmallVector < llvm : : Value * , 8 > arguments ; <nl> - auto * metadataFn = constructSimpleCall ( arguments ) ; <nl> - auto * call = IGF . Builder . CreateCall ( metadataFn , arguments ) ; <nl> + case 1 : { <nl> + auto arg0 = extractAndMarkInOut ( params [ 0 ] ) ; <nl> + auto call = IGF . Builder . CreateCall ( IGF . IGM . getGetFunctionMetadata1Fn ( ) , <nl> + { flags , arg0 , resultMetadata } ) ; <nl> call - > setDoesNotThrow ( ) ; <nl> return setLocal ( CanType ( type ) , call ) ; <nl> - } <nl> + } <nl> <nl> - default : <nl> - auto arrayTy = llvm : : ArrayType : : get ( IGF . IGM . Int8PtrTy , numParams + 3 ) ; <nl> - Address buffer = IGF . createAlloca ( <nl> - arrayTy , IGF . IGM . getPointerAlignment ( ) , " function - arguments " ) ; <nl> - IGF . Builder . CreateLifetimeStart ( buffer , <nl> - IGF . IGM . getPointerSize ( ) * numParams ) ; <nl> - Address pointerToFirstArg = <nl> - IGF . Builder . CreateStructGEP ( buffer , 0 , Size ( 0 ) ) ; <nl> - Address flagsPtr = IGF . Builder . CreateBitCast ( <nl> - pointerToFirstArg , IGF . IGM . SizeTy - > getPointerTo ( ) ) ; <nl> - IGF . Builder . CreateStore ( flags , flagsPtr ) ; <nl> - <nl> - ConstantInitBuilder paramFlags ( IGF . IGM ) ; <nl> - auto flagsArr = paramFlags . beginArray ( ) ; <nl> - bool hasFlags = false ; <nl> - <nl> - collectParameters ( [ & ] ( unsigned i , llvm : : Value * typeRef , uint8_t flags ) { <nl> - auto argPtr = IGF . Builder . CreateStructGEP ( buffer , i + 1 , <nl> - IGF . IGM . getPointerSize ( ) ) ; <nl> - hasFlags | = flags ; <nl> - flagsArr . addInt32 ( flags ) ; <nl> - IGF . Builder . CreateStore ( typeRef , argPtr ) ; <nl> - } ) ; <nl> - <nl> - auto paramFlagsLoc = IGF . Builder . CreateStructGEP ( <nl> - buffer , numParams + 1 , IGF . IGM . getPointerSize ( ) ) ; <nl> - <nl> - llvm : : Value * flagsArrPtr = <nl> - llvm : : ConstantPointerNull : : get ( IGF . IGM . Int8PtrTy ) ; <nl> - if ( hasFlags ) { <nl> - flagsArrPtr = processParameterFlags ( flagsArr , IGF . IGM . Int8PtrTy ) ; <nl> - } else { <nl> - flagsArr . abandon ( ) ; <nl> + case 2 : { <nl> + auto arg0 = extractAndMarkInOut ( params [ 0 ] ) ; <nl> + auto arg1 = extractAndMarkInOut ( params [ 1 ] ) ; <nl> + auto call = IGF . Builder . CreateCall ( <nl> + IGF . IGM . getGetFunctionMetadata2Fn ( ) , <nl> + { flags , arg0 , arg1 , resultMetadata } ) ; <nl> + call - > setDoesNotThrow ( ) ; <nl> + return setLocal ( CanType ( type ) , call ) ; <nl> + } <nl> + <nl> + case 3 : { <nl> + auto arg0 = extractAndMarkInOut ( params [ 0 ] ) ; <nl> + auto arg1 = extractAndMarkInOut ( params [ 1 ] ) ; <nl> + auto arg2 = extractAndMarkInOut ( params [ 2 ] ) ; <nl> + auto call = IGF . Builder . CreateCall ( <nl> + IGF . IGM . getGetFunctionMetadata3Fn ( ) , <nl> + { flags , arg0 , arg1 , arg2 , <nl> + resultMetadata } ) ; <nl> + call - > setDoesNotThrow ( ) ; <nl> + return setLocal ( CanType ( type ) , call ) ; <nl> } <nl> <nl> - IGF . Builder . CreateStore ( flagsArrPtr , paramFlagsLoc ) ; <nl> + default : <nl> + auto arrayTy = llvm : : ArrayType : : get ( IGF . IGM . Int8PtrTy , numParams + 2 ) ; <nl> + Address buffer = IGF . createAlloca ( arrayTy , <nl> + IGF . IGM . getPointerAlignment ( ) , <nl> + " function - arguments " ) ; <nl> + IGF . Builder . CreateLifetimeStart ( buffer , <nl> + IGF . IGM . getPointerSize ( ) * numParams ) ; <nl> + Address pointerToFirstArg = IGF . Builder . CreateStructGEP ( buffer , 0 , <nl> + Size ( 0 ) ) ; <nl> + Address flagsPtr = IGF . Builder . CreateBitCast ( pointerToFirstArg , <nl> + IGF . IGM . SizeTy - > getPointerTo ( ) ) ; <nl> + IGF . Builder . CreateStore ( flags , flagsPtr ) ; <nl> + <nl> + for ( auto i : indices ( params ) ) { <nl> + auto argMetadata = extractAndMarkInOut ( params [ i ] ) ; <nl> + Address argPtr = IGF . Builder . CreateStructGEP ( buffer , i + 1 , <nl> + IGF . IGM . getPointerSize ( ) ) ; <nl> + IGF . Builder . CreateStore ( argMetadata , argPtr ) ; <nl> + } <nl> <nl> - Address resultPtr = IGF . Builder . CreateStructGEP ( <nl> - buffer , numParams + 2 , IGF . IGM . getPointerSize ( ) ) ; <nl> - resultPtr = IGF . Builder . CreateBitCast ( <nl> - resultPtr , IGF . IGM . TypeMetadataPtrTy - > getPointerTo ( ) ) ; <nl> - IGF . Builder . CreateStore ( resultMetadata , resultPtr ) ; <nl> + Address resultPtr = IGF . Builder . CreateStructGEP ( <nl> + buffer , numParams + 1 , IGF . IGM . getPointerSize ( ) ) ; <nl> + resultPtr = IGF . Builder . CreateBitCast ( resultPtr , <nl> + IGF . IGM . TypeMetadataPtrTy - > getPointerTo ( ) ) ; <nl> + IGF . Builder . CreateStore ( resultMetadata , resultPtr ) ; <nl> <nl> - auto call = IGF . Builder . CreateCall ( IGF . IGM . getGetFunctionMetadataFn ( ) , <nl> - pointerToFirstArg . getAddress ( ) ) ; <nl> - call - > setDoesNotThrow ( ) ; <nl> + auto call = IGF . Builder . CreateCall ( IGF . IGM . getGetFunctionMetadataFn ( ) , <nl> + pointerToFirstArg . getAddress ( ) ) ; <nl> + call - > setDoesNotThrow ( ) ; <nl> <nl> - IGF . Builder . CreateLifetimeEnd ( buffer , <nl> - IGF . IGM . getPointerSize ( ) * numParams ) ; <nl> - return setLocal ( type , call ) ; <nl> + IGF . Builder . CreateLifetimeEnd ( buffer , <nl> + IGF . IGM . getPointerSize ( ) * numParams ) ; <nl> + <nl> + return setLocal ( type , call ) ; <nl> } <nl> } <nl> <nl> mmm a / stdlib / public / runtime / Casting . cpp <nl> ppp b / stdlib / public / runtime / Casting . cpp <nl> static bool _dynamicCastToFunction ( OpaqueValue * dest , <nl> if ( srcFn - > getNumArguments ( ) ! = targetFn - > getNumArguments ( ) ) <nl> return _fail ( src , srcType , targetType , flags ) ; <nl> for ( unsigned i = 0 , e = srcFn - > getNumArguments ( ) ; i < e ; + + i ) <nl> - if ( srcFn - > getArguments ( ) [ i ] ! = targetFn - > getArguments ( ) [ i ] | | <nl> - srcFn - > getParameterFlags ( i ) ! = targetFn - > getParameterFlags ( i ) ) <nl> + if ( srcFn - > getArguments ( ) [ i ] ! = targetFn - > getArguments ( ) [ i ] ) <nl> return _fail ( src , srcType , targetType , flags ) ; <nl> <nl> return _succeed ( dest , src , srcType , flags ) ; <nl> mmm a / stdlib / public / runtime / Demangle . cpp <nl> ppp b / stdlib / public / runtime / Demangle . cpp <nl> <nl> / / <nl> / / = = = mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - = = = / / <nl> <nl> - # include " swift / AST / Types . h " <nl> # include " swift / Runtime / Metadata . h " <nl> # include " swift / Strings . h " <nl> # include " Private . h " <nl> swift : : _swift_buildDemanglingForMetadata ( const Metadata * type , <nl> std : : vector < NodePointer > inputs ; <nl> for ( unsigned i = 0 , e = func - > getNumArguments ( ) ; i < e ; + + i ) { <nl> auto arg = func - > getArguments ( ) [ i ] ; <nl> - auto flags = ParameterTypeFlags : : fromRaw ( func - > getParameterFlags ( i ) ) ; <nl> - auto input = _swift_buildDemanglingForMetadata ( arg , Dem ) ; <nl> - <nl> - if ( flags . isInOut ( ) ) { <nl> + auto input = _swift_buildDemanglingForMetadata ( arg . getPointer ( ) , Dem ) ; <nl> + if ( arg . getFlag ( ) ) { <nl> NodePointer inout = Dem . createNode ( Node : : Kind : : InOut ) ; <nl> inout - > addChild ( input , Dem ) ; <nl> input = inout ; <nl> - } else if ( flags . isShared ( ) ) { <nl> - NodePointer shared = Dem . createNode ( Node : : Kind : : Shared ) ; <nl> - shared - > addChild ( input , Dem ) ; <nl> - input = shared ; <nl> } <nl> inputs . push_back ( input ) ; <nl> } <nl> mmm a / stdlib / public / runtime / Metadata . cpp <nl> ppp b / stdlib / public / runtime / Metadata . cpp <nl> <nl> / / <nl> / / = = = mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - = = = / / <nl> <nl> - # include " swift / Runtime / Metadata . h " <nl> - # include " MetadataCache . h " <nl> + # include " llvm / Support / MathExtras . h " <nl> + # include " swift / Demangling / Demangler . h " <nl> # include " swift / Basic / LLVM . h " <nl> - # include " swift / Basic / Lazy . h " <nl> # include " swift / Basic / Range . h " <nl> - # include " swift / Demangling / Demangler . h " <nl> + # include " swift / Basic / Lazy . h " <nl> # include " swift / Runtime / Casting . h " <nl> # include " swift / Runtime / HeapObject . h " <nl> + # include " swift / Runtime / Metadata . h " <nl> # include " swift / Runtime / Mutex . h " <nl> # include " swift / Strings . h " <nl> - # include " llvm / Support / MathExtras . h " <nl> - # include " llvm / Support / PointerLikeTypeTraits . h " <nl> + # include " MetadataCache . h " <nl> # include < algorithm > <nl> - # include < cctype > <nl> # include < condition_variable > <nl> - # include < iostream > <nl> # include < new > <nl> + # include < cctype > <nl> + # include < iostream > <nl> # if defined ( _WIN32 ) <nl> # define WIN32_LEAN_AND_MEAN <nl> / / Avoid defining macro max ( ) , min ( ) which conflict with std : : max ( ) , std : : min ( ) <nl> class FunctionCacheEntry { <nl> } <nl> <nl> const Metadata * getResult ( ) const { <nl> - auto opaqueResult = FlagsArgsAndResult [ getFlags ( ) . getNumArguments ( ) + 2 ] ; <nl> + auto opaqueResult = FlagsArgsAndResult [ getFlags ( ) . getNumArguments ( ) + 1 ] ; <nl> return reinterpret_cast < const Metadata * > ( opaqueResult ) ; <nl> } <nl> <nl> class FunctionCacheEntry { <nl> return getFlags ( ) . getNumArguments ( ) = = 0 <nl> ? nullptr : & FlagsArgsAndResult [ 1 ] ; <nl> } <nl> - <nl> - uint32_t getParameterFlags ( unsigned index ) const { <nl> - auto numArguments = getFlags ( ) . getNumArguments ( ) ; <nl> - assert ( index < numArguments ) ; <nl> - auto * flags = reinterpret_cast < const uint32_t * > ( <nl> - FlagsArgsAndResult [ numArguments + 1 ] ) ; <nl> - return flags [ index ] ; <nl> - } <nl> } ; <nl> <nl> FunctionCacheEntry ( Key key ) ; <nl> class FunctionCacheEntry { <nl> return result ; <nl> <nl> for ( unsigned i = 0 , e = keyFlags . getNumArguments ( ) ; i ! = e ; + + i ) { <nl> - if ( auto result = compareIntegers ( key . getParameterFlags ( i ) , <nl> - Data . getParameterFlags ( i ) ) ) <nl> - return result ; <nl> - <nl> - if ( auto result = comparePointers ( <nl> - key . getArguments ( ) [ i ] , <nl> - reinterpret_cast < const void * > ( Data . getArguments ( ) [ i ] ) ) ) <nl> + if ( auto result = <nl> + comparePointers ( key . getArguments ( ) [ i ] , <nl> + Data . getArguments ( ) [ i ] . getOpaqueValue ( ) ) ) <nl> return result ; <nl> } <nl> <nl> const FunctionTypeMetadata * <nl> swift : : swift_getFunctionTypeMetadata1 ( FunctionTypeFlags flags , <nl> const void * arg0 , <nl> const Metadata * result ) { <nl> - return swift_getFunctionTypeMetadata1WithFlags ( flags , arg0 , nullptr , result ) ; <nl> - } <nl> - <nl> - const FunctionTypeMetadata * <nl> - swift : : swift_getFunctionTypeMetadata1WithFlags ( FunctionTypeFlags flags , <nl> - const void * arg0 , <nl> - const uint32_t * paramFlags , <nl> - const Metadata * result ) { <nl> assert ( flags . getNumArguments ( ) = = 1 <nl> & & " wrong number of arguments in function metadata flags ? ! " ) ; <nl> const void * flagsArgsAndResult [ ] = { <nl> - reinterpret_cast < const void * > ( flags . getIntValue ( ) ) , arg0 , paramFlags , <nl> - static_cast < const void * > ( result ) } ; <nl> + reinterpret_cast < const void * > ( flags . getIntValue ( ) ) , <nl> + arg0 , <nl> + static_cast < const void * > ( result ) <nl> + } ; <nl> return swift_getFunctionTypeMetadata ( flagsArgsAndResult ) ; <nl> - } <nl> - <nl> - const FunctionTypeMetadata * <nl> + } <nl> + const FunctionTypeMetadata * <nl> swift : : swift_getFunctionTypeMetadata2 ( FunctionTypeFlags flags , <nl> const void * arg0 , <nl> const void * arg1 , <nl> const Metadata * result ) { <nl> - return swift_getFunctionTypeMetadata2WithFlags ( <nl> - flags , arg0 , arg1 , nullptr , result ) ; <nl> - } <nl> - <nl> - const FunctionTypeMetadata * <nl> - swift : : swift_getFunctionTypeMetadata2WithFlags ( FunctionTypeFlags flags , <nl> - const void * arg0 , <nl> - const void * arg1 , <nl> - const uint32_t * paramFlags , <nl> - const Metadata * result ) { <nl> assert ( flags . getNumArguments ( ) = = 2 <nl> & & " wrong number of arguments in function metadata flags ? ! " ) ; <nl> const void * flagsArgsAndResult [ ] = { <nl> - reinterpret_cast < const void * > ( flags . getIntValue ( ) ) , arg0 , arg1 , <nl> - paramFlags , static_cast < const void * > ( result ) } ; <nl> + reinterpret_cast < const void * > ( flags . getIntValue ( ) ) , <nl> + arg0 , <nl> + arg1 , <nl> + static_cast < const void * > ( result ) <nl> + } ; <nl> return swift_getFunctionTypeMetadata ( flagsArgsAndResult ) ; <nl> - } <nl> - <nl> - const FunctionTypeMetadata * <nl> + } <nl> + const FunctionTypeMetadata * <nl> swift : : swift_getFunctionTypeMetadata3 ( FunctionTypeFlags flags , <nl> const void * arg0 , <nl> const void * arg1 , <nl> const void * arg2 , <nl> const Metadata * result ) { <nl> - return swift_getFunctionTypeMetadata3WithFlags ( flags , arg0 , arg1 , arg2 , <nl> - nullptr , result ) ; <nl> - } <nl> - <nl> - const FunctionTypeMetadata * <nl> - swift : : swift_getFunctionTypeMetadata3WithFlags ( FunctionTypeFlags flags , <nl> - const void * arg0 , <nl> - const void * arg1 , <nl> - const void * arg2 , <nl> - const uint32_t * paramFlags , <nl> - const Metadata * result ) { <nl> assert ( flags . getNumArguments ( ) = = 3 <nl> & & " wrong number of arguments in function metadata flags ? ! " ) ; <nl> const void * flagsArgsAndResult [ ] = { <nl> - reinterpret_cast < const void * > ( flags . getIntValue ( ) ) , <nl> - arg0 , <nl> - arg1 , <nl> - arg2 , <nl> - paramFlags , <nl> - static_cast < const void * > ( result ) } ; <nl> + reinterpret_cast < const void * > ( flags . getIntValue ( ) ) , <nl> + arg0 , <nl> + arg1 , <nl> + arg2 , <nl> + static_cast < const void * > ( result ) <nl> + } ; <nl> return swift_getFunctionTypeMetadata ( flagsArgsAndResult ) ; <nl> } <nl> <nl> FunctionCacheEntry : : FunctionCacheEntry ( Key key ) { <nl> <nl> for ( size_t i = 0 ; i < numArguments ; + + i ) { <nl> auto opaqueArg = key . getArguments ( ) [ i ] ; <nl> - Data . getArguments ( ) [ i ] = <nl> - reinterpret_cast < FunctionTypeMetadata : : Argument > ( opaqueArg ) ; <nl> + auto arg = FunctionTypeMetadata : : Argument : : getFromOpaqueValue ( opaqueArg ) ; <nl> + Data . getArguments ( ) [ i ] = arg ; <nl> } <nl> } <nl> <nl> mmm a / test / IRGen / function_metadata . swift <nl> ppp b / test / IRGen / function_metadata . swift <nl> func test_arch ( ) { <nl> / / CHECK : call % swift . type * @ swift_getFunctionTypeMetadata1 ( [ [ WORD ] ] 1 , i8 * bitcast ( % swift . type * getelementptr inbounds ( % swift . full_type , % swift . full_type * @ _T0ytN , i32 0 , i32 1 ) to i8 * ) , % swift . type * getelementptr inbounds ( % swift . full_type , % swift . full_type * @ _T0ytN , i32 0 , i32 1 ) ) <nl> arch ( { ( _ : ( ) ) - > ( ) in } ) <nl> <nl> - / / CHECK : call % swift . type * @ swift_getFunctionTypeMetadata1WithFlags ( [ [ WORD ] ] 1 , i8 * bitcast ( % swift . type * @ _T0SiN to i8 * ) , i32 * getelementptr inbounds ( [ 1 x i32 ] , [ 1 x i32 ] * @ parameter - flags , i32 0 , i32 0 ) , % swift . type * getelementptr inbounds ( % swift . full_type , % swift . full_type * @ _T0ytN , i32 0 , i32 1 ) ) <nl> + / / CHECK : call % swift . type * @ swift_getFunctionTypeMetadata1 ( [ [ WORD ] ] 1 , i8 * inttoptr ( [ [ WORD ] ] or ( [ [ WORD ] ] ptrtoint ( % swift . type * @ _T0SiN to [ [ WORD ] ] ) , [ [ WORD ] ] 1 ) to i8 * ) , % swift . type * getelementptr inbounds ( % swift . full_type , % swift . full_type * @ _T0ytN , i32 0 , i32 1 ) ) <nl> arch ( { ( x : inout Int ) - > ( ) in } ) <nl> <nl> / / CHECK : call % swift . type * @ swift_getFunctionTypeMetadata1 ( [ [ WORD ] ] 1 , i8 * % 3 , % swift . type * getelementptr inbounds ( % swift . full_type , % swift . full_type * @ _T0ytN , i32 0 , i32 1 ) ) <nl> arch ( { ( x : ( Int , Float ) ) - > ( ) in } ) <nl> <nl> - / / CHECK : call % swift . type * @ swift_getFunctionTypeMetadata2WithFlags ( [ [ WORD ] ] 2 , i8 * bitcast ( % swift . type * @ _T0SiN to i8 * ) , i8 * bitcast ( % swift . type * @ _T0SiN to i8 * ) , i32 * getelementptr inbounds ( [ 2 x i32 ] , [ 2 x i32 ] * @ parameter - flags . 17 , i32 0 , i32 0 ) , % swift . type * getelementptr inbounds ( % swift . full_type , % swift . full_type * @ _T0ytN , i32 0 , i32 1 ) ) <nl> + / / CHECK : call % swift . type * @ swift_getFunctionTypeMetadata2 ( [ [ WORD ] ] 2 , i8 * inttoptr ( [ [ WORD ] ] or ( [ [ WORD ] ] ptrtoint ( % swift . type * @ _T0SiN to [ [ WORD ] ] ) , [ [ WORD ] ] 1 ) to i8 * ) , i8 * bitcast ( % swift . type * @ _T0SiN to i8 * ) , % swift . type * getelementptr inbounds ( % swift . full_type , % swift . full_type * @ _T0ytN , i32 0 , i32 1 ) ) <nl> arch ( { ( x : inout Int , y : Int ) - > ( ) in } ) <nl> <nl> / / CHECK : call % swift . type * @ swift_getFunctionTypeMetadata2 ( [ [ WORD ] ] 2 , i8 * bitcast ( % swift . type * @ _T0SfN to i8 * ) , i8 * bitcast ( % swift . type * @ _T0SiN to i8 * ) , % swift . type * getelementptr inbounds ( % swift . full_type , % swift . full_type * @ _T0ytN , i32 0 , i32 1 ) ) <nl> arch ( { ( a : Float , b : Int ) - > ( ) in } ) <nl> <nl> - / / CHECK : call % swift . type * @ swift_getFunctionTypeMetadata3WithFlags ( [ [ WORD ] ] 3 , i8 * bitcast ( % swift . type * @ _T0SiN to i8 * ) , i8 * bitcast ( % swift . type * @ _T0SfN to i8 * ) , i8 * bitcast ( % swift . type * @ _T0SSN to i8 * ) , i32 * getelementptr inbounds ( [ 3 x i32 ] , [ 3 x i32 ] * @ parameter - flags . 24 , i32 0 , i32 0 ) , % swift . type * getelementptr inbounds ( % swift . full_type , % swift . full_type * @ _T0ytN , i32 0 , i32 1 ) ) <nl> + / / CHECK : call % swift . type * @ swift_getFunctionTypeMetadata3 ( [ [ WORD ] ] 3 , i8 * inttoptr ( [ [ WORD ] ] or ( [ [ WORD ] ] ptrtoint ( % swift . type * @ _T0SiN to [ [ WORD ] ] ) , [ [ WORD ] ] 1 ) to i8 * ) , i8 * bitcast ( % swift . type * @ _T0SfN to i8 * ) , i8 * bitcast ( % swift . type * @ _T0SSN to i8 * ) , % swift . type * getelementptr inbounds ( % swift . full_type , % swift . full_type * @ _T0ytN , i32 0 , i32 1 ) ) <nl> arch ( { ( x : inout Int , y : Float , z : String ) - > ( ) in } ) <nl> <nl> / / CHECK : call % swift . type * @ swift_getFunctionTypeMetadata3 ( [ [ WORD ] ] 3 , i8 * bitcast ( % swift . type * @ _T0SfN to i8 * ) , i8 * bitcast ( % swift . type * @ _T0SfN to i8 * ) , i8 * bitcast ( % swift . type * @ _T0SiN to i8 * ) , % swift . type * getelementptr inbounds ( % swift . full_type , % swift . full_type * @ _T0ytN , i32 0 , i32 1 ) ) <nl> arch ( { ( a : Float , b : Float , c : Int ) - > ( ) in } ) <nl> <nl> - / / CHECK : [ [ T0 : % . * ] ] = getelementptr inbounds [ 7 x i8 * ] , [ 7 x i8 * ] * % function - arguments , i32 0 , i32 0 <nl> + / / CHECK : [ [ T0 : % . * ] ] = getelementptr inbounds [ 6 x i8 * ] , [ 6 x i8 * ] * % function - arguments , i32 0 , i32 0 <nl> / / CHECK : store [ [ WORD ] ] 4 <nl> - / / CHECK : getelementptr inbounds [ 7 x i8 * ] , [ 7 x i8 * ] * % function - arguments , i32 0 , i32 1 <nl> - / / CHECK : store i8 * bitcast ( % swift . type * @ _T0SiN to i8 * ) , i8 * * % 5 , align 8 <nl> - / / CHECK : getelementptr inbounds [ 7 x i8 * ] , [ 7 x i8 * ] * % function - arguments , i32 0 , i32 2 <nl> + / / CHECK : getelementptr inbounds [ 6 x i8 * ] , [ 6 x i8 * ] * % function - arguments , i32 0 , i32 1 <nl> + / / CHECK : store i8 * inttoptr ( [ [ WORD ] ] or ( [ [ WORD ] ] ptrtoint ( % swift . type * @ _T0SiN to [ [ WORD ] ] ) , [ [ WORD ] ] 1 ) to i8 * ) <nl> + / / CHECK : getelementptr inbounds [ 6 x i8 * ] , [ 6 x i8 * ] * % function - arguments , i32 0 , i32 2 <nl> / / CHECK : store i8 * bitcast ( % swift . type * @ _T0SdN to i8 * ) <nl> - / / CHECK : getelementptr inbounds [ 7 x i8 * ] , [ 7 x i8 * ] * % function - arguments , i32 0 , i32 3 <nl> + / / CHECK : getelementptr inbounds [ 6 x i8 * ] , [ 6 x i8 * ] * % function - arguments , i32 0 , i32 3 <nl> / / CHECK : store i8 * bitcast ( % swift . type * @ _T0SSN to i8 * ) <nl> - / / CHECK : getelementptr inbounds [ 7 x i8 * ] , [ 7 x i8 * ] * % function - arguments , i32 0 , i32 4 <nl> + / / CHECK : getelementptr inbounds [ 6 x i8 * ] , [ 6 x i8 * ] * % function - arguments , i32 0 , i32 4 <nl> / / CHECK : store i8 * bitcast ( % swift . type * @ _T0s4Int8VN to i8 * ) <nl> - / / CHECK : getelementptr inbounds [ 7 x i8 * ] , [ 7 x i8 * ] * % function - arguments , i32 0 , i32 5 <nl> - / / CHECK : store i8 * bitcast ( [ 4 x i32 ] * @ parameter - flags . 31 to i8 * ) , i8 * * % 9 , align 8 <nl> - / / CHECK : getelementptr inbounds [ 7 x i8 * ] , [ 7 x i8 * ] * % function - arguments , i32 0 , i32 6 <nl> - / / CHECK : bitcast i8 * * % 10 to % swift . type * * <nl> + / / CHECK : getelementptr inbounds [ 6 x i8 * ] , [ 6 x i8 * ] * % function - arguments , i32 0 , i32 5 <nl> / / CHECK : store % swift . type * getelementptr inbounds ( % swift . full_type , % swift . full_type * @ _T0ytN , i32 0 , i32 1 ) <nl> / / CHECK : call % swift . type * @ swift_getFunctionTypeMetadata ( i8 * * [ [ T0 ] ] ) { { # [ 0 - 9 ] + } } <nl> arch ( { ( x : inout Int , y : Double , z : String , w : Int8 ) - > ( ) in } ) <nl> | Revert " [ IRGen ] Add parameter flags to function type metadata " | apple/swift | 659c1bc2e081d9aed71fe1dabf794c366353c456 | 2017-11-07T08:24:24Z |
mmm a / CMakeLists . txt <nl> ppp b / CMakeLists . txt <nl> else ( ) <nl> message ( STATUS " mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - " ) <nl> endif ( ) <nl> <nl> + include ( installer ) <nl> + <nl> add_subdirectory ( libraries ) <nl> add_subdirectory ( plugins ) <nl> add_subdirectory ( programs ) <nl> add_subdirectory ( tools ) <nl> <nl> configure_file ( $ { CMAKE_CURRENT_SOURCE_DIR } / genesis . json $ { CMAKE_CURRENT_BINARY_DIR } / genesis . json COPYONLY ) <nl> <nl> - include ( installer ) <nl> + <nl> include ( doxygen ) <nl> | Merge pull request from EOSIO / DAWN - 527 | EOSIO/eos | ecafed5aa4ee38034163b6d393b39ac0d0ec7785 | 2018-01-29T17:00:04Z |
mmm a / src / netbase . cpp <nl> ppp b / src / netbase . cpp <nl> bool CNetAddr : : IsRFC4843 ( ) const <nl> return ( GetByte ( 15 ) = = 0x20 & & GetByte ( 14 ) = = 0x01 & & GetByte ( 13 ) = = 0x00 & & ( GetByte ( 12 ) & 0xF0 ) = = 0x10 ) ; <nl> } <nl> <nl> + bool CNetAddr : : IsOnionCat ( ) const <nl> + { <nl> + static const unsigned char pchOnionCat [ ] = { 0xFD , 0x87 , 0xD8 , 0x7E , 0xEB , 0x43 } ; <nl> + return ( memcmp ( ip , pchOnionCat , sizeof ( pchOnionCat ) ) = = 0 ) ; <nl> + } <nl> + <nl> + bool CNetAddr : : IsGarliCat ( ) const <nl> + { <nl> + static const unsigned char pchGarliCat [ ] = { 0xFD , 0x60 , 0xDB , 0x4D , 0xDD , 0xB5 } ; <nl> + return ( memcmp ( ip , pchGarliCat , sizeof ( pchGarliCat ) ) = = 0 ) ; <nl> + } <nl> + <nl> bool CNetAddr : : IsLocal ( ) const <nl> { <nl> / / IPv4 loopback <nl> bool CNetAddr : : IsValid ( ) const <nl> <nl> bool CNetAddr : : IsRoutable ( ) const <nl> { <nl> - return IsValid ( ) & & ! ( IsRFC1918 ( ) | | IsRFC3927 ( ) | | IsRFC4862 ( ) | | IsRFC4193 ( ) | | IsRFC4843 ( ) | | IsLocal ( ) ) ; <nl> + return IsValid ( ) & & ! ( IsRFC1918 ( ) | | IsRFC3927 ( ) | | IsRFC4862 ( ) | | ( IsRFC4193 ( ) & & ! IsOnionCat ( ) & & ! IsGarliCat ( ) ) | | IsRFC4843 ( ) | | IsLocal ( ) ) ; <nl> } <nl> <nl> std : : string CNetAddr : : ToStringIP ( ) const <nl> mmm a / src / netbase . h <nl> ppp b / src / netbase . h <nl> class CNetAddr <nl> bool IsRFC4862 ( ) const ; / / IPv6 autoconfig ( FE80 : : / 64 ) <nl> bool IsRFC6052 ( ) const ; / / IPv6 well - known prefix ( 64 : FF9B : : / 96 ) <nl> bool IsRFC6145 ( ) const ; / / IPv6 IPv4 - translated address ( : : FFFF : 0 : 0 : 0 / 96 ) <nl> + bool IsOnionCat ( ) const ; <nl> + bool IsGarliCat ( ) const ; <nl> bool IsLocal ( ) const ; <nl> bool IsRoutable ( ) const ; <nl> bool IsValid ( ) const ; <nl> | Preliminary support for Tor / I2P hidden services | bitcoin/bitcoin | d32148567f5866a7cd2a77a2f44f846134011c9c | 2012-05-11T13:29:19Z |
mmm a / contracts / eosiolib / multi_index . hpp <nl> ppp b / contracts / eosiolib / multi_index . hpp <nl> <nl> # include < iterator > <nl> # include < limits > <nl> # include < algorithm > <nl> + # include < memory > <nl> <nl> # include < boost / multi_index_container . hpp > <nl> # include < boost / multi_index / mem_fun . hpp > <nl> <nl> <nl> namespace eosio { <nl> <nl> - namespace bmi = boost : : multi_index ; <nl> using boost : : multi_index : : const_mem_fun ; <nl> <nl> - / * <nl> - template < class Class , typename Type , Type ( Class : : * PtrToMemberFunction ) ( ) const > <nl> - struct const_mem_fun <nl> - { <nl> - typedef typename std : : remove_reference < Type > : : type result_type ; <nl> - <nl> - template < typename ChainedPtr > <nl> - <nl> - typename std : : enable_if < <nl> - ! std : : is_convertible < const ChainedPtr & , const Class & > : : value , Type > : : type <nl> - operator ( ) ( const ChainedPtr & x ) const <nl> - { <nl> - return operator ( ) ( * x ) ; <nl> - } <nl> - <nl> - Type operator ( ) ( const Class & x ) const <nl> - { <nl> - return ( x . * PtrToMemberFunction ) ( ) ; <nl> - } <nl> - <nl> - Type operator ( ) ( const std : : reference_wrapper < const Class > & x ) const <nl> - { <nl> - return operator ( ) ( x . get ( ) ) ; <nl> - } <nl> - <nl> - Type operator ( ) ( const std : : reference_wrapper < Class > & x ) const <nl> - { <nl> - return operator ( ) ( x . get ( ) ) ; <nl> - } <nl> - } ; <nl> - * / <nl> - <nl> namespace hana = boost : : hana ; <nl> <nl> template < typename T > <nl> struct secondary_iterator ; <nl> # define WRAP_SECONDARY_SIMPLE_TYPE ( IDX , TYPE ) \ <nl> template < > \ <nl> struct secondary_iterator < TYPE > { \ <nl> - static int db_idx_next ( int iterator , uint64_t * primary ) { return db_ # # IDX # # _next ( iterator , primary ) ; } \ <nl> - static int db_idx_previous ( int iterator , uint64_t * primary ) { return db_ # # IDX # # _previous ( iterator , primary ) ; } \ <nl> - static void db_idx_remove ( int iterator ) { db_ # # IDX # # _remove ( iterator ) ; } \ <nl> - static int db_idx_end ( uint64_t code , uint64_t scope , uint64_t table ) { return db_ # # IDX # # _end ( code , scope , table ) ; } \ <nl> + static int32_t db_idx_next ( int32_t iterator , uint64_t * primary ) { return db_ # # IDX # # _next ( iterator , primary ) ; } \ <nl> + static int32_t db_idx_previous ( int32_t iterator , uint64_t * primary ) { return db_ # # IDX # # _previous ( iterator , primary ) ; } \ <nl> + static void db_idx_remove ( int32_t iterator ) { db_ # # IDX # # _remove ( iterator ) ; } \ <nl> + static int32_t db_idx_end ( uint64_t code , uint64_t scope , uint64_t table ) { return db_ # # IDX # # _end ( code , scope , table ) ; } \ <nl> } ; \ <nl> - int db_idx_store ( uint64_t scope , uint64_t table , uint64_t payer , uint64_t id , const TYPE & secondary ) { \ <nl> + int32_t db_idx_store ( uint64_t scope , uint64_t table , uint64_t payer , uint64_t id , const TYPE & secondary ) { \ <nl> return db_ # # IDX # # _store ( scope , table , payer , id , & secondary ) ; \ <nl> } \ <nl> - void db_idx_update ( int iterator , uint64_t payer , const TYPE & secondary ) { \ <nl> + void db_idx_update ( int32_t iterator , uint64_t payer , const TYPE & secondary ) { \ <nl> db_ # # IDX # # _update ( iterator , payer , & secondary ) ; \ <nl> } \ <nl> - int db_idx_find_primary ( uint64_t code , uint64_t scope , uint64_t table , uint64_t primary , TYPE & secondary ) { \ <nl> + int32_t db_idx_find_primary ( uint64_t code , uint64_t scope , uint64_t table , uint64_t primary , TYPE & secondary ) { \ <nl> return db_ # # IDX # # _find_primary ( code , scope , table , & secondary , primary ) ; \ <nl> } \ <nl> - int db_idx_find_secondary ( uint64_t code , uint64_t scope , uint64_t table , const TYPE & secondary , uint64_t & primary ) { \ <nl> + int32_t db_idx_find_secondary ( uint64_t code , uint64_t scope , uint64_t table , const TYPE & secondary , uint64_t & primary ) { \ <nl> return db_ # # IDX # # _find_secondary ( code , scope , table , & secondary , & primary ) ; \ <nl> } \ <nl> - int db_idx_lowerbound ( uint64_t code , uint64_t scope , uint64_t table , TYPE & secondary , uint64_t & primary ) { \ <nl> + int32_t db_idx_lowerbound ( uint64_t code , uint64_t scope , uint64_t table , TYPE & secondary , uint64_t & primary ) { \ <nl> return db_ # # IDX # # _lowerbound ( code , scope , table , & secondary , & primary ) ; \ <nl> } \ <nl> - int db_idx_upperbound ( uint64_t code , uint64_t scope , uint64_t table , TYPE & secondary , uint64_t & primary ) { \ <nl> + int32_t db_idx_upperbound ( uint64_t code , uint64_t scope , uint64_t table , TYPE & secondary , uint64_t & primary ) { \ <nl> return db_ # # IDX # # _upperbound ( code , scope , table , & secondary , & primary ) ; \ <nl> } <nl> <nl> # define WRAP_SECONDARY_ARRAY_TYPE ( IDX , TYPE ) \ <nl> template < > \ <nl> struct secondary_iterator < TYPE > { \ <nl> - static int db_idx_next ( int iterator , uint64_t * primary ) { return db_ # # IDX # # _next ( iterator , primary ) ; } \ <nl> - static int db_idx_previous ( int iterator , uint64_t * primary ) { return db_ # # IDX # # _previous ( iterator , primary ) ; } \ <nl> - static void db_idx_remove ( int iterator ) { db_ # # IDX # # _remove ( iterator ) ; } \ <nl> - static int db_idx_end ( uint64_t code , uint64_t scope , uint64_t table ) { return db_ # # IDX # # _end ( code , scope , table ) ; } \ <nl> + static int32_t db_idx_next ( int32_t iterator , uint64_t * primary ) { return db_ # # IDX # # _next ( iterator , primary ) ; } \ <nl> + static int32_t db_idx_previous ( int32_t iterator , uint64_t * primary ) { return db_ # # IDX # # _previous ( iterator , primary ) ; } \ <nl> + static void db_idx_remove ( int32_t iterator ) { db_ # # IDX # # _remove ( iterator ) ; } \ <nl> + static int32_t db_idx_end ( uint64_t code , uint64_t scope , uint64_t table ) { return db_ # # IDX # # _end ( code , scope , table ) ; } \ <nl> } ; \ <nl> - int db_idx_store ( uint64_t scope , uint64_t table , uint64_t payer , uint64_t id , const TYPE & secondary ) { \ <nl> + int32_t db_idx_store ( uint64_t scope , uint64_t table , uint64_t payer , uint64_t id , const TYPE & secondary ) { \ <nl> return db_ # # IDX # # _store ( scope , table , payer , id , secondary . data ( ) , TYPE : : num_words ( ) ) ; \ <nl> } \ <nl> - void db_idx_update ( int iterator , uint64_t payer , const TYPE & secondary ) { \ <nl> + void db_idx_update ( int32_t iterator , uint64_t payer , const TYPE & secondary ) { \ <nl> db_ # # IDX # # _update ( iterator , payer , secondary . data ( ) , TYPE : : num_words ( ) ) ; \ <nl> } \ <nl> - int db_idx_find_primary ( uint64_t code , uint64_t scope , uint64_t table , uint64_t primary , TYPE & secondary ) { \ <nl> + int32_t db_idx_find_primary ( uint64_t code , uint64_t scope , uint64_t table , uint64_t primary , TYPE & secondary ) { \ <nl> return db_ # # IDX # # _find_primary ( code , scope , table , secondary . data ( ) , TYPE : : num_words ( ) , primary ) ; \ <nl> } \ <nl> - int db_idx_find_secondary ( uint64_t code , uint64_t scope , uint64_t table , const TYPE & secondary , uint64_t & primary ) { \ <nl> + int32_t db_idx_find_secondary ( uint64_t code , uint64_t scope , uint64_t table , const TYPE & secondary , uint64_t & primary ) { \ <nl> return db_ # # IDX # # _find_secondary ( code , scope , table , secondary . data ( ) , TYPE : : num_words ( ) , & primary ) ; \ <nl> } \ <nl> - int db_idx_lowerbound ( uint64_t code , uint64_t scope , uint64_t table , TYPE & secondary , uint64_t & primary ) { \ <nl> + int32_t db_idx_lowerbound ( uint64_t code , uint64_t scope , uint64_t table , TYPE & secondary , uint64_t & primary ) { \ <nl> return db_ # # IDX # # _lowerbound ( code , scope , table , secondary . data ( ) , TYPE : : num_words ( ) , & primary ) ; \ <nl> } \ <nl> - int db_idx_upperbound ( uint64_t code , uint64_t scope , uint64_t table , TYPE & secondary , uint64_t & primary ) { \ <nl> + int32_t db_idx_upperbound ( uint64_t code , uint64_t scope , uint64_t table , TYPE & secondary , uint64_t & primary ) { \ <nl> return db_ # # IDX # # _upperbound ( code , scope , table , secondary . data ( ) , TYPE : : num_words ( ) , & primary ) ; \ <nl> } <nl> <nl> struct indexed_by { <nl> typedef Extractor secondary_extractor_type ; <nl> } ; <nl> <nl> - / * <nl> - <nl> - class table_row { <nl> - public : <nl> - virtual ~ table_row ( ) { } ; <nl> - virtual uint64_t get_primary ( ) const = 0 ; <nl> - virtual int * __get_secondary_iterators_start_address ( ) const { return nullptr ; } ; <nl> - <nl> - private : <nl> - table_row * __next ; <nl> - table_row * __prev ; <nl> - int __primary_itr ; <nl> - } ; <nl> - <nl> template < uint64_t TableName , typename T , typename . . . Indices > <nl> class multi_index <nl> { <nl> private : <nl> <nl> - static_assert ( std : : is_base_of < table_row , T > : : value , " type T must derive from table_row " ) ; <nl> - <nl> static_assert ( sizeof . . . ( Indices ) < = 16 , " multi_index only supports a maximum of 16 secondary indices " ) ; <nl> <nl> constexpr static bool validate_table_name ( uint64_t n ) { <nl> class multi_index <nl> <nl> static_assert ( validate_table_name ( TableName ) , " multi_index does not support table names with a length greater than 12 " ) ; <nl> <nl> - friend class multi_index_impl ; <nl> - <nl> - struct _item : public T <nl> - { <nl> - int __iters [ sizeof . . . ( Indices ) ] ; <nl> - } <nl> - <nl> - struct item : public std : : conditional < sizeof . . . ( Indices ) = = 0 , T , _item > <nl> - { <nl> - public : <nl> - <nl> - <nl> - virtual <nl> - typename std : : enable_if < sizeof . . . ( Indices ) ! = 0 , int * > : : type <nl> - __get_secondary_iterators_start_address ( ) const override <nl> - { <nl> - return <nl> - } <nl> - } <nl> - <nl> - } ; <nl> - <nl> - class multi_index_impl <nl> - { <nl> - private : <nl> - <nl> - <nl> - <nl> - } ; <nl> - * / <nl> - <nl> - template < uint64_t TableName , typename T , typename . . . Indices > <nl> - class multi_index <nl> - { <nl> - private : <nl> - <nl> - static_assert ( sizeof . . . ( Indices ) < = 16 , " multi_index only supports a maximum of 16 secondary indices " ) ; <nl> + uint64_t _code ; <nl> + uint64_t _scope ; <nl> <nl> - constexpr static bool validate_table_name ( uint64_t n ) { <nl> - / / Limit table names to 12 characters so that the last character ( 4 bits ) can be used to distinguish between the secondary indices . <nl> - return ( n & 0x000000000000000FULL ) = = 0 ; <nl> - } <nl> + mutable uint64_t _next_primary_key ; <nl> <nl> - static_assert ( validate_table_name ( TableName ) , " multi_index does not support table names with a length greater than 12 " ) ; <nl> + enum next_primary_key_tags : uint64_t { <nl> + no_available_primary_key = static_cast < uint64_t > ( - 2 ) , / / Must be the smallest uint64_t value compared to all other tags <nl> + unset_next_primary_key = static_cast < uint64_t > ( - 1 ) <nl> + } ; <nl> <nl> struct item : public T <nl> { <nl> template < typename Constructor > <nl> - item ( const multi_index & idx , Constructor & & c ) <nl> - : __idx ( std : : cref ( idx ) ) { <nl> + item ( const multi_index * idx , Constructor & & c ) <nl> + : __idx ( idx ) { <nl> c ( * this ) ; <nl> } <nl> <nl> - std : : reference_wrapper < const multi_index > __idx ; <nl> - int __primary_itr ; <nl> - int __iters [ sizeof . . . ( Indices ) + ( sizeof . . . ( Indices ) = = 0 ) ] ; <nl> + const multi_index * __idx ; <nl> + int32_t __primary_itr ; <nl> + int32_t __iters [ sizeof . . . ( Indices ) + ( sizeof . . . ( Indices ) = = 0 ) ] ; <nl> } ; <nl> <nl> - uint64_t _code ; <nl> - uint64_t _scope ; <nl> - <nl> - mutable uint64_t _next_primary_key ; <nl> + struct item_ptr <nl> + { <nl> + item_ptr ( std : : unique_ptr < item > & & i , uint64_t pk , int32_t pitr ) <nl> + : _item ( std : : move ( i ) ) , _primary_key ( pk ) , _primary_itr ( pitr ) { } <nl> <nl> - enum next_primary_key_tags : uint64_t { <nl> - no_available_primary_key = static_cast < uint64_t > ( - 2 ) , / / Must be the smallest uint64_t value compared to all other tags <nl> - unset_next_primary_key = static_cast < uint64_t > ( - 1 ) <nl> + std : : unique_ptr < item > _item ; <nl> + uint64_t _primary_key ; <nl> + int32_t _primary_itr ; <nl> } ; <nl> <nl> + mutable std : : vector < item_ptr > _items_vector ; <nl> + <nl> template < uint64_t IndexName , typename Extractor , uint64_t Number , bool IsConst > <nl> struct index { <nl> public : <nl> class multi_index <nl> <nl> const_iterator & operator + + ( ) { <nl> eosio_assert ( _item ! = nullptr , " cannot increment end iterator " ) ; <nl> - const auto & idx = _idx . get ( ) ; <nl> <nl> if ( _item - > __iters [ Number ] = = - 1 ) { <nl> secondary_key_type temp_secondary_key ; <nl> - auto idxitr = db_idx_find_primary ( idx . get_code ( ) , <nl> - idx . get_scope ( ) , <nl> - idx . name ( ) , <nl> + auto idxitr = db_idx_find_primary ( _idx - > get_code ( ) , _idx - > get_scope ( ) , _idx - > name ( ) , <nl> _item - > primary_key ( ) , temp_secondary_key ) ; <nl> auto & mi = const_cast < item & > ( * _item ) ; <nl> mi . __iters [ Number ] = idxitr ; <nl> class multi_index <nl> return * this ; <nl> } <nl> <nl> - const T & obj = * idx . _multidx . find ( next_pk ) ; <nl> + const T & obj = * _idx - > _multidx - > find ( next_pk ) ; <nl> auto & mi = const_cast < item & > ( static_cast < const item & > ( obj ) ) ; <nl> mi . __iters [ Number ] = next_itr ; <nl> _item = & mi ; <nl> class multi_index <nl> <nl> const_iterator & operator - - ( ) { <nl> uint64_t prev_pk = 0 ; <nl> - int prev_itr = - 1 ; <nl> - const auto & idx = _idx . get ( ) ; <nl> + int32_t prev_itr = - 1 ; <nl> <nl> if ( ! _item ) { <nl> - auto ei = secondary_iterator < secondary_key_type > : : db_idx_end ( idx . get_code ( ) , idx . get_scope ( ) , idx . name ( ) ) ; <nl> + auto ei = secondary_iterator < secondary_key_type > : : db_idx_end ( _idx - > get_code ( ) , _idx - > get_scope ( ) , _idx - > name ( ) ) ; <nl> eosio_assert ( ei ! = - 1 , " cannot decrement end iterator when the index is empty " ) ; <nl> prev_itr = secondary_iterator < secondary_key_type > : : db_idx_previous ( ei , & prev_pk ) ; <nl> eosio_assert ( prev_itr > = 0 , " cannot decrement end iterator when the index is empty " ) ; <nl> } else { <nl> if ( _item - > __iters [ Number ] = = - 1 ) { <nl> secondary_key_type temp_secondary_key ; <nl> - auto idxitr = db_idx_find_primary ( idx . get_code ( ) , <nl> - idx . get_scope ( ) , <nl> - idx . name ( ) , <nl> + auto idxitr = db_idx_find_primary ( _idx - > get_code ( ) , _idx - > get_scope ( ) , _idx - > name ( ) , <nl> _item - > primary_key ( ) , temp_secondary_key ) ; <nl> auto & mi = const_cast < item & > ( * _item ) ; <nl> mi . __iters [ Number ] = idxitr ; <nl> class multi_index <nl> eosio_assert ( prev_itr > = 0 , " cannot decrement iterator at beginning of index " ) ; <nl> } <nl> <nl> - const T & obj = * idx . _multidx . find ( prev_pk ) ; <nl> + const T & obj = * _idx - > _multidx - > find ( prev_pk ) ; <nl> auto & mi = const_cast < item & > ( static_cast < const item & > ( obj ) ) ; <nl> mi . __iters [ Number ] = prev_itr ; <nl> _item = & mi ; <nl> class multi_index <nl> <nl> private : <nl> friend struct index ; <nl> - const_iterator ( const index & idx , const item * i = nullptr ) <nl> - : _idx ( std : : cref ( idx ) ) , _item ( i ) { } <nl> + const_iterator ( const index * idx , const item * i = nullptr ) <nl> + : _idx ( idx ) , _item ( i ) { } <nl> <nl> - std : : reference_wrapper < const index > _idx ; <nl> - const item * _item ; <nl> + const index * _idx ; <nl> + const item * _item ; <nl> } ; / / / struct multi_index : : index : : const_iterator <nl> <nl> typedef std : : reverse_iterator < const_iterator > const_reverse_iterator ; <nl> class multi_index <nl> } <nl> const_iterator begin ( ) const { return cbegin ( ) ; } <nl> <nl> - const_iterator cend ( ) const { return const_iterator ( * this ) ; } <nl> + const_iterator cend ( ) const { return const_iterator ( this ) ; } <nl> const_iterator end ( ) const { return cend ( ) ; } <nl> <nl> const_reverse_iterator crbegin ( ) const { return std : : make_reverse_iterator ( cend ( ) ) ; } <nl> class multi_index <nl> <nl> const_iterator find ( secondary_key_type & & secondary ) const { <nl> auto lb = lower_bound ( secondary ) ; <nl> - auto e = end ( ) ; <nl> + auto e = cend ( ) ; <nl> if ( lb = = e ) return e ; <nl> <nl> if ( secondary ! = secondary_extractor_type ( ) ( * lb ) ) <nl> class multi_index <nl> const_iterator lower_bound ( const secondary_key_type & secondary ) const { <nl> uint64_t primary = 0 ; <nl> secondary_key_type secondary_copy ( secondary ) ; <nl> - auto itr = lower_bound ( get_code ( ) , get_scope ( ) , secondary_copy , primary ) ; <nl> - if ( itr < 0 ) return end ( ) ; <nl> + auto itr = db_idx_lowerbound ( get_code ( ) , get_scope ( ) , name ( ) , secondary_copy , primary ) ; <nl> + if ( itr < 0 ) return cend ( ) ; <nl> <nl> - const T & obj = * _multidx . find ( primary ) ; <nl> + const T & obj = * _multidx - > find ( primary ) ; <nl> auto & mi = const_cast < item & > ( static_cast < const item & > ( obj ) ) ; <nl> mi . __iters [ Number ] = itr ; <nl> <nl> - return { * this , & mi } ; <nl> + return { this , & mi } ; <nl> } <nl> + <nl> const_iterator upper_bound ( secondary_key_type & & secondary ) const { <nl> return upper_bound ( secondary ) ; <nl> } <nl> const_iterator upper_bound ( const secondary_key_type & secondary ) const { <nl> uint64_t primary = 0 ; <nl> secondary_key_type secondary_copy ( secondary ) ; <nl> - auto itr = upper_bound ( get_code ( ) , get_scope ( ) , secondary_copy , primary ) ; <nl> - if ( itr < 0 ) return end ( ) ; <nl> + auto itr = db_idx_upperbound ( get_code ( ) , get_scope ( ) , name ( ) , secondary_copy , primary ) ; <nl> + if ( itr < 0 ) return cend ( ) ; <nl> <nl> - const T & obj = * _multidx . find ( primary ) ; <nl> + const T & obj = * _multidx - > find ( primary ) ; <nl> auto & mi = const_cast < item & > ( static_cast < const item & > ( obj ) ) ; <nl> mi . __iters [ Number ] = itr ; <nl> <nl> - return { * this , & mi } ; <nl> + return { this , & mi } ; <nl> } <nl> <nl> const_iterator iterator_to ( const T & obj ) { <nl> const auto & objitem = static_cast < const item & > ( obj ) ; <nl> - eosio_assert ( & objitem . __idx . get ( ) = = & _multidx , " object passed to iterator_to is not in multi_index " ) ; <nl> + eosio_assert ( objitem . __idx = = _multidx , " object passed to iterator_to is not in multi_index " ) ; <nl> <nl> if ( objitem . __iters [ Number ] = = - 1 ) { <nl> secondary_key_type temp_secondary_key ; <nl> - auto idxitr = db_idx_find_primary ( get_code ( ) , <nl> - get_scope ( ) , <nl> - name ( ) , <nl> + auto idxitr = db_idx_find_primary ( get_code ( ) , get_scope ( ) , name ( ) , <nl> objitem . primary_key ( ) , temp_secondary_key ) ; <nl> auto & mi = const_cast < item & > ( objitem ) ; <nl> mi . __iters [ Number ] = idxitr ; <nl> } <nl> <nl> - return { * this , & objitem } ; <nl> + return { this , & objitem } ; <nl> } <nl> <nl> template < typename Lambda > <nl> void modify ( const_iterator itr , uint64_t payer , Lambda & & updater ) { <nl> - eosio_assert ( itr ! = end ( ) , " cannot pass end iterator to modify " ) ; <nl> + eosio_assert ( itr ! = cend ( ) , " cannot pass end iterator to modify " ) ; <nl> <nl> - _multidx . modify ( * itr , payer , std : : forward < Lambda & & > ( updater ) ) ; <nl> + _multidx - > modify ( * itr , payer , std : : forward < Lambda & & > ( updater ) ) ; <nl> } <nl> <nl> const_iterator erase ( const_iterator itr ) { <nl> - eosio_assert ( itr ! = end ( ) , " cannot pass end iterator to erase " ) ; <nl> + eosio_assert ( itr ! = cend ( ) , " cannot pass end iterator to erase " ) ; <nl> <nl> const auto & obj = * itr ; <nl> + + itr ; <nl> <nl> - _multidx . erase ( obj ) ; <nl> + _multidx - > erase ( obj ) ; <nl> <nl> return itr ; <nl> } <nl> <nl> - uint64_t get_code ( ) const { return _multidx . get_code ( ) ; } <nl> - uint64_t get_scope ( ) const { return _multidx . get_scope ( ) ; } <nl> + uint64_t get_code ( ) const { return _multidx - > get_code ( ) ; } <nl> + uint64_t get_scope ( ) const { return _multidx - > get_scope ( ) ; } <nl> <nl> static auto extract_secondary_key ( const T & obj ) { return secondary_extractor_type ( ) ( obj ) ; } <nl> <nl> - static int store ( uint64_t scope , uint64_t payer , const T & obj ) { <nl> - return db_idx_store ( scope , name ( ) , payer , obj . primary_key ( ) , extract_secondary_key ( obj ) ) ; <nl> - } <nl> - <nl> - static void update ( int iterator , uint64_t payer , const secondary_key_type & secondary ) { <nl> - db_idx_update ( iterator , payer , secondary ) ; <nl> - } <nl> - <nl> - static int find_primary ( uint64_t code , uint64_t scope , uint64_t primary , secondary_key_type & secondary ) { <nl> - return db_idx_find_primary ( code , scope , name ( ) , primary , secondary ) ; <nl> - } <nl> - <nl> - static void remove ( int itr ) { <nl> - secondary_iterator < secondary_key_type > : : db_idx_remove ( itr ) ; <nl> - } <nl> - <nl> - static int find_secondary ( uint64_t code , uint64_t scope , secondary_key_type & secondary , uint64_t & primary ) { <nl> - return db_idx_find_secondary ( code , scope , name ( ) , secondary , primary ) ; <nl> - } <nl> - <nl> - static int lower_bound ( uint64_t code , uint64_t scope , secondary_key_type & secondary , uint64_t & primary ) { <nl> - return db_idx_lowerbound ( code , scope , name ( ) , secondary , primary ) ; <nl> - } <nl> - <nl> - static int upper_bound ( uint64_t code , uint64_t scope , secondary_key_type & secondary , uint64_t & primary ) { <nl> - return db_idx_upperbound ( code , scope , name ( ) , secondary , primary ) ; <nl> - } <nl> - <nl> private : <nl> friend class multi_index ; <nl> <nl> - index ( typename std : : conditional < IsConst , const multi_index & , multi_index & > : : type midx ) <nl> + index ( typename std : : conditional < IsConst , const multi_index * , multi_index * > : : type midx ) <nl> : _multidx ( midx ) { } <nl> <nl> - typename std : : conditional < IsConst , const multi_index & , multi_index & > : : type _multidx ; <nl> + typename std : : conditional < IsConst , const multi_index * , multi_index * > : : type _multidx ; <nl> } ; / / / struct multi_index : : index <nl> <nl> template < uint64_t I > <nl> class multi_index <nl> <nl> indices_type _indices ; <nl> <nl> - struct by_primary_key ; <nl> - struct by_primary_itr ; <nl> - <nl> - / * <nl> - mutable boost : : multi_index_container < item , <nl> - bmi : : indexed_by < <nl> - bmi : : ordered_unique < bmi : : tag < by_primary_key > , bmi : : const_mem_fun < T , uint64_t , & T : : primary_key > > , <nl> - bmi : : ordered_unique < bmi : : tag < by_primary_itr > , bmi : : member < item , int , & item : : __primary_itr > > <nl> - > <nl> - > _items_index ; <nl> - * / <nl> - <nl> - mutable std : : vector < item > _items_vector ; <nl> - <nl> - const item & load_object_by_primary_iterator ( int itr ) const { <nl> - auto itr2 = std : : find_if ( _items_vector . rbegin ( ) , _items_vector . rend ( ) , [ & ] ( const item & objitem ) { <nl> - return objitem . __primary_itr = = itr ; <nl> + const item & load_object_by_primary_iterator ( int32_t itr ) const { <nl> + auto itr2 = std : : find_if ( _items_vector . rbegin ( ) , _items_vector . rend ( ) , [ & ] ( const item_ptr & ptr ) { <nl> + return ptr . _primary_itr = = itr ; <nl> } ) ; <nl> - <nl> if ( itr2 ! = _items_vector . rend ( ) ) <nl> - return * itr2 ; <nl> - <nl> - / * <nl> - const auto & by_pitr = _items_index . template get < by_primary_itr > ( ) ; <nl> - auto cacheitr = by_pitr . find ( itr ) ; <nl> - if ( cacheitr ! = by_pitr . end ( ) ) <nl> - return * cacheitr ; <nl> - * / <nl> + return * itr2 - > _item ; <nl> <nl> auto size = db_get_i64 ( itr , nullptr , 0 ) ; <nl> eosio_assert ( size > = 0 , " error reading iterator " ) ; <nl> class multi_index <nl> <nl> datastream < const char * > ds ( tmp , uint32_t ( size ) ) ; <nl> <nl> - / / auto result = _items_index . emplace ( * this , [ & ] ( auto & i ) { <nl> - _items_vector . emplace_back ( * this , [ & ] ( auto & i ) { <nl> + auto itm = std : : make_unique < item > ( this , [ & ] ( auto & i ) { <nl> T & val = static_cast < T & > ( i ) ; <nl> ds > > val ; <nl> <nl> class multi_index <nl> } ) ; <nl> } ) ; <nl> <nl> - / / eosio_assert ( result . second , " failed to insert object , likely a uniqueness constraint was violated " ) ; <nl> + const item * ptr = itm . get ( ) ; <nl> + auto pk = itm - > primary_key ( ) ; <nl> + auto pitr = itm - > __primary_itr ; <nl> + <nl> + _items_vector . emplace_back ( std : : move ( itm ) , pk , pitr ) ; <nl> <nl> - / / return * result . first ; <nl> - return _items_vector . back ( ) ; <nl> + return * ptr ; <nl> } / / / load_object_by_primary_iterator <nl> <nl> public : <nl> class multi_index <nl> : _code ( code ) , _scope ( scope ) , _next_primary_key ( unset_next_primary_key ) <nl> { } <nl> <nl> - uint64_t get_code ( ) const { return _code ; } <nl> + uint64_t get_code ( ) const { return _code ; } <nl> uint64_t get_scope ( ) const { return _scope ; } <nl> <nl> struct const_iterator : public std : : iterator < std : : bidirectional_iterator_tag , const T > { <nl> class multi_index <nl> <nl> const_iterator & operator + + ( ) { <nl> eosio_assert ( _item ! = nullptr , " cannot increment end iterator " ) ; <nl> - const auto & multidx = _multidx . get ( ) ; <nl> <nl> uint64_t next_pk ; <nl> auto next_itr = db_next_i64 ( _item - > __primary_itr , & next_pk ) ; <nl> if ( next_itr < 0 ) <nl> _item = nullptr ; <nl> else <nl> - _item = & multidx . load_object_by_primary_iterator ( next_itr ) ; <nl> + _item = & _multidx - > load_object_by_primary_iterator ( next_itr ) ; <nl> return * this ; <nl> } <nl> const_iterator & operator - - ( ) { <nl> uint64_t prev_pk ; <nl> - int prev_itr = - 1 ; <nl> - const auto & multidx = _multidx . get ( ) ; <nl> + int32_t prev_itr = - 1 ; <nl> <nl> if ( ! _item ) { <nl> - auto ei = db_end_i64 ( multidx . get_code ( ) , multidx . get_scope ( ) , TableName ) ; <nl> + auto ei = db_end_i64 ( _multidx - > get_code ( ) , _multidx - > get_scope ( ) , TableName ) ; <nl> eosio_assert ( ei ! = - 1 , " cannot decrement end iterator when the table is empty " ) ; <nl> prev_itr = db_previous_i64 ( ei , & prev_pk ) ; <nl> eosio_assert ( prev_itr > = 0 , " cannot decrement end iterator when the table is empty " ) ; <nl> class multi_index <nl> eosio_assert ( prev_itr > = 0 , " cannot decrement iterator at beginning of table " ) ; <nl> } <nl> <nl> - _item = & multidx . load_object_by_primary_iterator ( prev_itr ) ; <nl> + _item = & _multidx - > load_object_by_primary_iterator ( prev_itr ) ; <nl> return * this ; <nl> } <nl> <nl> private : <nl> - const_iterator ( const multi_index & mi , const item * i = nullptr ) <nl> - : _multidx ( std : : cref ( mi ) ) , _item ( i ) { } <nl> + const_iterator ( const multi_index * mi , const item * i = nullptr ) <nl> + : _multidx ( mi ) , _item ( i ) { } <nl> <nl> - std : : reference_wrapper < const multi_index > _multidx ; <nl> - const item * _item ; <nl> + const multi_index * _multidx ; <nl> + const item * _item ; <nl> friend class multi_index ; <nl> } ; / / / struct multi_index : : const_iterator <nl> <nl> class multi_index <nl> } <nl> const_iterator begin ( ) const { return cbegin ( ) ; } <nl> <nl> - const_iterator cend ( ) const { return const_iterator ( * this ) ; } <nl> + const_iterator cend ( ) const { return const_iterator ( this ) ; } <nl> const_iterator end ( ) const { return cend ( ) ; } <nl> <nl> const_reverse_iterator crbegin ( ) const { return std : : make_reverse_iterator ( cend ( ) ) ; } <nl> class multi_index <nl> const_iterator lower_bound ( uint64_t primary ) const { <nl> auto itr = db_lowerbound_i64 ( _code , _scope , TableName , primary ) ; <nl> if ( itr < 0 ) return end ( ) ; <nl> - auto & obj = load_object_by_primary_iterator ( itr ) ; <nl> - return { * this , & obj } ; <nl> + const auto & obj = load_object_by_primary_iterator ( itr ) ; <nl> + return { this , & obj } ; <nl> } <nl> <nl> const_iterator upper_bound ( uint64_t primary ) const { <nl> auto itr = db_upperbound_i64 ( _code , _scope , TableName , primary ) ; <nl> if ( itr < 0 ) return end ( ) ; <nl> - auto & obj = load_object_by_primary_iterator ( itr ) ; <nl> - return { * this , & obj } ; <nl> + const auto & obj = load_object_by_primary_iterator ( itr ) ; <nl> + return { this , & obj } ; <nl> } <nl> <nl> / * * Ideally this method would only be used to determine the appropriate primary key to use within new objects added to a <nl> class multi_index <nl> <nl> static_assert ( res ! = hana : : nothing , " name provided is not the name of any secondary index within multi_index " ) ; <nl> <nl> - return typename decltype ( + hana : : at_c < 0 > ( res . value ( ) ) ) : : type ( * this ) ; <nl> + return typename decltype ( + hana : : at_c < 0 > ( res . value ( ) ) ) : : type ( this ) ; <nl> } <nl> <nl> template < uint64_t IndexName > <nl> class multi_index <nl> <nl> static_assert ( res ! = hana : : nothing , " name provided is not the name of any secondary index within multi_index " ) ; <nl> <nl> - return typename decltype ( + hana : : at_c < 1 > ( res . value ( ) ) ) : : type ( * this ) ; <nl> + return typename decltype ( + hana : : at_c < 1 > ( res . value ( ) ) ) : : type ( this ) ; <nl> } <nl> <nl> const_iterator iterator_to ( const T & obj ) const { <nl> const auto & objitem = static_cast < const item & > ( obj ) ; <nl> - eosio_assert ( & objitem . __idx . get ( ) = = this , " object passed to iterator_to is not in multi_index " ) ; <nl> - return { * this , & objitem } ; <nl> + eosio_assert ( objitem . __idx = = this , " object passed to iterator_to is not in multi_index " ) ; <nl> + return { this , & objitem } ; <nl> } <nl> <nl> template < typename Lambda > <nl> const_iterator emplace ( uint64_t payer , Lambda & & constructor ) { <nl> - / / auto result = _items_index . emplace ( * this , [ & ] ( auto & i ) { <nl> - _items_vector . emplace_back ( * this , [ & ] ( auto & i ) { <nl> + auto itm = std : : make_unique < item > ( this , [ & ] ( auto & i ) { <nl> T & obj = static_cast < T & > ( i ) ; <nl> constructor ( obj ) ; <nl> <nl> class multi_index <nl> boost : : hana : : for_each ( _indices , [ & ] ( auto & idx ) { <nl> typedef typename decltype ( + hana : : at_c < 0 > ( idx ) ) : : type index_type ; <nl> <nl> - i . __iters [ index_type : : number ( ) ] = index_type : : store ( _scope , payer , obj ) ; <nl> + i . __iters [ index_type : : number ( ) ] = db_idx_store ( _scope , index_type : : name ( ) , payer , obj . primary_key ( ) , index_type : : extract_secondary_key ( obj ) ) ; <nl> } ) ; <nl> } ) ; <nl> <nl> - / / / eosio_assert ( result . second , " could not insert object , uniqueness constraint in cache violated " ) <nl> - / / return { * this , & * result . first } ; <nl> - return { * this , & _items_vector . back ( ) } ; <nl> + const item * ptr = itm . get ( ) ; <nl> + auto pk = itm - > primary_key ( ) ; <nl> + auto pitr = itm - > __primary_itr ; <nl> + <nl> + _items_vector . emplace_back ( std : : move ( itm ) , pk , pitr ) ; <nl> + <nl> + return { this , ptr } ; <nl> } <nl> <nl> template < typename Lambda > <nl> void modify ( const_iterator itr , uint64_t payer , Lambda & & updater ) { <nl> - eosio_assert ( itr ! = end ( ) , " cannot pass end iterator to update " ) ; <nl> + eosio_assert ( itr ! = end ( ) , " cannot pass end iterator to modify " ) ; <nl> <nl> modify ( * itr , payer , std : : forward < Lambda & & > ( updater ) ) ; <nl> } <nl> class multi_index <nl> const auto & objitem = static_cast < const item & > ( obj ) ; <nl> auto & mutableitem = const_cast < item & > ( objitem ) ; <nl> <nl> - / / eosio_assert ( & objitem . __idx = = this , " invalid object " ) ; <nl> - <nl> auto secondary_keys = boost : : hana : : transform ( _indices , [ & ] ( auto & & idx ) { <nl> typedef typename decltype ( + hana : : at_c < 0 > ( idx ) ) : : type index_type ; <nl> <nl> class multi_index <nl> auto indexitr = mutableitem . __iters [ index_type : : number ( ) ] ; <nl> <nl> if ( indexitr < 0 ) <nl> - indexitr = mutableitem . __iters [ index_type : : number ( ) ] = index_type : : find_primary ( _code , _scope , pk , secondary ) ; <nl> + indexitr = mutableitem . __iters [ index_type : : number ( ) ] = db_idx_find_primary ( _code , _scope , index_type : : name ( ) , pk , secondary ) ; <nl> <nl> - index_type : : update ( indexitr , payer , secondary ) ; <nl> + db_idx_update ( indexitr , payer , secondary ) ; <nl> } <nl> } ) ; <nl> } <nl> class multi_index <nl> } <nl> <nl> const_iterator find ( uint64_t primary ) const { <nl> - auto itr2 = std : : find_if ( _items_vector . rbegin ( ) , _items_vector . rend ( ) , [ & ] ( const item & objitem ) { <nl> - return objitem . __primary_itr ! = - 1 & & objitem . primary_key ( ) = = primary ; <nl> + auto itr2 = std : : find_if ( _items_vector . rbegin ( ) , _items_vector . rend ( ) , [ & ] ( const item_ptr & ptr ) { <nl> + return ptr . _item - > primary_key ( ) = = primary ; <nl> } ) ; <nl> - <nl> if ( itr2 ! = _items_vector . rend ( ) ) <nl> - return iterator_to ( * itr2 ) ; <nl> - <nl> - / * <nl> - auto cacheitr = _items_index . find ( primary ) ; <nl> - if ( cacheitr ! = _items_index . end ( ) ) <nl> - return iterator_to ( * cacheitr ) ; <nl> - * / <nl> + return iterator_to ( * ( itr2 - > _item ) ) ; <nl> <nl> - int itr = db_find_i64 ( _code , _scope , TableName , primary ) ; <nl> + auto itr = db_find_i64 ( _code , _scope , TableName , primary ) ; <nl> if ( itr < 0 ) return end ( ) ; <nl> <nl> const item & i = load_object_by_primary_iterator ( itr ) ; <nl> class multi_index <nl> <nl> void erase ( const T & obj ) { <nl> const auto & objitem = static_cast < const item & > ( obj ) ; <nl> - / / auto & mutableitem = const_cast < item & > ( objitem ) ; <nl> - / / eosio_assert ( & objitem . __idx = = this , " invalid object " ) ; <nl> + eosio_assert ( objitem . __idx = = this , " object passed to erase is not in multi_index " ) ; <nl> + <nl> + auto pk = objitem . primary_key ( ) ; <nl> + auto itr2 = std : : find_if ( _items_vector . rbegin ( ) , _items_vector . rend ( ) , [ & ] ( const item_ptr & ptr ) { <nl> + return ptr . _item - > primary_key ( ) = = pk ; <nl> + } ) ; <nl> + <nl> + eosio_assert ( itr2 ! = _items_vector . rend ( ) , " attempt to remove object that was not in multi_index " ) ; <nl> + <nl> + _items_vector . erase ( - - ( itr2 . base ( ) ) ) ; <nl> <nl> db_remove_i64 ( objitem . __primary_itr ) ; <nl> <nl> class multi_index <nl> <nl> auto i = objitem . __iters [ index_type : : number ( ) ] ; <nl> if ( i < 0 ) { <nl> - typename index_type : : secondary_key_type second ; <nl> - i = index_type : : find_primary ( _code , _scope , objitem . primary_key ( ) , second ) ; <nl> + typename index_type : : secondary_key_type secondary ; <nl> + i = db_idx_find_primary ( _code , _scope , index_type : : name ( ) , objitem . primary_key ( ) , secondary ) ; <nl> } <nl> if ( i > = 0 ) <nl> - index_type : : remove ( i ) ; <nl> + secondary_iterator < typename index_type : : secondary_key_type > : : db_idx_remove ( i ) ; <nl> } ) ; <nl> - <nl> - auto pk = objitem . primary_key ( ) ; <nl> - auto itr2 = std : : find_if ( _items_vector . rbegin ( ) , _items_vector . rend ( ) , [ & ] ( const item & oi ) { <nl> - return oi . __primary_itr ! = - 1 & & oi . primary_key ( ) = = pk ; <nl> - } ) ; <nl> - <nl> - if ( itr2 ! = _items_vector . rend ( ) ) <nl> - ( - - ( itr2 . base ( ) ) ) - > __primary_itr = - 1 ; / / Mark item as deleted <nl> - <nl> - / * <nl> - auto cacheitr = _items_index . find ( objitem . primary_key ( ) ) ; <nl> - if ( cacheitr ! = _items_index . end ( ) ) { <nl> - _items_index . erase ( cacheitr ) ; <nl> - } <nl> - * / <nl> } <nl> <nl> } ; <nl> mmm a / contracts / test_api_multi_index / test_multi_index . cpp <nl> ppp b / contracts / test_api_multi_index / test_multi_index . cpp <nl> namespace _test_multi_index { <nl> / / modify and erase <nl> { <nl> const uint64_t ssn = 421 ; <nl> - const auto & new_person = table . emplace ( payer , [ & ] ( auto & r ) { <nl> + auto new_person = table . emplace ( payer , [ & ] ( auto & r ) { <nl> r . id = ssn ; <nl> r . sec = N ( bob ) ; <nl> } ) ; <nl> | indirect access to items , properly erase items , and code cleanup | EOSIO/eos | 28771835d2934832ac4b1c50f4a6d891961e8a6f | 2018-03-13T22:13:10Z |
mmm a / include / swift / AST / GenericEnvironment . h <nl> ppp b / include / swift / AST / GenericEnvironment . h <nl> <nl> # define SWIFT_AST_GENERIC_ENVIRONMENT_H <nl> <nl> # include " swift / AST / ProtocolConformance . h " <nl> + # include " swift / AST / SubstitutionMap . h " <nl> <nl> namespace swift { <nl> <nl> class GenericEnvironment final { <nl> / / / Derive a contextual type substitution map from a substitution array . <nl> / / / This is just like GenericSignature : : getSubstitutionMap ( ) , except <nl> / / / with contextual types instead of interface types . <nl> + SubstitutionMap <nl> + getSubstitutionMap ( ModuleDecl * mod , <nl> + GenericSignature * sig , <nl> + ArrayRef < Substitution > subs ) const ; <nl> + <nl> + / / / Same as above , but updates an existing map . <nl> void <nl> getSubstitutionMap ( ModuleDecl * mod , <nl> GenericSignature * sig , <nl> ArrayRef < Substitution > subs , <nl> - TypeSubstitutionMap & subsMap , <nl> - ArchetypeConformanceMap & conformanceMap ) const ; <nl> + SubstitutionMap & subMap ) const ; <nl> <nl> ArrayRef < Substitution > <nl> getForwardingSubstitutions ( ModuleDecl * M , GenericSignature * sig ) const ; <nl> mmm a / include / swift / AST / GenericSignature . h <nl> ppp b / include / swift / AST / GenericSignature . h <nl> <nl> namespace swift { <nl> <nl> class ArchetypeBuilder ; <nl> + class ProtocolConformanceRef ; <nl> class ProtocolType ; <nl> - <nl> - using TypeConformanceMap <nl> - = llvm : : DenseMap < TypeBase * , ArrayRef < ProtocolConformanceRef > > ; <nl> + class Substitution ; <nl> + class SubstitutionMap ; <nl> <nl> / / / Iterator that walks the generic parameter types declared in a generic <nl> / / / signature and their dependent members . <nl> class GenericSignature final : public llvm : : FoldingSetNode , <nl> <nl> / / / Build an interface type substitution map from a vector of Substitutions <nl> / / / that correspond to the generic parameters in this generic signature . <nl> - / / / The order of primary archetypes in the substitution vector must match <nl> - / / / the order of generic parameters in getGenericParams ( ) . <nl> - TypeSubstitutionMap getSubstitutionMap ( ArrayRef < Substitution > args ) const ; <nl> + SubstitutionMap getSubstitutionMap ( ArrayRef < Substitution > args ) const ; <nl> <nl> - / / / Variant of the above that also returns conformances . <nl> - void getSubstitutionMap ( ArrayRef < Substitution > subs , <nl> - TypeSubstitutionMap & subMap , <nl> - TypeConformanceMap & conformanceMap ) const ; <nl> + / / / Same as above , but updates an existing map . <nl> + void getSubstitutionMap ( ArrayRef < Substitution > args , <nl> + SubstitutionMap & subMap ) const ; <nl> <nl> using LookupConformanceFn = <nl> llvm : : function_ref < ProtocolConformanceRef ( CanType , Type , ProtocolType * ) > ; <nl> class GenericSignature final : public llvm : : FoldingSetNode , <nl> / / / Build an array of substitutions from an interface type substitution map , <nl> / / / using the given function to look up conformances . <nl> void getSubstitutions ( ModuleDecl & mod , <nl> - const TypeSubstitutionMap & subMap , <nl> - const TypeConformanceMap & conformanceMap , <nl> + const SubstitutionMap & subMap , <nl> SmallVectorImpl < Substitution > & result ) const ; <nl> <nl> / / / Return a range that iterates through first all of the generic parameters <nl> mmm a / include / swift / AST / ProtocolConformance . h <nl> ppp b / include / swift / AST / ProtocolConformance . h <nl> class alignas ( 1 < < DeclAlignInBits ) ProtocolConformance { <nl> / / / applies to the substituted type . <nl> ProtocolConformance * subst ( ModuleDecl * module , <nl> Type substType , <nl> - TypeSubstitutionMap & subMap , <nl> - ArchetypeConformanceMap & conformanceMap ) ; <nl> + const SubstitutionMap & subMap ) const ; <nl> } ; <nl> <nl> / / / Normal protocol conformance , which involves mapping each of the protocol <nl> mmm a / include / swift / AST / Substitution . h <nl> ppp b / include / swift / AST / Substitution . h <nl> <nl> # ifndef SWIFT_AST_SUBSTITUTION_H <nl> # define SWIFT_AST_SUBSTITUTION_H <nl> <nl> + # include " swift / AST / SubstitutionMap . h " <nl> # include " swift / AST / Type . h " <nl> # include " llvm / ADT / ArrayRef . h " <nl> # include " llvm / ADT / Optional . h " <nl> namespace llvm { <nl> } <nl> <nl> namespace swift { <nl> - class ArchetypeType ; <nl> class GenericEnvironment ; <nl> - class ProtocolConformanceRef ; <nl> - <nl> - / / / Data structure type used internally by Substitution : : subst to track <nl> - / / / conformances applied to archetypes . <nl> - class ArchetypeConformanceMap { <nl> - using ParentType = std : : pair < ArchetypeType * , AssociatedTypeDecl * > ; <nl> - <nl> - llvm : : DenseMap < ArchetypeType * , ArrayRef < ProtocolConformanceRef > > map ; <nl> - llvm : : DenseMap < ArchetypeType * , SmallVector < ParentType , 1 > > parents ; <nl> - <nl> - Optional < ProtocolConformanceRef > <nl> - lookupArchetypeConformance ( ProtocolDecl * proto , <nl> - ArrayRef < ProtocolConformanceRef > conformances ) const ; <nl> - <nl> - public : <nl> - Optional < ProtocolConformanceRef > <nl> - lookupArchetypeConformance ( ArchetypeType * replacement , <nl> - ProtocolDecl * proto ) const ; <nl> - <nl> - void addArchetypeConformances ( ArchetypeType * replacement , <nl> - ArrayRef < ProtocolConformanceRef > conformances ) ; <nl> - <nl> - void addArchetypeParent ( ArchetypeType * replacement , ArchetypeType * parent , <nl> - AssociatedTypeDecl * assocType ) ; <nl> - } ; <nl> <nl> / / / Substitution - A substitution into a generic specialization . <nl> class Substitution { <nl> class Substitution { <nl> ArrayRef < Substitution > subs ) const ; <nl> <nl> Substitution subst ( ModuleDecl * module , <nl> - TypeSubstitutionMap & subMap , <nl> - ArchetypeConformanceMap & conformanceMap ) const ; <nl> + const SubstitutionMap & subMap ) const ; <nl> <nl> private : <nl> friend class ProtocolConformance ; <nl> new file mode 100644 <nl> index 000000000000 . . ea62585b4d19 <nl> mmm / dev / null <nl> ppp b / include / swift / AST / SubstitutionMap . h <nl> <nl> + / / = = = mmm SubstitutionMap . h - Swift Substitution Map ASTs mmmmmm - - * - C + + - * - = = = / / <nl> + / / <nl> + / / This source file is part of the Swift . org open source project <nl> + / / <nl> + / / Copyright ( c ) 2014 - 2016 Apple Inc . and the Swift project authors <nl> + / / Licensed under Apache License v2 . 0 with Runtime Library Exception <nl> + / / <nl> + / / See http : / / swift . org / LICENSE . txt for license information <nl> + / / See http : / / swift . org / CONTRIBUTORS . txt for the list of Swift project authors <nl> + / / <nl> + / / = = = mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - = = = / / <nl> + / / <nl> + / / This file defines the SubstitutionMap class . <nl> + / / <nl> + / / This is a data structure type describing the mapping of abstract types to <nl> + / / replacement types , together with associated conformances to use for deriving <nl> + / / nested types . <nl> + / / <nl> + / / Depending on how the SubstitutionMap is constructed , the abstract types are <nl> + / / either archetypes or interface types . Care must be exercised to only look up <nl> + / / one or the other . <nl> + / / <nl> + / / = = = mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - = = = / / <nl> + <nl> + # ifndef SWIFT_AST_SUBSTITUTION_MAP_H <nl> + # define SWIFT_AST_SUBSTITUTION_MAP_H <nl> + <nl> + # include " swift / AST / ProtocolConformanceRef . h " <nl> + # include " swift / AST / Type . h " <nl> + # include " llvm / ADT / ArrayRef . h " <nl> + # include " llvm / ADT / DenseMap . h " <nl> + # include " llvm / ADT / Optional . h " <nl> + # include " llvm / ADT / SmallVector . h " <nl> + <nl> + namespace swift { <nl> + <nl> + class SubstitutionMap { <nl> + using ParentType = std : : pair < CanType , AssociatedTypeDecl * > ; <nl> + <nl> + llvm : : DenseMap < TypeBase * , Type > subMap ; <nl> + llvm : : DenseMap < TypeBase * , ArrayRef < ProtocolConformanceRef > > conformanceMap ; <nl> + llvm : : DenseMap < TypeBase * , SmallVector < ParentType , 1 > > parentMap ; <nl> + <nl> + Optional < ProtocolConformanceRef > <nl> + lookupConformance ( ProtocolDecl * proto , <nl> + ArrayRef < ProtocolConformanceRef > conformances ) const ; <nl> + <nl> + template < typename Fn > <nl> + Optional < ProtocolConformanceRef > forEachParent ( CanType type , Fn fn ) const ; <nl> + <nl> + public : <nl> + Optional < ProtocolConformanceRef > <nl> + lookupConformance ( CanType type , ProtocolDecl * proto ) const ; <nl> + <nl> + const llvm : : DenseMap < TypeBase * , Type > & getMap ( ) const { <nl> + return subMap ; <nl> + } <nl> + <nl> + void addSubstitution ( CanType type , Type replacement ) ; <nl> + <nl> + void addConformances ( CanType type , ArrayRef < ProtocolConformanceRef > conformances ) ; <nl> + <nl> + void addParent ( CanType type , CanType parent , <nl> + AssociatedTypeDecl * assocType ) ; <nl> + <nl> + void removeType ( CanType type ) ; <nl> + } ; <nl> + <nl> + } / / end namespace swift <nl> + <nl> + # endif <nl> mmm a / include / swift / AST / Type . h <nl> ppp b / include / swift / AST / Type . h <nl> class NormalProtocolConformance ; <nl> enum OptionalTypeKind : unsigned ; <nl> class ProtocolDecl ; <nl> class StructDecl ; <nl> + class SubstitutionMap ; <nl> class TypeBase ; <nl> class Type ; <nl> class TypeWalker ; <nl> class Type { <nl> / / / Replace references to substitutable types with new , concrete types and <nl> / / / return the substituted result . <nl> / / / <nl> - / / / \ param module The module in which the substitution occurs . <nl> + / / / \ param module The module to use for conformance lookups . <nl> / / / <nl> / / / \ param substitutions The mapping from substitutable types to their <nl> / / / replacements . <nl> class Type { <nl> const TypeSubstitutionMap & substitutions , <nl> SubstOptions options ) const ; <nl> <nl> + / / / Replace references to substitutable types with new , concrete types and <nl> + / / / return the substituted result . <nl> + / / / <nl> + / / / \ param substitutions The mapping from substitutable types to their <nl> + / / / replacements and conformances . <nl> + / / / <nl> + / / / \ param options Options that affect the substitutions . <nl> + / / / <nl> + / / / \ returns the substituted type , or a null type if an error occurred . <nl> + Type subst ( const SubstitutionMap & substitutions , <nl> + SubstOptions options ) const ; <nl> + <nl> bool isPrivateStdlibType ( bool whitelistProtocols = true ) const ; <nl> <nl> void dump ( ) const ; <nl> mmm a / include / swift / AST / Types . h <nl> ppp b / include / swift / AST / Types . h <nl> class GenericFunctionType : public AnyFunctionType , <nl> / / / function type and return the resulting non - generic type . <nl> / / / <nl> / / / The order of Substitutions must match the order of generic parameters . <nl> - FunctionType * substGenericArgs ( ModuleDecl * M , ArrayRef < Substitution > subs ) ; <nl> + FunctionType * substGenericArgs ( ArrayRef < Substitution > subs ) ; <nl> <nl> void Profile ( llvm : : FoldingSetNodeID & ID ) { <nl> Profile ( ID , getGenericSignature ( ) , getInput ( ) , getResult ( ) , <nl> mmm a / include / swift / SIL / TypeSubstCloner . h <nl> ppp b / include / swift / SIL / TypeSubstCloner . h <nl> class TypeSubstCloner : public SILClonerWithScopes < ImplClass > { <nl> <nl> TypeSubstCloner ( SILFunction & To , <nl> SILFunction & From , <nl> - TypeSubstitutionMap & ContextSubs , <nl> + const SubstitutionMap & ContextSubs , <nl> ArrayRef < Substitution > ApplySubs , <nl> SILOpenedArchetypesTracker & OpenedArchetypesTracker , <nl> bool Inlining = false ) <nl> class TypeSubstCloner : public SILClonerWithScopes < ImplClass > { <nl> <nl> TypeSubstCloner ( SILFunction & To , <nl> SILFunction & From , <nl> - TypeSubstitutionMap & ContextSubs , <nl> + const SubstitutionMap & ContextSubs , <nl> ArrayRef < Substitution > ApplySubs , <nl> bool Inlining = false ) <nl> : SILClonerWithScopes < ImplClass > ( To , Inlining ) , <nl> class TypeSubstCloner : public SILClonerWithScopes < ImplClass > { <nl> <nl> protected : <nl> SILType remapType ( SILType Ty ) { <nl> - return SILType : : substType ( Original . getModule ( ) , SwiftMod , SubsMap , Ty ) ; <nl> + return SILType : : substType ( Original . getModule ( ) , SwiftMod , <nl> + SubsMap . getMap ( ) , Ty ) ; <nl> } <nl> <nl> CanType remapASTType ( CanType ty ) { <nl> - return ty . subst ( SwiftMod , SubsMap , None ) - > getCanonicalType ( ) ; <nl> + return ty . subst ( SubsMap , None ) - > getCanonicalType ( ) ; <nl> } <nl> <nl> Substitution remapSubstitution ( Substitution sub ) { <nl> class TypeSubstCloner : public SILClonerWithScopes < ImplClass > { <nl> / / / The Swift module that the cloned function belongs to . <nl> Module * SwiftMod ; <nl> / / / The substitutions list for the specialization . <nl> - TypeSubstitutionMap & SubsMap ; <nl> + const SubstitutionMap & SubsMap ; <nl> / / / The original function to specialize . <nl> SILFunction & Original ; <nl> / / / The substitutions used at the call site . <nl> mmm a / include / swift / SILOptimizer / Utils / GenericCloner . h <nl> ppp b / include / swift / SILOptimizer / Utils / GenericCloner . h <nl> class GenericCloner : public TypeSubstCloner < GenericCloner > { <nl> GenericCloner ( SILFunction * F , <nl> IsFragile_t Fragile , <nl> const ReabstractionInfo & ReInfo , <nl> - TypeSubstitutionMap & ContextSubs , <nl> + SubstitutionMap & ContextSubs , <nl> ArrayRef < Substitution > ParamSubs , <nl> StringRef NewName , <nl> CloneCollector : : CallbackType Callback ) <nl> class GenericCloner : public TypeSubstCloner < GenericCloner > { <nl> cloneFunction ( SILFunction * F , <nl> IsFragile_t Fragile , <nl> const ReabstractionInfo & ReInfo , <nl> - TypeSubstitutionMap & ContextSubs , <nl> + SubstitutionMap & ContextSubs , <nl> ArrayRef < Substitution > ParamSubs , <nl> StringRef NewName , <nl> CloneCollector : : CallbackType Callback = nullptr ) { <nl> mmm a / include / swift / SILOptimizer / Utils / Generics . h <nl> ppp b / include / swift / SILOptimizer / Utils / Generics . h <nl> class GenericFuncSpecializer { <nl> IsFragile_t Fragile ; <nl> const ReabstractionInfo & ReInfo ; <nl> <nl> - TypeSubstitutionMap ContextSubs ; <nl> + SubstitutionMap ContextSubs ; <nl> std : : string ClonedName ; <nl> public : <nl> GenericFuncSpecializer ( SILFunction * GenericFunc , <nl> mmm a / include / swift / SILOptimizer / Utils / Local . h <nl> ppp b / include / swift / SILOptimizer / Utils / Local . h <nl> void replaceDeadApply ( ApplySite Old , ValueBase * New ) ; <nl> <nl> / / / \ brief Return true if the substitution map contains a <nl> / / / substitution that is an unbound generic type . <nl> - bool hasUnboundGenericTypes ( TypeSubstitutionMap & SubsMap ) ; <nl> + bool hasUnboundGenericTypes ( const TypeSubstitutionMap & SubsMap ) ; <nl> <nl> / / / Return true if the substitution list contains a substitution <nl> / / / that is an unbound generic . <nl> bool hasUnboundGenericTypes ( ArrayRef < Substitution > Subs ) ; <nl> <nl> / / / \ brief Return true if the substitution map contains a <nl> / / / substitution that refers to the dynamic Self type . <nl> - bool hasDynamicSelfTypes ( TypeSubstitutionMap & SubsMap ) ; <nl> + bool hasDynamicSelfTypes ( const TypeSubstitutionMap & SubsMap ) ; <nl> <nl> / / / \ brief Return true if the substitution list contains a <nl> / / / substitution that refers to the dynamic Self type . <nl> mmm a / include / swift / SILOptimizer / Utils / SILInliner . h <nl> ppp b / include / swift / SILOptimizer / Utils / SILInliner . h <nl> class SILInliner : public TypeSubstCloner < SILInliner > { <nl> } ; <nl> <nl> SILInliner ( SILFunction & To , SILFunction & From , InlineKind IKind , <nl> - TypeSubstitutionMap & ContextSubs , ArrayRef < Substitution > ApplySubs , <nl> + SubstitutionMap & ContextSubs , ArrayRef < Substitution > ApplySubs , <nl> SILOpenedArchetypesTracker & OpenedArchetypesTracker , <nl> CloneCollector : : CallbackType Callback = nullptr ) <nl> : TypeSubstCloner < SILInliner > ( To , From , ContextSubs , ApplySubs , <nl> mmm a / lib / AST / CMakeLists . txt <nl> ppp b / lib / AST / CMakeLists . txt <nl> add_swift_library ( swiftAST STATIC <nl> Stmt . cpp <nl> SourceEntityWalker . cpp <nl> Substitution . cpp <nl> + SubstitutionMap . cpp <nl> Type . cpp <nl> TypeJoinMeet . cpp <nl> TypeRefinementContext . cpp <nl> mmm a / lib / AST / GenericEnvironment . cpp <nl> ppp b / lib / AST / GenericEnvironment . cpp <nl> GenericEnvironment : : getForwardingSubstitutions ( <nl> return sig - > getASTContext ( ) . AllocateCopy ( result ) ; <nl> } <nl> <nl> + SubstitutionMap GenericEnvironment : : <nl> + getSubstitutionMap ( ModuleDecl * mod , <nl> + GenericSignature * sig , <nl> + ArrayRef < Substitution > subs ) const { <nl> + SubstitutionMap result ; <nl> + getSubstitutionMap ( mod , sig , subs , result ) ; <nl> + return result ; <nl> + } <nl> + <nl> void GenericEnvironment : : <nl> getSubstitutionMap ( ModuleDecl * mod , <nl> GenericSignature * sig , <nl> ArrayRef < Substitution > subs , <nl> - TypeSubstitutionMap & subsMap , <nl> - ArchetypeConformanceMap & conformanceMap ) const { <nl> - <nl> + SubstitutionMap & result ) const { <nl> for ( auto depTy : sig - > getAllDependentTypes ( ) ) { <nl> <nl> / / Map the interface type to a context type . <nl> getSubstitutionMap ( ModuleDecl * mod , <nl> subs = subs . slice ( 1 ) ; <nl> <nl> / / Record the replacement type and its conformances . <nl> - subsMap [ archetype ] = sub . getReplacement ( ) ; <nl> - conformanceMap . addArchetypeConformances ( archetype , sub . getConformances ( ) ) ; <nl> + result . addSubstitution ( CanType ( archetype ) , sub . getReplacement ( ) ) ; <nl> + result . addConformances ( CanType ( archetype ) , sub . getConformances ( ) ) ; <nl> } <nl> <nl> for ( auto reqt : sig - > getRequirements ( ) ) { <nl> getSubstitutionMap ( ModuleDecl * mod , <nl> continue ; <nl> <nl> if ( archetype - > getParent ( ) ! = firstBaseArchetype ) <nl> - conformanceMap . addArchetypeParent ( archetype , firstBaseArchetype , <nl> - first - > getAssocType ( ) ) ; <nl> + result . addParent ( CanType ( archetype ) , <nl> + CanType ( firstBaseArchetype ) , <nl> + first - > getAssocType ( ) ) ; <nl> if ( archetype - > getParent ( ) ! = secondBaseArchetype ) <nl> - conformanceMap . addArchetypeParent ( archetype , secondBaseArchetype , <nl> - second - > getAssocType ( ) ) ; <nl> + result . addParent ( CanType ( archetype ) , <nl> + CanType ( secondBaseArchetype ) , <nl> + second - > getAssocType ( ) ) ; <nl> } <nl> <nl> assert ( subs . empty ( ) & & " did not use all substitutions ? ! " ) ; <nl> mmm a / lib / AST / GenericSignature . cpp <nl> ppp b / lib / AST / GenericSignature . cpp <nl> ASTContext & GenericSignature : : getASTContext ( ) const { <nl> return getASTContext ( getGenericParams ( ) , getRequirements ( ) ) ; <nl> } <nl> <nl> - TypeSubstitutionMap <nl> + SubstitutionMap <nl> GenericSignature : : getSubstitutionMap ( ArrayRef < Substitution > subs ) const { <nl> - TypeSubstitutionMap subMap ; <nl> - TypeConformanceMap conformanceMap ; <nl> - <nl> - getSubstitutionMap ( subs , subMap , conformanceMap ) ; <nl> - <nl> - return subMap ; <nl> + SubstitutionMap result ; <nl> + getSubstitutionMap ( subs , result ) ; <nl> + return result ; <nl> } <nl> <nl> - void GenericSignature : : <nl> - getSubstitutionMap ( ArrayRef < Substitution > subs , <nl> - TypeSubstitutionMap & subMap , <nl> - TypeConformanceMap & conformanceMap ) const { <nl> - <nl> + void <nl> + GenericSignature : : getSubstitutionMap ( ArrayRef < Substitution > subs , <nl> + SubstitutionMap & result ) const { <nl> / / An empty parameter list gives an empty map . <nl> - if ( subs . empty ( ) ) { <nl> + if ( subs . empty ( ) ) <nl> assert ( getGenericParams ( ) . empty ( ) ) ; <nl> - return ; <nl> - } <nl> <nl> for ( auto depTy : getAllDependentTypes ( ) ) { <nl> auto sub = subs . front ( ) ; <nl> subs = subs . slice ( 1 ) ; <nl> <nl> - auto canTy = depTy - > getCanonicalType ( ) . getPointer ( ) ; <nl> - subMap [ canTy ] = sub . getReplacement ( ) ; <nl> - conformanceMap [ canTy ] = sub . getConformances ( ) ; <nl> + auto canTy = depTy - > getCanonicalType ( ) ; <nl> + result . addSubstitution ( canTy , sub . getReplacement ( ) ) ; <nl> + result . addConformances ( canTy , sub . getConformances ( ) ) ; <nl> } <nl> - <nl> + <nl> + / / TODO : same - type constraints <nl> + <nl> assert ( subs . empty ( ) & & " did not use all substitutions ? ! " ) ; <nl> } <nl> <nl> getSubstitutions ( ModuleDecl & mod , <nl> } <nl> } <nl> <nl> - static Optional < ProtocolConformanceRef > <nl> - lookupDependentConformance ( ProtocolDecl * proto , <nl> - ArrayRef < ProtocolConformanceRef > conformances ) { <nl> - for ( ProtocolConformanceRef found : conformances ) { <nl> - auto foundProto = found . getRequirement ( ) ; <nl> - if ( foundProto = = proto ) { <nl> - return found ; <nl> - } else if ( foundProto - > inheritsFrom ( proto ) ) { <nl> - if ( found . isConcrete ( ) ) { <nl> - return ProtocolConformanceRef ( <nl> - found . getConcrete ( ) - > getInheritedConformance ( proto ) ) ; <nl> - } <nl> - <nl> - return found ; <nl> - } <nl> - } <nl> - <nl> - return None ; <nl> - } <nl> - <nl> - static Optional < ProtocolConformanceRef > <nl> - lookupDependentConformance ( CanType original , <nl> - ProtocolDecl * proto , <nl> - const TypeConformanceMap & conformanceMap ) { <nl> - / / Check for conformances for the type that apply to the original type . <nl> - auto it = conformanceMap . find ( original . getPointer ( ) ) ; <nl> - if ( it ! = conformanceMap . end ( ) ) { <nl> - if ( auto conformance = lookupDependentConformance ( proto , it - > second ) ) { <nl> - return conformance ; <nl> - } <nl> - } <nl> - <nl> - / / Check if we have substitutions for the parent . <nl> - if ( auto memberTy = dyn_cast < DependentMemberType > ( original ) ) { <nl> - if ( auto parent = memberTy - > getBase ( ) ) { <nl> - auto * assocType = memberTy - > getAssocType ( ) ; <nl> - auto * parentProto = assocType - > getProtocol ( ) ; <nl> - auto conformance = lookupDependentConformance ( <nl> - parent - > getCanonicalType ( ) , parentProto , conformanceMap ) ; <nl> - <nl> - if ( conformance ) { <nl> - if ( ! conformance - > isConcrete ( ) ) <nl> - return ProtocolConformanceRef ( proto ) ; <nl> - <nl> - auto sub = conformance - > getConcrete ( ) - > getTypeWitnessSubstAndDecl ( <nl> - assocType , nullptr ) . first ; <nl> - <nl> - return lookupDependentConformance ( proto , sub . getConformances ( ) ) ; <nl> - } <nl> - } <nl> - } <nl> - <nl> - return None ; <nl> - } <nl> - <nl> void GenericSignature : : <nl> getSubstitutions ( ModuleDecl & mod , <nl> - const TypeSubstitutionMap & subMap , <nl> - const TypeConformanceMap & conformanceMap , <nl> + const SubstitutionMap & subMap , <nl> SmallVectorImpl < Substitution > & result ) const { <nl> auto lookupConformanceFn = <nl> [ & ] ( CanType original , Type replacement , ProtocolType * protoType ) <nl> - > ProtocolConformanceRef { <nl> - return * lookupDependentConformance ( original , <nl> - protoType - > getDecl ( ) , <nl> - conformanceMap ) ; <nl> + return * subMap . lookupConformance ( original , protoType - > getDecl ( ) ) ; <nl> } ; <nl> <nl> - getSubstitutions ( mod , subMap , lookupConformanceFn , result ) ; <nl> + getSubstitutions ( mod , subMap . getMap ( ) , lookupConformanceFn , result ) ; <nl> } <nl> <nl> bool GenericSignature : : requiresClass ( Type type , ModuleDecl & mod ) { <nl> mmm a / lib / AST / ProtocolConformance . cpp <nl> ppp b / lib / AST / ProtocolConformance . cpp <nl> SpecializedProtocolConformance : : getTypeWitnessSubstAndDecl ( <nl> auto * genericEnv = GenericConformance - > getGenericEnvironment ( ) ; <nl> auto * genericSig = GenericConformance - > getGenericSignature ( ) ; <nl> <nl> - TypeSubstitutionMap substitutionMap ; <nl> - <nl> - / / FIXME : We could have a new version of Type : : subst ( ) that <nl> - / / takes a conformanceMap in addition to a substitutionMap , <nl> - / / but for now this is ignored below <nl> - ArchetypeConformanceMap conformanceMap ; <nl> - <nl> - / / Compute a context type substitution map from the <nl> - / / substitution array stored in this conformance <nl> - genericEnv - > getSubstitutionMap ( conformingModule , genericSig , <nl> - GenericSubstitutions , <nl> - substitutionMap , <nl> - conformanceMap ) ; <nl> + auto substitutionMap = genericEnv - > getSubstitutionMap ( <nl> + conformingModule , genericSig , GenericSubstitutions ) ; <nl> <nl> auto genericWitnessAndDecl <nl> = GenericConformance - > getTypeWitnessSubstAndDecl ( assocType , resolver ) ; <nl> SpecializedProtocolConformance : : getTypeWitnessSubstAndDecl ( <nl> <nl> / / Apply the substitution we computed above <nl> auto specializedType <nl> - = genericWitness . getReplacement ( ) . subst ( conformingModule , substitutionMap , <nl> - None ) ; <nl> + = genericWitness . getReplacement ( ) . subst ( substitutionMap , None ) ; <nl> <nl> / / If the type witness was unchanged , just copy it directly . <nl> if ( specializedType . getPointer ( ) = = genericWitness . getReplacement ( ) . getPointer ( ) ) { <nl> SpecializedProtocolConformance : : getTypeWitnessSubstAndDecl ( <nl> } <nl> <nl> / / Gather the conformances for the type witness . These should never fail . <nl> + / / FIXME : We should just be able to use the SubstitutionMap from above , <nl> + / / but we have no way to force inherited conformances to be filled in <nl> + / / through that mechanism . <nl> SmallVector < ProtocolConformanceRef , 4 > conformances ; <nl> for ( auto proto : assocType - > getConformingProtocols ( resolver ) ) { <nl> auto conforms = conformingModule - > lookupConformance ( specializedType , proto , <nl> bool ProtocolConformance : : isVisibleFrom ( const DeclContext * dc ) const { <nl> <nl> ProtocolConformance * ProtocolConformance : : subst ( Module * module , <nl> Type substType , <nl> - TypeSubstitutionMap & subMap , <nl> - ArchetypeConformanceMap & conformanceMap ) { <nl> + const SubstitutionMap & subMap ) const { <nl> if ( getType ( ) - > isEqual ( substType ) ) <nl> - return this ; <nl> + return const_cast < ProtocolConformance * > ( this ) ; <nl> <nl> switch ( getKind ( ) ) { <nl> case ProtocolConformanceKind : : Normal : <nl> ProtocolConformance * ProtocolConformance : : subst ( Module * module , <nl> = = substType - > getNominalOrBoundGenericNominal ( ) <nl> & & " substitution mapped to different nominal ? ! " ) ; <nl> return module - > getASTContext ( ) <nl> - . getSpecializedConformance ( substType , this , <nl> + . getSpecializedConformance ( substType , <nl> + const_cast < ProtocolConformance * > ( this ) , <nl> substType - > gatherAllSubstitutions ( module , nullptr ) ) ; <nl> } <nl> assert ( substType - > isEqual ( getType ( ) ) <nl> & & " substitution changed non - specialized type ? ! " ) ; <nl> - return this ; <nl> + return const_cast < ProtocolConformance * > ( this ) ; <nl> <nl> case ProtocolConformanceKind : : Inherited : { <nl> / / Substitute the base . <nl> ProtocolConformance * ProtocolConformance : : subst ( Module * module , <nl> = cast < InheritedProtocolConformance > ( this ) - > getInheritedConformance ( ) ; <nl> ProtocolConformance * newBase ; <nl> if ( inheritedConformance - > getType ( ) - > isSpecialized ( ) ) { <nl> - newBase = inheritedConformance - > subst ( module , substType , subMap , <nl> - conformanceMap ) ; <nl> + newBase = inheritedConformance - > subst ( module , substType , subMap ) ; <nl> } else { <nl> newBase = inheritedConformance ; <nl> } <nl> ProtocolConformance * ProtocolConformance : : subst ( Module * module , <nl> SmallVector < Substitution , 8 > newSubs ; <nl> newSubs . reserve ( spec - > getGenericSubstitutions ( ) . size ( ) ) ; <nl> for ( auto & sub : spec - > getGenericSubstitutions ( ) ) <nl> - newSubs . push_back ( sub . subst ( module , subMap , conformanceMap ) ) ; <nl> + newSubs . push_back ( sub . subst ( module , subMap ) ) ; <nl> <nl> auto ctxNewSubs = module - > getASTContext ( ) . AllocateCopy ( newSubs ) ; <nl> <nl> ProtocolConformance : : getInheritedConformance ( ProtocolDecl * protocol ) const { <nl> assert ( inherited - > getType ( ) - > isEqual ( spec - > getGenericConformance ( ) - > getType ( ) ) <nl> & & " inherited conformance doesn ' t match type ? ! " ) ; <nl> <nl> - / / Fill in the substitution and conformance maps . <nl> - TypeSubstitutionMap subMap ; <nl> - ArchetypeConformanceMap conformanceMap ; <nl> - <nl> auto subs = spec - > getGenericSubstitutions ( ) ; <nl> <nl> auto * conformingDC = spec - > getDeclContext ( ) ; <nl> ProtocolConformance : : getInheritedConformance ( ProtocolDecl * protocol ) const { <nl> auto * sig = conformingDC - > getGenericSignatureOfContext ( ) ; <nl> auto * env = conformingDC - > getGenericEnvironmentOfContext ( ) ; <nl> <nl> - env - > getSubstitutionMap ( conformingModule , sig , subs , <nl> - subMap , conformanceMap ) ; <nl> + auto subMap = env - > getSubstitutionMap ( conformingModule , sig , subs ) ; <nl> <nl> - auto r = inherited - > subst ( conformingModule , getType ( ) , <nl> - subMap , conformanceMap ) ; <nl> + auto r = inherited - > subst ( conformingModule , getType ( ) , subMap ) ; <nl> assert ( getType ( ) - > isEqual ( r - > getType ( ) ) <nl> & & " substitution didn ' t produce conformance for same type ? ! " ) ; <nl> return r ; <nl> mmm a / lib / AST / Substitution . cpp <nl> ppp b / lib / AST / Substitution . cpp <nl> <nl> # include " swift / AST / ASTContext . h " <nl> # include " swift / AST / GenericEnvironment . h " <nl> # include " swift / AST / Module . h " <nl> + # include " swift / AST / SubstitutionMap . h " <nl> # include " swift / AST / Types . h " <nl> # include " llvm / ADT / DenseMap . h " <nl> <nl> using namespace swift ; <nl> <nl> - Optional < ProtocolConformanceRef > ArchetypeConformanceMap : : <nl> - lookupArchetypeConformance ( ProtocolDecl * proto , <nl> - ArrayRef < ProtocolConformanceRef > conformances ) const { <nl> - for ( ProtocolConformanceRef found : conformances ) { <nl> - auto foundProto = found . getRequirement ( ) ; <nl> - if ( foundProto = = proto ) { <nl> - return found ; <nl> - } else if ( foundProto - > inheritsFrom ( proto ) ) { <nl> - if ( found . isConcrete ( ) ) { <nl> - return ProtocolConformanceRef ( <nl> - found . getConcrete ( ) - > getInheritedConformance ( proto ) ) ; <nl> - } <nl> - <nl> - return found ; <nl> - } <nl> - } <nl> - <nl> - return None ; <nl> - } <nl> - <nl> - Optional < ProtocolConformanceRef > ArchetypeConformanceMap : : <nl> - lookupArchetypeConformance ( ArchetypeType * replacement , <nl> - ProtocolDecl * proto ) const { <nl> - / / Check for conformances for the type that apply to the original <nl> - / / substituted archetype . <nl> - auto foundReplacement = map . find ( replacement ) ; <nl> - if ( foundReplacement ! = map . end ( ) ) { <nl> - auto substReplacement = foundReplacement - > second ; <nl> - if ( auto conformance = lookupArchetypeConformance ( proto , substReplacement ) ) <nl> - return conformance ; <nl> - } <nl> - <nl> - / / Check if we have substitutions from one of our parent archetypes . <nl> - auto foundParents = parents . find ( replacement ) ; <nl> - if ( foundParents = = parents . end ( ) ) <nl> - return None ; <nl> - <nl> - for ( auto parent : foundParents - > second ) { <nl> - auto * parentProto = parent . second - > getProtocol ( ) ; <nl> - auto conformance = <nl> - lookupArchetypeConformance ( parent . first , parentProto ) ; <nl> - <nl> - if ( conformance ) { <nl> - if ( ! conformance - > isConcrete ( ) ) <nl> - return ProtocolConformanceRef ( proto ) ; <nl> - <nl> - auto sub = conformance - > getConcrete ( ) - > getTypeWitnessSubstAndDecl ( <nl> - parent . second , nullptr ) . first ; <nl> - <nl> - if ( auto result = lookupArchetypeConformance ( proto , sub . getConformances ( ) ) ) <nl> - return result ; <nl> - } <nl> - } <nl> - <nl> - return None ; <nl> - } <nl> - <nl> - void ArchetypeConformanceMap : : <nl> - addArchetypeConformances ( ArchetypeType * replacement , <nl> - ArrayRef < ProtocolConformanceRef > conformances ) { <nl> - assert ( replacement ) ; <nl> - <nl> - auto result = map . insert ( std : : make_pair ( replacement , conformances ) ) ; <nl> - assert ( result . second ) ; <nl> - ( void ) result ; <nl> - <nl> - if ( auto * parent = replacement - > getParent ( ) ) <nl> - addArchetypeParent ( replacement , parent , replacement - > getAssocType ( ) ) ; <nl> - } <nl> - <nl> - void ArchetypeConformanceMap : : <nl> - addArchetypeParent ( ArchetypeType * replacement , <nl> - ArchetypeType * parent , <nl> - AssociatedTypeDecl * assocType ) { <nl> - assert ( replacement & & parent & & assocType ) ; <nl> - parents [ replacement ] . push_back ( std : : make_pair ( parent , assocType ) ) ; <nl> - } <nl> - <nl> bool Substitution : : operator = = ( const Substitution & other ) const { <nl> / / The archetypes may be missing , but we can compare them directly <nl> / / because archetypes are always canonical . <nl> Substitution Substitution : : subst ( Module * module , <nl> GenericSignature * sig , <nl> GenericEnvironment * env , <nl> ArrayRef < Substitution > subs ) const { <nl> - TypeSubstitutionMap subMap ; <nl> - ArchetypeConformanceMap conformanceMap ; <nl> - <nl> assert ( sig & & env ) ; <nl> - env - > getSubstitutionMap ( module , sig , subs , subMap , conformanceMap ) ; <nl> - return subst ( module , subMap , conformanceMap ) ; <nl> + auto subMap = env - > getSubstitutionMap ( module , sig , subs ) ; <nl> + return subst ( module , subMap ) ; <nl> } <nl> <nl> Substitution Substitution : : subst ( Module * module , <nl> - TypeSubstitutionMap & subMap , <nl> - ArchetypeConformanceMap & conformanceMap ) const { <nl> + const SubstitutionMap & subMap ) const { <nl> / / Substitute the replacement . <nl> - Type substReplacement = Replacement . subst ( module , subMap , None ) ; <nl> + Type substReplacement = Replacement . subst ( subMap , None ) ; <nl> assert ( substReplacement & & " substitution replacement failed " ) ; <nl> <nl> if ( substReplacement - > isEqual ( Replacement ) ) <nl> Substitution Substitution : : subst ( Module * module , <nl> / / If we have a concrete conformance , we need to substitute the <nl> / / conformance to apply to the new type . <nl> if ( c . isConcrete ( ) ) { <nl> - auto substC = c . getConcrete ( ) - > subst ( module , substReplacement , <nl> - subMap , conformanceMap ) ; <nl> + auto substC = c . getConcrete ( ) - > subst ( module , substReplacement , subMap ) ; <nl> substConformances . push_back ( ProtocolConformanceRef ( substC ) ) ; <nl> if ( c ! = substConformances . back ( ) ) <nl> conformancesChanged = true ; <nl> Substitution Substitution : : subst ( Module * module , <nl> <nl> / / If the original type was an archetype , check the conformance map . <nl> if ( auto replacementArch = Replacement - > getAs < ArchetypeType > ( ) ) { <nl> - conformance = conformanceMap . lookupArchetypeConformance ( <nl> - replacementArch , proto ) ; <nl> + conformance = subMap . lookupConformance ( CanType ( replacementArch ) , proto ) ; <nl> } <nl> <nl> / / If that didn ' t find anything , we can still synthesize AnyObject <nl> new file mode 100644 <nl> index 000000000000 . . d1d1e6b87556 <nl> mmm / dev / null <nl> ppp b / lib / AST / SubstitutionMap . cpp <nl> <nl> + / / = = = mmm SubstitutionMap . cpp - Type substitution map mmmmmmmmmmmmmmmmmmmmm - = = = / / <nl> + / / <nl> + / / This source file is part of the Swift . org open source project <nl> + / / <nl> + / / Copyright ( c ) 2014 - 2016 Apple Inc . and the Swift project authors <nl> + / / Licensed under Apache License v2 . 0 with Runtime Library Exception <nl> + / / <nl> + / / See http : / / swift . org / LICENSE . txt for license information <nl> + / / See http : / / swift . org / CONTRIBUTORS . txt for the list of Swift project authors <nl> + / / <nl> + / / = = = mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - = = = / / <nl> + / / <nl> + / / This file defines the SubstitutionMap class . <nl> + / / <nl> + / / = = = mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - = = = / / <nl> + <nl> + # include " swift / AST / SubstitutionMap . h " <nl> + # include " swift / AST / Decl . h " <nl> + # include " swift / AST / ProtocolConformance . h " <nl> + # include " swift / AST / Types . h " <nl> + <nl> + using namespace swift ; <nl> + <nl> + Optional < ProtocolConformanceRef > SubstitutionMap : : <nl> + lookupConformance ( ProtocolDecl * proto , <nl> + ArrayRef < ProtocolConformanceRef > conformances ) const { <nl> + for ( ProtocolConformanceRef found : conformances ) { <nl> + auto foundProto = found . getRequirement ( ) ; <nl> + if ( foundProto = = proto ) <nl> + return found ; <nl> + if ( foundProto - > inheritsFrom ( proto ) ) <nl> + return found . getInherited ( proto ) ; <nl> + } <nl> + <nl> + return None ; <nl> + } <nl> + <nl> + template < typename Fn > <nl> + Optional < ProtocolConformanceRef > <nl> + SubstitutionMap : : forEachParent ( CanType type , Fn fn ) const { <nl> + auto foundParents = parentMap . find ( type . getPointer ( ) ) ; <nl> + if ( foundParents ! = parentMap . end ( ) ) { <nl> + for ( auto parent : foundParents - > second ) { <nl> + if ( auto result = fn ( parent . first , parent . second ) ) <nl> + return result ; <nl> + } <nl> + } <nl> + <nl> + if ( auto archetypeType = dyn_cast < ArchetypeType > ( type ) ) <nl> + if ( auto * parent = archetypeType - > getParent ( ) ) <nl> + return fn ( CanType ( parent ) , archetypeType - > getAssocType ( ) ) ; <nl> + <nl> + if ( auto memberType = dyn_cast < DependentMemberType > ( type ) ) <nl> + return fn ( CanType ( memberType - > getBase ( ) ) , memberType - > getAssocType ( ) ) ; <nl> + <nl> + return None ; <nl> + } <nl> + <nl> + Optional < ProtocolConformanceRef > <nl> + SubstitutionMap : : lookupConformance ( CanType type , <nl> + ProtocolDecl * proto ) const { <nl> + / / Check for conformances for the type that apply to the original <nl> + / / substituted archetype . <nl> + auto foundReplacement = conformanceMap . find ( type . getPointer ( ) ) ; <nl> + if ( foundReplacement ! = conformanceMap . end ( ) ) { <nl> + auto substReplacement = foundReplacement - > second ; <nl> + if ( auto conformance = lookupConformance ( proto , substReplacement ) ) <nl> + return conformance ; <nl> + } <nl> + <nl> + / / Check if we have substitutions from one of our parent types . <nl> + return forEachParent ( type , [ & ] ( CanType parent , AssociatedTypeDecl * assocType ) <nl> + - > Optional < ProtocolConformanceRef > { <nl> + <nl> + auto * parentProto = assocType - > getProtocol ( ) ; <nl> + auto conformance = lookupConformance ( parent , parentProto ) ; <nl> + <nl> + if ( ! conformance ) <nl> + return None ; <nl> + <nl> + if ( ! conformance - > isConcrete ( ) ) <nl> + return ProtocolConformanceRef ( proto ) ; <nl> + <nl> + auto sub = conformance - > getConcrete ( ) - > getTypeWitnessSubstAndDecl ( <nl> + assocType , nullptr ) . first ; <nl> + <nl> + return lookupConformance ( proto , sub . getConformances ( ) ) ; <nl> + } ) ; <nl> + } <nl> + <nl> + void SubstitutionMap : : <nl> + addSubstitution ( CanType type , Type replacement ) { <nl> + auto result = subMap . insert ( std : : make_pair ( type . getPointer ( ) , replacement ) ) ; <nl> + assert ( result . second ) ; <nl> + ( void ) result ; <nl> + } <nl> + <nl> + void SubstitutionMap : : <nl> + addConformances ( CanType type , ArrayRef < ProtocolConformanceRef > conformances ) { <nl> + if ( conformances . empty ( ) ) <nl> + return ; <nl> + <nl> + auto result = conformanceMap . insert ( <nl> + std : : make_pair ( type . getPointer ( ) , conformances ) ) ; <nl> + assert ( result . second ) ; <nl> + ( void ) result ; <nl> + } <nl> + <nl> + void SubstitutionMap : : <nl> + addParent ( CanType type , CanType parent , AssociatedTypeDecl * assocType ) { <nl> + assert ( type & & parent & & assocType ) ; <nl> + parentMap [ type . getPointer ( ) ] . push_back ( std : : make_pair ( parent , assocType ) ) ; <nl> + } <nl> + <nl> + void SubstitutionMap : : removeType ( CanType type ) { <nl> + subMap . erase ( type . getPointer ( ) ) ; <nl> + conformanceMap . erase ( type . getPointer ( ) ) ; <nl> + parentMap . erase ( type . getPointer ( ) ) ; <nl> + } <nl> mmm a / lib / AST / Type . cpp <nl> ppp b / lib / AST / Type . cpp <nl> Type TypeBase : : getSuperclass ( LazyResolver * resolver ) { <nl> auto * sig = classDecl - > getGenericSignatureOfContext ( ) ; <nl> auto subs = sig - > getSubstitutionMap ( gatherAllSubstitutions ( module , resolver ) ) ; <nl> <nl> - return superclassTy . subst ( module , subs , None ) ; <nl> + return superclassTy . subst ( subs , None ) ; <nl> } <nl> <nl> bool TypeBase : : isExactSuperclassOf ( Type ty , LazyResolver * resolver ) { <nl> PolymorphicFunctionType : : getGenericParameters ( ) const { <nl> } <nl> <nl> FunctionType * <nl> - GenericFunctionType : : substGenericArgs ( Module * M , ArrayRef < Substitution > args ) { <nl> + GenericFunctionType : : substGenericArgs ( ArrayRef < Substitution > args ) { <nl> auto params = getGenericParams ( ) ; <nl> ( void ) params ; <nl> <nl> - TypeSubstitutionMap subs <nl> - = getGenericSignature ( ) - > getSubstitutionMap ( args ) ; <nl> + auto subs = getGenericSignature ( ) - > getSubstitutionMap ( args ) ; <nl> <nl> - Type input = getInput ( ) . subst ( M , subs , SubstFlags : : IgnoreMissing ) ; <nl> - Type result = getResult ( ) . subst ( M , subs , SubstFlags : : IgnoreMissing ) ; <nl> + Type input = getInput ( ) . subst ( subs , SubstFlags : : IgnoreMissing ) ; <nl> + Type result = getResult ( ) . subst ( subs , SubstFlags : : IgnoreMissing ) ; <nl> return FunctionType : : get ( input , result , getExtInfo ( ) ) ; <nl> } <nl> <nl> - static Type getMemberForBaseType ( Module * module , <nl> + using ConformanceSource = <nl> + llvm : : PointerUnion < ModuleDecl * , const SubstitutionMap * > ; <nl> + <nl> + static Type getMemberForBaseType ( ConformanceSource conformances , <nl> + Type origBase , <nl> Type substBase , <nl> AssociatedTypeDecl * assocType , <nl> Identifier name , <nl> SubstOptions options ) { <nl> / / Error recovery path . <nl> if ( substBase - > isOpenedExistential ( ) ) <nl> - return ErrorType : : get ( module - > getASTContext ( ) ) ; <nl> + return ErrorType : : get ( substBase - > getASTContext ( ) ) ; <nl> <nl> / / If the parent is an archetype , extract the child archetype with the <nl> / / given name . <nl> static Type getMemberForBaseType ( Module * module , <nl> / / If the archetype doesn ' t have the requested type and the parent is not <nl> / / self derived , error out <nl> return parent - > isSelfDerived ( ) ? parent - > getNestedTypeValue ( name ) <nl> - : ErrorType : : get ( module - > getASTContext ( ) ) ; <nl> + : ErrorType : : get ( substBase - > getASTContext ( ) ) ; <nl> } <nl> <nl> / / If looking for an associated type and the archetype is constrained to a <nl> / / class , continue to the default associated type lookup <nl> if ( ! assocType | | ! archetypeParent - > getSuperclass ( ) ) { <nl> / / else just error out <nl> - return ErrorType : : get ( module - > getASTContext ( ) ) ; <nl> + return ErrorType : : get ( substBase - > getASTContext ( ) ) ; <nl> } <nl> } <nl> <nl> static Type getMemberForBaseType ( Module * module , <nl> if ( assocType ) { <nl> auto proto = assocType - > getProtocol ( ) ; <nl> / / FIXME : Introduce substituted type node here ? <nl> - auto conformance = module - > lookupConformance ( substBase , proto , resolver ) ; <nl> + Optional < ProtocolConformanceRef > conformance ; <nl> + if ( conformances . is < ModuleDecl * > ( ) ) { <nl> + conformance = conformances . get < ModuleDecl * > ( ) - > lookupConformance ( <nl> + substBase , proto , resolver ) ; <nl> + } else { <nl> + conformance = conformances . get < const SubstitutionMap * > ( ) - > lookupConformance ( <nl> + origBase - > getCanonicalType ( ) , proto ) ; <nl> + } <nl> + <nl> if ( ! conformance ) <nl> return Type ( ) ; <nl> <nl> static Type getMemberForBaseType ( Module * module , <nl> <nl> / / FIXME : This is a fallback . We want the above , conformance - based <nl> / / result to be the only viable path . <nl> - if ( resolver ) { <nl> - if ( Type memberType = resolver - > resolveMemberType ( module , substBase , name ) ) { <nl> - return memberType ; <nl> - } <nl> + if ( resolver & & conformances . is < ModuleDecl * > ( ) ) { <nl> + return resolver - > resolveMemberType ( <nl> + conformances . get < ModuleDecl * > ( ) , substBase , name ) ; <nl> } <nl> <nl> return Type ( ) ; <nl> } <nl> <nl> - Type DependentMemberType : : substBaseType ( Module * module , <nl> + Type DependentMemberType : : substBaseType ( ModuleDecl * module , <nl> Type substBase , <nl> LazyResolver * resolver ) { <nl> if ( substBase . getPointer ( ) = = getBase ( ) . getPointer ( ) & & <nl> substBase - > hasTypeParameter ( ) ) <nl> return this ; <nl> <nl> - return getMemberForBaseType ( module , substBase , getAssocType ( ) , getName ( ) , <nl> + return getMemberForBaseType ( module , Type ( ) , substBase , <nl> + getAssocType ( ) , getName ( ) , <nl> None ) ; <nl> } <nl> <nl> - Type Type : : subst ( Module * module , <nl> - const TypeSubstitutionMap & substitutions , <nl> - SubstOptions options ) const { <nl> + static Type substType ( <nl> + Type derivedType , <nl> + llvm : : PointerUnion < ModuleDecl * , const SubstitutionMap * > conformances , <nl> + const TypeSubstitutionMap & substitutions , <nl> + SubstOptions options ) { <nl> / / / Return the original type or a null type , depending on the ' ignoreMissing ' <nl> / / / flag . <nl> auto failed = [ & ] ( Type t ) { <nl> return options . contains ( SubstFlags : : IgnoreMissing ) ? t : Type ( ) ; <nl> } ; <nl> - <nl> - return transform ( [ & ] ( Type type ) - > Type { <nl> + <nl> + return derivedType . transform ( [ & ] ( Type type ) - > Type { <nl> assert ( ( options . contains ( SubstFlags : : AllowLoweredTypes ) | | <nl> ! isa < SILFunctionType > ( type . getPointer ( ) ) ) & & <nl> " should not be doing AST type - substitution on a lowered SIL type ; " <nl> Type Type : : subst ( Module * module , <nl> substitutions . find ( depMemTy - > getCanonicalType ( ) . getPointer ( ) ) ; <nl> if ( known ! = substitutions . end ( ) & & known - > second ) { <nl> return SubstitutedType : : get ( type , known - > second , <nl> - module - > getASTContext ( ) ) ; <nl> + type - > getASTContext ( ) ) ; <nl> } <nl> <nl> - auto newBase = depMemTy - > getBase ( ) . subst ( module , substitutions , options ) ; <nl> + auto newBase = substType ( depMemTy - > getBase ( ) , conformances , <nl> + substitutions , options ) ; <nl> if ( ! newBase ) <nl> return failed ( type ) ; <nl> <nl> - if ( Type r = getMemberForBaseType ( module , newBase , <nl> + if ( Type r = getMemberForBaseType ( conformances , <nl> + depMemTy - > getBase ( ) , newBase , <nl> depMemTy - > getAssocType ( ) , <nl> depMemTy - > getName ( ) , options ) ) <nl> return r ; <nl> Type Type : : subst ( Module * module , <nl> auto known = substitutions . find ( key ) ; <nl> if ( known ! = substitutions . end ( ) & & known - > second ) <nl> return SubstitutedType : : get ( type , known - > second , <nl> - module - > getASTContext ( ) ) ; <nl> + type - > getASTContext ( ) ) ; <nl> <nl> / / If we don ' t have a substitution for this type and it doesn ' t have a <nl> / / parent , then we ' re not substituting it . <nl> Type Type : : subst ( Module * module , <nl> return type ; <nl> <nl> / / Substitute into the parent type . <nl> - Type substParent = Type ( parent ) . subst ( module , substitutions , options ) ; <nl> + Type substParent = substType ( parent , conformances , substitutions , options ) ; <nl> if ( ! substParent ) <nl> return Type ( ) ; <nl> <nl> Type Type : : subst ( Module * module , <nl> } <nl> <nl> <nl> - if ( Type r = getMemberForBaseType ( module , substParent , assocType , <nl> - substOrig - > getName ( ) , options ) ) <nl> + if ( Type r = getMemberForBaseType ( conformances , parent , substParent , <nl> + assocType , substOrig - > getName ( ) , <nl> + options ) ) <nl> return r ; <nl> return failed ( type ) ; <nl> } ) ; <nl> } <nl> <nl> + Type Type : : subst ( Module * module , <nl> + const TypeSubstitutionMap & substitutions , <nl> + SubstOptions options ) const { <nl> + return substType ( * this , module , substitutions , options ) ; <nl> + } <nl> + <nl> + Type Type : : subst ( const SubstitutionMap & substitutions , <nl> + SubstOptions options ) const { <nl> + return substType ( * this , & substitutions , substitutions . getMap ( ) , options ) ; <nl> + } <nl> + <nl> Type TypeBase : : getSuperclassForDecl ( const ClassDecl * baseClass , <nl> LazyResolver * resolver ) { <nl> Type derivedType = this ; <nl> mmm a / lib / IRGen / GenReflection . cpp <nl> ppp b / lib / IRGen / GenReflection . cpp <nl> class CaptureDescriptorBuilder : public ReflectionMetadataBuilder { <nl> auto Src = Path . getMetadataSource ( SourceBuilder , Root ) ; <nl> <nl> auto SubstType = <nl> - Caller . mapTypeOutOfContext ( SubstMap [ GenericParam . getPointer ( ) ] ) ; <nl> + Caller . mapTypeOutOfContext ( <nl> + GenericParam . subst ( SubstMap , None ) ) ; <nl> SourceMap . push_back ( { SubstType - > getCanonicalType ( ) , Src } ) ; <nl> } ) ; <nl> <nl> mmm a / lib / SIL / SILFunctionType . cpp <nl> ppp b / lib / SIL / SILFunctionType . cpp <nl> SILFunctionType : : substGenericArgs ( SILModule & silModule , Module * astModule , <nl> } <nl> <nl> assert ( isPolymorphic ( ) ) ; <nl> - TypeSubstitutionMap map = GenericSig - > getSubstitutionMap ( subs ) ; <nl> - SILTypeSubstituter substituter ( silModule , astModule , map ) ; <nl> + auto map = GenericSig - > getSubstitutionMap ( subs ) ; <nl> + SILTypeSubstituter substituter ( silModule , astModule , map . getMap ( ) ) ; <nl> <nl> return substituter . visitSILFunctionType ( CanSILFunctionType ( this ) , <nl> / * dropGenerics * / true ) ; <nl> mmm a / lib / SILGen / SILGenApply . cpp <nl> ppp b / lib / SILGen / SILGenApply . cpp <nl> SILGenFunction : : emitApplyOfLibraryIntrinsic ( SILLocation loc , <nl> auto substFormalType = origFormalType ; <nl> if ( ! subs . empty ( ) ) { <nl> auto genericFnType = cast < GenericFunctionType > ( substFormalType ) ; <nl> - auto applied = genericFnType - > substGenericArgs ( SGM . SwiftModule , subs ) ; <nl> + auto applied = genericFnType - > substGenericArgs ( subs ) ; <nl> substFormalType = cast < FunctionType > ( applied - > getCanonicalType ( ) ) ; <nl> } <nl> <nl> static RValue emitApplyAllocatingInitializer ( SILGenFunction & SGF , <nl> auto subs = init . getSubstitutions ( ) ; <nl> if ( ! subs . empty ( ) ) { <nl> auto genericFnType = cast < GenericFunctionType > ( substFormalType ) ; <nl> - auto applied = genericFnType - > substGenericArgs ( SGF . SGM . SwiftModule , subs ) ; <nl> + auto applied = genericFnType - > substGenericArgs ( subs ) ; <nl> substFormalType = cast < FunctionType > ( applied - > getCanonicalType ( ) ) ; <nl> } <nl> <nl> emitSpecializedAccessorFunctionRef ( SILGenFunction & gen , <nl> CanAnyFunctionType substAccessorType = constantInfo . FormalInterfaceType ; <nl> if ( ! substitutions . empty ( ) ) { <nl> auto genericFn = cast < GenericFunctionType > ( substAccessorType ) ; <nl> - auto substFn = genericFn - > substGenericArgs ( gen . SGM . SwiftModule , substitutions ) ; <nl> + auto substFn = genericFn - > substGenericArgs ( substitutions ) ; <nl> substAccessorType = cast < FunctionType > ( substFn - > getCanonicalType ( ) ) ; <nl> } <nl> <nl> mmm a / lib / SILGen / SILGenDecl . cpp <nl> ppp b / lib / SILGen / SILGenDecl . cpp <nl> static bool maybeOpenCodeProtocolWitness ( SILGenFunction & gen , <nl> return false ; <nl> } <nl> <nl> - static void addConformanceToSubstitutionMap ( SILModule & M , <nl> - TypeSubstitutionMap & subs , <nl> - GenericEnvironment * genericEnv , <nl> - CanType base , <nl> - const ProtocolConformance * conformance ) { <nl> - conformance - > forEachTypeWitness ( nullptr , [ & ] ( AssociatedTypeDecl * assocTy , <nl> - Substitution sub , <nl> - TypeDecl * ) - > bool { <nl> - auto depTy = <nl> - CanDependentMemberType : : get ( base , assocTy , M . getASTContext ( ) ) ; <nl> - auto replacement = sub . getReplacement ( ) - > getCanonicalType ( ) ; <nl> - replacement = ArchetypeBuilder : : mapTypeOutOfContext ( M . getSwiftModule ( ) , <nl> - genericEnv , <nl> - replacement ) <nl> - - > getCanonicalType ( ) ; <nl> - subs . insert ( { depTy . getPointer ( ) , replacement } ) ; <nl> - for ( auto conformance : sub . getConformances ( ) ) { <nl> - if ( conformance . isAbstract ( ) ) <nl> - continue ; <nl> - addConformanceToSubstitutionMap ( M , subs , genericEnv , <nl> - depTy , conformance . getConcrete ( ) ) ; <nl> - } <nl> - return false ; <nl> - } ) ; <nl> - } <nl> - <nl> / / / Substitute the ` Self ` type from a protocol conformance into a protocol <nl> / / / requirement ' s type to get the type of the witness . <nl> static CanAnyFunctionType <nl> substSelfTypeIntoProtocolRequirementType ( SILModule & M , <nl> / / Build a substitution map to replace ` self ` and its associated types . <nl> auto & C = M . getASTContext ( ) ; <nl> CanType selfParamTy = CanGenericTypeParamType : : get ( 0 , 0 , C ) ; <nl> - <nl> - TypeSubstitutionMap subs ; <nl> - subs . insert ( { selfParamTy . getPointer ( ) , conformance - > getInterfaceType ( ) <nl> - - > getCanonicalType ( ) } ) ; <nl> - addConformanceToSubstitutionMap ( M , subs , <nl> - conformance - > getGenericEnvironment ( ) , <nl> - selfParamTy , conformance ) ; <nl> <nl> - ArchetypeBuilder builder ( * M . getSwiftModule ( ) , <nl> - M . getASTContext ( ) . Diags ) ; <nl> + Type concreteTy = conformance - > getInterfaceType ( ) ; <nl> + <nl> + SubstitutionMap subs ; <nl> + subs . addSubstitution ( selfParamTy , concreteTy ) ; <nl> + <nl> + / / FIXME : conformance substitutions should be in terms of interface types <nl> + auto concreteSubs = concreteTy - > gatherAllSubstitutions ( M . getSwiftModule ( ) , <nl> + nullptr , nullptr ) ; <nl> + auto specialized = conformance ; <nl> + if ( conformance - > getGenericSignature ( ) ) <nl> + specialized = C . getSpecializedConformance ( <nl> + concreteTy , conformance , concreteSubs ) ; <nl> + <nl> + SmallVector < ProtocolConformanceRef , 1 > conformances ; <nl> + conformances . push_back ( ProtocolConformanceRef ( specialized ) ) ; <nl> + subs . addConformances ( selfParamTy , C . AllocateCopy ( conformances ) ) ; <nl> + <nl> + ArchetypeBuilder builder ( * M . getSwiftModule ( ) , C . Diags ) ; <nl> <nl> SmallVector < GenericTypeParamType * , 4 > allParams ; <nl> <nl> substSelfTypeIntoProtocolRequirementType ( SILModule & M , <nl> continue ; <nl> <nl> / / Substitute the constrained types . <nl> - auto first = reqt . getFirstType ( ) . subst ( M . getSwiftModule ( ) , subs , <nl> - SubstFlags : : IgnoreMissing ) ; <nl> - auto second = reqt . getSecondType ( ) . subst ( M . getSwiftModule ( ) , subs , <nl> - SubstFlags : : IgnoreMissing ) ; <nl> + auto first = reqt . getFirstType ( ) . subst ( subs , SubstFlags : : IgnoreMissing ) <nl> + - > getCanonicalType ( ) ; <nl> + auto second = reqt . getSecondType ( ) . subst ( subs , SubstFlags : : IgnoreMissing ) <nl> + - > getCanonicalType ( ) ; <nl> <nl> if ( ! first - > isTypeParameter ( ) ) { <nl> assert ( second - > isTypeParameter ( ) ) ; <nl> substSelfTypeIntoProtocolRequirementType ( SILModule & M , <nl> } <nl> <nl> / / Substitute away ` Self ` in parameter and result types . <nl> - auto input = reqtTy - > getInput ( ) . subst ( M . getSwiftModule ( ) , subs , <nl> - SubstFlags : : IgnoreMissing ) <nl> + auto input = reqtTy - > getInput ( ) . subst ( subs , SubstFlags : : IgnoreMissing ) <nl> - > getCanonicalType ( ) ; <nl> - auto result = reqtTy - > getResult ( ) . subst ( M . getSwiftModule ( ) , subs , <nl> - SubstFlags : : IgnoreMissing ) <nl> + auto result = reqtTy - > getResult ( ) . subst ( subs , SubstFlags : : IgnoreMissing ) <nl> - > getCanonicalType ( ) ; <nl> <nl> / / The result might be fully concrete , if the witness had no generic <nl> mmm a / lib / SILGen / SILGenPoly . cpp <nl> ppp b / lib / SILGen / SILGenPoly . cpp <nl> SILGenFunction : : emitVTableThunk ( SILDeclRef derived , <nl> <nl> inputSubstType = cast < FunctionType > ( <nl> cast < GenericFunctionType > ( inputSubstType ) <nl> - - > substGenericArgs ( SGM . SwiftModule , subs ) - > getCanonicalType ( ) ) ; <nl> + - > substGenericArgs ( subs ) - > getCanonicalType ( ) ) ; <nl> outputSubstType = cast < FunctionType > ( <nl> cast < GenericFunctionType > ( outputSubstType ) <nl> - - > substGenericArgs ( SGM . SwiftModule , subs ) - > getCanonicalType ( ) ) ; <nl> + - > substGenericArgs ( subs ) - > getCanonicalType ( ) ) ; <nl> } <nl> <nl> / / Emit the indirect return and arguments . <nl> void SILGenFunction : : emitProtocolWitness ( Type selfType , <nl> if ( ! witnessSubs . empty ( ) ) { <nl> witnessSubstTy = cast < FunctionType > ( <nl> cast < GenericFunctionType > ( witnessSubstTy ) <nl> - - > substGenericArgs ( SGM . M . getSwiftModule ( ) , witnessSubs ) <nl> + - > substGenericArgs ( witnessSubs ) <nl> - > getCanonicalType ( ) ) ; <nl> } <nl> CanType reqtSubstInputTy = F . mapTypeIntoContext ( reqtSubstTy . getInput ( ) ) <nl> mmm a / lib / SILOptimizer / IPO / CapturePromotion . cpp <nl> ppp b / lib / SILOptimizer / IPO / CapturePromotion . cpp <nl> class ClosureCloner : public TypeSubstCloner < ClosureCloner > { <nl> <nl> ClosureCloner ( SILFunction * Orig , IsFragile_t Fragile , <nl> StringRef ClonedName , <nl> - TypeSubstitutionMap & InterfaceSubs , <nl> - TypeSubstitutionMap & ContextSubs , <nl> + SubstitutionMap & InterfaceSubs , <nl> + SubstitutionMap & ContextSubs , <nl> ArrayRef < Substitution > ApplySubs , <nl> IndicesSet & PromotableIndices ) ; <nl> <nl> class ClosureCloner : public TypeSubstCloner < ClosureCloner > { <nl> private : <nl> static SILFunction * initCloned ( SILFunction * Orig , IsFragile_t Fragile , <nl> StringRef ClonedName , <nl> - TypeSubstitutionMap & InterfaceSubs , <nl> + SubstitutionMap & InterfaceSubs , <nl> IndicesSet & PromotableIndices ) ; <nl> <nl> void visitDebugValueAddrInst ( DebugValueAddrInst * Inst ) ; <nl> ReachabilityInfo : : isReachable ( SILBasicBlock * From , SILBasicBlock * To ) { <nl> <nl> ClosureCloner : : ClosureCloner ( SILFunction * Orig , IsFragile_t Fragile , <nl> StringRef ClonedName , <nl> - TypeSubstitutionMap & InterfaceSubs , <nl> - TypeSubstitutionMap & ContextSubs , <nl> + SubstitutionMap & InterfaceSubs , <nl> + SubstitutionMap & ContextSubs , <nl> ArrayRef < Substitution > ApplySubs , <nl> IndicesSet & PromotableIndices ) <nl> : TypeSubstCloner < ClosureCloner > ( <nl> static std : : string getSpecializedName ( SILFunction * F , <nl> SILFunction * <nl> ClosureCloner : : initCloned ( SILFunction * Orig , IsFragile_t Fragile , <nl> StringRef ClonedName , <nl> - TypeSubstitutionMap & InterfaceSubs , <nl> + SubstitutionMap & InterfaceSubs , <nl> IndicesSet & PromotableIndices ) { <nl> SILModule & M = Orig - > getModule ( ) ; <nl> <nl> ClosureCloner : : initCloned ( SILFunction * Orig , IsFragile_t Fragile , <nl> OrigFTI - > getOptionalErrorResult ( ) , <nl> M . getASTContext ( ) ) ; <nl> <nl> - auto SubstTy = SILType : : substFuncType ( M , SM , InterfaceSubs , ClonedTy , <nl> + auto SubstTy = SILType : : substFuncType ( M , SM , InterfaceSubs . getMap ( ) , ClonedTy , <nl> / * dropGenerics = * / false ) ; <nl> <nl> assert ( ( Orig - > isTransparent ( ) | | Orig - > isBare ( ) | | Orig - > getLocation ( ) ) <nl> constructClonedFunction ( PartialApplyInst * PAI , FunctionRefInst * FRI , <nl> SILFunction * F = PAI - > getFunction ( ) ; <nl> <nl> / / Create the substitution maps . <nl> - TypeSubstitutionMap InterfaceSubs ; <nl> - TypeSubstitutionMap ContextSubs ; <nl> - ArchetypeConformanceMap ConformanceMap ; <nl> + SubstitutionMap InterfaceSubs ; <nl> + SubstitutionMap ContextSubs ; <nl> <nl> ArrayRef < Substitution > ApplySubs = PAI - > getSubstitutions ( ) ; <nl> auto genericSig = F - > getLoweredFunctionType ( ) - > getGenericSignature ( ) ; <nl> constructClonedFunction ( PartialApplyInst * PAI , FunctionRefInst * FRI , <nl> <nl> if ( ! ApplySubs . empty ( ) ) { <nl> InterfaceSubs = genericSig - > getSubstitutionMap ( ApplySubs ) ; <nl> - genericParams - > getSubstitutionMap ( F - > getModule ( ) . getSwiftModule ( ) , <nl> - genericSig , ApplySubs , <nl> - ContextSubs , ConformanceMap ) ; <nl> + ContextSubs = genericParams - > getSubstitutionMap ( <nl> + F - > getModule ( ) . getSwiftModule ( ) , <nl> + genericSig , ApplySubs ) ; <nl> } else { <nl> assert ( ! genericSig & & " Function type has Unexpected generic signature ! " ) ; <nl> assert ( ! genericParams & & <nl> mmm a / lib / SILOptimizer / Mandatory / MandatoryInlining . cpp <nl> ppp b / lib / SILOptimizer / Mandatory / MandatoryInlining . cpp <nl> runOnFunctionRecursively ( SILFunction * F , FullApplySite AI , <nl> else <nl> I = ApplyBlock - > end ( ) ; <nl> <nl> - TypeSubstitutionMap ContextSubs ; <nl> - ArchetypeConformanceMap ConformanceMap ; <nl> + SubstitutionMap ContextSubs ; <nl> <nl> std : : vector < Substitution > ApplySubs ( InnerAI . getSubstitutions ( ) ) ; <nl> <nl> runOnFunctionRecursively ( SILFunction * F , FullApplySite AI , <nl> auto sig = CalleeFunction - > getLoweredFunctionType ( ) <nl> - > getGenericSignature ( ) ; <nl> params - > getSubstitutionMap ( F - > getModule ( ) . getSwiftModule ( ) , <nl> - sig , ApplySubs , <nl> - ContextSubs , ConformanceMap ) ; <nl> + sig , ApplySubs , ContextSubs ) ; <nl> } <nl> <nl> SILOpenedArchetypesTracker OpenedArchetypesTracker ( * F ) ; <nl> mmm a / lib / SILOptimizer / Transforms / PerformanceInliner . cpp <nl> ppp b / lib / SILOptimizer / Transforms / PerformanceInliner . cpp <nl> bool SILPerformanceInliner : : inlineCallsIntoFunction ( SILFunction * Caller ) { <nl> <nl> / / Notice that we will skip all of the newly inlined ApplyInsts . That ' s <nl> / / okay because we will visit them in our next invocation of the inliner . <nl> - TypeSubstitutionMap ContextSubs ; <nl> + SubstitutionMap ContextSubs ; <nl> SILInliner Inliner ( * Caller , * Callee , <nl> SILInliner : : InlineKind : : PerformanceInline , ContextSubs , <nl> AI . getSubstitutions ( ) , <nl> mmm a / lib / SILOptimizer / Utils / Devirtualize . cpp <nl> ppp b / lib / SILOptimizer / Utils / Devirtualize . cpp <nl> getSubstitutionsForCallee ( SILModule & M , <nl> if ( auto metatypeType = dyn_cast < MetatypeType > ( derivedClass ) ) <nl> derivedClass = CanType ( metatypeType - > getInstanceType ( ) ) ; <nl> <nl> - auto * Module = M . getSwiftModule ( ) ; <nl> + SubstitutionMap subMap ; <nl> <nl> - TypeSubstitutionMap subMap ; <nl> - TypeConformanceMap conformanceMap ; <nl> + if ( auto origCalleeSig = AI . getOrigCalleeType ( ) - > getGenericSignature ( ) ) { <nl> + auto calleeSelfType = AI . getSubstCalleeType ( ) - > getSelfParameter ( ) . getType ( ) ; <nl> + if ( auto metatypeType = dyn_cast < MetatypeType > ( calleeSelfType ) ) <nl> + calleeSelfType = CanType ( metatypeType - > getInstanceType ( ) ) ; <nl> + auto * calleeClassDecl = calleeSelfType - > getClassOrBoundGenericClass ( ) ; <nl> + assert ( calleeClassDecl & & " self is not a class type " ) ; <nl> <nl> - if ( auto derivedCalleeSig = AI . getOrigCalleeType ( ) - > getGenericSignature ( ) ) { <nl> - auto * derivedClassDecl = derivedClass - > getClassOrBoundGenericClass ( ) ; <nl> - assert ( derivedClassDecl & & " self is not a class type " ) ; <nl> - <nl> - auto derivedSubs = AI . getSubstitutions ( ) ; <nl> + auto origSubs = AI . getSubstitutions ( ) ; <nl> <nl> / / Decompose the original substitution using the derived method signature . <nl> - derivedCalleeSig - > getSubstitutionMap ( derivedSubs , subMap , conformanceMap ) ; <nl> + origCalleeSig - > getSubstitutionMap ( origSubs , subMap ) ; <nl> <nl> / / Drop any generic parameters that come from the derived class , leaving <nl> / / only generic parameters of the method itself . <nl> - if ( auto derivedClassSig = derivedClassDecl - > getGenericSignatureOfContext ( ) ) { <nl> + if ( auto derivedClassSig = calleeClassDecl - > getGenericSignatureOfContext ( ) ) { <nl> for ( auto depTy : derivedClassSig - > getAllDependentTypes ( ) ) { <nl> - auto canTy = depTy - > getCanonicalType ( ) . getPointer ( ) ; <nl> - subMap . erase ( canTy ) ; <nl> - conformanceMap . erase ( canTy ) ; <nl> + subMap . removeType ( depTy - > getCanonicalType ( ) ) ; <nl> } <nl> } <nl> } <nl> getSubstitutionsForCallee ( SILModule & M , <nl> / / parameter . <nl> auto baseClass = derivedClass - > getSuperclassForDecl ( baseClassDecl , nullptr ) <nl> - > getCanonicalType ( ) ; <nl> - auto baseClassSubs = baseClass - > gatherAllSubstitutions ( Module , nullptr ) ; <nl> + auto baseClassSubs = baseClass - > gatherAllSubstitutions ( <nl> + M . getSwiftModule ( ) , nullptr ) ; <nl> <nl> / / Decompose the base class substitutions , adding them to the same <nl> / / substitution maps as above . <nl> - baseClassSig - > getSubstitutionMap ( baseClassSubs , subMap , conformanceMap ) ; <nl> + baseClassSig - > getSubstitutionMap ( baseClassSubs , subMap ) ; <nl> } <nl> <nl> / / Build the new substitutions using the base method signature . <nl> auto baseCalleeSig = baseCalleeType - > getGenericSignature ( ) ; <nl> - baseCalleeSig - > getSubstitutions ( * Module , subMap , conformanceMap , newSubs ) ; <nl> + baseCalleeSig - > getSubstitutions ( * M . getSwiftModule ( ) , subMap , newSubs ) ; <nl> } <nl> <nl> SILFunction * swift : : getTargetClassMethod ( SILModule & M , <nl> static void getWitnessMethodSubstitutions ( <nl> / / Otherwise , we need to build new caller - side substitutions <nl> / / written in terms of the witness thunk ' s generic signature , <nl> / / mapping to the archetypes of the caller . <nl> - TypeSubstitutionMap subMap ; <nl> - TypeConformanceMap conformanceMap ; <nl> + SubstitutionMap subMap ; <nl> <nl> / / Take apart caller - side substitutions . <nl> / / <nl> - / / Note that the Self - derived archetypes appearing on the left <nl> - / / hand side of the map do not end up being used . <nl> - requirementSig - > getSubstitutionMap ( origSubs , subMap , conformanceMap ) ; <nl> + / / Note that the Self - derived dependent types appearing on the left <nl> + / / hand side of the map are dropped . <nl> + requirementSig - > getSubstitutionMap ( origSubs , subMap ) ; <nl> + <nl> + auto selfParamTy = conformance - > getProtocol ( ) - > getSelfInterfaceType ( ) ; <nl> + auto rootedInSelf = [ & ] ( Type t ) - > bool { <nl> + while ( auto dmt = t - > getAs < DependentMemberType > ( ) ) { <nl> + t = dmt - > getBase ( ) ; <nl> + } <nl> + return t - > isEqual ( selfParamTy ) ; <nl> + } ; <nl> + <nl> + for ( auto depTy : requirementSig - > getAllDependentTypes ( ) ) { <nl> + if ( rootedInSelf ( depTy ) ) <nl> + subMap . removeType ( depTy - > getCanonicalType ( ) ) ; <nl> + } <nl> <nl> / / Take apart substitutions from the conforming type . <nl> / / <nl> static void getWitnessMethodSubstitutions ( <nl> auto * rootConformance = conformance - > getRootNormalConformance ( ) ; <nl> auto * witnessSig = rootConformance - > getGenericSignature ( ) ; <nl> <nl> - witnessSig - > getSubstitutionMap ( witnessSubs , subMap , conformanceMap ) ; <nl> + witnessSig - > getSubstitutionMap ( witnessSubs , subMap ) ; <nl> } <nl> <nl> / / Now , apply both sets of substitutions computed above to the <nl> / / forwarding substitutions of the witness thunk . <nl> witnessThunkSig - > getSubstitutions ( * M . getSwiftModule ( ) , <nl> - subMap , conformanceMap , newSubs ) ; <nl> + subMap , newSubs ) ; <nl> } <nl> <nl> static void getWitnessMethodSubstitutions ( ApplySite AI , SILFunction * F , <nl> mmm a / lib / SILOptimizer / Utils / Generics . cpp <nl> ppp b / lib / SILOptimizer / Utils / Generics . cpp <nl> ReabstractionInfo : : ReabstractionInfo ( SILFunction * OrigF , <nl> return ; <nl> } <nl> <nl> - TypeSubstitutionMap InterfaceSubs ; <nl> + SubstitutionMap InterfaceSubs ; <nl> if ( OrigF - > getLoweredFunctionType ( ) - > getGenericSignature ( ) ) <nl> InterfaceSubs = OrigF - > getLoweredFunctionType ( ) - > getGenericSignature ( ) <nl> - > getSubstitutionMap ( ParamSubs ) ; <nl> <nl> / / We do not support partial specialization . <nl> - if ( hasUnboundGenericTypes ( InterfaceSubs ) ) { <nl> + if ( hasUnboundGenericTypes ( InterfaceSubs . getMap ( ) ) ) { <nl> DEBUG ( llvm : : dbgs ( ) < < <nl> " Cannot specialize with unbound interface substitutions . \ n " ) ; <nl> DEBUG ( for ( auto Sub : ParamSubs ) { <nl> ReabstractionInfo : : ReabstractionInfo ( SILFunction * OrigF , <nl> } ) ; <nl> return ; <nl> } <nl> - if ( hasDynamicSelfTypes ( InterfaceSubs ) ) { <nl> + if ( hasDynamicSelfTypes ( InterfaceSubs . getMap ( ) ) ) { <nl> DEBUG ( llvm : : dbgs ( ) < < " Cannot specialize with dynamic self . \ n " ) ; <nl> return ; <nl> } <nl> ReabstractionInfo : : ReabstractionInfo ( SILFunction * OrigF , <nl> SILModule & M = OrigF - > getModule ( ) ; <nl> Module * SM = M . getSwiftModule ( ) ; <nl> <nl> - SubstitutedType = SILType : : substFuncType ( M , SM , InterfaceSubs , <nl> + SubstitutedType = SILType : : substFuncType ( M , SM , InterfaceSubs . getMap ( ) , <nl> OrigF - > getLoweredFunctionType ( ) , <nl> / * dropGenerics = * / true ) ; <nl> <nl> GenericFuncSpecializer : : GenericFuncSpecializer ( SILFunction * GenericFunc , <nl> if ( auto * env = GenericFunc - > getGenericEnvironment ( ) ) { <nl> auto sig = GenericFunc - > getLoweredFunctionType ( ) - > getGenericSignature ( ) ; <nl> <nl> - ArchetypeConformanceMap conformanceMap ; <nl> env - > getSubstitutionMap ( M . getSwiftModule ( ) , sig , <nl> - ParamSubs , ContextSubs , <nl> - conformanceMap ) ; <nl> + ParamSubs , ContextSubs ) ; <nl> } <nl> <nl> Mangle : : Mangler Mangler ; <nl> mmm a / lib / SILOptimizer / Utils / Local . cpp <nl> ppp b / lib / SILOptimizer / Utils / Local . cpp <nl> void swift : : replaceDeadApply ( ApplySite Old , ValueBase * New ) { <nl> recursivelyDeleteTriviallyDeadInstructions ( OldApply , true ) ; <nl> } <nl> <nl> - bool swift : : hasUnboundGenericTypes ( TypeSubstitutionMap & SubsMap ) { <nl> + bool swift : : hasUnboundGenericTypes ( const TypeSubstitutionMap & SubsMap ) { <nl> / / Check whether any of the substitutions are dependent . <nl> for ( auto & entry : SubsMap ) <nl> if ( entry . second - > getCanonicalType ( ) - > hasArchetype ( ) ) <nl> bool swift : : hasUnboundGenericTypes ( ArrayRef < Substitution > Subs ) { <nl> return false ; <nl> } <nl> <nl> - bool swift : : hasDynamicSelfTypes ( TypeSubstitutionMap & SubsMap ) { <nl> + bool swift : : hasDynamicSelfTypes ( const TypeSubstitutionMap & SubsMap ) { <nl> / / Check whether any of the substitutions are refer to dynamic self . <nl> for ( auto & entry : SubsMap ) <nl> if ( entry . second - > getCanonicalType ( ) - > hasDynamicSelfType ( ) ) <nl> mmm a / lib / Sema / CodeSynthesis . cpp <nl> ppp b / lib / Sema / CodeSynthesis . cpp <nl> void TypeChecker : : completePropertyBehaviorStorage ( VarDecl * VD , <nl> / / Substitute the storage type into the conforming context . <nl> auto sig = BehaviorConformance - > getProtocol ( ) - > getGenericSignatureOfContext ( ) ; <nl> <nl> - TypeSubstitutionMap interfaceMap = sig - > getSubstitutionMap ( SelfInterfaceSubs ) ; <nl> - auto SubstStorageInterfaceTy = StorageTy . subst ( VD - > getModuleContext ( ) , <nl> - interfaceMap , SubstOptions ( ) ) ; <nl> + auto interfaceMap = sig - > getSubstitutionMap ( SelfInterfaceSubs ) ; <nl> + auto SubstStorageInterfaceTy = StorageTy . subst ( interfaceMap , SubstOptions ( ) ) ; <nl> assert ( SubstStorageInterfaceTy & & " storage type substitution failed ? ! " ) ; <nl> <nl> - TypeSubstitutionMap contextMap = sig - > getSubstitutionMap ( SelfContextSubs ) ; <nl> - auto SubstStorageContextTy = StorageTy . subst ( VD - > getModuleContext ( ) , <nl> - contextMap , SubstOptions ( ) ) ; <nl> + auto contextMap = sig - > getSubstitutionMap ( SelfContextSubs ) ; <nl> + auto SubstStorageContextTy = StorageTy . subst ( contextMap , SubstOptions ( ) ) ; <nl> assert ( SubstStorageContextTy & & " storage type substitution failed ? ! " ) ; <nl> <nl> auto DC = VD - > getDeclContext ( ) ; <nl> void TypeChecker : : completePropertyBehaviorParameter ( VarDecl * VD , <nl> GenericSignature * genericSig = nullptr ; <nl> GenericEnvironment * genericEnv = nullptr ; <nl> <nl> - TypeSubstitutionMap interfaceMap = sig - > getSubstitutionMap ( SelfInterfaceSubs ) ; <nl> - auto SubstInterfaceTy = ParameterTy . subst ( VD - > getModuleContext ( ) , <nl> - interfaceMap , SubstOptions ( ) ) ; <nl> + auto interfaceMap = sig - > getSubstitutionMap ( SelfInterfaceSubs ) ; <nl> + auto SubstInterfaceTy = ParameterTy . subst ( interfaceMap , SubstOptions ( ) ) ; <nl> assert ( SubstInterfaceTy & & " storage type substitution failed ? ! " ) ; <nl> <nl> - TypeSubstitutionMap contextMap = sig - > getSubstitutionMap ( SelfContextSubs ) ; <nl> - auto SubstContextTy = ParameterTy . subst ( VD - > getModuleContext ( ) , <nl> - contextMap , SubstOptions ( ) ) ; <nl> + auto contextMap = sig - > getSubstitutionMap ( SelfContextSubs ) ; <nl> + auto SubstContextTy = ParameterTy . subst ( contextMap , SubstOptions ( ) ) ; <nl> assert ( SubstContextTy & & " storage type substitution failed ? ! " ) ; <nl> <nl> auto SubstBodyResultTy = SubstContextTy - > castTo < AnyFunctionType > ( ) <nl> void TypeChecker : : completePropertyBehaviorParameter ( VarDecl * VD , <nl> for ( unsigned i : indices ( * DeclaredParams ) ) { <nl> auto declaredParam = DeclaredParams - > get ( i ) ; <nl> auto declaredParamTy = declaredParam - > getInterfaceType ( ) ; <nl> - auto interfaceTy = declaredParamTy . subst ( DC - > getParentModule ( ) , <nl> - interfaceMap , <nl> - SubstOptions ( ) ) ; <nl> + auto interfaceTy = declaredParamTy . subst ( interfaceMap , SubstOptions ( ) ) ; <nl> assert ( interfaceTy ) ; <nl> - auto contextTy = declaredParamTy . subst ( DC - > getParentModule ( ) , <nl> - contextMap , SubstOptions ( ) ) ; <nl> + auto contextTy = declaredParamTy . subst ( contextMap , SubstOptions ( ) ) ; <nl> assert ( contextTy ) ; <nl> <nl> SmallString < 64 > ParamNameBuf ; <nl> swift : : createDesignatedInitOverride ( TypeChecker & tc , <nl> <nl> / / Apply the superclass substitutions to produce a contextual <nl> / / type in terms of the derived class archetypes . <nl> - auto paramSubstTy = paramTy . subst ( moduleDecl , subsMap , SubstOptions ( ) ) ; <nl> + auto paramSubstTy = paramTy . subst ( subsMap , SubstOptions ( ) ) ; <nl> decl - > overwriteType ( paramSubstTy ) ; <nl> <nl> / / Map it to an interface type in terms of the derived class <nl> mmm a / lib / Sema / TypeCheckDecl . cpp <nl> ppp b / lib / Sema / TypeCheckDecl . cpp <nl> static void checkVarBehavior ( VarDecl * decl , TypeChecker & TC ) { <nl> auto sig = behaviorProto - > getGenericSignatureOfContext ( ) ; <nl> auto map = sig - > getSubstitutionMap ( interfaceSubs ) ; <nl> auto substValueTy = behavior - > ValueDecl - > getInterfaceType ( ) <nl> - . subst ( decl - > getModuleContext ( ) , map , SubstOptions ( ) ) ; <nl> + . subst ( map , SubstOptions ( ) ) ; <nl> <nl> if ( ! substValueTy - > isEqual ( decl - > getInterfaceType ( ) ) ) { <nl> TC . diagnose ( behavior - > getLoc ( ) , <nl> | Merge pull request from slavapestov / add - substitution - map | apple/swift | 4ab09b44883d3dfd38feaea0b7c85143a6ef166b | 2016-09-09T06:30:37Z |
mmm a / modules / core / include / opencv2 / core / cvdef . h <nl> ppp b / modules / core / include / opencv2 / core / cvdef . h <nl> CV_INLINE int cvIsInf ( double value ) <nl> / / atomic increment on the linux version of the Intel ( tm ) compiler <nl> # define CV_XADD ( addr , delta ) ( int ) _InterlockedExchangeAdd ( const_cast < void * > ( reinterpret_cast < volatile void * > ( addr ) ) , delta ) <nl> # elif defined __GNUC__ <nl> - # if defined __clang__ & & __clang_major__ > = 3 & & ! defined __ANDROID__ <nl> + # if defined __clang__ & & __clang_major__ > = 3 & & ! defined __ANDROID__ & & ! defined __EMSCRIPTEN__ <nl> # ifdef __ATOMIC_ACQ_REL <nl> # define CV_XADD ( addr , delta ) __c11_atomic_fetch_add ( ( _Atomic ( int ) * ) ( addr ) , delta , __ATOMIC_ACQ_REL ) <nl> # else <nl> mmm a / modules / core / src / system . cpp <nl> ppp b / modules / core / src / system . cpp <nl> std : : wstring GetTempFileNameWinRT ( std : : wstring prefix ) <nl> <nl> # include < stdarg . h > <nl> <nl> - # if defined __linux__ | | defined __APPLE__ <nl> + # if defined __linux__ | | defined __APPLE__ | | defined __EMSCRIPTEN__ <nl> # include < unistd . h > <nl> # include < stdio . h > <nl> # include < sys / types . h > <nl> | Merge pull request from severin - lemaignan : emscripten | opencv/opencv | 17f53bc30129196d1f52097e9bfa450e10f471fc | 2013-12-03T08:14:09Z |
mmm a / lib / AST / ASTPrinter . cpp <nl> ppp b / lib / AST / ASTPrinter . cpp <nl> void PrintAST : : visitConstructorDecl ( ConstructorDecl * decl ) { <nl> recordDeclLoc ( decl , <nl> [ & ] { <nl> Printer < < " init " ; <nl> + } , [ & ] { / / Signature <nl> switch ( decl - > getFailability ( ) ) { <nl> case OTK_None : <nl> break ; <nl> void PrintAST : : visitConstructorDecl ( ConstructorDecl * decl ) { <nl> Printer < < " ! " ; <nl> break ; <nl> } <nl> - } , [ & ] { / / Parameters <nl> + <nl> if ( decl - > isGeneric ( ) ) <nl> printGenericParams ( decl - > getGenericParams ( ) ) ; <nl> <nl> mmm a / test / SourceKit / SourceDocInfo / cursor_info . swift <nl> ppp b / test / SourceKit / SourceDocInfo / cursor_info . swift <nl> public class SubscriptCursorTest { <nl> } <nl> <nl> class C3 { <nl> - deinit { } <nl> + deinit { } <nl> + init ! ( x : Int ) { return nil } <nl> + init ? ( y : Int ) { return nil } <nl> + init ( z : Int ) throws { } <nl> } <nl> <nl> / / RUN : rm - rf % t . tmp <nl> class C3 { <nl> / / CHECK29 - NEXT : C3 - > ( ) <nl> / / CHECK29 - NEXT : < Declaration > deinit < / Declaration > <nl> / / CHECK29 - NEXT : < decl . function . destructor > < decl . name > deinit < / decl . name > < / decl . function . destructor > <nl> + <nl> + / / RUN : % sourcekitd - test - req = cursor - pos = 75 : 3 % s - - - F % S / . . / Inputs / libIDE - mock - sdk - I % t . tmp % mcp_opt % s | FileCheck % s - check - prefix = CHECK30 <nl> + / / CHECK30 : source . lang . swift . decl . function . constructor ( 75 : 3 - 75 : 16 ) <nl> + / / CHECK30 - NEXT : init ( x : ) <nl> + / / CHECK30 - NEXT : s : FC11cursor_info2C3cFT1xSi_GSQS0__ <nl> + / / CHECK30 - NEXT : C3 . Type - > ( x : Int ) - > C3 ! <nl> + / / CHECK30 - NEXT : < Declaration > init ! ( x : < Type usr = " s : Si " > Int < / Type > ) < / Declaration > <nl> + / / CHECK30 - NEXT : < decl . function . constructor > < decl . name > init < / decl . name > ! ( x : < ref . struct usr = " s : Si " > Int < / ref . struct > ) < / decl . function . constructor > <nl> + <nl> + / / RUN : % sourcekitd - test - req = cursor - pos = 76 : 3 % s - - - F % S / . . / Inputs / libIDE - mock - sdk - I % t . tmp % mcp_opt % s | FileCheck % s - check - prefix = CHECK31 <nl> + / / CHECK31 : source . lang . swift . decl . function . constructor ( 76 : 3 - 76 : 16 ) <nl> + / / CHECK31 - NEXT : init ( y : ) <nl> + / / CHECK31 - NEXT : s : FC11cursor_info2C3cFT1ySi_GSqS0__ <nl> + / / CHECK31 - NEXT : C3 . Type - > ( y : Int ) - > C3 ? <nl> + / / CHECK31 - NEXT : < Declaration > init ? ( y : < Type usr = " s : Si " > Int < / Type > ) < / Declaration > <nl> + / / CHECK31 - NEXT : < decl . function . constructor > < decl . name > init < / decl . name > ? ( y : < ref . struct usr = " s : Si " > Int < / ref . struct > ) < / decl . function . constructor > <nl> + <nl> + / / RUN : % sourcekitd - test - req = cursor - pos = 77 : 3 % s - - - F % S / . . / Inputs / libIDE - mock - sdk - I % t . tmp % mcp_opt % s | FileCheck % s - check - prefix = CHECK32 <nl> + / / CHECK32 : source . lang . swift . decl . function . constructor ( 77 : 3 - 77 : 15 ) <nl> + / / CHECK32 - NEXT : init ( z : ) <nl> + / / CHECK32 - NEXT : s : FC11cursor_info2C3cFzT1zSi_S0_ <nl> + / / CHECK32 - NEXT : C3 . Type - > ( z : Int ) throws - > C3 <nl> + / / CHECK32 - NEXT : < Declaration > init ( z : < Type usr = " s : Si " > Int < / Type > ) throws < / Declaration > <nl> + / / CHECK32 - NEXT : < decl . function . constructor > < decl . name > init < / decl . name > ( z : < ref . struct usr = " s : Si " > Int < / ref . struct > ) throws < / decl . function . constructor > <nl> | [ SourceKit ] Move bang / question - mark out of annotated name for init | apple/swift | f3ca9dc99259b0ff564e61eb1179aec8ae86d482 | 2016-02-15T18:07:49Z |
mmm a / tensorflow / compiler / xla / service / cpu / BUILD <nl> ppp b / tensorflow / compiler / xla / service / cpu / BUILD <nl> cc_library ( <nl> " / / tensorflow / compiler / xla / service : hlo_dataflow_analysis " , <nl> " / / tensorflow / compiler / xla / service : hlo_execution_profile " , <nl> " / / tensorflow / compiler / xla / service : logical_buffer " , <nl> + " / / tensorflow / compiler / xla / service : maybe_owning_device_memory " , <nl> " / / tensorflow / compiler / xla / service : shaped_buffer " , <nl> " / / tensorflow / core : lib " , <nl> " / / tensorflow / core : stream_executor_no_cuda " , <nl> + " / / tensorflow / core / platform : logging " , <nl> + " / / tensorflow / core / platform : macros " , <nl> + " / / tensorflow / core / platform : mutex " , <nl> + " / / tensorflow / core / platform : platform_port " , <nl> + " / / tensorflow / core / platform : types " , <nl> " / / tensorflow / core / profiler / lib : traceme " , <nl> " / / tensorflow / stream_executor : device_memory_allocator " , <nl> " / / tensorflow / stream_executor / host : host_stream " , <nl> mmm a / tensorflow / compiler / xla / service / cpu / cpu_executable . cc <nl> ppp b / tensorflow / compiler / xla / service / cpu / cpu_executable . cc <nl> limitations under the License . <nl> # include " tensorflow / compiler / xla / service / hlo_computation . h " <nl> # include " tensorflow / compiler / xla / service / hlo_module . h " <nl> # include " tensorflow / compiler / xla / service / logical_buffer . h " <nl> + # include " tensorflow / compiler / xla / service / maybe_owning_device_memory . h " <nl> # include " tensorflow / compiler / xla / service / shaped_buffer . h " <nl> # include " tensorflow / compiler / xla / shape_tree . h " <nl> # include " tensorflow / compiler / xla / shape_util . h " <nl> limitations under the License . <nl> # include " tensorflow / core / platform / mem . h " <nl> # include " tensorflow / core / platform / mutex . h " <nl> # include " tensorflow / core / platform / types . h " <nl> + # include " tensorflow / stream_executor / device_memory_allocator . h " <nl> # include " tensorflow / stream_executor / host / host_stream . h " <nl> <nl> namespace xla { <nl> CpuExecutable : : CpuExecutable ( <nl> < < reinterpret_cast < void * > ( compute_function_ ) ; <nl> } <nl> <nl> - StatusOr < std : : pair < std : : vector < se : : DeviceMemoryBase > , <nl> - std : : vector < se : : OwningDeviceMemory > > > <nl> + StatusOr < std : : tuple < std : : vector < se : : DeviceMemoryBase > , <nl> + std : : vector < se : : OwningDeviceMemory > , <nl> + std : : vector < se : : OwningDeviceMemory > > > <nl> CpuExecutable : : CreateBufferTable ( <nl> se : : DeviceMemoryAllocator * memory_allocator , int device_ordinal , <nl> - absl : : Span < const ShapedBuffer * const > arguments ) { <nl> + std : : vector < ShapeTree < MaybeOwningDeviceMemory > > arguments ) { <nl> std : : vector < se : : DeviceMemoryBase > unowning_buffers ( <nl> assignment_ - > Allocations ( ) . size ( ) ) ; <nl> std : : vector < se : : OwningDeviceMemory > owning_buffers ( <nl> CpuExecutable : : CreateBufferTable ( <nl> VLOG ( 3 ) < < allocation . ToString ( ) ; <nl> <nl> if ( allocation . is_entry_computation_parameter ( ) ) { <nl> - unowning_buffers [ i ] = arguments [ allocation . parameter_number ( ) ] - > buffer ( <nl> - allocation . param_shape_index ( ) ) ; <nl> + unowning_buffers [ i ] = arguments [ allocation . parameter_number ( ) ] <nl> + . element ( allocation . param_shape_index ( ) ) <nl> + . AsDeviceMemoryBase ( ) ; <nl> CHECK_EQ ( allocation . size ( ) , unowning_buffers [ i ] . size ( ) ) <nl> < < " Size mismatch on param " < < allocation . parameter_number ( ) <nl> < < " at shape index " < < allocation . param_shape_index ( ) . ToString ( ) ; <nl> CpuExecutable : : CreateBufferTable ( <nl> assignment_ - > GetUniqueTopLevelOutputSlice ( ) ) ; <nl> VLOG ( 3 ) < < " result index : " < < result_slice . index ( ) ; <nl> <nl> - return { { std : : move ( unowning_buffers ) , std : : move ( owning_buffers ) } } ; <nl> + std : : vector < se : : OwningDeviceMemory > buffers_to_free ; <nl> + for ( ShapeTree < MaybeOwningDeviceMemory > & argument : arguments ) { <nl> + for ( std : : pair < ShapeIndex , MaybeOwningDeviceMemory > & buffer : argument ) { <nl> + auto maybe_owning_buffer = buffer . second . Release ( ) ; <nl> + if ( maybe_owning_buffer ) { <nl> + buffers_to_free . push_back ( std : : move ( * maybe_owning_buffer ) ) ; <nl> + } <nl> + } <nl> + } <nl> + return std : : make_tuple ( std : : move ( unowning_buffers ) , std : : move ( owning_buffers ) , <nl> + std : : move ( buffers_to_free ) ) ; <nl> } <nl> <nl> Status CpuExecutable : : ExecuteComputeFunction ( <nl> StatusOr < ScopedShapedBuffer > CpuExecutable : : CreateResultShapedBuffer ( <nl> return std : : move ( result_buffer ) ; <nl> } <nl> <nl> - StatusOr < ScopedShapedBuffer > CpuExecutable : : ExecuteAsyncOnStream ( <nl> + StatusOr < ExecutionOutput > CpuExecutable : : ExecuteAsyncOnStream ( <nl> const ServiceExecutableRunOptions * run_options , <nl> - absl : : Span < const ShapedBuffer * const > arguments , <nl> + std : : vector < ShapeTree < MaybeOwningDeviceMemory > > arguments , <nl> HloExecutionProfile * hlo_execution_profile ) { <nl> if ( GetRootValueSet ( ) . IsAmbiguous ( ) ) { <nl> return Unimplemented ( " Points - to set of root instruction is ambiguous " ) ; <nl> StatusOr < ScopedShapedBuffer > CpuExecutable : : ExecuteAsyncOnStream ( <nl> for ( int64 i = 0 ; i < entry_comp - > num_parameters ( ) ; + + i ) { <nl> const Shape & expected_shape = <nl> entry_comp - > parameter_instruction ( i ) - > shape ( ) ; <nl> - const Shape & actual_shape = arguments [ i ] - > on_device_shape ( ) ; <nl> + const Shape & actual_shape = arguments [ i ] . shape ( ) ; <nl> CHECK ( expected_shape = = actual_shape ) < < absl : : StreamFormat ( <nl> " Shape mismatch on argument % d . Expected % s , but was % s . " , i , <nl> expected_shape . ToString ( / * print_layout = * / true ) , <nl> StatusOr < ScopedShapedBuffer > CpuExecutable : : ExecuteAsyncOnStream ( <nl> se : : DeviceMemoryAllocator * memory_allocator = run_options - > allocator ( ) ; <nl> std : : vector < se : : OwningDeviceMemory > owning_buffers ; <nl> std : : vector < se : : DeviceMemoryBase > unowning_buffers ; <nl> + std : : vector < se : : OwningDeviceMemory > buffers_to_release ; <nl> TF_ASSIGN_OR_RETURN ( <nl> - std : : tie ( unowning_buffers , owning_buffers ) , <nl> + std : : tie ( unowning_buffers , owning_buffers , buffers_to_release ) , <nl> CreateBufferTable ( memory_allocator , stream - > parent ( ) - > device_ordinal ( ) , <nl> - arguments ) ) ; <nl> + std : : move ( arguments ) ) ) ; <nl> <nl> TF_ASSIGN_OR_RETURN ( <nl> ScopedShapedBuffer result , <nl> StatusOr < ScopedShapedBuffer > CpuExecutable : : ExecuteAsyncOnStream ( <nl> std : : move ( owning_buffers ) ) , <nl> hlo_execution_profile } ) ; <nl> <nl> - return std : : move ( result ) ; <nl> + return ExecutionOutput ( std : : move ( result ) , std : : move ( buffers_to_release ) , { } , <nl> + se : : OwningDeviceMemory ( ) ) ; <nl> } <nl> <nl> / * static * / int64 CpuExecutable : : ShapeSizeBytes ( const Shape & shape ) { <nl> mmm a / tensorflow / compiler / xla / service / cpu / cpu_executable . h <nl> ppp b / tensorflow / compiler / xla / service / cpu / cpu_executable . h <nl> class CpuExecutable : public Executable { <nl> std : : unique_ptr < HloProfileIndexMap > hlo_profile_index_map ) ; <nl> ~ CpuExecutable ( ) override { } <nl> <nl> - StatusOr < ScopedShapedBuffer > ExecuteAsyncOnStream ( <nl> + StatusOr < ExecutionOutput > ExecuteAsyncOnStream ( <nl> const ServiceExecutableRunOptions * run_options , <nl> - absl : : Span < const ShapedBuffer * const > arguments , <nl> + std : : vector < ShapeTree < MaybeOwningDeviceMemory > > arguments , <nl> HloExecutionProfile * hlo_execution_profile ) override ; <nl> <nl> / / This should be called after set_ir_module_string . <nl> class CpuExecutable : public Executable { <nl> / / allocated by this routine . This routine allocates buffers for temporary <nl> / / storage and the live - out buffer into which the computation writes it <nl> / / result . <nl> - StatusOr < std : : pair < std : : vector < se : : DeviceMemoryBase > , <nl> - std : : vector < se : : OwningDeviceMemory > > > <nl> + / / <nl> + / / - buffers_to_free : buffers whose ownership was donated by the caller that <nl> + / / are to be freed by the caller . <nl> + StatusOr < std : : tuple < std : : vector < se : : DeviceMemoryBase > , <nl> + std : : vector < se : : OwningDeviceMemory > , <nl> + std : : vector < se : : OwningDeviceMemory > > > <nl> CreateBufferTable ( se : : DeviceMemoryAllocator * memory_allocator , <nl> int device_ordinal , <nl> - absl : : Span < const ShapedBuffer * const > arguments ) ; <nl> + std : : vector < ShapeTree < MaybeOwningDeviceMemory > > arguments ) ; <nl> <nl> / / Calls the generated function performing the computation with the given <nl> / / arguments using the supplied buffers . <nl> mmm a / tensorflow / compiler / xla / service / executable . cc <nl> ppp b / tensorflow / compiler / xla / service / executable . cc <nl> limitations under the License . <nl> # include " tensorflow / compiler / xla / debug_options_flags . h " <nl> # include " tensorflow / compiler / xla / service / dump . h " <nl> # include " tensorflow / compiler / xla / service / hlo_graph_dumper . h " <nl> + # include " tensorflow / compiler / xla / service / maybe_owning_device_memory . h " <nl> # include " tensorflow / compiler / xla / status . h " <nl> # include " tensorflow / compiler / xla / status_macros . h " <nl> # include " tensorflow / core / lib / core / status . h " <nl> StatusOr < ScopedShapedBuffer > Executable : : ExecuteOnStream ( <nl> return result ; <nl> } <nl> <nl> + static ShapeTree < MaybeOwningDeviceMemory > MakeMaybeOwningDeviceMemoryTree ( <nl> + const ShapedBuffer & shaped_buffer ) { <nl> + ShapeTree < MaybeOwningDeviceMemory > result ( shaped_buffer . on_device_shape ( ) ) ; <nl> + auto in_it = shaped_buffer . buffers ( ) . begin ( ) ; <nl> + auto out_it = result . begin ( ) ; <nl> + for ( ; in_it ! = shaped_buffer . buffers ( ) . end ( ) ; + + in_it , + + out_it ) { <nl> + DCHECK ( out_it ! = result . end ( ) ) ; <nl> + out_it - > second = MaybeOwningDeviceMemory ( in_it - > second ) ; <nl> + } <nl> + return result ; <nl> + } <nl> + <nl> + StatusOr < ScopedShapedBuffer > Executable : : ExecuteAsyncOnStream ( <nl> + const ServiceExecutableRunOptions * run_options , <nl> + absl : : Span < const ShapedBuffer * const > arguments , <nl> + HloExecutionProfile * hlo_execution_profile ) { <nl> + std : : vector < ShapeTree < MaybeOwningDeviceMemory > > args ( arguments . size ( ) ) ; <nl> + auto out_it = args . begin ( ) ; <nl> + for ( const ShapedBuffer * arg : arguments ) { <nl> + * out_it + + = MakeMaybeOwningDeviceMemoryTree ( * arg ) ; <nl> + } <nl> + TF_ASSIGN_OR_RETURN ( ExecutionOutput out , <nl> + ExecuteAsyncOnStream ( run_options , std : : move ( args ) , <nl> + hlo_execution_profile ) ) ; <nl> + return out . ConsumeResult ( ) ; <nl> + } <nl> + <nl> StatusOr < ExecutionOutput > Executable : : ExecuteOnStream ( <nl> const ServiceExecutableRunOptions * run_options , <nl> - std : : vector < ShapeTree < xla : : MaybeOwningDeviceMemory > > arguments , <nl> + std : : vector < ShapeTree < MaybeOwningDeviceMemory > > arguments , <nl> HloExecutionProfile * hlo_execution_profile ) { <nl> StatusOr < ExecutionOutput > result = ExecuteAsyncOnStream ( <nl> run_options , std : : move ( arguments ) , hlo_execution_profile ) ; <nl> StatusOr < ExecutionOutput > Executable : : ExecuteOnStream ( <nl> return result ; <nl> } <nl> <nl> - StatusOr < ExecutionOutput > Executable : : ExecuteAsyncOnStream ( <nl> - const ServiceExecutableRunOptions * / * run_options * / , <nl> - std : : vector < ShapeTree < xla : : MaybeOwningDeviceMemory > > / * arguments * / , <nl> - HloExecutionProfile * / * hlo_execution_profile * / ) { <nl> - return Unimplemented ( <nl> - " MaybeOwningDeviceMemory version of overload is not implemented " ) ; <nl> - } <nl> - <nl> StatusOr < std : : vector < ScopedShapedBuffer > > Executable : : ExecuteOnStreams ( <nl> absl : : Span < const ServiceExecutableRunOptions > run_options , <nl> absl : : Span < const absl : : Span < const ShapedBuffer * const > > arguments ) { <nl> mmm a / tensorflow / compiler / xla / service / executable . h <nl> ppp b / tensorflow / compiler / xla / service / executable . h <nl> class Executable { <nl> / / If the hlo_execution_profile is provided as non - nullptr , profiling will be <nl> / / enabled . Note that profiling is tricky to use correctly , as the profiling <nl> / / objects ( when they exist ) must out - live the task . <nl> - virtual StatusOr < ScopedShapedBuffer > ExecuteAsyncOnStream ( <nl> + StatusOr < ScopedShapedBuffer > ExecuteAsyncOnStream ( <nl> const ServiceExecutableRunOptions * run_options , <nl> absl : : Span < const ShapedBuffer * const > arguments , <nl> - HloExecutionProfile * hlo_execution_profile ) = 0 ; <nl> + HloExecutionProfile * hlo_execution_profile ) ; <nl> <nl> / / Same as ExecuteAsyncOnStream ( ) , but blocks waiting for the computation to <nl> / / complete . <nl> StatusOr < ExecutionOutput > ExecuteOnStream ( <nl> const ServiceExecutableRunOptions * run_options , <nl> - std : : vector < ShapeTree < xla : : MaybeOwningDeviceMemory > > arguments , <nl> + std : : vector < ShapeTree < MaybeOwningDeviceMemory > > arguments , <nl> HloExecutionProfile * hlo_execution_profile ) ; <nl> <nl> virtual StatusOr < ExecutionOutput > ExecuteAsyncOnStream ( <nl> const ServiceExecutableRunOptions * run_options , <nl> - std : : vector < ShapeTree < xla : : MaybeOwningDeviceMemory > > arguments , <nl> - HloExecutionProfile * hlo_execution_profile ) ; <nl> + std : : vector < ShapeTree < MaybeOwningDeviceMemory > > arguments , <nl> + HloExecutionProfile * hlo_execution_profile ) = 0 ; <nl> <nl> / / Same as ExecuteOnStream ( ) , but runs this executable on multiple <nl> / / streams . arguments [ i ] contains the arguments to the execution on <nl> mmm a / tensorflow / compiler / xla / service / gpu / gpu_executable . cc <nl> ppp b / tensorflow / compiler / xla / service / gpu / gpu_executable . cc <nl> GpuExecutable : : ResolveConstantGlobals ( se : : Stream * stream ) { <nl> return & module_globals_ . emplace ( executor , std : : move ( globals ) ) . first - > second ; <nl> } <nl> <nl> - StatusOr < ScopedShapedBuffer > GpuExecutable : : Execute ( <nl> + StatusOr < ExecutionOutput > GpuExecutable : : ExecuteAsyncOnStream ( <nl> const ServiceExecutableRunOptions * run_options , <nl> - absl : : Span < const ShapedBuffer * const > arguments , <nl> - HloExecutionProfile * hlo_execution_profile , bool block_host_until_done ) { <nl> - se : : DeviceMemoryAllocator * memory_allocator = run_options - > allocator ( ) ; <nl> + std : : vector < ShapeTree < MaybeOwningDeviceMemory > > arguments , <nl> + HloExecutionProfile * hlo_execution_profile ) { <nl> + se : : DeviceMemoryAllocator * const memory_allocator = run_options - > allocator ( ) ; <nl> + / / Force synchronous execution if the allocator requires it . <nl> + const bool block_host_until_done = <nl> + ! memory_allocator - > AllowsAsynchronousDeallocation ( ) ; <nl> <nl> if ( GetRootValueSet ( ) . IsAmbiguous ( ) ) { <nl> return Unimplemented ( " Points - to set of root instruction is ambiguous " ) ; <nl> StatusOr < ScopedShapedBuffer > GpuExecutable : : Execute ( <nl> if ( allocation . is_entry_computation_parameter ( ) ) { <nl> auto param_no = allocation . parameter_number ( ) ; <nl> se : : DeviceMemoryBase buffer = <nl> - arguments [ param_no ] - > buffer ( allocation . param_shape_index ( ) ) ; <nl> + arguments [ param_no ] <nl> + . element ( allocation . param_shape_index ( ) ) <nl> + . AsDeviceMemoryBase ( ) ; <nl> <nl> / / All top - level buffers and sub - buffers must have an explicit , non - null <nl> / / pointer , except for zero - sized buffers , which may be null . <nl> StatusOr < ScopedShapedBuffer > GpuExecutable : : Execute ( <nl> } ) ) ; <nl> TF_RETURN_IF_ERROR ( buffer_allocations - > TearDown ( buffers_in_result ) ) ; <nl> <nl> - return std : : move ( shaped_buffer ) ; <nl> - } <nl> - <nl> - StatusOr < ScopedShapedBuffer > GpuExecutable : : ExecuteAsyncOnStream ( <nl> - const ServiceExecutableRunOptions * run_options , <nl> - absl : : Span < const ShapedBuffer * const > arguments , <nl> - HloExecutionProfile * hlo_execution_profile ) { <nl> - se : : DeviceMemoryAllocator * memory_allocator = run_options - > allocator ( ) ; <nl> - / / Force synchronous execution if the allocator requires it . <nl> - bool block_host_until_done = <nl> - ! memory_allocator - > AllowsAsynchronousDeallocation ( ) ; <nl> - return Execute ( run_options , arguments , hlo_execution_profile , <nl> - block_host_until_done ) ; <nl> + std : : vector < se : : OwningDeviceMemory > buffers_to_free ; <nl> + for ( ShapeTree < MaybeOwningDeviceMemory > & argument : arguments ) { <nl> + for ( std : : pair < ShapeIndex , MaybeOwningDeviceMemory > & buffer : argument ) { <nl> + auto maybe_owning_buffer = buffer . second . Release ( ) ; <nl> + if ( maybe_owning_buffer ) { <nl> + buffers_to_free . push_back ( std : : move ( * maybe_owning_buffer ) ) ; <nl> + } <nl> + } <nl> + } <nl> + return ExecutionOutput ( std : : move ( shaped_buffer ) , std : : move ( buffers_to_free ) , <nl> + { } , { } ) ; <nl> } <nl> <nl> const InstructionValueSet & GpuExecutable : : GetRootValueSet ( ) const { <nl> mmm a / tensorflow / compiler / xla / service / gpu / gpu_executable . h <nl> ppp b / tensorflow / compiler / xla / service / gpu / gpu_executable . h <nl> class GpuExecutable : public Executable { <nl> <nl> / / ExecuteAsyncOnStream will fail if the compute capability of the stream <nl> / / doesn ' t match the compute capability passed to this object ' s constructor . <nl> - StatusOr < ScopedShapedBuffer > ExecuteAsyncOnStream ( <nl> + StatusOr < ExecutionOutput > ExecuteAsyncOnStream ( <nl> const ServiceExecutableRunOptions * run_options , <nl> - absl : : Span < const ShapedBuffer * const > arguments , <nl> + std : : vector < ShapeTree < MaybeOwningDeviceMemory > > arguments , <nl> HloExecutionProfile * hlo_execution_profile ) override ; <nl> <nl> std : : shared_ptr < const BufferAssignment > GetBufferAssignment ( ) const { <nl> class GpuExecutable : public Executable { <nl> } <nl> <nl> private : <nl> - StatusOr < ScopedShapedBuffer > Execute ( <nl> - const ServiceExecutableRunOptions * run_options , <nl> - absl : : Span < const ShapedBuffer * const > arguments , <nl> - HloExecutionProfile * hlo_execution_profile , bool block_host_until_done ) ; <nl> - <nl> / / If ` block_host_until_done ` is false , execution will not block the host <nl> / / until the kernels have completed . This is used as an optimization for <nl> / / clients , such as Tensorflow , that use a single stream of execution for <nl> mmm a / tensorflow / compiler / xla / service / hlo_input_output_alias_config . cc <nl> ppp b / tensorflow / compiler / xla / service / hlo_input_output_alias_config . cc <nl> absl : : optional < ShapeIndex > HloInputOutputAliasConfig : : GetAliasedOutput ( <nl> absl : : optional < HloInputOutputAliasConfig : : Alias > <nl> HloInputOutputAliasConfig : : GetAliasedParameter ( <nl> const ShapeIndex & output_index ) const { <nl> - CHECK ( ShapeUtil : : IndexIsValid ( alias_ . shape ( ) , output_index ) ) ; <nl> + CHECK ( ShapeUtil : : IndexIsValid ( alias_ . shape ( ) , output_index ) ) <nl> + < < ToString ( ) < < " " < < alias_ . shape ( ) . ToString ( ) < < " " < < output_index ; <nl> return alias_ . element ( output_index ) ; <nl> } <nl> <nl> mmm a / tensorflow / compiler / xla / service / interpreter / BUILD <nl> ppp b / tensorflow / compiler / xla / service / interpreter / BUILD <nl> cc_library ( <nl> " / / tensorflow / compiler / xla / service : hlo_evaluator " , <nl> " / / tensorflow / compiler / xla / service : hlo_execution_profile " , <nl> " / / tensorflow / compiler / xla / service : hlo_module_config " , <nl> + " / / tensorflow / compiler / xla / service : maybe_owning_device_memory " , <nl> " / / tensorflow / compiler / xla / service : shaped_buffer " , <nl> " / / tensorflow / compiler / xla / service : transfer_manager " , <nl> " / / tensorflow / core : lib " , <nl> " / / tensorflow / core : stream_executor_no_cuda " , <nl> + " / / tensorflow / core / platform : macros " , <nl> + " / / tensorflow / core / platform : mutex " , <nl> + " / / tensorflow / core / platform : types " , <nl> " @ com_google_absl / / absl / memory " , <nl> " @ com_google_absl / / absl / types : span " , <nl> ] , <nl> mmm a / tensorflow / compiler / xla / service / interpreter / executable . cc <nl> ppp b / tensorflow / compiler / xla / service / interpreter / executable . cc <nl> limitations under the License . <nl> # include " tensorflow / compiler / xla / service / hlo_computation . h " <nl> # include " tensorflow / compiler / xla / service / hlo_instruction . h " <nl> # include " tensorflow / compiler / xla / service / interpreter / executor . h " <nl> + # include " tensorflow / compiler / xla / service / maybe_owning_device_memory . h " <nl> # include " tensorflow / compiler / xla / service / transfer_manager . h " <nl> # include " tensorflow / compiler / xla / shape_util . h " <nl> # include " tensorflow / compiler / xla / status_macros . h " <nl> namespace interpreter { <nl> InterpreterExecutable : : InterpreterExecutable ( <nl> std : : unique_ptr < HloModule > hlo_module , <nl> std : : unique_ptr < HloEvaluator > evaluator ) <nl> - : Executable ( std : : move ( hlo_module ) , / * hlo_profile_printer = * / nullptr , <nl> + : Executable ( std : : move ( hlo_module ) , / * hlo_profile_printer_data = * / nullptr , <nl> / * hlo_profile_index_map = * / nullptr ) , <nl> evaluator_ ( std : : move ( evaluator ) ) { } <nl> <nl> InterpreterExecutable : : ~ InterpreterExecutable ( ) { } <nl> <nl> - StatusOr < ScopedShapedBuffer > InterpreterExecutable : : ExecuteAsyncOnStream ( <nl> + StatusOr < ExecutionOutput > InterpreterExecutable : : ExecuteAsyncOnStream ( <nl> const ServiceExecutableRunOptions * run_options , <nl> - absl : : Span < const ShapedBuffer * const > arguments , <nl> + std : : vector < ShapeTree < MaybeOwningDeviceMemory > > arguments , <nl> HloExecutionProfile * hlo_execution_profile ) { <nl> se : : Stream * stream = run_options - > stream ( ) ; <nl> se : : StreamExecutor * executor = stream - > parent ( ) ; <nl> const se : : Platform * platform = executor - > platform ( ) ; <nl> <nl> + / / Convert the ShapeTree to a ShapedBuffer . We do this so we can call <nl> + / / TransferManager methods below . <nl> + std : : vector < ShapedBuffer > argument_buffers ; <nl> + argument_buffers . reserve ( arguments . size ( ) ) ; <nl> + for ( const ShapeTree < MaybeOwningDeviceMemory > & arg : arguments ) { <nl> + argument_buffers . push_back ( ShapedBuffer ( arg . shape ( ) , arg . shape ( ) , <nl> + / * platform = * / nullptr , <nl> + / * device_ordinal = * / 0 ) ) ; <nl> + auto in_it = arg . begin ( ) ; <nl> + auto out_it = argument_buffers . back ( ) . buffers ( ) . begin ( ) ; <nl> + for ( ; in_it ! = arg . end ( ) ; + + in_it , + + out_it ) { <nl> + out_it - > second = in_it - > second . AsDeviceMemoryBase ( ) ; <nl> + } <nl> + } <nl> + <nl> VLOG ( 1 ) < < " Execute " < < module ( ) . name ( ) ; <nl> if ( VLOG_IS_ON ( 2 ) ) { <nl> - for ( const auto & a : arguments ) { <nl> - VLOG ( 2 ) < < " - - argument " < < * a ; <nl> + for ( const auto & a : argument_buffers ) { <nl> + VLOG ( 2 ) < < " - - argument " < < a ; <nl> } <nl> } <nl> <nl> StatusOr < ScopedShapedBuffer > InterpreterExecutable : : ExecuteAsyncOnStream ( <nl> / / Check that the args have the right shape . <nl> for ( int64 i = 0 ; i < computation - > num_parameters ( ) ; + + i ) { <nl> const auto & expected_shape = computation - > parameter_instruction ( i ) - > shape ( ) ; <nl> - const auto & actual_shape = arguments [ i ] - > on_device_shape ( ) ; <nl> + const auto & actual_shape = argument_buffers [ i ] . on_device_shape ( ) ; <nl> if ( ! Shape : : Equal ( ) . MinorToMajorOnlyInLayout ( ) ( expected_shape , <nl> actual_shape ) ) { <nl> return InvalidArgument ( <nl> StatusOr < ScopedShapedBuffer > InterpreterExecutable : : ExecuteAsyncOnStream ( <nl> for ( int64 p = 0 ; p < computation - > num_parameters ( ) ; + + p ) { <nl> TF_ASSIGN_OR_RETURN ( Literal arg_literal , <nl> transfer_manager - > TransferLiteralFromDevice ( <nl> - run_options - > stream ( ) , * arguments [ p ] ) ) ; <nl> + run_options - > stream ( ) , argument_buffers [ p ] ) ) ; <nl> arg_literals . push_back ( std : : move ( arg_literal ) ) ; <nl> } <nl> <nl> StatusOr < ScopedShapedBuffer > InterpreterExecutable : : ExecuteAsyncOnStream ( <nl> profile - > set_compute_time_ns ( std : : max ( nanoseconds , 1 . 0 ) ) ; <nl> } <nl> <nl> - return std : : move ( result ) ; <nl> + std : : vector < se : : OwningDeviceMemory > buffers_to_free ; <nl> + for ( ShapeTree < MaybeOwningDeviceMemory > & argument : arguments ) { <nl> + for ( std : : pair < ShapeIndex , MaybeOwningDeviceMemory > & buffer : argument ) { <nl> + auto maybe_owning_buffer = buffer . second . Release ( ) ; <nl> + if ( maybe_owning_buffer ) { <nl> + buffers_to_free . push_back ( std : : move ( * maybe_owning_buffer ) ) ; <nl> + } <nl> + } <nl> + } <nl> + return ExecutionOutput ( std : : move ( result ) , std : : move ( buffers_to_free ) , { } , { } ) ; <nl> } <nl> <nl> / * static * / int64 InterpreterExecutable : : ShapeSizeBytes ( const Shape & shape ) { <nl> mmm a / tensorflow / compiler / xla / service / interpreter / executable . h <nl> ppp b / tensorflow / compiler / xla / service / interpreter / executable . h <nl> class InterpreterExecutable : public Executable { <nl> std : : unique_ptr < HloEvaluator > evaluator ) ; <nl> ~ InterpreterExecutable ( ) override ; <nl> <nl> - StatusOr < ScopedShapedBuffer > ExecuteAsyncOnStream ( <nl> + StatusOr < ExecutionOutput > ExecuteAsyncOnStream ( <nl> const ServiceExecutableRunOptions * run_options , <nl> - absl : : Span < const ShapedBuffer * const > arguments , <nl> + std : : vector < ShapeTree < MaybeOwningDeviceMemory > > arguments , <nl> HloExecutionProfile * hlo_execution_profile ) override <nl> LOCKS_EXCLUDED ( evaluator_lock_ ) ; <nl> <nl> mmm a / tensorflow / compiler / xla / service / maybe_owning_device_memory . cc <nl> ppp b / tensorflow / compiler / xla / service / maybe_owning_device_memory . cc <nl> limitations under the License . <nl> # include " absl / types / variant . h " <nl> namespace xla { <nl> <nl> - tensorflow : : se : : DeviceMemoryBase MaybeOwningDeviceMemory : : AsDeviceMemoryBase ( ) { <nl> + tensorflow : : se : : DeviceMemoryBase MaybeOwningDeviceMemory : : AsDeviceMemoryBase ( ) <nl> + const { <nl> if ( HasOwnership ( ) ) { <nl> return * absl : : get < tensorflow : : se : : OwningDeviceMemory > ( mem_ ) ; <nl> } else { <nl> mmm a / tensorflow / compiler / xla / service / maybe_owning_device_memory . h <nl> ppp b / tensorflow / compiler / xla / service / maybe_owning_device_memory . h <nl> class MaybeOwningDeviceMemory { <nl> <nl> / / Fetches the underlying DeviceMemoryBase from a MaybeOwningDeviceMemory . The <nl> / / caller of this function is * not * responsible for freeing the memory . <nl> - tensorflow : : se : : DeviceMemoryBase AsDeviceMemoryBase ( ) ; <nl> + tensorflow : : se : : DeviceMemoryBase AsDeviceMemoryBase ( ) const ; <nl> <nl> / / Release the tensorflow : : se : : OwningDeviceMemory without freeing it , and <nl> / / moves the ownership of the memory buffer from the object to the caller . <nl> | [ XLA ] Refactor Executable : : ExecuteAsyncOnStream . | tensorflow/tensorflow | 56221776d3f705fb5f9574d11d0ec604e9a2738c | 2019-12-04T00:58:31Z |
mmm a / Code / Tools / CryCommonTools / ZipDir / ZipDir . h <nl> ppp b / Code / Tools / CryCommonTools / ZipDir / ZipDir . h <nl> <nl> <nl> # include < CryCore / smartptr . h > <nl> # include " ZipFileFormat . h " <nl> - # include " ZipDirStructures . h " <nl> + # include " zipdirstructures . h " <nl> # include < CryCore / smartptr . h > <nl> # include " ZipDirTree . h " <nl> # include " ZipDirList . h " <nl> mmm a / Code / Tools / CryCommonTools / ZipDir / ZipDirCache . cpp <nl> ppp b / Code / Tools / CryCommonTools / ZipDir / ZipDirCache . cpp <nl> <nl> # include " StdAfx . h " <nl> # include < CryCore / smartptr . h > <nl> # include " ZipFileFormat . h " <nl> - # include " ZipDirStructures . h " <nl> + # include " zipdirstructures . h " <nl> # include " ZipDirTree . h " <nl> # include " ZipDirCache . h " <nl> # include " ZipDirFind . h " <nl> mmm a / Code / Tools / CryCommonTools / ZipDir / ZipDirCacheFactory . cpp <nl> ppp b / Code / Tools / CryCommonTools / ZipDir / ZipDirCacheFactory . cpp <nl> <nl> # include < zlib . h > <nl> # include < CryCore / smartptr . h > <nl> # include " ZipFileFormat . h " <nl> - # include " ZipDirStructures . h " <nl> + # include " zipdirstructures . h " <nl> # include " ZipDirTree . h " <nl> # include " ZipDirCache . h " <nl> # include " ZipDirCacheRW . h " <nl> mmm a / Code / Tools / CryCommonTools / ZipDir / ZipDirCacheRW . cpp <nl> ppp b / Code / Tools / CryCommonTools / ZipDir / ZipDirCacheRW . cpp <nl> <nl> # include < CryCore / smartptr . h > <nl> # include " Util . h " <nl> # include " ZipFileFormat . h " <nl> - # include " ZipDirStructures . h " <nl> + # include " zipdirstructures . h " <nl> # include " ZipDirTree . h " <nl> # include " ZipDirList . h " <nl> # include " ZipDirCache . h " <nl> bool ZipDir : : CacheRW : : WriteCDR ( FILE * fTarget , bool encryptCDR ) <nl> / / arrFiles . SortByFileOffset ( ) ; <nl> size_t nSizeCDR = arrFiles . GetStats ( ) . nSizeCDR ; <nl> void * pCDR = malloc ( nSizeCDR ) ; <nl> - size_t nSizeCDRSerialized = arrFiles . MakeZipCDR ( m_lCDROffset , pCDR , encryptCDR ) ; <nl> + size_t nSizeCDRSerialized = arrFiles . MakeZipCDR ( m_lCDROffset , pCDR , encryptCDR ) ; <nl> assert ( nSizeCDRSerialized = = nSizeCDR ) ; <nl> <nl> if ( encryptCDR ) <nl> mmm a / Code / Tools / CryCommonTools / ZipDir / ZipDirFind . cpp <nl> ppp b / Code / Tools / CryCommonTools / ZipDir / ZipDirFind . cpp <nl> <nl> # include " StdAfx . h " <nl> # include < CryCore / smartptr . h > <nl> # include " ZipFileFormat . h " <nl> - # include " ZipDirStructures . h " <nl> + # include " zipdirstructures . h " <nl> # include " ZipDirCache . h " <nl> # include " ZipDirFind . h " <nl> # include " StringHelpers . h " <nl> mmm a / Code / Tools / CryCommonTools / ZipDir / ZipDirFindRW . cpp <nl> ppp b / Code / Tools / CryCommonTools / ZipDir / ZipDirFindRW . cpp <nl> <nl> # include " StdAfx . h " <nl> # include < CryCore / smartptr . h > <nl> # include " ZipFileFormat . h " <nl> - # include " ZipDirStructures . h " <nl> + # include " zipdirstructures . h " <nl> # include " ZipDirTree . h " <nl> # include " ZipDirCacheRW . h " <nl> # include " ZipDirFindRW . h " <nl> mmm a / Code / Tools / CryCommonTools / ZipDir / ZipDirList . cpp <nl> ppp b / Code / Tools / CryCommonTools / ZipDir / ZipDirList . cpp <nl> <nl> # undef max <nl> # include < algorithm > <nl> # include " ZipFileFormat . h " <nl> - # include " ZipDirStructures . h " <nl> + # include " zipdirstructures . h " <nl> # include " ZipDirList . h " <nl> # include " ZipDirTree . h " <nl> <nl> mmm a / Code / Tools / CryCommonTools / ZipDir / ZipDirStructures . cpp <nl> ppp b / Code / Tools / CryCommonTools / ZipDir / ZipDirStructures . cpp <nl> <nl> # include " StdAfx . h " <nl> # include < zlib . h > <nl> # include " ZipFileFormat . h " <nl> - # include " ZipDirStructures . h " <nl> + # include " zipdirstructures . h " <nl> # include < time . h > <nl> # include < CryString / CryStringUtils . h > <nl> <nl> uint64 ZipDir : : FileEntry : : GetModificationTime ( ) <nl> st . wMilliseconds = 0 ; <nl> FILETIME ft ; <nl> SystemTimeToFileTime ( & st , & ft ) ; <nl> + <nl> LARGE_INTEGER lt ; <nl> lt . HighPart = ft . dwHighDateTime ; <nl> lt . LowPart = ft . dwLowDateTime ; <nl> bool ZipDir : : FileEntry : : CompareFileTimeNTFS ( __int64 timestamp ) <nl> ft . dwLowDateTime = timestamp & 0xFFFFFFFF ; <nl> <nl> WORD dosTime , dosDate ; <nl> - FileTimeToDosDateTime ( & ft , & dosDate , & dosTime ) ; <nl> + FileTimeToDosDateTime ( & ft , & dosDate , & dosTime ) ; <nl> <nl> return ( nLastModTime = = dosTime & & nLastModDate = = dosDate ) ; <nl> } <nl> mmm a / Code / Tools / CryCommonTools / ZipDir / ZipDirTree . cpp <nl> ppp b / Code / Tools / CryCommonTools / ZipDir / ZipDirTree . cpp <nl> <nl> <nl> # include " StdAfx . h " <nl> # include " ZipFileFormat . h " <nl> - # include " ZipDirStructures . h " <nl> + # include " zipdirstructures . h " <nl> # include " ZipDirTree . h " <nl> <nl> <nl> | ! T ( Tools ) Fix file casing in CryCommonTools / ZipDir . | CRYTEK/CRYENGINE | 29ae287bd24e60b833396961dac7bb5131dd8216 | 2018-02-16T17:33:51Z |
mmm a / src / btree / secondary_operations . cc <nl> ppp b / src / btree / secondary_operations . cc <nl> struct btree_sindex_block_t { <nl> char sindex_blob [ SINDEX_BLOB_MAXREFLEN ] ; <nl> } __attribute__ ( ( __packed__ ) ) ; <nl> <nl> - / / RSI : Can this be in the . cc file ? <nl> template < cluster_version_t W > <nl> struct btree_sindex_block_magic_t { static const block_magic_t value ; } ; <nl> <nl> | Removed RSI made obsolete . | rethinkdb/rethinkdb | b1d6fcb9f3da10f079f7fcb7621122eba218e99d | 2014-06-23T19:29:08Z |
mmm a / modules / gpu / include / opencv2 / gpu / gpu . hpp <nl> ppp b / modules / gpu / include / opencv2 / gpu / gpu . hpp <nl> namespace cv <nl> / / Checks whether the GPU module can be run on the given device <nl> bool isCompatible ( ) const ; <nl> <nl> + int deviceID ( ) const { return device_id_ ; } <nl> + <nl> private : <nl> void query ( ) ; <nl> void queryMemory ( size_t & free_memory , size_t & total_memory ) const ; <nl> namespace cv <nl> / / ! supports CV_8UC1 , CV_8UC4 , CV_32SC1 , CV_32FC1 types <nl> CV_EXPORTS void multiply ( const GpuMat & a , const GpuMat & b , GpuMat & c , Stream & stream = Stream : : Null ( ) ) ; <nl> / / ! multiplies matrix to a scalar ( c = a * s ) <nl> - / / ! supports CV_32FC1 and CV_32FC2 type <nl> + / / ! supports CV_32FC1 type <nl> CV_EXPORTS void multiply ( const GpuMat & a , const Scalar & sc , GpuMat & c , Stream & stream = Stream : : Null ( ) ) ; <nl> <nl> / / ! computes element - wise quotient of the two arrays ( c = a / b ) <nl> / / ! supports CV_8UC1 , CV_8UC4 , CV_32SC1 , CV_32FC1 types <nl> CV_EXPORTS void divide ( const GpuMat & a , const GpuMat & b , GpuMat & c , Stream & stream = Stream : : Null ( ) ) ; <nl> / / ! computes element - wise quotient of matrix and scalar ( c = a / s ) <nl> - / / ! supports CV_32FC1 and CV_32FC2 type <nl> + / / ! supports CV_32FC1 type <nl> CV_EXPORTS void divide ( const GpuMat & a , const Scalar & sc , GpuMat & c , Stream & stream = Stream : : Null ( ) ) ; <nl> <nl> / / ! computes exponent of each matrix element ( b = e * * a ) <nl> namespace cv <nl> void radiusMatch ( const GpuMat & queryDescs , std : : vector < std : : vector < DMatch > > & matches , float maxDistance , <nl> const std : : vector < GpuMat > & masks = std : : vector < GpuMat > ( ) , bool compactResult = false ) ; <nl> <nl> - private : <nl> DistType distType ; <nl> <nl> + private : <nl> std : : vector < GpuMat > trainDescCollection ; <nl> } ; <nl> <nl> mmm a / modules / gpu / src / calib3d . cpp <nl> ppp b / modules / gpu / src / calib3d . cpp <nl> <nl> - / * M / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / <nl> - / / IMPORTANT : READ BEFORE DOWNLOADING , COPYING , INSTALLING OR USING . <nl> - / / <nl> - / / By downloading , copying , installing or using the software you agree to this license . <nl> - / / If you do not agree to this license , do not download , install , <nl> - / / copy or use the software . <nl> - / / <nl> - / / <nl> - / / License Agreement <nl> - / / For Open Source Computer Vision Library <nl> - / / <nl> - / / Copyright ( C ) 2000 - 2008 , Intel Corporation , all rights reserved . <nl> - / / Copyright ( C ) 2009 , Willow Garage Inc . , all rights reserved . <nl> - / / Third party copyrights are property of their respective owners . <nl> - / / <nl> - / / Redistribution and use in source and binary forms , with or without modification , <nl> - / / are permitted provided that the following conditions are met : <nl> - / / <nl> - / / * Redistribution ' s of source code must retain the above copyright notice , <nl> - / / this list of conditions and the following disclaimer . <nl> - / / <nl> - / / * Redistribution ' s in binary form must reproduce the above copyright notice , <nl> - / / this list of conditions and the following disclaimer in the documentation <nl> - / / and / or other materials provided with the distribution . <nl> - / / <nl> - / / * The name of the copyright holders may not be used to endorse or promote products <nl> - / / derived from this software without specific prior written permission . <nl> - / / <nl> - / / This software is provided by the copyright holders and contributors " as is " and <nl> - / / any express or implied warranties , including , but not limited to , the implied <nl> - / / warranties of merchantability and fitness for a particular purpose are disclaimed . <nl> - / / In no event shall the Intel Corporation or contributors be liable for any direct , <nl> - / / indirect , incidental , special , exemplary , or consequential damages <nl> - / / ( including , but not limited to , procurement of substitute goods or services ; <nl> - / / loss of use , data , or profits ; or business interruption ) however caused <nl> - / / and on any theory of liability , whether in contract , strict liability , <nl> - / / or tort ( including negligence or otherwise ) arising in any way out of <nl> - / / the use of this software , even if advised of the possibility of such damage . <nl> - / / <nl> - / / M * / <nl> - <nl> - # include " precomp . hpp " <nl> - <nl> - # if ! defined ( HAVE_CUDA ) <nl> - <nl> - void cv : : gpu : : transformPoints ( const GpuMat & , const Mat & , const Mat & , GpuMat & , Stream & ) { throw_nogpu ( ) ; } <nl> - <nl> - void cv : : gpu : : projectPoints ( const GpuMat & , const Mat & , const Mat & , const Mat & , const Mat & , GpuMat & , Stream & ) { throw_nogpu ( ) ; } <nl> - <nl> - void cv : : gpu : : solvePnPRansac ( const Mat & , const Mat & , const Mat & , const Mat & , Mat & , Mat & , bool , int , float , int , vector < int > * ) { throw_nogpu ( ) ; } <nl> - <nl> - # else <nl> - <nl> - using namespace cv ; <nl> - using namespace cv : : gpu ; <nl> - <nl> - namespace cv { namespace gpu { namespace transform_points <nl> - { <nl> - void call ( const DevMem2D_ < float3 > src , const float * rot , const float * transl , DevMem2D_ < float3 > dst , cudaStream_t stream ) ; <nl> - } } } <nl> - <nl> - namespace <nl> - { <nl> - void transformPointsCaller ( const GpuMat & src , const Mat & rvec , const Mat & tvec , GpuMat & dst , cudaStream_t stream ) <nl> - { <nl> - CV_Assert ( src . rows = = 1 & & src . cols > 0 & & src . type ( ) = = CV_32FC3 ) ; <nl> - CV_Assert ( rvec . size ( ) = = Size ( 3 , 1 ) & & rvec . type ( ) = = CV_32F ) ; <nl> - CV_Assert ( tvec . size ( ) = = Size ( 3 , 1 ) & & tvec . type ( ) = = CV_32F ) ; <nl> - <nl> - / / Convert rotation vector into matrix <nl> - Mat rot ; <nl> - Rodrigues ( rvec , rot ) ; <nl> - <nl> - dst . create ( src . size ( ) , src . type ( ) ) ; <nl> - transform_points : : call ( src , rot . ptr < float > ( ) , tvec . ptr < float > ( ) , dst , stream ) ; <nl> - } <nl> - } <nl> - <nl> - void cv : : gpu : : transformPoints ( const GpuMat & src , const Mat & rvec , const Mat & tvec , GpuMat & dst , Stream & stream ) <nl> - { <nl> - : : transformPointsCaller ( src , rvec , tvec , dst , StreamAccessor : : getStream ( stream ) ) ; <nl> - } <nl> - <nl> - namespace cv { namespace gpu { namespace project_points <nl> - { <nl> - void call ( const DevMem2D_ < float3 > src , const float * rot , const float * transl , const float * proj , DevMem2D_ < float2 > dst , cudaStream_t stream ) ; <nl> - } } } <nl> - <nl> - <nl> - namespace <nl> - { <nl> - void projectPointsCaller ( const GpuMat & src , const Mat & rvec , const Mat & tvec , const Mat & camera_mat , const Mat & dist_coef , GpuMat & dst , cudaStream_t stream ) <nl> - { <nl> - CV_Assert ( src . rows = = 1 & & src . cols > 0 & & src . type ( ) = = CV_32FC3 ) ; <nl> - CV_Assert ( rvec . size ( ) = = Size ( 3 , 1 ) & & rvec . type ( ) = = CV_32F ) ; <nl> - CV_Assert ( tvec . size ( ) = = Size ( 3 , 1 ) & & tvec . type ( ) = = CV_32F ) ; <nl> - CV_Assert ( camera_mat . size ( ) = = Size ( 3 , 3 ) & & camera_mat . type ( ) = = CV_32F ) ; <nl> - CV_Assert ( dist_coef . empty ( ) ) ; / / Undistortion isn ' t supported <nl> - <nl> - / / Convert rotation vector into matrix <nl> - Mat rot ; <nl> - Rodrigues ( rvec , rot ) ; <nl> - <nl> - dst . create ( src . size ( ) , CV_32FC2 ) ; <nl> - project_points : : call ( src , rot . ptr < float > ( ) , tvec . ptr < float > ( ) , camera_mat . ptr < float > ( ) , dst , stream ) ; <nl> - } <nl> - } <nl> - <nl> - void cv : : gpu : : projectPoints ( const GpuMat & src , const Mat & rvec , const Mat & tvec , const Mat & camera_mat , const Mat & dist_coef , GpuMat & dst , Stream & stream ) <nl> - { <nl> - : : projectPointsCaller ( src , rvec , tvec , camera_mat , dist_coef , dst , StreamAccessor : : getStream ( stream ) ) ; <nl> - } <nl> - <nl> - <nl> - namespace cv { namespace gpu { namespace solve_pnp_ransac <nl> - { <nl> - int maxNumIters ( ) ; <nl> - <nl> - void computeHypothesisScores ( <nl> - const int num_hypotheses , const int num_points , const float * rot_matrices , <nl> - const float3 * transl_vectors , const float3 * object , const float2 * image , <nl> - const float dist_threshold , int * hypothesis_scores ) ; <nl> - } } } <nl> - <nl> - namespace <nl> - { <nl> - / / Selects subset_size random different points from [ 0 , num_points - 1 ] range <nl> - void selectRandom ( int subset_size , int num_points , vector < int > & subset ) <nl> - { <nl> - subset . resize ( subset_size ) ; <nl> - for ( int i = 0 ; i < subset_size ; + + i ) <nl> - { <nl> - bool was ; <nl> - do <nl> - { <nl> - subset [ i ] = rand ( ) % num_points ; <nl> - was = false ; <nl> - for ( int j = 0 ; j < i ; + + j ) <nl> - if ( subset [ j ] = = subset [ i ] ) <nl> - { <nl> - was = true ; <nl> - break ; <nl> - } <nl> - } while ( was ) ; <nl> - } <nl> - } <nl> - <nl> - / / Computes rotation , translation pair for small subsets if the input data <nl> - class TransformHypothesesGenerator <nl> - { <nl> - public : <nl> - TransformHypothesesGenerator ( const Mat & object_ , const Mat & image_ , const Mat & dist_coef_ , <nl> - const Mat & camera_mat_ , int num_points_ , int subset_size_ , <nl> - Mat rot_matrices_ , Mat transl_vectors_ ) <nl> - : object ( & object_ ) , image ( & image_ ) , dist_coef ( & dist_coef_ ) , camera_mat ( & camera_mat_ ) , <nl> - num_points ( num_points_ ) , subset_size ( subset_size_ ) , rot_matrices ( rot_matrices_ ) , <nl> - transl_vectors ( transl_vectors_ ) { } <nl> - <nl> - void operator ( ) ( const BlockedRange & range ) const <nl> - { <nl> - / / Input data for generation of the current hypothesis <nl> - vector < int > subset_indices ( subset_size ) ; <nl> - Mat_ < Point3f > object_subset ( 1 , subset_size ) ; <nl> - Mat_ < Point2f > image_subset ( 1 , subset_size ) ; <nl> - <nl> - / / Current hypothesis data <nl> - Mat rot_vec ( 1 , 3 , CV_64F ) ; <nl> - Mat rot_mat ( 3 , 3 , CV_64F ) ; <nl> - Mat transl_vec ( 1 , 3 , CV_64F ) ; <nl> - <nl> - for ( int iter = range . begin ( ) ; iter < range . end ( ) ; + + iter ) <nl> - { <nl> - selectRandom ( subset_size , num_points , subset_indices ) ; <nl> - for ( int i = 0 ; i < subset_size ; + + i ) <nl> - { <nl> - object_subset ( 0 , i ) = object - > at < Point3f > ( subset_indices [ i ] ) ; <nl> - image_subset ( 0 , i ) = image - > at < Point2f > ( subset_indices [ i ] ) ; <nl> - } <nl> - <nl> - solvePnP ( object_subset , image_subset , * camera_mat , * dist_coef , rot_vec , transl_vec ) ; <nl> - <nl> - / / Remember translation vector <nl> - Mat transl_vec_ = transl_vectors . colRange ( iter * 3 , ( iter + 1 ) * 3 ) ; <nl> - transl_vec = transl_vec . reshape ( 0 , 1 ) ; <nl> - transl_vec . convertTo ( transl_vec_ , CV_32F ) ; <nl> - <nl> - / / Remember rotation matrix <nl> - Rodrigues ( rot_vec , rot_mat ) ; <nl> - Mat rot_mat_ = rot_matrices . colRange ( iter * 9 , ( iter + 1 ) * 9 ) . reshape ( 0 , 3 ) ; <nl> - rot_mat . convertTo ( rot_mat_ , CV_32F ) ; <nl> - } <nl> - } <nl> - <nl> - const Mat * object ; <nl> - const Mat * image ; <nl> - const Mat * dist_coef ; <nl> - const Mat * camera_mat ; <nl> - int num_points ; <nl> - int subset_size ; <nl> - <nl> - / / Hypotheses storage ( global ) <nl> - Mat rot_matrices ; <nl> - Mat transl_vectors ; <nl> - } ; <nl> - } <nl> - <nl> + / * M / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / <nl> + / / IMPORTANT : READ BEFORE DOWNLOADING , COPYING , INSTALLING OR USING . <nl> + / / <nl> + / / By downloading , copying , installing or using the software you agree to this license . <nl> + / / If you do not agree to this license , do not download , install , <nl> + / / copy or use the software . <nl> + / / <nl> + / / <nl> + / / License Agreement <nl> + / / For Open Source Computer Vision Library <nl> + / / <nl> + / / Copyright ( C ) 2000 - 2008 , Intel Corporation , all rights reserved . <nl> + / / Copyright ( C ) 2009 , Willow Garage Inc . , all rights reserved . <nl> + / / Third party copyrights are property of their respective owners . <nl> + / / <nl> + / / Redistribution and use in source and binary forms , with or without modification , <nl> + / / are permitted provided that the following conditions are met : <nl> + / / <nl> + / / * Redistribution ' s of source code must retain the above copyright notice , <nl> + / / this list of conditions and the following disclaimer . <nl> + / / <nl> + / / * Redistribution ' s in binary form must reproduce the above copyright notice , <nl> + / / this list of conditions and the following disclaimer in the documentation <nl> + / / and / or other materials provided with the distribution . <nl> + / / <nl> + / / * The name of the copyright holders may not be used to endorse or promote products <nl> + / / derived from this software without specific prior written permission . <nl> + / / <nl> + / / This software is provided by the copyright holders and contributors " as is " and <nl> + / / any express or implied warranties , including , but not limited to , the implied <nl> + / / warranties of merchantability and fitness for a particular purpose are disclaimed . <nl> + / / In no event shall the Intel Corporation or contributors be liable for any direct , <nl> + / / indirect , incidental , special , exemplary , or consequential damages <nl> + / / ( including , but not limited to , procurement of substitute goods or services ; <nl> + / / loss of use , data , or profits ; or business interruption ) however caused <nl> + / / and on any theory of liability , whether in contract , strict liability , <nl> + / / or tort ( including negligence or otherwise ) arising in any way out of <nl> + / / the use of this software , even if advised of the possibility of such damage . <nl> + / / <nl> + / / M * / <nl> + <nl> + # include " precomp . hpp " <nl> + <nl> + # if ! defined ( HAVE_CUDA ) <nl> + <nl> + void cv : : gpu : : transformPoints ( const GpuMat & , const Mat & , const Mat & , GpuMat & , Stream & ) { throw_nogpu ( ) ; } <nl> + <nl> + void cv : : gpu : : projectPoints ( const GpuMat & , const Mat & , const Mat & , const Mat & , const Mat & , GpuMat & , Stream & ) { throw_nogpu ( ) ; } <nl> + <nl> + void cv : : gpu : : solvePnPRansac ( const Mat & , const Mat & , const Mat & , const Mat & , Mat & , Mat & , bool , int , float , int , vector < int > * ) { throw_nogpu ( ) ; } <nl> + <nl> + # else <nl> + <nl> + using namespace cv ; <nl> + using namespace cv : : gpu ; <nl> + <nl> + namespace cv { namespace gpu { namespace transform_points <nl> + { <nl> + void call ( const DevMem2D_ < float3 > src , const float * rot , const float * transl , DevMem2D_ < float3 > dst , cudaStream_t stream ) ; <nl> + } } } <nl> + <nl> + namespace <nl> + { <nl> + void transformPointsCaller ( const GpuMat & src , const Mat & rvec , const Mat & tvec , GpuMat & dst , cudaStream_t stream ) <nl> + { <nl> + CV_Assert ( src . rows = = 1 & & src . cols > 0 & & src . type ( ) = = CV_32FC3 ) ; <nl> + CV_Assert ( rvec . size ( ) = = Size ( 3 , 1 ) & & rvec . type ( ) = = CV_32F ) ; <nl> + CV_Assert ( tvec . size ( ) = = Size ( 3 , 1 ) & & tvec . type ( ) = = CV_32F ) ; <nl> + <nl> + / / Convert rotation vector into matrix <nl> + Mat rot ; <nl> + Rodrigues ( rvec , rot ) ; <nl> + <nl> + dst . create ( src . size ( ) , src . type ( ) ) ; <nl> + transform_points : : call ( src , rot . ptr < float > ( ) , tvec . ptr < float > ( ) , dst , stream ) ; <nl> + } <nl> + } <nl> + <nl> + void cv : : gpu : : transformPoints ( const GpuMat & src , const Mat & rvec , const Mat & tvec , GpuMat & dst , Stream & stream ) <nl> + { <nl> + : : transformPointsCaller ( src , rvec , tvec , dst , StreamAccessor : : getStream ( stream ) ) ; <nl> + } <nl> + <nl> + namespace cv { namespace gpu { namespace project_points <nl> + { <nl> + void call ( const DevMem2D_ < float3 > src , const float * rot , const float * transl , const float * proj , DevMem2D_ < float2 > dst , cudaStream_t stream ) ; <nl> + } } } <nl> + <nl> + <nl> + namespace <nl> + { <nl> + void projectPointsCaller ( const GpuMat & src , const Mat & rvec , const Mat & tvec , const Mat & camera_mat , const Mat & dist_coef , GpuMat & dst , cudaStream_t stream ) <nl> + { <nl> + CV_Assert ( src . rows = = 1 & & src . cols > 0 & & src . type ( ) = = CV_32FC3 ) ; <nl> + CV_Assert ( rvec . size ( ) = = Size ( 3 , 1 ) & & rvec . type ( ) = = CV_32F ) ; <nl> + CV_Assert ( tvec . size ( ) = = Size ( 3 , 1 ) & & tvec . type ( ) = = CV_32F ) ; <nl> + CV_Assert ( camera_mat . size ( ) = = Size ( 3 , 3 ) & & camera_mat . type ( ) = = CV_32F ) ; <nl> + CV_Assert ( dist_coef . empty ( ) ) ; / / Undistortion isn ' t supported <nl> + <nl> + / / Convert rotation vector into matrix <nl> + Mat rot ; <nl> + Rodrigues ( rvec , rot ) ; <nl> + <nl> + dst . create ( src . size ( ) , CV_32FC2 ) ; <nl> + project_points : : call ( src , rot . ptr < float > ( ) , tvec . ptr < float > ( ) , camera_mat . ptr < float > ( ) , dst , stream ) ; <nl> + } <nl> + } <nl> + <nl> + void cv : : gpu : : projectPoints ( const GpuMat & src , const Mat & rvec , const Mat & tvec , const Mat & camera_mat , const Mat & dist_coef , GpuMat & dst , Stream & stream ) <nl> + { <nl> + : : projectPointsCaller ( src , rvec , tvec , camera_mat , dist_coef , dst , StreamAccessor : : getStream ( stream ) ) ; <nl> + } <nl> + <nl> + <nl> + namespace cv { namespace gpu { namespace solve_pnp_ransac <nl> + { <nl> + int maxNumIters ( ) ; <nl> + <nl> + void computeHypothesisScores ( <nl> + const int num_hypotheses , const int num_points , const float * rot_matrices , <nl> + const float3 * transl_vectors , const float3 * object , const float2 * image , <nl> + const float dist_threshold , int * hypothesis_scores ) ; <nl> + } } } <nl> + <nl> + namespace <nl> + { <nl> + / / Selects subset_size random different points from [ 0 , num_points - 1 ] range <nl> + void selectRandom ( int subset_size , int num_points , vector < int > & subset ) <nl> + { <nl> + subset . resize ( subset_size ) ; <nl> + for ( int i = 0 ; i < subset_size ; + + i ) <nl> + { <nl> + bool was ; <nl> + do <nl> + { <nl> + subset [ i ] = rand ( ) % num_points ; <nl> + was = false ; <nl> + for ( int j = 0 ; j < i ; + + j ) <nl> + if ( subset [ j ] = = subset [ i ] ) <nl> + { <nl> + was = true ; <nl> + break ; <nl> + } <nl> + } while ( was ) ; <nl> + } <nl> + } <nl> + <nl> + / / Computes rotation , translation pair for small subsets if the input data <nl> + class TransformHypothesesGenerator <nl> + { <nl> + public : <nl> + TransformHypothesesGenerator ( const Mat & object_ , const Mat & image_ , const Mat & dist_coef_ , <nl> + const Mat & camera_mat_ , int num_points_ , int subset_size_ , <nl> + Mat rot_matrices_ , Mat transl_vectors_ ) <nl> + : object ( & object_ ) , image ( & image_ ) , dist_coef ( & dist_coef_ ) , camera_mat ( & camera_mat_ ) , <nl> + num_points ( num_points_ ) , subset_size ( subset_size_ ) , rot_matrices ( rot_matrices_ ) , <nl> + transl_vectors ( transl_vectors_ ) { } <nl> + <nl> + void operator ( ) ( const BlockedRange & range ) const <nl> + { <nl> + / / Input data for generation of the current hypothesis <nl> + vector < int > subset_indices ( subset_size ) ; <nl> + Mat_ < Point3f > object_subset ( 1 , subset_size ) ; <nl> + Mat_ < Point2f > image_subset ( 1 , subset_size ) ; <nl> + <nl> + / / Current hypothesis data <nl> + Mat rot_vec ( 1 , 3 , CV_64F ) ; <nl> + Mat rot_mat ( 3 , 3 , CV_64F ) ; <nl> + Mat transl_vec ( 1 , 3 , CV_64F ) ; <nl> + <nl> + for ( int iter = range . begin ( ) ; iter < range . end ( ) ; + + iter ) <nl> + { <nl> + selectRandom ( subset_size , num_points , subset_indices ) ; <nl> + for ( int i = 0 ; i < subset_size ; + + i ) <nl> + { <nl> + object_subset ( 0 , i ) = object - > at < Point3f > ( subset_indices [ i ] ) ; <nl> + image_subset ( 0 , i ) = image - > at < Point2f > ( subset_indices [ i ] ) ; <nl> + } <nl> + <nl> + solvePnP ( object_subset , image_subset , * camera_mat , * dist_coef , rot_vec , transl_vec ) ; <nl> + <nl> + / / Remember translation vector <nl> + Mat transl_vec_ = transl_vectors . colRange ( iter * 3 , ( iter + 1 ) * 3 ) ; <nl> + transl_vec = transl_vec . reshape ( 0 , 1 ) ; <nl> + transl_vec . convertTo ( transl_vec_ , CV_32F ) ; <nl> + <nl> + / / Remember rotation matrix <nl> + Rodrigues ( rot_vec , rot_mat ) ; <nl> + Mat rot_mat_ = rot_matrices . colRange ( iter * 9 , ( iter + 1 ) * 9 ) . reshape ( 0 , 3 ) ; <nl> + rot_mat . convertTo ( rot_mat_ , CV_32F ) ; <nl> + } <nl> + } <nl> + <nl> + const Mat * object ; <nl> + const Mat * image ; <nl> + const Mat * dist_coef ; <nl> + const Mat * camera_mat ; <nl> + int num_points ; <nl> + int subset_size ; <nl> + <nl> + / / Hypotheses storage ( global ) <nl> + Mat rot_matrices ; <nl> + Mat transl_vectors ; <nl> + } ; <nl> + } <nl> + <nl> void cv : : gpu : : solvePnPRansac ( const Mat & object , const Mat & image , const Mat & camera_mat , <nl> const Mat & dist_coef , Mat & rvec , Mat & tvec , bool use_extrinsic_guess , <nl> int num_iters , float max_dist , int min_inlier_count , <nl> - vector < int > * inliers ) <nl> - { <nl> - CV_Assert ( object . rows = = 1 & & object . cols > 0 & & object . type ( ) = = CV_32FC3 ) ; <nl> - CV_Assert ( image . rows = = 1 & & image . cols > 0 & & image . type ( ) = = CV_32FC2 ) ; <nl> - CV_Assert ( object . cols = = image . cols ) ; <nl> - CV_Assert ( camera_mat . size ( ) = = Size ( 3 , 3 ) & & camera_mat . type ( ) = = CV_32F ) ; <nl> - CV_Assert ( ! use_extrinsic_guess ) ; / / We don ' t support initial guess for now <nl> - CV_Assert ( num_iters < = solve_pnp_ransac : : maxNumIters ( ) ) ; <nl> - <nl> - const int subset_size = 4 ; <nl> - const int num_points = object . cols ; <nl> - CV_Assert ( num_points > = subset_size ) ; <nl> - <nl> - / / Unapply distortion and intrinsic camera transformations <nl> - Mat eye_camera_mat = Mat : : eye ( 3 , 3 , CV_32F ) ; <nl> - Mat empty_dist_coef ; <nl> - Mat image_normalized ; <nl> - undistortPoints ( image , image_normalized , camera_mat , dist_coef , Mat ( ) , eye_camera_mat ) ; <nl> - <nl> - / / Hypotheses storage ( global ) <nl> - Mat rot_matrices ( 1 , num_iters * 9 , CV_32F ) ; <nl> - Mat transl_vectors ( 1 , num_iters * 3 , CV_32F ) ; <nl> - <nl> - / / Generate set of hypotheses using small subsets of the input data <nl> - TransformHypothesesGenerator body ( object , image_normalized , empty_dist_coef , eye_camera_mat , <nl> - num_points , subset_size , rot_matrices , transl_vectors ) ; <nl> - parallel_for ( BlockedRange ( 0 , num_iters ) , body ) ; <nl> - <nl> - / / Compute scores ( i . e . number of inliers ) for each hypothesis <nl> - GpuMat d_object ( object ) ; <nl> - GpuMat d_image_normalized ( image_normalized ) ; <nl> - GpuMat d_hypothesis_scores ( 1 , num_iters , CV_32S ) ; <nl> - solve_pnp_ransac : : computeHypothesisScores ( <nl> - num_iters , num_points , rot_matrices . ptr < float > ( ) , transl_vectors . ptr < float3 > ( ) , <nl> - d_object . ptr < float3 > ( ) , d_image_normalized . ptr < float2 > ( ) , max_dist * max_dist , <nl> - d_hypothesis_scores . ptr < int > ( ) ) ; <nl> - <nl> - / / Find the best hypothesis index <nl> - Point best_idx ; <nl> - double best_score ; <nl> - minMaxLoc ( d_hypothesis_scores , NULL , & best_score , NULL , & best_idx ) ; <nl> - int num_inliers = static_cast < int > ( best_score ) ; <nl> - <nl> - / / Extract the best hypothesis data <nl> - <nl> - Mat rot_mat = rot_matrices . colRange ( best_idx . x * 9 , ( best_idx . x + 1 ) * 9 ) . reshape ( 0 , 3 ) ; <nl> - Rodrigues ( rot_mat , rvec ) ; <nl> - rvec = rvec . reshape ( 0 , 1 ) ; <nl> - <nl> - tvec = transl_vectors . colRange ( best_idx . x * 3 , ( best_idx . x + 1 ) * 3 ) . clone ( ) ; <nl> - tvec = tvec . reshape ( 0 , 1 ) ; <nl> - <nl> - / / Build vector of inlier indices <nl> - if ( inliers ! = NULL ) <nl> - { <nl> - inliers - > clear ( ) ; <nl> - inliers - > reserve ( num_inliers ) ; <nl> - <nl> - Point3f p , p_transf ; <nl> - Point2f p_proj ; <nl> - const float * rot = rot_mat . ptr < float > ( ) ; <nl> - const float * transl = tvec . ptr < float > ( ) ; <nl> - <nl> - for ( int i = 0 ; i < num_points ; + + i ) <nl> - { <nl> - p = object . at < Point3f > ( 0 , i ) ; <nl> - p_transf . x = rot [ 0 ] * p . x + rot [ 1 ] * p . y + rot [ 2 ] * p . z + transl [ 0 ] ; <nl> - p_transf . y = rot [ 3 ] * p . x + rot [ 4 ] * p . y + rot [ 5 ] * p . z + transl [ 1 ] ; <nl> - p_transf . z = rot [ 6 ] * p . x + rot [ 7 ] * p . y + rot [ 8 ] * p . z + transl [ 2 ] ; <nl> - p_proj . x = p_transf . x / p_transf . z ; <nl> - p_proj . y = p_transf . y / p_transf . z ; <nl> - if ( norm ( p_proj - image_normalized . at < Point2f > ( 0 , i ) ) < max_dist ) <nl> - inliers - > push_back ( i ) ; <nl> - } <nl> - } <nl> - } <nl> - <nl> - # endif <nl> - <nl> - <nl> + vector < int > * inliers ) <nl> + { <nl> + CV_Assert ( object . rows = = 1 & & object . cols > 0 & & object . type ( ) = = CV_32FC3 ) ; <nl> + CV_Assert ( image . rows = = 1 & & image . cols > 0 & & image . type ( ) = = CV_32FC2 ) ; <nl> + CV_Assert ( object . cols = = image . cols ) ; <nl> + CV_Assert ( camera_mat . size ( ) = = Size ( 3 , 3 ) & & camera_mat . type ( ) = = CV_32F ) ; <nl> + CV_Assert ( ! use_extrinsic_guess ) ; / / We don ' t support initial guess for now <nl> + CV_Assert ( num_iters < = solve_pnp_ransac : : maxNumIters ( ) ) ; <nl> + <nl> + const int subset_size = 4 ; <nl> + const int num_points = object . cols ; <nl> + CV_Assert ( num_points > = subset_size ) ; <nl> + <nl> + / / Unapply distortion and intrinsic camera transformations <nl> + Mat eye_camera_mat = Mat : : eye ( 3 , 3 , CV_32F ) ; <nl> + Mat empty_dist_coef ; <nl> + Mat image_normalized ; <nl> + undistortPoints ( image , image_normalized , camera_mat , dist_coef , Mat ( ) , eye_camera_mat ) ; <nl> + <nl> + / / Hypotheses storage ( global ) <nl> + Mat rot_matrices ( 1 , num_iters * 9 , CV_32F ) ; <nl> + Mat transl_vectors ( 1 , num_iters * 3 , CV_32F ) ; <nl> + <nl> + / / Generate set of hypotheses using small subsets of the input data <nl> + TransformHypothesesGenerator body ( object , image_normalized , empty_dist_coef , eye_camera_mat , <nl> + num_points , subset_size , rot_matrices , transl_vectors ) ; <nl> + parallel_for ( BlockedRange ( 0 , num_iters ) , body ) ; <nl> + <nl> + / / Compute scores ( i . e . number of inliers ) for each hypothesis <nl> + GpuMat d_object ( object ) ; <nl> + GpuMat d_image_normalized ( image_normalized ) ; <nl> + GpuMat d_hypothesis_scores ( 1 , num_iters , CV_32S ) ; <nl> + solve_pnp_ransac : : computeHypothesisScores ( <nl> + num_iters , num_points , rot_matrices . ptr < float > ( ) , transl_vectors . ptr < float3 > ( ) , <nl> + d_object . ptr < float3 > ( ) , d_image_normalized . ptr < float2 > ( ) , max_dist * max_dist , <nl> + d_hypothesis_scores . ptr < int > ( ) ) ; <nl> + <nl> + / / Find the best hypothesis index <nl> + Point best_idx ; <nl> + double best_score ; <nl> + minMaxLoc ( d_hypothesis_scores , NULL , & best_score , NULL , & best_idx ) ; <nl> + int num_inliers = static_cast < int > ( best_score ) ; <nl> + <nl> + / / Extract the best hypothesis data <nl> + <nl> + Mat rot_mat = rot_matrices . colRange ( best_idx . x * 9 , ( best_idx . x + 1 ) * 9 ) . reshape ( 0 , 3 ) ; <nl> + Rodrigues ( rot_mat , rvec ) ; <nl> + rvec = rvec . reshape ( 0 , 1 ) ; <nl> + <nl> + tvec = transl_vectors . colRange ( best_idx . x * 3 , ( best_idx . x + 1 ) * 3 ) . clone ( ) ; <nl> + tvec = tvec . reshape ( 0 , 1 ) ; <nl> + <nl> + / / Build vector of inlier indices <nl> + if ( inliers ! = NULL ) <nl> + { <nl> + inliers - > clear ( ) ; <nl> + inliers - > reserve ( num_inliers ) ; <nl> + <nl> + Point3f p , p_transf ; <nl> + Point2f p_proj ; <nl> + const float * rot = rot_mat . ptr < float > ( ) ; <nl> + const float * transl = tvec . ptr < float > ( ) ; <nl> + <nl> + for ( int i = 0 ; i < num_points ; + + i ) <nl> + { <nl> + p = object . at < Point3f > ( 0 , i ) ; <nl> + p_transf . x = rot [ 0 ] * p . x + rot [ 1 ] * p . y + rot [ 2 ] * p . z + transl [ 0 ] ; <nl> + p_transf . y = rot [ 3 ] * p . x + rot [ 4 ] * p . y + rot [ 5 ] * p . z + transl [ 1 ] ; <nl> + p_transf . z = rot [ 6 ] * p . x + rot [ 7 ] * p . y + rot [ 8 ] * p . z + transl [ 2 ] ; <nl> + p_proj . x = p_transf . x / p_transf . z ; <nl> + p_proj . y = p_transf . y / p_transf . z ; <nl> + if ( norm ( p_proj - image_normalized . at < Point2f > ( 0 , i ) ) < max_dist ) <nl> + inliers - > push_back ( i ) ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + # endif <nl> + <nl> + <nl> mmm a / modules / gpu / src / cuda / brute_force_matcher . cu <nl> ppp b / modules / gpu / src / cuda / brute_force_matcher . cu <nl> namespace cv { namespace gpu { namespace bfmatcher <nl> matchCached_caller < 16 , 16 , 64 , true , Dist > ( queryDescs , train , mask , trainIdx , imgIdx , distance , stream ) ; <nl> else if ( queryDescs . cols < 128 ) <nl> matchCached_caller < 16 , 16 , 128 , false , Dist > ( queryDescs , train , mask , trainIdx , imgIdx , distance , stream ) ; <nl> - else if ( queryDescs . cols = = 128 ) <nl> + else if ( queryDescs . cols = = 128 & & cc_12 ) <nl> matchCached_caller < 16 , 16 , 128 , true , Dist > ( queryDescs , train , mask , trainIdx , imgIdx , distance , stream ) ; <nl> - else if ( queryDescs . cols < 256 ) <nl> + else if ( queryDescs . cols < 256 & & cc_12 ) <nl> matchCached_caller < 16 , 16 , 256 , false , Dist > ( queryDescs , train , mask , trainIdx , imgIdx , distance , stream ) ; <nl> else if ( queryDescs . cols = = 256 & & cc_12 ) <nl> matchCached_caller < 16 , 16 , 256 , true , Dist > ( queryDescs , train , mask , trainIdx , imgIdx , distance , stream ) ; <nl> mmm a / modules / gpu / src / cuda / mathfunc . cu <nl> ppp b / modules / gpu / src / cuda / mathfunc . cu <nl> namespace cv { namespace gpu { namespace mathfunc <nl> { <nl> static __device__ __forceinline__ void calc ( int x , int y , float x_data , float y_data , float * dst , size_t dst_step , float scale ) <nl> { <nl> - dst [ y * dst_step + x ] = scale * atan2f ( y_data , x_data ) ; <nl> + float angle = atan2f ( y_data , x_data ) ; <nl> + angle + = ( angle < 0 ) * 2 . 0 * CV_PI ; <nl> + dst [ y * dst_step + x ] = scale * angle ; <nl> } <nl> } ; <nl> template < typename Mag , typename Angle > <nl> mmm a / modules / gpu / src / element_operations . cpp <nl> ppp b / modules / gpu / src / element_operations . cpp <nl> void cv : : gpu : : subtract ( const GpuMat & src , const Scalar & sc , GpuMat & dst , Stream & <nl> <nl> void cv : : gpu : : multiply ( const GpuMat & src , const Scalar & sc , GpuMat & dst , Stream & stream ) <nl> { <nl> - typedef void ( * caller_t ) ( const GpuMat & src , const Scalar & sc , GpuMat & dst , cudaStream_t stream ) ; <nl> - static const caller_t callers [ ] = { 0 , NppArithmScalar < 1 , nppiMulC_32f_C1R > : : calc , NppArithmScalar < 2 , nppiMulC_32fc_C1R > : : calc } ; <nl> + CV_Assert ( src . type ( ) = = CV_32FC1 ) ; <nl> <nl> - CV_Assert ( src . type ( ) = = CV_32FC1 | | src . type ( ) = = CV_32FC2 ) ; <nl> + dst . create ( src . size ( ) , src . type ( ) ) ; <nl> <nl> - callers [ src . channels ( ) ] ( src , sc , dst , StreamAccessor : : getStream ( stream ) ) ; <nl> + NppiSize sz ; <nl> + sz . width = src . cols ; <nl> + sz . height = src . rows ; <nl> + <nl> + cudaStream_t cudaStream = StreamAccessor : : getStream ( stream ) ; <nl> + <nl> + NppStreamHandler h ( cudaStream ) ; <nl> + <nl> + nppSafeCall ( nppiMulC_32f_C1R ( src . ptr < Npp32f > ( ) , src . step , ( Npp32f ) sc [ 0 ] , dst . ptr < Npp32f > ( ) , dst . step , sz ) ) ; <nl> + <nl> + if ( cudaStream = = 0 ) <nl> + cudaSafeCall ( cudaDeviceSynchronize ( ) ) ; <nl> } <nl> <nl> void cv : : gpu : : divide ( const GpuMat & src , const Scalar & sc , GpuMat & dst , Stream & stream ) <nl> { <nl> - typedef void ( * caller_t ) ( const GpuMat & src , const Scalar & sc , GpuMat & dst , cudaStream_t stream ) ; <nl> - static const caller_t callers [ ] = { 0 , NppArithmScalar < 1 , nppiDivC_32f_C1R > : : calc , NppArithmScalar < 2 , nppiDivC_32fc_C1R > : : calc } ; <nl> + CV_Assert ( src . type ( ) = = CV_32FC1 ) ; <nl> <nl> - CV_Assert ( src . type ( ) = = CV_32FC1 | | src . type ( ) = = CV_32FC2 ) ; <nl> + dst . create ( src . size ( ) , src . type ( ) ) ; <nl> <nl> - callers [ src . channels ( ) ] ( src , sc , dst , StreamAccessor : : getStream ( stream ) ) ; <nl> + NppiSize sz ; <nl> + sz . width = src . cols ; <nl> + sz . height = src . rows ; <nl> + <nl> + cudaStream_t cudaStream = StreamAccessor : : getStream ( stream ) ; <nl> + <nl> + NppStreamHandler h ( cudaStream ) ; <nl> + <nl> + nppSafeCall ( nppiDivC_32f_C1R ( src . ptr < Npp32f > ( ) , src . step , ( Npp32f ) sc [ 0 ] , dst . ptr < Npp32f > ( ) , dst . step , sz ) ) ; <nl> + <nl> + if ( cudaStream = = 0 ) <nl> + cudaSafeCall ( cudaDeviceSynchronize ( ) ) ; <nl> } <nl> <nl> <nl> mmm a / modules / gpu / test / nvidia / NCVAutoTestLister . hpp <nl> ppp b / modules / gpu / test / nvidia / NCVAutoTestLister . hpp <nl> <nl> <nl> # include " NCVTest . hpp " <nl> <nl> + enum OutputLevel <nl> + { <nl> + OutputLevelNone , <nl> + OutputLevelCompact , <nl> + OutputLevelFull <nl> + } ; <nl> + <nl> class NCVAutoTestLister <nl> { <nl> public : <nl> <nl> - NCVAutoTestLister ( std : : string testSuiteName , NcvBool bStopOnFirstFail = false , NcvBool bCompactOutput = true ) <nl> + NCVAutoTestLister ( std : : string testSuiteName , OutputLevel outputLevel = OutputLevelCompact , NcvBool bStopOnFirstFail = false ) <nl> : <nl> testSuiteName ( testSuiteName ) , <nl> - bStopOnFirstFail ( bStopOnFirstFail ) , <nl> - bCompactOutput ( bCompactOutput ) <nl> + outputLevel ( outputLevel ) , <nl> + bStopOnFirstFail ( bStopOnFirstFail ) <nl> { <nl> } <nl> <nl> class NCVAutoTestLister <nl> Ncv32u nFailed = 0 ; <nl> Ncv32u nFailedMem = 0 ; <nl> <nl> - if ( bCompactOutput ) <nl> + if ( outputLevel = = OutputLevelCompact ) <nl> { <nl> printf ( " Test suite ' % s ' with % d tests \ n " , <nl> testSuiteName . c_str ( ) , <nl> class NCVAutoTestLister <nl> NCVTestReport curReport ; <nl> bool res = curTest . executeTest ( curReport ) ; <nl> <nl> - if ( ! bCompactOutput ) <nl> + if ( outputLevel = = OutputLevelFull ) <nl> { <nl> printf ( " Test % 3i % 16s ; Consumed mem GPU = % 8d , CPU = % 8d ; % s \ n " , <nl> i , <nl> class NCVAutoTestLister <nl> if ( res ) <nl> { <nl> nPassed + + ; <nl> - if ( bCompactOutput ) <nl> + if ( outputLevel = = OutputLevelCompact ) <nl> { <nl> printf ( " . " ) ; <nl> } <nl> class NCVAutoTestLister <nl> if ( ! curReport . statsText [ " rcode " ] . compare ( " FAILED " ) ) <nl> { <nl> nFailed + + ; <nl> - if ( bCompactOutput ) <nl> + if ( outputLevel = = OutputLevelCompact ) <nl> { <nl> printf ( " x " ) ; <nl> } <nl> class NCVAutoTestLister <nl> else <nl> { <nl> nFailedMem + + ; <nl> - if ( bCompactOutput ) <nl> + if ( outputLevel = = OutputLevelCompact ) <nl> { <nl> printf ( " m " ) ; <nl> } <nl> class NCVAutoTestLister <nl> } <nl> fflush ( stdout ) ; <nl> } <nl> - if ( bCompactOutput ) <nl> + if ( outputLevel = = OutputLevelCompact ) <nl> { <nl> printf ( " \ n " ) ; <nl> } <nl> <nl> - printf ( " Test suite ' % s ' complete : % d total , % d passed , % d memory errors , % d failed \ n \ n " , <nl> - testSuiteName . c_str ( ) , <nl> - ( int ) ( this - > tests . size ( ) ) , <nl> - nPassed , <nl> - nFailedMem , <nl> - nFailed ) ; <nl> + if ( outputLevel ! = OutputLevelNone ) <nl> + { <nl> + printf ( " Test suite ' % s ' complete : % d total , % d passed , % d memory errors , % d failed \ n \ n " , <nl> + testSuiteName . c_str ( ) , <nl> + ( int ) ( this - > tests . size ( ) ) , <nl> + nPassed , <nl> + nFailedMem , <nl> + nFailed ) ; <nl> + } <nl> <nl> bool passed = nFailed = = 0 & & nFailedMem = = 0 ; <nl> return passed ; <nl> class NCVAutoTestLister <nl> <nl> private : <nl> <nl> - NcvBool bStopOnFirstFail ; <nl> - NcvBool bCompactOutput ; <nl> std : : string testSuiteName ; <nl> + OutputLevel outputLevel ; <nl> + NcvBool bStopOnFirstFail ; <nl> std : : vector < INCVTest * > tests ; <nl> } ; <nl> <nl> mmm a / modules / gpu / test / nvidia / main_nvidia . cpp <nl> ppp b / modules / gpu / test / nvidia / main_nvidia . cpp <nl> static void devNullOutput ( const char * msg ) <nl> <nl> } <nl> <nl> + bool nvidia_NPPST_Integral_Image ( const std : : string & test_data_path , OutputLevel outputLevel ) <nl> + { <nl> + path = test_data_path ; <nl> + ncvSetDebugOutputHandler ( devNullOutput ) ; <nl> <nl> - bool main_nvidia ( const std : : string & test_data_path ) <nl> + NCVAutoTestLister testListerII ( " NPPST Integral Image " , outputLevel ) ; <nl> + <nl> + NCVTestSourceProvider < Ncv8u > testSrcRandom_8u ( 2010 , 0 , 255 , 4096 , 4096 ) ; <nl> + NCVTestSourceProvider < Ncv32f > testSrcRandom_32f ( 2010 , - 1 . 0f , 1 . 0f , 4096 , 4096 ) ; <nl> + <nl> + generateIntegralTests < Ncv8u , Ncv32u > ( testListerII , testSrcRandom_8u , 4096 , 4096 ) ; <nl> + generateIntegralTests < Ncv32f , Ncv32f > ( testListerII , testSrcRandom_32f , 4096 , 4096 ) ; <nl> + <nl> + return testListerII . invoke ( ) ; <nl> + } <nl> + <nl> + bool nvidia_NPPST_Squared_Integral_Image ( const std : : string & test_data_path , OutputLevel outputLevel ) <nl> { <nl> path = test_data_path ; <nl> + ncvSetDebugOutputHandler ( devNullOutput ) ; <nl> <nl> - printf ( " Testing NVIDIA Computer Vision SDK \ n " ) ; <nl> - printf ( " = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = \ n " ) ; <nl> + NCVAutoTestLister testListerSII ( " NPPST Squared Integral Image " , outputLevel ) ; <nl> <nl> + NCVTestSourceProvider < Ncv8u > testSrcRandom_8u ( 2010 , 0 , 255 , 4096 , 4096 ) ; <nl> + <nl> + generateSquaredIntegralTests ( testListerSII , testSrcRandom_8u , 4096 , 4096 ) ; <nl> + <nl> + return testListerSII . invoke ( ) ; <nl> + } <nl> + <nl> + bool nvidia_NPPST_RectStdDev ( const std : : string & test_data_path , OutputLevel outputLevel ) <nl> + { <nl> + path = test_data_path ; <nl> ncvSetDebugOutputHandler ( devNullOutput ) ; <nl> + <nl> + NCVAutoTestLister testListerRStdDev ( " NPPST RectStdDev " , outputLevel ) ; <nl> + <nl> + NCVTestSourceProvider < Ncv8u > testSrcRandom_8u ( 2010 , 0 , 255 , 4096 , 4096 ) ; <nl> <nl> - NCVAutoTestLister testListerII ( " NPPST Integral Image " ) ; / / , , true , false ) ; <nl> - NCVAutoTestLister testListerSII ( " NPPST Squared Integral Image " ) ; / / , , true , false ) ; <nl> - NCVAutoTestLister testListerRStdDev ( " NPPST RectStdDev " ) ; / / , , true , false ) ; <nl> - NCVAutoTestLister testListerResize ( " NPPST Resize " ) ; / / , , true , false ) ; <nl> - NCVAutoTestLister testListerNPPSTVectorOperations ( " NPPST Vector Operations " ) ; / / , , true , false ) ; <nl> - NCVAutoTestLister testListerTranspose ( " NPPST Transpose " ) ; / / , , true , false ) ; <nl> + generateRectStdDevTests ( testListerRStdDev , testSrcRandom_8u , 4096 , 4096 ) ; <nl> <nl> - NCVAutoTestLister testListerVectorOperations ( " Vector Operations " ) ; / / , , true , false ) ; <nl> - NCVAutoTestLister testListerHaarLoader ( " Haar Cascade Loader " ) ; / / , , true , false ) ; <nl> - NCVAutoTestLister testListerHaarAppl ( " Haar Cascade Application " ) ; / / , , true , false ) ; <nl> - NCVAutoTestLister testListerHypFiltration ( " Hypotheses Filtration " ) ; / / , , true , false ) ; <nl> - NCVAutoTestLister testListerVisualize ( " Visualization " ) ; / / , , true , false ) ; <nl> + return testListerRStdDev . invoke ( ) ; <nl> + } <nl> + <nl> + bool nvidia_NPPST_Resize ( const std : : string & test_data_path , OutputLevel outputLevel ) <nl> + { <nl> + path = test_data_path ; <nl> + ncvSetDebugOutputHandler ( devNullOutput ) ; <nl> + <nl> + NCVAutoTestLister testListerResize ( " NPPST Resize " , outputLevel ) ; <nl> <nl> - printf ( " Initializing data source providers \ n " ) ; <nl> NCVTestSourceProvider < Ncv32u > testSrcRandom_32u ( 2010 , 0 , 0xFFFFFFFF , 4096 , 4096 ) ; <nl> - NCVTestSourceProvider < Ncv8u > testSrcRandom_8u ( 2010 , 0 , 255 , 4096 , 4096 ) ; <nl> NCVTestSourceProvider < Ncv64u > testSrcRandom_64u ( 2010 , 0 , - 1 , 4096 , 4096 ) ; <nl> - NCVTestSourceProvider < Ncv8u > testSrcFacesVGA_8u ( path + " group_1_640x480_VGA . pgm " ) ; <nl> - NCVTestSourceProvider < Ncv32f > testSrcRandom_32f ( 2010 , - 1 . 0f , 1 . 0f , 4096 , 4096 ) ; <nl> <nl> - printf ( " Generating NPPST test suites \ n " ) ; <nl> - generateIntegralTests < Ncv8u , Ncv32u > ( testListerII , testSrcRandom_8u , 4096 , 4096 ) ; <nl> - generateIntegralTests < Ncv32f , Ncv32f > ( testListerII , testSrcRandom_32f , 4096 , 4096 ) ; <nl> - generateSquaredIntegralTests ( testListerSII , testSrcRandom_8u , 4096 , 4096 ) ; <nl> - generateRectStdDevTests ( testListerRStdDev , testSrcRandom_8u , 4096 , 4096 ) ; <nl> generateResizeTests ( testListerResize , testSrcRandom_32u ) ; <nl> generateResizeTests ( testListerResize , testSrcRandom_64u ) ; <nl> + <nl> + return testListerResize . invoke ( ) ; <nl> + } <nl> + <nl> + bool nvidia_NPPST_Vector_Operations ( const std : : string & test_data_path , OutputLevel outputLevel ) <nl> + { <nl> + path = test_data_path ; <nl> + ncvSetDebugOutputHandler ( devNullOutput ) ; <nl> + <nl> + NCVAutoTestLister testListerNPPSTVectorOperations ( " NPPST Vector Operations " , outputLevel ) ; <nl> + <nl> + NCVTestSourceProvider < Ncv32u > testSrcRandom_32u ( 2010 , 0 , 0xFFFFFFFF , 4096 , 4096 ) ; <nl> + <nl> generateNPPSTVectorTests ( testListerNPPSTVectorOperations , testSrcRandom_32u , 4096 * 4096 ) ; <nl> + <nl> + return testListerNPPSTVectorOperations . invoke ( ) ; <nl> + } <nl> + <nl> + bool nvidia_NPPST_Transpose ( const std : : string & test_data_path , OutputLevel outputLevel ) <nl> + { <nl> + path = test_data_path ; <nl> + ncvSetDebugOutputHandler ( devNullOutput ) ; <nl> + <nl> + NCVAutoTestLister testListerTranspose ( " NPPST Transpose " , outputLevel ) ; <nl> + <nl> + NCVTestSourceProvider < Ncv32u > testSrcRandom_32u ( 2010 , 0 , 0xFFFFFFFF , 4096 , 4096 ) ; <nl> + NCVTestSourceProvider < Ncv64u > testSrcRandom_64u ( 2010 , 0 , - 1 , 4096 , 4096 ) ; <nl> + <nl> generateTransposeTests ( testListerTranspose , testSrcRandom_32u ) ; <nl> generateTransposeTests ( testListerTranspose , testSrcRandom_64u ) ; <nl> <nl> - printf ( " Generating NCV test suites \ n " ) ; <nl> - generateDrawRectsTests ( testListerVisualize , testSrcRandom_8u , testSrcRandom_32u , 4096 , 4096 ) ; <nl> - generateDrawRectsTests ( testListerVisualize , testSrcRandom_32u , testSrcRandom_32u , 4096 , 4096 ) ; <nl> + return testListerTranspose . invoke ( ) ; <nl> + } <nl> + <nl> + bool nvidia_NCV_Vector_Operations ( const std : : string & test_data_path , OutputLevel outputLevel ) <nl> + { <nl> + path = test_data_path ; <nl> + ncvSetDebugOutputHandler ( devNullOutput ) ; <nl> + <nl> + NCVAutoTestLister testListerVectorOperations ( " Vector Operations " , outputLevel ) ; <nl> + <nl> + NCVTestSourceProvider < Ncv32u > testSrcRandom_32u ( 2010 , 0 , 0xFFFFFFFF , 4096 , 4096 ) ; <nl> + <nl> generateVectorTests ( testListerVectorOperations , testSrcRandom_32u , 4096 * 4096 ) ; <nl> - generateHypothesesFiltrationTests ( testListerHypFiltration , testSrcRandom_32u , 1024 ) ; <nl> + <nl> + return testListerVectorOperations . invoke ( ) ; <nl> + } <nl> + <nl> + bool nvidia_NCV_Haar_Cascade_Loader ( const std : : string & test_data_path , OutputLevel outputLevel ) <nl> + { <nl> + path = test_data_path ; <nl> + ncvSetDebugOutputHandler ( devNullOutput ) ; <nl> + <nl> + NCVAutoTestLister testListerHaarLoader ( " Haar Cascade Loader " , outputLevel ) ; <nl> + <nl> generateHaarLoaderTests ( testListerHaarLoader ) ; <nl> + <nl> + return testListerHaarLoader . invoke ( ) ; <nl> + } <nl> + <nl> + bool nvidia_NCV_Haar_Cascade_Application ( const std : : string & test_data_path , OutputLevel outputLevel ) <nl> + { <nl> + path = test_data_path ; <nl> + ncvSetDebugOutputHandler ( devNullOutput ) ; <nl> + <nl> + NCVAutoTestLister testListerHaarAppl ( " Haar Cascade Application " , outputLevel ) ; <nl> + <nl> + NCVTestSourceProvider < Ncv8u > testSrcFacesVGA_8u ( path + " group_1_640x480_VGA . pgm " ) ; <nl> + <nl> generateHaarApplicationTests ( testListerHaarAppl , testSrcFacesVGA_8u , 1280 , 720 ) ; <nl> <nl> - / / Indicate if at least one test failed <nl> - bool passed = true ; <nl> - <nl> - / / Invoke all tests <nl> - passed & = testListerII . invoke ( ) ; <nl> - passed & = testListerSII . invoke ( ) ; <nl> - passed & = testListerRStdDev . invoke ( ) ; <nl> - passed & = testListerResize . invoke ( ) ; <nl> - passed & = testListerNPPSTVectorOperations . invoke ( ) ; <nl> - passed & = testListerTranspose . invoke ( ) ; <nl> - passed & = testListerVisualize . invoke ( ) ; <nl> - passed & = testListerVectorOperations . invoke ( ) ; <nl> - passed & = testListerHypFiltration . invoke ( ) ; <nl> - passed & = testListerHaarLoader . invoke ( ) ; <nl> - passed & = testListerHaarAppl . invoke ( ) ; <nl> - <nl> - return passed ; <nl> + return testListerHaarAppl . invoke ( ) ; <nl> + } <nl> + <nl> + bool nvidia_NCV_Hypotheses_Filtration ( const std : : string & test_data_path , OutputLevel outputLevel ) <nl> + { <nl> + path = test_data_path ; <nl> + ncvSetDebugOutputHandler ( devNullOutput ) ; <nl> + <nl> + NCVAutoTestLister testListerHypFiltration ( " Hypotheses Filtration " , outputLevel ) ; <nl> + <nl> + NCVTestSourceProvider < Ncv32u > testSrcRandom_32u ( 2010 , 0 , 0xFFFFFFFF , 4096 , 4096 ) ; <nl> + <nl> + generateHypothesesFiltrationTests ( testListerHypFiltration , testSrcRandom_32u , 1024 ) ; <nl> + <nl> + return testListerHypFiltration . invoke ( ) ; <nl> + } <nl> + <nl> + bool nvidia_NCV_Visualization ( const std : : string & test_data_path , OutputLevel outputLevel ) <nl> + { <nl> + path = test_data_path ; <nl> + ncvSetDebugOutputHandler ( devNullOutput ) ; <nl> + <nl> + NCVAutoTestLister testListerVisualize ( " Visualization " , outputLevel ) ; <nl> + <nl> + NCVTestSourceProvider < Ncv8u > testSrcRandom_8u ( 2010 , 0 , 255 , 4096 , 4096 ) ; <nl> + NCVTestSourceProvider < Ncv32u > testSrcRandom_32u ( 2010 , 0 , 0xFFFFFFFF , 4096 , 4096 ) ; <nl> + <nl> + generateDrawRectsTests ( testListerVisualize , testSrcRandom_8u , testSrcRandom_32u , 4096 , 4096 ) ; <nl> + generateDrawRectsTests ( testListerVisualize , testSrcRandom_32u , testSrcRandom_32u , 4096 , 4096 ) ; <nl> + <nl> + return testListerVisualize . invoke ( ) ; <nl> } <nl> mmm a / modules / gpu / test / test_arithm . cpp <nl> ppp b / modules / gpu / test / test_arithm . cpp <nl> <nl> / / <nl> / / M * / <nl> <nl> - # include < iostream > <nl> - # include < cmath > <nl> - # include < limits > <nl> # include " test_precomp . hpp " <nl> <nl> - using namespace cv ; <nl> - using namespace std ; <nl> - using namespace gpu ; <nl> + # ifdef HAVE_CUDA <nl> <nl> - # define CHECK ( pred , err ) if ( ! ( pred ) ) { \ <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " Fail : \ " % s \ " at line : % d \ n " , # pred , __LINE__ ) ; \ <nl> - ts - > set_failed_test_info ( err ) ; \ <nl> - return ; } <nl> - <nl> - class CV_GpuArithmTest : public cvtest : : BaseTest <nl> + struct ArithmTest : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int > > <nl> { <nl> - public : <nl> - CV_GpuArithmTest ( const char * / * test_name * / , const char * / * test_funcs * / ) { } <nl> - virtual ~ CV_GpuArithmTest ( ) { } <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int type ; <nl> <nl> - protected : <nl> - void run ( int ) ; <nl> + cv : : Size size ; <nl> + cv : : Mat mat1 , mat2 ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + type = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> <nl> - int test ( int type ) ; <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> <nl> - virtual int test ( const Mat & mat1 , const Mat & mat2 ) = 0 ; <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> <nl> - int CheckNorm ( const Mat & m1 , const Mat & m2 , double eps = 1e - 5 ) ; <nl> - int CheckNorm ( const Scalar & s1 , const Scalar & s2 , double eps = 1e - 5 ) ; <nl> - int CheckNorm ( double d1 , double d2 , double eps = 1e - 5 ) ; <nl> + size = cv : : Size ( rng . uniform ( 100 , 200 ) , rng . uniform ( 100 , 200 ) ) ; <nl> + <nl> + mat1 = cvtest : : randomMat ( rng , size , type , 1 , 16 , false ) ; <nl> + mat2 = cvtest : : randomMat ( rng , size , type , 1 , 16 , false ) ; <nl> + } <nl> } ; <nl> <nl> - int CV_GpuArithmTest : : test ( int type ) <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / add <nl> + <nl> + struct AddArray : ArithmTest { } ; <nl> + <nl> + TEST_P ( AddArray , Accuracy ) <nl> { <nl> - cv : : Size sz ( 200 , 200 ) ; <nl> - cv : : Mat mat1 ( sz , type ) , mat2 ( sz , type ) ; <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + PRINT_PARAM ( size ) ; <nl> <nl> - cv : : RNG & rng = ts - > get_rng ( ) ; <nl> + cv : : Mat dst_gold ; <nl> + cv : : add ( mat1 , mat2 , dst_gold ) ; <nl> <nl> - if ( type ! = CV_32FC1 ) <nl> - { <nl> - rng . fill ( mat1 , cv : : RNG : : UNIFORM , cv : : Scalar : : all ( 1 ) , cv : : Scalar : : all ( 20 ) ) ; <nl> - rng . fill ( mat2 , cv : : RNG : : UNIFORM , cv : : Scalar : : all ( 1 ) , cv : : Scalar : : all ( 20 ) ) ; <nl> - } <nl> - else <nl> - { <nl> - rng . fill ( mat1 , cv : : RNG : : UNIFORM , cv : : Scalar : : all ( 0 . 1 ) , cv : : Scalar : : all ( 1 . 0 ) ) ; <nl> - rng . fill ( mat2 , cv : : RNG : : UNIFORM , cv : : Scalar : : all ( 0 . 1 ) , cv : : Scalar : : all ( 1 . 0 ) ) ; <nl> - } <nl> + cv : : Mat dst ; <nl> <nl> - return test ( mat1 , mat2 ) ; <nl> - } <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuRes ; <nl> <nl> - int CV_GpuArithmTest : : CheckNorm ( const Mat & m1 , const Mat & m2 , double eps ) <nl> - { <nl> - double ret = norm ( m1 , m2 , NORM_INF ) ; <nl> + cv : : gpu : : add ( cv : : gpu : : GpuMat ( mat1 ) , cv : : gpu : : GpuMat ( mat2 ) , gpuRes ) ; <nl> <nl> - if ( ret < eps ) <nl> - return cvtest : : TS : : OK ; <nl> + gpuRes . download ( dst ) ; <nl> + ) ; <nl> <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ nNorm : % f \ n " , ret ) ; <nl> - return cvtest : : TS : : FAIL_GENERIC ; <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 0 . 0 ) ; <nl> } <nl> <nl> - int CV_GpuArithmTest : : CheckNorm ( const Scalar & s1 , const Scalar & s2 , double eps ) <nl> - { <nl> - int ret0 = CheckNorm ( s1 [ 0 ] , s2 [ 0 ] , eps ) , <nl> - ret1 = CheckNorm ( s1 [ 1 ] , s2 [ 1 ] , eps ) , <nl> - ret2 = CheckNorm ( s1 [ 2 ] , s2 [ 2 ] , eps ) , <nl> - ret3 = CheckNorm ( s1 [ 3 ] , s2 [ 3 ] , eps ) ; <nl> + INSTANTIATE_TEST_CASE_P ( Arithm , AddArray , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( CV_8UC1 , CV_8UC4 , CV_32SC1 , CV_32FC1 ) ) ) ; <nl> <nl> - return ( ret0 = = cvtest : : TS : : OK & & ret1 = = cvtest : : TS : : OK & & ret2 = = cvtest : : TS : : OK & & ret3 = = cvtest : : TS : : OK ) ? cvtest : : TS : : OK : cvtest : : TS : : FAIL_GENERIC ; <nl> - } <nl> + struct AddScalar : ArithmTest { } ; <nl> <nl> - int CV_GpuArithmTest : : CheckNorm ( double d1 , double d2 , double eps ) <nl> + TEST_P ( AddScalar , Accuracy ) <nl> { <nl> - double ret = : : fabs ( d1 - d2 ) ; <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + PRINT_PARAM ( size ) ; <nl> <nl> - if ( ret < eps ) <nl> - return cvtest : : TS : : OK ; <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ nNorm : % f \ n " , ret ) ; <nl> - return cvtest : : TS : : FAIL_GENERIC ; <nl> - } <nl> + cv : : Scalar val ( rng . uniform ( 0 . 1 , 3 . 0 ) , rng . uniform ( 0 . 1 , 3 . 0 ) ) ; <nl> <nl> - void CV_GpuArithmTest : : run ( int ) <nl> - { <nl> - int testResult = cvtest : : TS : : OK ; <nl> + PRINT_PARAM ( val ) ; <nl> + <nl> + cv : : Mat dst_gold ; <nl> + cv : : add ( mat1 , val , dst_gold ) ; <nl> <nl> - const int types [ ] = { CV_8UC1 , CV_8UC3 , CV_8UC4 , CV_32FC1 } ; <nl> - const char * type_names [ ] = { " CV_8UC1 " , " CV_8UC3 " , " CV_8UC4 " , " CV_32FC1 " } ; <nl> - const int type_count = sizeof ( types ) / sizeof ( types [ 0 ] ) ; <nl> + cv : : Mat dst ; <nl> <nl> - / / run tests <nl> - for ( int t = 0 ; t < type_count ; + + t ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " Start testing % s " , type_names [ t ] ) ; <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuRes ; <nl> <nl> - if ( cvtest : : TS : : OK = = test ( types [ t ] ) ) <nl> - ts - > printf ( cvtest : : TS : : LOG , " SUCCESS \ n " ) ; <nl> - else <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " FAIL \ n " ) ; <nl> - testResult = cvtest : : TS : : FAIL_MISMATCH ; <nl> - } <nl> - } <nl> + cv : : gpu : : add ( cv : : gpu : : GpuMat ( mat1 ) , val , gpuRes ) ; <nl> + <nl> + gpuRes . download ( dst ) ; <nl> + ) ; <nl> <nl> - ts - > set_failed_test_info ( testResult ) ; <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 1e - 5 ) ; <nl> } <nl> <nl> + INSTANTIATE_TEST_CASE_P ( Arithm , AddScalar , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( CV_32FC1 , CV_32FC2 ) ) ) ; <nl> + <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / Add <nl> + / / subtract <nl> + <nl> + struct SubtractArray : ArithmTest { } ; <nl> <nl> - struct CV_GpuNppImageAddTest : public CV_GpuArithmTest <nl> + TEST_P ( SubtractArray , Accuracy ) <nl> { <nl> - CV_GpuNppImageAddTest ( ) : CV_GpuArithmTest ( " GPU - NppImageAdd " , " add " ) { } <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + <nl> + cv : : Mat dst_gold ; <nl> + cv : : subtract ( mat1 , mat2 , dst_gold ) ; <nl> <nl> - virtual int test ( const Mat & mat1 , const Mat & mat2 ) <nl> - { <nl> - if ( mat1 . type ( ) ! = CV_8UC1 & & mat1 . type ( ) ! = CV_8UC4 & & mat1 . type ( ) ! = CV_32FC1 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ tUnsupported type \ t " ) ; <nl> - return cvtest : : TS : : OK ; <nl> - } <nl> + cv : : Mat dst ; <nl> <nl> - cv : : Mat cpuRes ; <nl> - cv : : add ( mat1 , mat2 , cpuRes ) ; <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuRes ; <nl> <nl> - GpuMat gpu1 ( mat1 ) ; <nl> - GpuMat gpu2 ( mat2 ) ; <nl> - GpuMat gpuRes ; <nl> - cv : : gpu : : add ( gpu1 , gpu2 , gpuRes ) ; <nl> + cv : : gpu : : subtract ( cv : : gpu : : GpuMat ( mat1 ) , cv : : gpu : : GpuMat ( mat2 ) , gpuRes ) ; <nl> <nl> - return CheckNorm ( cpuRes , gpuRes ) ; <nl> - } <nl> - } ; <nl> + gpuRes . download ( dst ) ; <nl> + ) ; <nl> <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / Sub <nl> - struct CV_GpuNppImageSubtractTest : public CV_GpuArithmTest <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 0 . 0 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( Arithm , SubtractArray , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( CV_8UC1 , CV_8UC4 , CV_32SC1 , CV_32FC1 ) ) ) ; <nl> + <nl> + struct SubtractScalar : ArithmTest { } ; <nl> + <nl> + TEST_P ( SubtractScalar , Accuracy ) <nl> { <nl> - CV_GpuNppImageSubtractTest ( ) : CV_GpuArithmTest ( " GPU - NppImageSubtract " , " subtract " ) { } <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + PRINT_PARAM ( size ) ; <nl> <nl> - int test ( const Mat & mat1 , const Mat & mat2 ) <nl> - { <nl> - if ( mat1 . type ( ) ! = CV_8UC1 & & mat1 . type ( ) ! = CV_8UC4 & & mat1 . type ( ) ! = CV_32FC1 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ tUnsupported type \ t " ) ; <nl> - return cvtest : : TS : : OK ; <nl> - } <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> <nl> - cv : : Mat cpuRes ; <nl> - cv : : subtract ( mat1 , mat2 , cpuRes ) ; <nl> + cv : : Scalar val ( rng . uniform ( 0 . 1 , 3 . 0 ) , rng . uniform ( 0 . 1 , 3 . 0 ) ) ; <nl> <nl> - GpuMat gpu1 ( mat1 ) ; <nl> - GpuMat gpu2 ( mat2 ) ; <nl> - GpuMat gpuRes ; <nl> - cv : : gpu : : subtract ( gpu1 , gpu2 , gpuRes ) ; <nl> + PRINT_PARAM ( val ) ; <nl> + <nl> + cv : : Mat dst_gold ; <nl> + cv : : subtract ( mat1 , val , dst_gold ) ; <nl> <nl> - return CheckNorm ( cpuRes , gpuRes ) ; <nl> - } <nl> - } ; <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuRes ; <nl> + <nl> + cv : : gpu : : subtract ( cv : : gpu : : GpuMat ( mat1 ) , val , gpuRes ) ; <nl> + <nl> + gpuRes . download ( dst ) ; <nl> + ) ; <nl> + <nl> + ASSERT_LE ( checkNorm ( dst_gold , dst ) , 1e - 5 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( Arithm , SubtractScalar , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( CV_32FC1 , CV_32FC2 ) ) ) ; <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> / / multiply <nl> - struct CV_GpuNppImageMultiplyTest : public CV_GpuArithmTest <nl> + <nl> + struct MultiplyArray : ArithmTest { } ; <nl> + <nl> + TEST_P ( MultiplyArray , Accuracy ) <nl> { <nl> - CV_GpuNppImageMultiplyTest ( ) : CV_GpuArithmTest ( " GPU - NppImageMultiply " , " multiply " ) { } <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + <nl> + cv : : Mat dst_gold ; <nl> + cv : : multiply ( mat1 , mat2 , dst_gold ) ; <nl> <nl> - int test ( const Mat & mat1 , const Mat & mat2 ) <nl> - { <nl> - if ( mat1 . type ( ) ! = CV_8UC1 & & mat1 . type ( ) ! = CV_8UC4 & & mat1 . type ( ) ! = CV_32FC1 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ tUnsupported type \ t " ) ; <nl> - return cvtest : : TS : : OK ; <nl> - } <nl> + cv : : Mat dst ; <nl> <nl> - cv : : Mat cpuRes ; <nl> - cv : : multiply ( mat1 , mat2 , cpuRes ) ; <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuRes ; <nl> <nl> - GpuMat gpu1 ( mat1 ) ; <nl> - GpuMat gpu2 ( mat2 ) ; <nl> - GpuMat gpuRes ; <nl> - cv : : gpu : : multiply ( gpu1 , gpu2 , gpuRes ) ; <nl> + cv : : gpu : : multiply ( cv : : gpu : : GpuMat ( mat1 ) , cv : : gpu : : GpuMat ( mat2 ) , gpuRes ) ; <nl> <nl> - return CheckNorm ( cpuRes , gpuRes ) ; <nl> - } <nl> - } ; <nl> + gpuRes . download ( dst ) ; <nl> + ) ; <nl> <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / divide <nl> - struct CV_GpuNppImageDivideTest : public CV_GpuArithmTest <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 0 . 0 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( Arithm , MultiplyArray , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( CV_8UC1 , CV_8UC4 , CV_32SC1 , CV_32FC1 ) ) ) ; <nl> + <nl> + struct MultiplyScalar : ArithmTest { } ; <nl> + <nl> + TEST_P ( MultiplyScalar , Accuracy ) <nl> { <nl> - CV_GpuNppImageDivideTest ( ) : CV_GpuArithmTest ( " GPU - NppImageDivide " , " divide " ) { } <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + PRINT_PARAM ( size ) ; <nl> <nl> - int test ( const Mat & mat1 , const Mat & mat2 ) <nl> - { <nl> - if ( mat1 . type ( ) ! = CV_8UC1 & & mat1 . type ( ) ! = CV_8UC4 & & mat1 . type ( ) ! = CV_32FC1 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ tUnsupported type \ t " ) ; <nl> - return cvtest : : TS : : OK ; <nl> - } <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> <nl> - cv : : Mat cpuRes ; <nl> - cv : : divide ( mat1 , mat2 , cpuRes ) ; <nl> + cv : : Scalar val ( rng . uniform ( 0 . 1 , 3 . 0 ) , rng . uniform ( 0 . 1 , 3 . 0 ) ) ; <nl> <nl> - GpuMat gpu1 ( mat1 ) ; <nl> - GpuMat gpu2 ( mat2 ) ; <nl> - GpuMat gpuRes ; <nl> - cv : : gpu : : divide ( gpu1 , gpu2 , gpuRes ) ; <nl> + PRINT_PARAM ( val ) ; <nl> + <nl> + cv : : Mat dst_gold ; <nl> + cv : : multiply ( mat1 , val , dst_gold ) ; <nl> <nl> - return CheckNorm ( cpuRes , gpuRes , 1 . 01f ) ; <nl> - } <nl> - } ; <nl> + cv : : Mat dst ; <nl> <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / transpose <nl> - struct CV_GpuNppImageTransposeTest : public CV_GpuArithmTest <nl> - { <nl> - CV_GpuNppImageTransposeTest ( ) : CV_GpuArithmTest ( " GPU - NppImageTranspose " , " transpose " ) { } <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuRes ; <nl> <nl> - int test ( const Mat & mat1 , const Mat & ) <nl> - { <nl> - if ( mat1 . type ( ) ! = CV_8UC1 & & mat1 . type ( ) ! = CV_8UC4 & & mat1 . type ( ) ! = CV_32FC1 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ tUnsupported type \ t " ) ; <nl> - return cvtest : : TS : : OK ; <nl> - } <nl> + cv : : gpu : : multiply ( cv : : gpu : : GpuMat ( mat1 ) , val , gpuRes ) ; <nl> <nl> - cv : : Mat cpuRes ; <nl> - cv : : transpose ( mat1 , cpuRes ) ; <nl> + gpuRes . download ( dst ) ; <nl> + ) ; <nl> <nl> - GpuMat gpu1 ( mat1 ) ; <nl> - GpuMat gpuRes ; <nl> - cv : : gpu : : transpose ( gpu1 , gpuRes ) ; <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 1e - 5 ) ; <nl> + } <nl> <nl> - return CheckNorm ( cpuRes , gpuRes ) ; <nl> - } <nl> - } ; <nl> + INSTANTIATE_TEST_CASE_P ( Arithm , MultiplyScalar , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( CV_32FC1 ) ) ) ; <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / absdiff <nl> - struct CV_GpuNppImageAbsdiffTest : public CV_GpuArithmTest <nl> + / / divide <nl> + <nl> + struct DivideArray : ArithmTest { } ; <nl> + <nl> + TEST_P ( DivideArray , Accuracy ) <nl> { <nl> - CV_GpuNppImageAbsdiffTest ( ) : CV_GpuArithmTest ( " GPU - NppImageAbsdiff " , " absdiff " ) { } <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + <nl> + cv : : Mat dst_gold ; <nl> + cv : : divide ( mat1 , mat2 , dst_gold ) ; <nl> <nl> - int test ( const Mat & mat1 , const Mat & mat2 ) <nl> - { <nl> - if ( mat1 . type ( ) ! = CV_8UC1 & & mat1 . type ( ) ! = CV_8UC4 & & mat1 . type ( ) ! = CV_32FC1 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ tUnsupported type \ t " ) ; <nl> - return cvtest : : TS : : OK ; <nl> - } <nl> + cv : : Mat dst ; <nl> <nl> - cv : : Mat cpuRes ; <nl> - cv : : absdiff ( mat1 , mat2 , cpuRes ) ; <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuRes ; <nl> <nl> - GpuMat gpu1 ( mat1 ) ; <nl> - GpuMat gpu2 ( mat2 ) ; <nl> - GpuMat gpuRes ; <nl> - cv : : gpu : : absdiff ( gpu1 , gpu2 , gpuRes ) ; <nl> + cv : : gpu : : divide ( cv : : gpu : : GpuMat ( mat1 ) , cv : : gpu : : GpuMat ( mat2 ) , gpuRes ) ; <nl> <nl> - return CheckNorm ( cpuRes , gpuRes ) ; <nl> - } <nl> - } ; <nl> + gpuRes . download ( dst ) ; <nl> + ) ; <nl> <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / compare <nl> - struct CV_GpuNppImageCompareTest : public CV_GpuArithmTest <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 1 . 0 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( Arithm , DivideArray , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( CV_8UC1 , CV_8UC4 , CV_32SC1 , CV_32FC1 ) ) ) ; <nl> + <nl> + struct DivideScalar : ArithmTest { } ; <nl> + <nl> + TEST_P ( DivideScalar , Accuracy ) <nl> { <nl> - CV_GpuNppImageCompareTest ( ) : CV_GpuArithmTest ( " GPU - NppImageCompare " , " compare " ) { } <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + PRINT_PARAM ( size ) ; <nl> <nl> - int test ( const Mat & mat1 , const Mat & mat2 ) <nl> - { <nl> - if ( mat1 . type ( ) ! = CV_32FC1 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ tUnsupported type \ t " ) ; <nl> - return cvtest : : TS : : OK ; <nl> - } <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> <nl> - int cmp_codes [ ] = { CMP_EQ , CMP_GT , CMP_GE , CMP_LT , CMP_LE , CMP_NE } ; <nl> - const char * cmp_str [ ] = { " CMP_EQ " , " CMP_GT " , " CMP_GE " , " CMP_LT " , " CMP_LE " , " CMP_NE " } ; <nl> - int cmp_num = sizeof ( cmp_codes ) / sizeof ( int ) ; <nl> + cv : : Scalar val ( rng . uniform ( 0 . 1 , 3 . 0 ) , rng . uniform ( 0 . 1 , 3 . 0 ) ) ; <nl> <nl> - int test_res = cvtest : : TS : : OK ; <nl> + PRINT_PARAM ( val ) ; <nl> + <nl> + cv : : Mat dst_gold ; <nl> + cv : : divide ( mat1 , val , dst_gold ) ; <nl> <nl> - for ( int i = 0 ; i < cmp_num ; + + i ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ nCompare operation : % s \ n " , cmp_str [ i ] ) ; <nl> + cv : : Mat dst ; <nl> <nl> - cv : : Mat cpuRes ; <nl> - cv : : compare ( mat1 , mat2 , cpuRes , cmp_codes [ i ] ) ; <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuRes ; <nl> <nl> - GpuMat gpu1 ( mat1 ) ; <nl> - GpuMat gpu2 ( mat2 ) ; <nl> - GpuMat gpuRes ; <nl> - cv : : gpu : : compare ( gpu1 , gpu2 , gpuRes , cmp_codes [ i ] ) ; <nl> + cv : : gpu : : divide ( cv : : gpu : : GpuMat ( mat1 ) , val , gpuRes ) ; <nl> <nl> - if ( CheckNorm ( cpuRes , gpuRes ) ! = cvtest : : TS : : OK ) <nl> - test_res = cvtest : : TS : : FAIL_GENERIC ; <nl> - } <nl> + gpuRes . download ( dst ) ; <nl> + ) ; <nl> <nl> - return test_res ; <nl> - } <nl> - } ; <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 1e - 5 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( Arithm , DivideScalar , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( CV_32FC1 ) ) ) ; <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / meanStdDev <nl> - struct CV_GpuNppImageMeanStdDevTest : public CV_GpuArithmTest <nl> - { <nl> - CV_GpuNppImageMeanStdDevTest ( ) : CV_GpuArithmTest ( " GPU - NppImageMeanStdDev " , " meanStdDev " ) { } <nl> + / / transpose <nl> <nl> - int test ( const Mat & mat1 , const Mat & ) <nl> - { <nl> - if ( mat1 . type ( ) ! = CV_8UC1 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ tUnsupported type \ t " ) ; <nl> - return cvtest : : TS : : OK ; <nl> - } <nl> + struct Transpose : ArithmTest { } ; <nl> <nl> - Scalar cpumean ; <nl> - Scalar cpustddev ; <nl> - cv : : meanStdDev ( mat1 , cpumean , cpustddev ) ; <nl> + TEST_P ( Transpose , Accuracy ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + PRINT_PARAM ( size ) ; <nl> <nl> - GpuMat gpu1 ( mat1 ) ; <nl> - Scalar gpumean ; <nl> - Scalar gpustddev ; <nl> - cv : : gpu : : meanStdDev ( gpu1 , gpumean , gpustddev ) ; <nl> + cv : : Mat dst_gold ; <nl> + cv : : transpose ( mat1 , dst_gold ) ; <nl> <nl> - int test_res = cvtest : : TS : : OK ; <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuRes ; <nl> <nl> - if ( CheckNorm ( cpumean , gpumean ) ! = cvtest : : TS : : OK ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ nMean FAILED \ n " ) ; <nl> - test_res = cvtest : : TS : : FAIL_GENERIC ; <nl> - } <nl> + cv : : gpu : : transpose ( cv : : gpu : : GpuMat ( mat1 ) , gpuRes ) ; <nl> <nl> - if ( CheckNorm ( cpustddev , gpustddev ) ! = cvtest : : TS : : OK ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ nStdDev FAILED \ n " ) ; <nl> - test_res = cvtest : : TS : : FAIL_GENERIC ; <nl> - } <nl> + gpuRes . download ( dst ) ; <nl> + ) ; <nl> <nl> - return test_res ; <nl> - } <nl> - } ; <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 0 . 0 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( Arithm , Transpose , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( CV_8UC1 , CV_8UC4 , CV_8SC1 , CV_8SC4 , CV_16UC2 , CV_16SC2 , CV_32SC1 , CV_32SC2 , CV_32FC1 , CV_32FC2 , CV_64FC1 ) ) ) ; <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / norm <nl> - struct CV_GpuNppImageNormTest : public CV_GpuArithmTest <nl> - { <nl> - CV_GpuNppImageNormTest ( ) : CV_GpuArithmTest ( " GPU - NppImageNorm " , " norm " ) { } <nl> + / / absdiff <nl> <nl> - int test ( const Mat & mat1 , const Mat & mat2 ) <nl> - { <nl> - if ( mat1 . type ( ) ! = CV_8UC1 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ tUnsupported type \ t " ) ; <nl> - return cvtest : : TS : : OK ; <nl> - } <nl> + struct AbsdiffArray : ArithmTest { } ; <nl> <nl> - int norms [ ] = { NORM_INF , NORM_L1 , NORM_L2 } ; <nl> - const char * norms_str [ ] = { " NORM_INF " , " NORM_L1 " , " NORM_L2 " } ; <nl> - int norms_num = sizeof ( norms ) / sizeof ( int ) ; <nl> + TEST_P ( AbsdiffArray , Accuracy ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + <nl> + cv : : Mat dst_gold ; <nl> + cv : : absdiff ( mat1 , mat2 , dst_gold ) ; <nl> <nl> - int test_res = cvtest : : TS : : OK ; <nl> + cv : : Mat dst ; <nl> <nl> - for ( int i = 0 ; i < norms_num ; + + i ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ nNorm type : % s \ n " , norms_str [ i ] ) ; <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuRes ; <nl> <nl> - double cpu_norm = cv : : norm ( mat1 , mat2 , norms [ i ] ) ; <nl> + cv : : gpu : : absdiff ( cv : : gpu : : GpuMat ( mat1 ) , cv : : gpu : : GpuMat ( mat2 ) , gpuRes ) ; <nl> <nl> - GpuMat gpu1 ( mat1 ) ; <nl> - GpuMat gpu2 ( mat2 ) ; <nl> - double gpu_norm = cv : : gpu : : norm ( gpu1 , gpu2 , norms [ i ] ) ; <nl> + gpuRes . download ( dst ) ; <nl> + ) ; <nl> <nl> - if ( CheckNorm ( cpu_norm , gpu_norm ) ! = cvtest : : TS : : OK ) <nl> - test_res = cvtest : : TS : : FAIL_GENERIC ; <nl> - } <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 0 . 0 ) ; <nl> + } <nl> <nl> - return test_res ; <nl> - } <nl> - } ; <nl> + INSTANTIATE_TEST_CASE_P ( Arithm , AbsdiffArray , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( CV_8UC1 , CV_8UC4 , CV_32SC1 , CV_32FC1 ) ) ) ; <nl> <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / flip <nl> - struct CV_GpuNppImageFlipTest : public CV_GpuArithmTest <nl> + struct AbsdiffScalar : ArithmTest { } ; <nl> + <nl> + TEST_P ( AbsdiffScalar , Accuracy ) <nl> { <nl> - CV_GpuNppImageFlipTest ( ) : CV_GpuArithmTest ( " GPU - NppImageFlip " , " flip " ) { } <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + PRINT_PARAM ( size ) ; <nl> <nl> - int test ( const Mat & mat1 , const Mat & ) <nl> - { <nl> - if ( mat1 . type ( ) ! = CV_8UC1 & & mat1 . type ( ) ! = CV_8UC4 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ tUnsupported type \ t " ) ; <nl> - return cvtest : : TS : : OK ; <nl> - } <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> <nl> - int flip_codes [ ] = { 0 , 1 , - 1 } ; <nl> - const char * flip_axis [ ] = { " X " , " Y " , " Both " } ; <nl> - int flip_codes_num = sizeof ( flip_codes ) / sizeof ( int ) ; <nl> + cv : : Scalar val ( rng . uniform ( 0 . 1 , 3 . 0 ) , rng . uniform ( 0 . 1 , 3 . 0 ) ) ; <nl> <nl> - int test_res = cvtest : : TS : : OK ; <nl> + PRINT_PARAM ( val ) ; <nl> + <nl> + cv : : Mat dst_gold ; <nl> + cv : : absdiff ( mat1 , val , dst_gold ) ; <nl> <nl> - for ( int i = 0 ; i < flip_codes_num ; + + i ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ nFlip Axis : % s \ n " , flip_axis [ i ] ) ; <nl> + cv : : Mat dst ; <nl> <nl> - Mat cpu_res ; <nl> - cv : : flip ( mat1 , cpu_res , flip_codes [ i ] ) ; <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuRes ; <nl> <nl> - GpuMat gpu1 ( mat1 ) ; <nl> - GpuMat gpu_res ; <nl> - cv : : gpu : : flip ( gpu1 , gpu_res , flip_codes [ i ] ) ; <nl> + cv : : gpu : : absdiff ( cv : : gpu : : GpuMat ( mat1 ) , val , gpuRes ) ; <nl> <nl> - if ( CheckNorm ( cpu_res , gpu_res ) ! = cvtest : : TS : : OK ) <nl> - test_res = cvtest : : TS : : FAIL_GENERIC ; <nl> - } <nl> + gpuRes . download ( dst ) ; <nl> + ) ; <nl> <nl> - return test_res ; <nl> - } <nl> - } ; <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 1e - 5 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( Arithm , AbsdiffScalar , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( CV_32FC1 ) ) ) ; <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / LUT <nl> - struct CV_GpuNppImageLUTTest : public CV_GpuArithmTest <nl> + / / compare <nl> + <nl> + struct Compare : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int > > <nl> { <nl> - CV_GpuNppImageLUTTest ( ) : CV_GpuArithmTest ( " GPU - NppImageLUT " , " LUT " ) { } <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int cmp_code ; <nl> + <nl> + cv : : Size size ; <nl> + cv : : Mat mat1 , mat2 ; <nl> <nl> - int test ( const Mat & mat1 , const Mat & ) <nl> + cv : : Mat dst_gold ; <nl> + <nl> + virtual void SetUp ( ) <nl> { <nl> - if ( mat1 . type ( ) ! = CV_8UC1 & & mat1 . type ( ) ! = CV_8UC3 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ tUnsupported type \ t " ) ; <nl> - return cvtest : : TS : : OK ; <nl> - } <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + cmp_code = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> <nl> - cv : : Mat lut ( 1 , 256 , CV_8UC1 ) ; <nl> - cv : : RNG & rng = ts - > get_rng ( ) ; <nl> - rng . fill ( lut , cv : : RNG : : UNIFORM , cv : : Scalar : : all ( 100 ) , cv : : Scalar : : all ( 200 ) ) ; <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> <nl> - cv : : Mat cpuRes ; <nl> - cv : : LUT ( mat1 , lut , cpuRes ) ; <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> <nl> - cv : : gpu : : GpuMat gpuRes ; <nl> - cv : : gpu : : LUT ( GpuMat ( mat1 ) , lut , gpuRes ) ; <nl> + size = cv : : Size ( rng . uniform ( 100 , 200 ) , rng . uniform ( 100 , 200 ) ) ; <nl> + <nl> + mat1 = cvtest : : randomMat ( rng , size , CV_32FC1 , 1 , 16 , false ) ; <nl> + mat2 = cvtest : : randomMat ( rng , size , CV_32FC1 , 1 , 16 , false ) ; <nl> <nl> - return CheckNorm ( cpuRes , gpuRes ) ; <nl> + cv : : compare ( mat1 , mat2 , dst_gold , cmp_code ) ; <nl> } <nl> } ; <nl> <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / exp <nl> - struct CV_GpuNppImageExpTest : public CV_GpuArithmTest <nl> + TEST_P ( Compare , Accuracy ) <nl> { <nl> - CV_GpuNppImageExpTest ( ) : CV_GpuArithmTest ( " GPU - NppImageExp " , " exp " ) { } <nl> + static const char * cmp_codes [ ] = { " CMP_EQ " , " CMP_GT " , " CMP_GE " , " CMP_LT " , " CMP_LE " , " CMP_NE " } ; <nl> + const char * cmpCodeStr = cmp_codes [ cmp_code ] ; <nl> <nl> - int test ( const Mat & mat1 , const Mat & ) <nl> - { <nl> - if ( mat1 . type ( ) ! = CV_32FC1 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ tUnsupported type \ t " ) ; <nl> - return cvtest : : TS : : OK ; <nl> - } <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + PRINT_PARAM ( cmpCodeStr ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuRes ; <nl> <nl> - cv : : Mat cpuRes ; <nl> - cv : : exp ( mat1 , cpuRes ) ; <nl> + cv : : gpu : : compare ( cv : : gpu : : GpuMat ( mat1 ) , cv : : gpu : : GpuMat ( mat2 ) , gpuRes , cmp_code ) ; <nl> <nl> - GpuMat gpu1 ( mat1 ) ; <nl> - GpuMat gpuRes ; <nl> - cv : : gpu : : exp ( gpu1 , gpuRes ) ; <nl> + gpuRes . download ( dst ) ; <nl> + ) ; <nl> <nl> - return CheckNorm ( cpuRes , gpuRes ) ; <nl> - } <nl> - } ; <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 0 . 0 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( Arithm , Compare , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( cv : : CMP_EQ , cv : : CMP_GT , cv : : CMP_GE , cv : : CMP_LT , cv : : CMP_LE , cv : : CMP_NE ) ) ) ; <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / log <nl> - struct CV_GpuNppImageLogTest : public CV_GpuArithmTest <nl> + / / meanStdDev <nl> + <nl> + struct MeanStdDev : testing : : TestWithParam < cv : : gpu : : DeviceInfo > <nl> { <nl> - CV_GpuNppImageLogTest ( ) : CV_GpuArithmTest ( " GPU - NppImageLog " , " log " ) { } <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> <nl> - int test ( const Mat & mat1 , const Mat & ) <nl> + cv : : Size size ; <nl> + cv : : Mat mat ; <nl> + <nl> + cv : : Scalar mean_gold ; <nl> + cv : : Scalar stddev_gold ; <nl> + <nl> + virtual void SetUp ( ) <nl> { <nl> - if ( mat1 . type ( ) ! = CV_32FC1 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ tUnsupported type \ t " ) ; <nl> - return cvtest : : TS : : OK ; <nl> - } <nl> + devInfo = GetParam ( ) ; <nl> <nl> - cv : : Mat cpuRes ; <nl> - cv : : log ( mat1 , cpuRes ) ; <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> <nl> - GpuMat gpu1 ( mat1 ) ; <nl> - GpuMat gpuRes ; <nl> - cv : : gpu : : log ( gpu1 , gpuRes ) ; <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> <nl> - return CheckNorm ( cpuRes , gpuRes ) ; <nl> + size = cv : : Size ( rng . uniform ( 100 , 200 ) , rng . uniform ( 100 , 200 ) ) ; <nl> + <nl> + mat = cvtest : : randomMat ( rng , size , CV_8UC1 , 1 , 255 , false ) ; <nl> + <nl> + cv : : meanStdDev ( mat , mean_gold , stddev_gold ) ; <nl> } <nl> } ; <nl> <nl> + TEST_P ( MeanStdDev , Accuracy ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + <nl> + cv : : Scalar mean ; <nl> + cv : : Scalar stddev ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : meanStdDev ( cv : : gpu : : GpuMat ( mat ) , mean , stddev ) ; <nl> + ) ; <nl> + <nl> + EXPECT_NEAR ( mean_gold [ 0 ] , mean [ 0 ] , 1e - 5 ) ; <nl> + EXPECT_NEAR ( mean_gold [ 1 ] , mean [ 1 ] , 1e - 5 ) ; <nl> + EXPECT_NEAR ( mean_gold [ 2 ] , mean [ 2 ] , 1e - 5 ) ; <nl> + EXPECT_NEAR ( mean_gold [ 3 ] , mean [ 3 ] , 1e - 5 ) ; <nl> + <nl> + EXPECT_NEAR ( stddev_gold [ 0 ] , stddev [ 0 ] , 1e - 5 ) ; <nl> + EXPECT_NEAR ( stddev_gold [ 1 ] , stddev [ 1 ] , 1e - 5 ) ; <nl> + EXPECT_NEAR ( stddev_gold [ 2 ] , stddev [ 2 ] , 1e - 5 ) ; <nl> + EXPECT_NEAR ( stddev_gold [ 3 ] , stddev [ 3 ] , 1e - 5 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( Arithm , MeanStdDev , testing : : ValuesIn ( devices ( ) ) ) ; <nl> + <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / magnitude <nl> - struct CV_GpuNppImageMagnitudeTest : public CV_GpuArithmTest <nl> + / / normDiff <nl> + <nl> + static const int norms [ ] = { cv : : NORM_INF , cv : : NORM_L1 , cv : : NORM_L2 } ; <nl> + static const char * norms_str [ ] = { " NORM_INF " , " NORM_L1 " , " NORM_L2 " } ; <nl> + <nl> + struct NormDiff : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int > > <nl> { <nl> - CV_GpuNppImageMagnitudeTest ( ) : CV_GpuArithmTest ( " GPU - NppImageMagnitude " , " magnitude " ) { } <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int normIdx ; <nl> + <nl> + cv : : Size size ; <nl> + cv : : Mat mat1 , mat2 ; <nl> + <nl> + double norm_gold ; <nl> <nl> - int test ( const Mat & mat1 , const Mat & mat2 ) <nl> + virtual void SetUp ( ) <nl> { <nl> - if ( mat1 . type ( ) ! = CV_32FC1 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ tUnsupported type \ t " ) ; <nl> - return cvtest : : TS : : OK ; <nl> - } <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + normIdx = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> <nl> - cv : : Mat cpuRes ; <nl> - cv : : magnitude ( mat1 , mat2 , cpuRes ) ; <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> <nl> - GpuMat gpu1 ( mat1 ) ; <nl> - GpuMat gpu2 ( mat2 ) ; <nl> - GpuMat gpuRes ; <nl> - cv : : gpu : : magnitude ( gpu1 , gpu2 , gpuRes ) ; <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> <nl> - return CheckNorm ( cpuRes , gpuRes ) ; <nl> + size = cv : : Size ( rng . uniform ( 100 , 200 ) , rng . uniform ( 100 , 200 ) ) ; <nl> + <nl> + mat1 = cvtest : : randomMat ( rng , size , CV_8UC1 , 1 , 255 , false ) ; <nl> + mat2 = cvtest : : randomMat ( rng , size , CV_8UC1 , 1 , 255 , false ) ; <nl> + <nl> + norm_gold = cv : : norm ( mat1 , mat2 , norms [ normIdx ] ) ; <nl> } <nl> } ; <nl> <nl> + TEST_P ( NormDiff , Accuracy ) <nl> + { <nl> + const char * normStr = norms_str [ normIdx ] ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + PRINT_PARAM ( normStr ) ; <nl> + <nl> + double norm ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + norm = cv : : gpu : : norm ( cv : : gpu : : GpuMat ( mat1 ) , cv : : gpu : : GpuMat ( mat2 ) , norms [ normIdx ] ) ; <nl> + ) ; <nl> + <nl> + EXPECT_NEAR ( norm_gold , norm , 1e - 6 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( Arithm , NormDiff , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Range ( 0 , 3 ) ) ) ; <nl> + <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / phase <nl> - struct CV_GpuNppImagePhaseTest : public CV_GpuArithmTest <nl> + / / flip <nl> + <nl> + struct Flip : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int , int > > <nl> { <nl> - CV_GpuNppImagePhaseTest ( ) : CV_GpuArithmTest ( " GPU - NppImagePhase " , " phase " ) { } <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int type ; <nl> + int flip_code ; <nl> + <nl> + cv : : Size size ; <nl> + cv : : Mat mat ; <nl> + <nl> + cv : : Mat dst_gold ; <nl> <nl> - int test ( const Mat & mat1 , const Mat & mat2 ) <nl> + virtual void SetUp ( ) <nl> { <nl> - if ( mat1 . type ( ) ! = CV_32FC1 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ tUnsupported type \ t " ) ; <nl> - return cvtest : : TS : : OK ; <nl> - } <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + type = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> + flip_code = std : : tr1 : : get < 2 > ( GetParam ( ) ) ; <nl> <nl> - cv : : Mat cpuRes ; <nl> - cv : : phase ( mat1 , mat2 , cpuRes , true ) ; <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> <nl> - GpuMat gpu1 ( mat1 ) ; <nl> - GpuMat gpu2 ( mat2 ) ; <nl> - GpuMat gpuRes ; <nl> - cv : : gpu : : phase ( gpu1 , gpu2 , gpuRes , true ) ; <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> <nl> - return CheckNorm ( cpuRes , gpuRes , 0 . 3f ) ; <nl> + size = cv : : Size ( rng . uniform ( 100 , 200 ) , rng . uniform ( 100 , 200 ) ) ; <nl> + <nl> + mat = cvtest : : randomMat ( rng , size , type , 1 , 255 , false ) ; <nl> + <nl> + cv : : flip ( mat , dst_gold , flip_code ) ; <nl> } <nl> } ; <nl> <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / cartToPolar <nl> - struct CV_GpuNppImageCartToPolarTest : public CV_GpuArithmTest <nl> + TEST_P ( Flip , Accuracy ) <nl> { <nl> - CV_GpuNppImageCartToPolarTest ( ) : CV_GpuArithmTest ( " GPU - NppImageCartToPolar " , " cartToPolar " ) { } <nl> + static const char * flip_axis [ ] = { " Both " , " X " , " Y " } ; <nl> + const char * flipAxisStr = flip_axis [ flip_code + 1 ] ; <nl> <nl> - int test ( const Mat & mat1 , const Mat & mat2 ) <nl> - { <nl> - if ( mat1 . type ( ) ! = CV_32FC1 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ tUnsupported type \ t " ) ; <nl> - return cvtest : : TS : : OK ; <nl> - } <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + PRINT_PARAM ( flipAxisStr ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpu_res ; <nl> <nl> - cv : : Mat cpuMag , cpuAngle ; <nl> - cv : : cartToPolar ( mat1 , mat2 , cpuMag , cpuAngle ) ; <nl> + cv : : gpu : : flip ( cv : : gpu : : GpuMat ( mat ) , gpu_res , flip_code ) ; <nl> <nl> - GpuMat gpu1 ( mat1 ) ; <nl> - GpuMat gpu2 ( mat2 ) ; <nl> - GpuMat gpuMag , gpuAngle ; <nl> - cv : : gpu : : cartToPolar ( gpu1 , gpu2 , gpuMag , gpuAngle ) ; <nl> + gpu_res . download ( dst ) ; <nl> + ) ; <nl> <nl> - int magRes = CheckNorm ( cpuMag , gpuMag ) ; <nl> - int angleRes = CheckNorm ( cpuAngle , gpuAngle , 0 . 005f ) ; <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 0 . 0 ) ; <nl> + } <nl> <nl> - return magRes = = cvtest : : TS : : OK & & angleRes = = cvtest : : TS : : OK ? cvtest : : TS : : OK : cvtest : : TS : : FAIL_GENERIC ; <nl> - } <nl> - } ; <nl> + INSTANTIATE_TEST_CASE_P ( Arithm , Flip , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( CV_8UC1 , CV_8UC4 ) , <nl> + testing : : Values ( 0 , 1 , - 1 ) ) ) ; <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / polarToCart <nl> - struct CV_GpuNppImagePolarToCartTest : public CV_GpuArithmTest <nl> + / / LUT <nl> + <nl> + struct LUT : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int > > <nl> { <nl> - CV_GpuNppImagePolarToCartTest ( ) : CV_GpuArithmTest ( " GPU - NppImagePolarToCart " , " polarToCart " ) { } <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int type ; <nl> <nl> - int test ( const Mat & mat1 , const Mat & mat2 ) <nl> + cv : : Size size ; <nl> + cv : : Mat mat ; <nl> + cv : : Mat lut ; <nl> + <nl> + cv : : Mat dst_gold ; <nl> + <nl> + virtual void SetUp ( ) <nl> { <nl> - if ( mat1 . type ( ) ! = CV_32FC1 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ tUnsupported type \ t " ) ; <nl> - return cvtest : : TS : : OK ; <nl> - } <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + type = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> <nl> - cv : : Mat cpuX , cpuY ; <nl> - cv : : polarToCart ( mat1 , mat2 , cpuX , cpuY ) ; <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> <nl> - GpuMat gpu1 ( mat1 ) ; <nl> - GpuMat gpu2 ( mat2 ) ; <nl> - GpuMat gpuX , gpuY ; <nl> - cv : : gpu : : polarToCart ( gpu1 , gpu2 , gpuX , gpuY ) ; <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> <nl> - int xRes = CheckNorm ( cpuX , gpuX ) ; <nl> - int yRes = CheckNorm ( cpuY , gpuY ) ; <nl> + size = cv : : Size ( rng . uniform ( 100 , 200 ) , rng . uniform ( 100 , 200 ) ) ; <nl> + <nl> + mat = cvtest : : randomMat ( rng , size , type , 1 , 255 , false ) ; <nl> + lut = cvtest : : randomMat ( rng , cv : : Size ( 256 , 1 ) , CV_8UC1 , 100 , 200 , false ) ; <nl> <nl> - return xRes = = cvtest : : TS : : OK & & yRes = = cvtest : : TS : : OK ? cvtest : : TS : : OK : cvtest : : TS : : FAIL_GENERIC ; <nl> + cv : : LUT ( mat , lut , dst_gold ) ; <nl> } <nl> } ; <nl> <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / Min max <nl> - <nl> - struct CV_GpuMinMaxTest : public cvtest : : BaseTest <nl> + TEST_P ( LUT , Accuracy ) <nl> { <nl> - CV_GpuMinMaxTest ( ) { } <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + PRINT_PARAM ( size ) ; <nl> <nl> - cv : : gpu : : GpuMat buf ; <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpu_res ; <nl> <nl> - void run ( int ) <nl> - { <nl> - bool double_ok = gpu : : TargetArchs : : builtWith ( gpu : : NATIVE_DOUBLE ) & & <nl> - gpu : : DeviceInfo ( ) . supports ( gpu : : NATIVE_DOUBLE ) ; <nl> - int depth_end = double_ok ? CV_64F : CV_32F ; <nl> + cv : : gpu : : LUT ( cv : : gpu : : GpuMat ( mat ) , lut , gpu_res ) ; <nl> <nl> - for ( int depth = CV_8U ; depth < = depth_end ; + + depth ) <nl> - { <nl> - for ( int i = 0 ; i < 3 ; + + i ) <nl> - { <nl> - int rows = 1 + rand ( ) % 1000 ; <nl> - int cols = 1 + rand ( ) % 1000 ; <nl> - test ( rows , cols , 1 , depth ) ; <nl> - test_masked ( rows , cols , 1 , depth ) ; <nl> - } <nl> - } <nl> - } <nl> + gpu_res . download ( dst ) ; <nl> + ) ; <nl> <nl> - void test ( int rows , int cols , int cn , int depth ) <nl> - { <nl> - cv : : Mat src ( rows , cols , CV_MAKE_TYPE ( depth , cn ) ) ; <nl> - cv : : RNG & rng = ts - > get_rng ( ) ; <nl> - rng . fill ( src , RNG : : UNIFORM , Scalar ( 0 ) , Scalar ( 255 ) ) ; <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 0 . 0 ) ; <nl> + } <nl> <nl> - double minVal , maxVal ; <nl> - cv : : Point minLoc , maxLoc ; <nl> + INSTANTIATE_TEST_CASE_P ( Arithm , LUT , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( CV_8UC1 , CV_8UC3 ) ) ) ; <nl> <nl> - if ( depth ! = CV_8S ) <nl> - { <nl> - cv : : minMaxLoc ( src , & minVal , & maxVal , & minLoc , & maxLoc ) ; <nl> - } <nl> - else <nl> - { <nl> - minVal = std : : numeric_limits < double > : : max ( ) ; <nl> - maxVal = - std : : numeric_limits < double > : : max ( ) ; <nl> - for ( int i = 0 ; i < src . rows ; + + i ) <nl> - for ( int j = 0 ; j < src . cols ; + + j ) <nl> - { <nl> - signed char val = src . at < signed char > ( i , j ) ; <nl> - if ( val < minVal ) minVal = val ; <nl> - if ( val > maxVal ) maxVal = val ; <nl> - } <nl> - } <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / exp <nl> <nl> - double minVal_ , maxVal_ ; <nl> - cv : : gpu : : minMax ( cv : : gpu : : GpuMat ( src ) , & minVal_ , & maxVal_ , cv : : gpu : : GpuMat ( ) , buf ) ; <nl> - <nl> - if ( abs ( minVal - minVal_ ) > 1e - 3f ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " \ nfail : minVal = % f minVal_ = % f rows = % d cols = % d depth = % d cn = % d \ n " , minVal , minVal_ , rows , cols , depth , cn ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - } <nl> - if ( abs ( maxVal - maxVal_ ) > 1e - 3f ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " \ nfail : maxVal = % f maxVal_ = % f rows = % d cols = % d depth = % d cn = % d \ n " , maxVal , maxVal_ , rows , cols , depth , cn ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - } <nl> - } <nl> + struct Exp : testing : : TestWithParam < cv : : gpu : : DeviceInfo > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + <nl> + cv : : Size size ; <nl> + cv : : Mat mat ; <nl> <nl> - void test_masked ( int rows , int cols , int cn , int depth ) <nl> + cv : : Mat dst_gold ; <nl> + <nl> + virtual void SetUp ( ) <nl> { <nl> - cv : : Mat src ( rows , cols , CV_MAKE_TYPE ( depth , cn ) ) ; <nl> - cv : : RNG & rng = ts - > get_rng ( ) ; <nl> - rng . fill ( src , RNG : : UNIFORM , Scalar ( 0 ) , Scalar ( 255 ) ) ; <nl> + devInfo = GetParam ( ) ; <nl> <nl> - cv : : Mat mask ( src . size ( ) , CV_8U ) ; <nl> - rng . fill ( mask , RNG : : UNIFORM , Scalar ( 0 ) , Scalar ( 2 ) ) ; <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> <nl> - double minVal , maxVal ; <nl> - cv : : Point minLoc , maxLoc ; <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> <nl> - Mat src_ = src . reshape ( 1 ) ; <nl> - if ( depth ! = CV_8S ) <nl> - { <nl> - cv : : minMaxLoc ( src_ , & minVal , & maxVal , & minLoc , & maxLoc , mask ) ; <nl> - } <nl> - else <nl> - { <nl> - / / OpenCV ' s minMaxLoc doesn ' t support CV_8S type <nl> - minVal = std : : numeric_limits < double > : : max ( ) ; <nl> - maxVal = - std : : numeric_limits < double > : : max ( ) ; <nl> - for ( int i = 0 ; i < src_ . rows ; + + i ) <nl> - for ( int j = 0 ; j < src_ . cols ; + + j ) <nl> - { <nl> - char val = src_ . at < char > ( i , j ) ; <nl> - if ( mask . at < unsigned char > ( i , j ) ) { if ( val < minVal ) minVal = val ; } <nl> - if ( mask . at < unsigned char > ( i , j ) ) { if ( val > maxVal ) maxVal = val ; } <nl> - } <nl> - } <nl> + size = cv : : Size ( rng . uniform ( 100 , 200 ) , rng . uniform ( 100 , 200 ) ) ; <nl> <nl> - double minVal_ , maxVal_ ; <nl> - cv : : Point minLoc_ , maxLoc_ ; <nl> - cv : : gpu : : minMax ( cv : : gpu : : GpuMat ( src ) , & minVal_ , & maxVal_ , cv : : gpu : : GpuMat ( mask ) , buf ) ; <nl> - <nl> - if ( abs ( minVal - minVal_ ) > 1e - 3f ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " \ nfail : minVal = % f minVal_ = % f rows = % d cols = % d depth = % d cn = % d \ n " , minVal , minVal_ , rows , cols , depth , cn ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - } <nl> - if ( abs ( maxVal - maxVal_ ) > 1e - 3f ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " \ nfail : maxVal = % f maxVal_ = % f rows = % d cols = % d depth = % d cn = % d \ n " , maxVal , maxVal_ , rows , cols , depth , cn ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - } <nl> - } <nl> + mat = cvtest : : randomMat ( rng , size , CV_32FC1 , - 10 . 0 , 2 . 0 , false ) ; <nl> + <nl> + cv : : exp ( mat , dst_gold ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( Exp , Accuracy ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpu_res ; <nl> + <nl> + cv : : gpu : : exp ( cv : : gpu : : GpuMat ( mat ) , gpu_res ) ; <nl> + <nl> + gpu_res . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 1e - 5 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( Arithm , Exp , testing : : ValuesIn ( devices ( ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / log <nl> + <nl> + struct Log : testing : : TestWithParam < cv : : gpu : : DeviceInfo > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + <nl> + cv : : Size size ; <nl> + cv : : Mat mat ; <nl> + <nl> + cv : : Mat dst_gold ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = GetParam ( ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + size = cv : : Size ( rng . uniform ( 100 , 200 ) , rng . uniform ( 100 , 200 ) ) ; <nl> + <nl> + mat = cvtest : : randomMat ( rng , size , CV_32FC1 , 0 . 0 , 100 . 0 , false ) ; <nl> + <nl> + cv : : log ( mat , dst_gold ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( Log , Accuracy ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpu_res ; <nl> + <nl> + cv : : gpu : : log ( cv : : gpu : : GpuMat ( mat ) , gpu_res ) ; <nl> + <nl> + gpu_res . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 1e - 5 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( Arithm , Log , testing : : ValuesIn ( devices ( ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / magnitude <nl> + <nl> + struct Magnitude : testing : : TestWithParam < cv : : gpu : : DeviceInfo > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + <nl> + cv : : Size size ; <nl> + cv : : Mat mat1 , mat2 ; <nl> + <nl> + cv : : Mat dst_gold ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = GetParam ( ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + size = cv : : Size ( rng . uniform ( 100 , 200 ) , rng . uniform ( 100 , 200 ) ) ; <nl> + <nl> + mat1 = cvtest : : randomMat ( rng , size , CV_32FC1 , 0 . 0 , 100 . 0 , false ) ; <nl> + mat2 = cvtest : : randomMat ( rng , size , CV_32FC1 , 0 . 0 , 100 . 0 , false ) ; <nl> + <nl> + cv : : magnitude ( mat1 , mat2 , dst_gold ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( Magnitude , Accuracy ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpu_res ; <nl> + <nl> + cv : : gpu : : magnitude ( cv : : gpu : : GpuMat ( mat1 ) , cv : : gpu : : GpuMat ( mat2 ) , gpu_res ) ; <nl> + <nl> + gpu_res . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 1e - 4 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( Arithm , Magnitude , testing : : ValuesIn ( devices ( ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / phase <nl> + <nl> + struct Phase : testing : : TestWithParam < cv : : gpu : : DeviceInfo > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + <nl> + cv : : Size size ; <nl> + cv : : Mat mat1 , mat2 ; <nl> + <nl> + cv : : Mat dst_gold ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = GetParam ( ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + size = cv : : Size ( rng . uniform ( 100 , 200 ) , rng . uniform ( 100 , 200 ) ) ; <nl> + <nl> + mat1 = cvtest : : randomMat ( rng , size , CV_32FC1 , 0 . 0 , 100 . 0 , false ) ; <nl> + mat2 = cvtest : : randomMat ( rng , size , CV_32FC1 , 0 . 0 , 100 . 0 , false ) ; <nl> + <nl> + cv : : phase ( mat1 , mat2 , dst_gold ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( Phase , Accuracy ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpu_res ; <nl> + <nl> + cv : : gpu : : phase ( cv : : gpu : : GpuMat ( mat1 ) , cv : : gpu : : GpuMat ( mat2 ) , gpu_res ) ; <nl> + <nl> + gpu_res . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 1e - 3 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( Arithm , Phase , testing : : ValuesIn ( devices ( ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / cartToPolar <nl> + <nl> + struct CartToPolar : testing : : TestWithParam < cv : : gpu : : DeviceInfo > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + <nl> + cv : : Size size ; <nl> + cv : : Mat mat1 , mat2 ; <nl> + <nl> + cv : : Mat mag_gold ; <nl> + cv : : Mat angle_gold ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = GetParam ( ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + size = cv : : Size ( rng . uniform ( 100 , 200 ) , rng . uniform ( 100 , 200 ) ) ; <nl> + <nl> + mat1 = cvtest : : randomMat ( rng , size , CV_32FC1 , - 100 . 0 , 100 . 0 , false ) ; <nl> + mat2 = cvtest : : randomMat ( rng , size , CV_32FC1 , - 100 . 0 , 100 . 0 , false ) ; <nl> + <nl> + cv : : cartToPolar ( mat1 , mat2 , mag_gold , angle_gold ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( CartToPolar , Accuracy ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + <nl> + cv : : Mat mag , angle ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuMag ; <nl> + cv : : gpu : : GpuMat gpuAngle ; <nl> + <nl> + cv : : gpu : : cartToPolar ( cv : : gpu : : GpuMat ( mat1 ) , cv : : gpu : : GpuMat ( mat2 ) , gpuMag , gpuAngle ) ; <nl> + <nl> + gpuMag . download ( mag ) ; <nl> + gpuAngle . download ( angle ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( mag_gold , mag , 1e - 4 ) ; <nl> + EXPECT_MAT_NEAR ( angle_gold , angle , 1e - 3 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( Arithm , CartToPolar , testing : : ValuesIn ( devices ( ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / polarToCart <nl> + <nl> + struct PolarToCart : testing : : TestWithParam < cv : : gpu : : DeviceInfo > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + <nl> + cv : : Size size ; <nl> + cv : : Mat mag ; <nl> + cv : : Mat angle ; <nl> + <nl> + cv : : Mat x_gold ; <nl> + cv : : Mat y_gold ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = GetParam ( ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + size = cv : : Size ( rng . uniform ( 100 , 200 ) , rng . uniform ( 100 , 200 ) ) ; <nl> + <nl> + mag = cvtest : : randomMat ( rng , size , CV_32FC1 , - 100 . 0 , 100 . 0 , false ) ; <nl> + angle = cvtest : : randomMat ( rng , size , CV_32FC1 , 0 . 0 , 2 . 0 * CV_PI , false ) ; <nl> + <nl> + cv : : polarToCart ( mag , angle , x_gold , y_gold ) ; <nl> + } <nl> } ; <nl> <nl> + TEST_P ( PolarToCart , Accuracy ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + <nl> + cv : : Mat x , y ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuX ; <nl> + cv : : gpu : : GpuMat gpuY ; <nl> + <nl> + cv : : gpu : : polarToCart ( cv : : gpu : : GpuMat ( mag ) , cv : : gpu : : GpuMat ( angle ) , gpuX , gpuY ) ; <nl> + <nl> + gpuX . download ( x ) ; <nl> + gpuY . download ( y ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( x_gold , x , 1e - 4 ) ; <nl> + EXPECT_MAT_NEAR ( y_gold , y , 1e - 4 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( Arithm , PolarToCart , testing : : ValuesIn ( devices ( ) ) ) ; <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / Min max loc <nl> + / / minMax <nl> <nl> - struct CV_GpuMinMaxLocTest : public cvtest : : BaseTest <nl> + struct MinMax : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int > > <nl> { <nl> - CV_GpuMinMaxLocTest ( ) { } <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int type ; <nl> + <nl> + cv : : Size size ; <nl> + cv : : Mat mat ; <nl> + cv : : Mat mask ; <nl> <nl> - GpuMat valbuf , locbuf ; <nl> + double minVal_gold ; <nl> + double maxVal_gold ; <nl> <nl> - void run ( int ) <nl> + virtual void SetUp ( ) <nl> { <nl> - bool double_ok = gpu : : TargetArchs : : builtWith ( gpu : : NATIVE_DOUBLE ) & & <nl> - gpu : : DeviceInfo ( ) . supports ( gpu : : NATIVE_DOUBLE ) ; <nl> - int depth_end = double_ok ? CV_64F : CV_32F ; <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + type = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + size = cv : : Size ( rng . uniform ( 100 , 200 ) , rng . uniform ( 100 , 200 ) ) ; <nl> <nl> - for ( int depth = CV_8U ; depth < = depth_end ; + + depth ) <nl> + mat = cvtest : : randomMat ( rng , size , type , 0 . 0 , 127 . 0 , false ) ; <nl> + mask = cvtest : : randomMat ( rng , size , CV_8UC1 , 0 , 2 , false ) ; <nl> + <nl> + if ( type ! = CV_8S ) <nl> + { <nl> + cv : : minMaxLoc ( mat , & minVal_gold , & maxVal_gold , 0 , 0 , mask ) ; <nl> + } <nl> + else <nl> { <nl> - int rows = 1 , cols = 3 ; <nl> - test ( rows , cols , depth ) ; <nl> - for ( int i = 0 ; i < 4 ; + + i ) <nl> + / / OpenCV ' s minMaxLoc doesn ' t support CV_8S type <nl> + minVal_gold = std : : numeric_limits < double > : : max ( ) ; <nl> + maxVal_gold = - std : : numeric_limits < double > : : max ( ) ; <nl> + for ( int i = 0 ; i < mat . rows ; + + i ) <nl> { <nl> - int rows = 1 + rand ( ) % 1000 ; <nl> - int cols = 1 + rand ( ) % 1000 ; <nl> - test ( rows , cols , depth ) ; <nl> + const signed char * mat_row = mat . ptr < signed char > ( i ) ; <nl> + const unsigned char * mask_row = mask . ptr < unsigned char > ( i ) ; <nl> + for ( int j = 0 ; j < mat . cols ; + + j ) <nl> + { <nl> + if ( mask_row [ j ] ) <nl> + { <nl> + signed char val = mat_row [ j ] ; <nl> + if ( val < minVal_gold ) minVal_gold = val ; <nl> + if ( val > maxVal_gold ) maxVal_gold = val ; <nl> + } <nl> + } <nl> } <nl> } <nl> } <nl> + } ; <nl> + <nl> + TEST_P ( MinMax , Accuracy ) <nl> + { <nl> + if ( type = = CV_64F & & ! supportFeature ( devInfo , cv : : gpu : : NATIVE_DOUBLE ) ) <nl> + return ; <nl> <nl> - void test ( int rows , int cols , int depth ) <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) <nl> + PRINT_PARAM ( size ) ; <nl> + <nl> + double minVal , maxVal ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : minMax ( cv : : gpu : : GpuMat ( mat ) , & minVal , & maxVal , cv : : gpu : : GpuMat ( mask ) ) ; <nl> + ) ; <nl> + <nl> + EXPECT_DOUBLE_EQ ( minVal_gold , minVal ) ; <nl> + EXPECT_DOUBLE_EQ ( maxVal_gold , maxVal ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( Arithm , MinMax , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( CV_8U , CV_8S , CV_16U , CV_16S , CV_32S , CV_32F , CV_64F ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / minMaxLoc <nl> + <nl> + struct MinMaxLoc : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int > > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int type ; <nl> + <nl> + cv : : Size size ; <nl> + cv : : Mat mat ; <nl> + cv : : Mat mask ; <nl> + <nl> + double minVal_gold ; <nl> + double maxVal_gold ; <nl> + cv : : Point minLoc_gold ; <nl> + cv : : Point maxLoc_gold ; <nl> + <nl> + virtual void SetUp ( ) <nl> { <nl> - cv : : Mat src ( rows , cols , depth ) ; <nl> - cv : : RNG & rng = ts - > get_rng ( ) ; <nl> - rng . fill ( src , RNG : : UNIFORM , Scalar ( 0 ) , Scalar ( 255 ) ) ; <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + type = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> <nl> - cv : : Mat mask ( src . size ( ) , CV_8U ) ; <nl> - rng . fill ( mask , RNG : : UNIFORM , Scalar ( 0 ) , Scalar ( 2 ) ) ; <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> <nl> - / / At least one of the mask elements must be non zero as OpenCV returns 0 <nl> - / / in such case , when our implementation returns maximum or minimum value <nl> - mask . at < unsigned char > ( 0 , 0 ) = 1 ; <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> <nl> - double minVal , maxVal ; <nl> - cv : : Point minLoc , maxLoc ; <nl> + size = cv : : Size ( rng . uniform ( 100 , 200 ) , rng . uniform ( 100 , 200 ) ) ; <nl> <nl> - if ( depth ! = CV_8S ) <nl> - cv : : minMaxLoc ( src , & minVal , & maxVal , & minLoc , & maxLoc , mask ) ; <nl> + mat = cvtest : : randomMat ( rng , size , type , 0 . 0 , 127 . 0 , false ) ; <nl> + mask = cvtest : : randomMat ( rng , size , CV_8UC1 , 0 , 2 , false ) ; <nl> + <nl> + if ( type ! = CV_8S ) <nl> + { <nl> + cv : : minMaxLoc ( mat , & minVal_gold , & maxVal_gold , & minLoc_gold , & maxLoc_gold , mask ) ; <nl> + } <nl> else <nl> { <nl> / / OpenCV ' s minMaxLoc doesn ' t support CV_8S type <nl> - minVal = std : : numeric_limits < double > : : max ( ) ; <nl> - maxVal = - std : : numeric_limits < double > : : max ( ) ; <nl> - for ( int i = 0 ; i < src . rows ; + + i ) <nl> - for ( int j = 0 ; j < src . cols ; + + j ) <nl> + minVal_gold = std : : numeric_limits < double > : : max ( ) ; <nl> + maxVal_gold = - std : : numeric_limits < double > : : max ( ) ; <nl> + for ( int i = 0 ; i < mat . rows ; + + i ) <nl> + { <nl> + const signed char * mat_row = mat . ptr < signed char > ( i ) ; <nl> + const unsigned char * mask_row = mask . ptr < unsigned char > ( i ) ; <nl> + for ( int j = 0 ; j < mat . cols ; + + j ) <nl> { <nl> - char val = src . at < char > ( i , j ) ; <nl> - if ( mask . at < unsigned char > ( i , j ) ) <nl> - { <nl> - if ( val < minVal ) { minVal = val ; minLoc = cv : : Point ( j , i ) ; } <nl> - if ( val > maxVal ) { maxVal = val ; maxLoc = cv : : Point ( j , i ) ; } <nl> + if ( mask_row [ j ] ) <nl> + { <nl> + signed char val = mat_row [ j ] ; <nl> + if ( val < minVal_gold ) { minVal_gold = val ; minLoc_gold = cv : : Point ( j , i ) ; } <nl> + if ( val > maxVal_gold ) { maxVal_gold = val ; maxLoc_gold = cv : : Point ( j , i ) ; } <nl> } <nl> } <nl> + } <nl> } <nl> - <nl> - double minVal_ , maxVal_ ; <nl> - cv : : Point minLoc_ , maxLoc_ ; <nl> - cv : : gpu : : minMaxLoc ( cv : : gpu : : GpuMat ( src ) , & minVal_ , & maxVal_ , & minLoc_ , & maxLoc_ , cv : : gpu : : GpuMat ( mask ) , valbuf , locbuf ) ; <nl> - <nl> - CHECK ( minVal = = minVal_ , cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - CHECK ( maxVal = = maxVal_ , cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - CHECK ( 0 = = memcmp ( src . ptr ( minLoc . y ) + minLoc . x * src . elemSize ( ) , src . ptr ( minLoc_ . y ) + minLoc_ . x * src . elemSize ( ) , src . elemSize ( ) ) , <nl> - cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - CHECK ( 0 = = memcmp ( src . ptr ( maxLoc . y ) + maxLoc . x * src . elemSize ( ) , src . ptr ( maxLoc_ . y ) + maxLoc_ . x * src . elemSize ( ) , src . elemSize ( ) ) , <nl> - cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - } <nl> + } <nl> } ; <nl> <nl> + TEST_P ( MinMaxLoc , Accuracy ) <nl> + { <nl> + if ( type = = CV_64F & & ! supportFeature ( devInfo , cv : : gpu : : NATIVE_DOUBLE ) ) <nl> + return ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) <nl> + PRINT_PARAM ( size ) ; <nl> + <nl> + double minVal , maxVal ; <nl> + cv : : Point minLoc , maxLoc ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : minMaxLoc ( cv : : gpu : : GpuMat ( mat ) , & minVal , & maxVal , & minLoc , & maxLoc , cv : : gpu : : GpuMat ( mask ) ) ; <nl> + ) ; <nl> + <nl> + EXPECT_DOUBLE_EQ ( minVal_gold , minVal ) ; <nl> + EXPECT_DOUBLE_EQ ( maxVal_gold , maxVal ) ; <nl> + <nl> + int cmpMinVals = memcmp ( mat . data + minLoc_gold . y * mat . step + minLoc_gold . x * mat . elemSize ( ) , <nl> + mat . data + minLoc . y * mat . step + minLoc . x * mat . elemSize ( ) , <nl> + mat . elemSize ( ) ) ; <nl> + int cmpMaxVals = memcmp ( mat . data + maxLoc_gold . y * mat . step + maxLoc_gold . x * mat . elemSize ( ) , <nl> + mat . data + maxLoc . y * mat . step + maxLoc . x * mat . elemSize ( ) , <nl> + mat . elemSize ( ) ) ; <nl> + <nl> + EXPECT_EQ ( 0 , cmpMinVals ) ; <nl> + EXPECT_EQ ( 0 , cmpMaxVals ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( Arithm , MinMaxLoc , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( CV_8U , CV_8S , CV_16U , CV_16S , CV_32S , CV_32F , CV_64F ) ) ) ; <nl> + <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / Count non zero <nl> - struct CV_GpuCountNonZeroTest : cvtest : : BaseTest <nl> + / / countNonZero <nl> + <nl> + struct CountNonZero : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int > > <nl> { <nl> - CV_GpuCountNonZeroTest ( ) { } <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int type ; <nl> + <nl> + cv : : Size size ; <nl> + cv : : Mat mat ; <nl> + <nl> + int n_gold ; <nl> <nl> - void run ( int ) <nl> + virtual void SetUp ( ) <nl> { <nl> - int depth_end ; <nl> - if ( cv : : gpu : : DeviceInfo ( ) . supports ( cv : : gpu : : NATIVE_DOUBLE ) ) <nl> - depth_end = CV_64F ; <nl> - else <nl> - depth_end = CV_32F ; <nl> - for ( int depth = CV_8U ; depth < = CV_32F ; + + depth ) <nl> - { <nl> - for ( int i = 0 ; i < 4 ; + + i ) <nl> - { <nl> - int rows = 1 + rand ( ) % 1000 ; <nl> - int cols = 1 + rand ( ) % 1000 ; <nl> - test ( rows , cols , depth ) ; <nl> - } <nl> - } <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + type = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + size = cv : : Size ( rng . uniform ( 100 , 200 ) , rng . uniform ( 100 , 200 ) ) ; <nl> + <nl> + cv : : Mat matBase = cvtest : : randomMat ( rng , size , CV_8U , 0 . 0 , 1 . 0 , false ) ; <nl> + matBase . convertTo ( mat , type ) ; <nl> + <nl> + n_gold = cv : : countNonZero ( mat ) ; <nl> } <nl> + } ; <nl> + <nl> + TEST_P ( CountNonZero , Accuracy ) <nl> + { <nl> + if ( type = = CV_64F & & ! supportFeature ( devInfo , cv : : gpu : : NATIVE_DOUBLE ) ) <nl> + return ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) <nl> + PRINT_PARAM ( size ) ; <nl> + <nl> + int n ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + n = cv : : gpu : : countNonZero ( cv : : gpu : : GpuMat ( mat ) ) ; <nl> + ) ; <nl> + <nl> + ASSERT_EQ ( n_gold , n ) ; <nl> + } <nl> <nl> - void test ( int rows , int cols , int depth ) <nl> + INSTANTIATE_TEST_CASE_P ( Arithm , CountNonZero , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( CV_8U , CV_8S , CV_16U , CV_16S , CV_32S , CV_32F , CV_64F ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / sum <nl> + <nl> + struct Sum : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int > > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int type ; <nl> + <nl> + cv : : Size size ; <nl> + cv : : Mat mat ; <nl> + <nl> + cv : : Scalar sum_gold ; <nl> + <nl> + virtual void SetUp ( ) <nl> { <nl> - cv : : Mat src ( rows , cols , depth ) ; <nl> - cv : : RNG rng ; <nl> - if ( depth = = 5 ) <nl> - rng . fill ( src , RNG : : UNIFORM , Scalar ( - 1000 . f ) , Scalar ( 1000 . f ) ) ; <nl> - else if ( depth = = 6 ) <nl> - rng . fill ( src , RNG : : UNIFORM , Scalar ( - 1000 . ) , Scalar ( 1000 . ) ) ; <nl> - else <nl> - for ( int i = 0 ; i < src . rows ; + + i ) <nl> - { <nl> - Mat row ( 1 , src . cols * src . elemSize ( ) , CV_8U , src . ptr ( i ) ) ; <nl> - rng . fill ( row , RNG : : UNIFORM , Scalar ( 0 ) , Scalar ( 256 ) ) ; <nl> - } <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + type = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + size = cv : : Size ( rng . uniform ( 100 , 200 ) , rng . uniform ( 100 , 200 ) ) ; <nl> + <nl> + mat = cvtest : : randomMat ( rng , size , CV_8U , 0 . 0 , 10 . 0 , false ) ; <nl> + <nl> + sum_gold = cv : : sum ( mat ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( Sum , Accuracy ) <nl> + { <nl> + if ( type = = CV_64F & & ! supportFeature ( devInfo , cv : : gpu : : NATIVE_DOUBLE ) ) <nl> + return ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) <nl> + PRINT_PARAM ( size ) ; <nl> + <nl> + cv : : Scalar sum ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + sum = cv : : gpu : : sum ( cv : : gpu : : GpuMat ( mat ) ) ; <nl> + ) ; <nl> + <nl> + EXPECT_NEAR ( sum [ 0 ] , sum_gold [ 0 ] , mat . size ( ) . area ( ) * 1e - 5 ) ; <nl> + EXPECT_NEAR ( sum [ 1 ] , sum_gold [ 1 ] , mat . size ( ) . area ( ) * 1e - 5 ) ; <nl> + EXPECT_NEAR ( sum [ 2 ] , sum_gold [ 2 ] , mat . size ( ) . area ( ) * 1e - 5 ) ; <nl> + EXPECT_NEAR ( sum [ 3 ] , sum_gold [ 3 ] , mat . size ( ) . area ( ) * 1e - 5 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( Arithm , Sum , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( CV_8U , CV_8S , CV_16U , CV_16S , CV_32S , CV_32F , CV_64F ) ) ) ; <nl> + <nl> + struct AbsSum : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int > > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int type ; <nl> + <nl> + cv : : Size size ; <nl> + cv : : Mat mat ; <nl> + <nl> + cv : : Scalar sum_gold ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + type = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + size = cv : : Size ( rng . uniform ( 100 , 200 ) , rng . uniform ( 100 , 200 ) ) ; <nl> + <nl> + mat = cvtest : : randomMat ( rng , size , CV_8U , 0 . 0 , 10 . 0 , false ) ; <nl> + <nl> + sum_gold = cv : : norm ( mat , cv : : NORM_L1 ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( AbsSum , Accuracy ) <nl> + { <nl> + if ( type = = CV_64F & & ! supportFeature ( devInfo , cv : : gpu : : NATIVE_DOUBLE ) ) <nl> + return ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) <nl> + PRINT_PARAM ( size ) ; <nl> + <nl> + cv : : Scalar sum ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + sum = cv : : gpu : : absSum ( cv : : gpu : : GpuMat ( mat ) ) ; <nl> + ) ; <nl> + <nl> + EXPECT_NEAR ( sum [ 0 ] , sum_gold [ 0 ] , mat . size ( ) . area ( ) * 1e - 5 ) ; <nl> + EXPECT_NEAR ( sum [ 1 ] , sum_gold [ 1 ] , mat . size ( ) . area ( ) * 1e - 5 ) ; <nl> + EXPECT_NEAR ( sum [ 2 ] , sum_gold [ 2 ] , mat . size ( ) . area ( ) * 1e - 5 ) ; <nl> + EXPECT_NEAR ( sum [ 3 ] , sum_gold [ 3 ] , mat . size ( ) . area ( ) * 1e - 5 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( Arithm , AbsSum , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( CV_8U , CV_8S , CV_16U , CV_16S , CV_32S , CV_32F , CV_64F ) ) ) ; <nl> + <nl> + struct SqrSum : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int > > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int type ; <nl> + <nl> + cv : : Size size ; <nl> + cv : : Mat mat ; <nl> + <nl> + cv : : Scalar sum_gold ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + type = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + size = cv : : Size ( rng . uniform ( 100 , 200 ) , rng . uniform ( 100 , 200 ) ) ; <nl> + <nl> + mat = cvtest : : randomMat ( rng , size , CV_8U , 0 . 0 , 10 . 0 , false ) ; <nl> + <nl> + cv : : Mat sqrmat ; <nl> + cv : : multiply ( mat , mat , sqrmat ) ; <nl> + sum_gold = cv : : sum ( sqrmat ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( SqrSum , Accuracy ) <nl> + { <nl> + if ( type = = CV_64F & & ! supportFeature ( devInfo , cv : : gpu : : NATIVE_DOUBLE ) ) <nl> + return ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) <nl> + PRINT_PARAM ( size ) ; <nl> + <nl> + cv : : Scalar sum ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + sum = cv : : gpu : : sqrSum ( cv : : gpu : : GpuMat ( mat ) ) ; <nl> + ) ; <nl> + <nl> + EXPECT_NEAR ( sum [ 0 ] , sum_gold [ 0 ] , mat . size ( ) . area ( ) * 1e - 5 ) ; <nl> + EXPECT_NEAR ( sum [ 1 ] , sum_gold [ 1 ] , mat . size ( ) . area ( ) * 1e - 5 ) ; <nl> + EXPECT_NEAR ( sum [ 2 ] , sum_gold [ 2 ] , mat . size ( ) . area ( ) * 1e - 5 ) ; <nl> + EXPECT_NEAR ( sum [ 3 ] , sum_gold [ 3 ] , mat . size ( ) . area ( ) * 1e - 5 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( Arithm , SqrSum , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( CV_8U , CV_8S , CV_16U , CV_16S , CV_32S , CV_32F , CV_64F ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / bitwise <nl> + <nl> + struct BitwiseNot : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int > > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int type ; <nl> + <nl> + cv : : Size size ; <nl> + cv : : Mat mat ; <nl> + <nl> + cv : : Mat dst_gold ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + type = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> <nl> - int n_gold = cv : : countNonZero ( src ) ; <nl> - int n = cv : : gpu : : countNonZero ( cv : : gpu : : GpuMat ( src ) ) ; <nl> + size = cv : : Size ( rng . uniform ( 100 , 200 ) , rng . uniform ( 100 , 200 ) ) ; <nl> <nl> - if ( n ! = n_gold ) <nl> + mat . create ( size , type ) ; <nl> + <nl> + for ( int i = 0 ; i < mat . rows ; + + i ) <nl> { <nl> - ts - > printf ( cvtest : : TS : : LOG , " % d % d % d % d % d \ n " , n , n_gold , depth , cols , rows ) ; <nl> - n_gold = cv : : countNonZero ( src ) ; <nl> + cv : : Mat row ( 1 , mat . cols * mat . elemSize ( ) , CV_8U , ( void * ) mat . ptr ( i ) ) ; <nl> + rng . fill ( row , cv : : RNG : : UNIFORM , cv : : Scalar ( 0 ) , cv : : Scalar ( 255 ) ) ; <nl> } <nl> <nl> - CHECK ( n = = n_gold , cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> + dst_gold = ~ mat ; <nl> } <nl> } ; <nl> <nl> + TEST_P ( BitwiseNot , Accuracy ) <nl> + { <nl> + if ( mat . depth ( ) = = CV_64F & & ! supportFeature ( devInfo , cv : : gpu : : NATIVE_DOUBLE ) ) <nl> + return ; <nl> <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / sum <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) <nl> + PRINT_PARAM ( size ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat dev_dst ; <nl> + <nl> + cv : : gpu : : bitwise_not ( cv : : gpu : : GpuMat ( mat ) , dev_dst ) ; <nl> + <nl> + dev_dst . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 0 . 0 ) ; <nl> + } <nl> <nl> - struct CV_GpuSumTest : cvtest : : BaseTest <nl> + INSTANTIATE_TEST_CASE_P ( Arithm , BitwiseNot , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : ValuesIn ( all_types ( ) ) ) ) ; <nl> + <nl> + struct BitwiseOr : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int > > <nl> { <nl> - CV_GpuSumTest ( ) { } <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int type ; <nl> + <nl> + cv : : Size size ; <nl> + cv : : Mat mat1 ; <nl> + cv : : Mat mat2 ; <nl> + <nl> + cv : : Mat dst_gold ; <nl> <nl> - void run ( int ) <nl> + virtual void SetUp ( ) <nl> { <nl> - Mat src ; <nl> - Scalar a , b ; <nl> - double max_err = 1e - 5 ; <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + type = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + size = cv : : Size ( rng . uniform ( 100 , 200 ) , rng . uniform ( 100 , 200 ) ) ; <nl> <nl> - int typemax = CV_32F ; <nl> - for ( int type = CV_8U ; type < = typemax ; + + type ) <nl> + mat1 . create ( size , type ) ; <nl> + mat2 . create ( size , type ) ; <nl> + <nl> + for ( int i = 0 ; i < mat1 . rows ; + + i ) <nl> { <nl> - / / <nl> - / / sum <nl> - / / <nl> - <nl> - gen ( 1 + rand ( ) % 500 , 1 + rand ( ) % 500 , CV_MAKETYPE ( type , 1 ) , src ) ; <nl> - a = sum ( src ) ; <nl> - b = sum ( GpuMat ( src ) ) ; <nl> - if ( abs ( a [ 0 ] - b [ 0 ] ) > src . size ( ) . area ( ) * max_err ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " 1 cols : % d , rows : % d , expected : % f , actual : % f \ n " , src . cols , src . rows , a [ 0 ] , b [ 0 ] ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return ; <nl> - } <nl> + cv : : Mat row1 ( 1 , mat1 . cols * mat1 . elemSize ( ) , CV_8U , ( void * ) mat1 . ptr ( i ) ) ; <nl> + rng . fill ( row1 , cv : : RNG : : UNIFORM , cv : : Scalar ( 0 ) , cv : : Scalar ( 255 ) ) ; <nl> <nl> - gen ( 1 + rand ( ) % 500 , 1 + rand ( ) % 500 , CV_MAKETYPE ( type , 2 ) , src ) ; <nl> - a = sum ( src ) ; <nl> - b = sum ( GpuMat ( src ) ) ; <nl> - if ( abs ( a [ 0 ] - b [ 0 ] ) + abs ( a [ 1 ] - b [ 1 ] ) > src . size ( ) . area ( ) * max_err ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " 2 cols : % d , rows : % d , expected : % f , actual : % f \ n " , src . cols , src . rows , a [ 1 ] , b [ 1 ] ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return ; <nl> - } <nl> + cv : : Mat row2 ( 1 , mat2 . cols * mat2 . elemSize ( ) , CV_8U , ( void * ) mat2 . ptr ( i ) ) ; <nl> + rng . fill ( row2 , cv : : RNG : : UNIFORM , cv : : Scalar ( 0 ) , cv : : Scalar ( 255 ) ) ; <nl> + } <nl> <nl> - gen ( 1 + rand ( ) % 500 , 1 + rand ( ) % 500 , CV_MAKETYPE ( type , 3 ) , src ) ; <nl> - a = sum ( src ) ; <nl> - b = sum ( GpuMat ( src ) ) ; <nl> - if ( abs ( a [ 0 ] - b [ 0 ] ) + abs ( a [ 1 ] - b [ 1 ] ) + abs ( a [ 2 ] - b [ 2 ] ) > src . size ( ) . area ( ) * max_err ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " 3 cols : % d , rows : % d , expected : % f , actual : % f \ n " , src . cols , src . rows , a [ 2 ] , b [ 2 ] ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return ; <nl> - } <nl> + dst_gold = mat1 | mat2 ; <nl> + } <nl> + } ; <nl> <nl> - gen ( 1 + rand ( ) % 500 , 1 + rand ( ) % 500 , CV_MAKETYPE ( type , 4 ) , src ) ; <nl> - a = sum ( src ) ; <nl> - b = sum ( GpuMat ( src ) ) ; <nl> - if ( abs ( a [ 0 ] - b [ 0 ] ) + abs ( a [ 1 ] - b [ 1 ] ) + abs ( a [ 2 ] - b [ 2 ] ) + abs ( a [ 3 ] - b [ 3 ] ) > src . size ( ) . area ( ) * max_err ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " 4 cols : % d , rows : % d , expected : % f , actual : % f \ n " , src . cols , src . rows , a [ 3 ] , b [ 3 ] ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return ; <nl> - } <nl> + TEST_P ( BitwiseOr , Accuracy ) <nl> + { <nl> + if ( mat1 . depth ( ) = = CV_64F & & ! supportFeature ( devInfo , cv : : gpu : : NATIVE_DOUBLE ) ) <nl> + return ; <nl> <nl> - gen ( 1 + rand ( ) % 500 , 1 + rand ( ) % 500 , type , src ) ; <nl> - a = sum ( src ) ; <nl> - b = sum ( GpuMat ( src ) ) ; <nl> - if ( abs ( a [ 0 ] - b [ 0 ] ) > src . size ( ) . area ( ) * max_err ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " cols : % d , rows : % d , expected : % f , actual : % f \ n " , src . cols , src . rows , a [ 0 ] , b [ 0 ] ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return ; <nl> - } <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) <nl> + PRINT_PARAM ( size ) ; <nl> <nl> - / / <nl> - / / absSum <nl> - / / <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat dev_dst ; <nl> <nl> - gen ( 1 + rand ( ) % 200 , 1 + rand ( ) % 200 , CV_MAKETYPE ( type , 1 ) , src ) ; <nl> - b = absSum ( GpuMat ( src ) ) ; <nl> - a = norm ( src , NORM_L1 ) ; <nl> - if ( abs ( a [ 0 ] - b [ 0 ] ) > src . size ( ) . area ( ) * max_err ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " type : % d , cols : % d , rows : % d , expected : % f , actual : % f \ n " , type , src . cols , src . rows , a [ 0 ] , b [ 0 ] ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return ; <nl> - } <nl> + cv : : gpu : : bitwise_or ( cv : : gpu : : GpuMat ( mat1 ) , cv : : gpu : : GpuMat ( mat2 ) , dev_dst ) ; <nl> <nl> - / / <nl> - / / sqrSum <nl> - / / <nl> + dev_dst . download ( dst ) ; <nl> + ) ; <nl> <nl> - if ( type ! = CV_8S ) <nl> - { <nl> - gen ( 1 + rand ( ) % 200 , 1 + rand ( ) % 200 , CV_MAKETYPE ( type , 1 ) , src ) ; <nl> - b = sqrSum ( GpuMat ( src ) ) ; <nl> - Mat sqrsrc ; <nl> - multiply ( src , src , sqrsrc ) ; <nl> - a = sum ( sqrsrc ) ; <nl> - if ( abs ( a [ 0 ] - b [ 0 ] ) > src . size ( ) . area ( ) * max_err ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " type : % d , cols : % d , rows : % d , expected : % f , actual : % f \ n " , type , src . cols , src . rows , a [ 0 ] , b [ 0 ] ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return ; <nl> - } <nl> - gen ( 1 + rand ( ) % 200 , 1 + rand ( ) % 200 , CV_MAKETYPE ( type , 2 ) , src ) ; <nl> - b = sqrSum ( GpuMat ( src ) ) ; <nl> - multiply ( src , src , sqrsrc ) ; <nl> - a = sum ( sqrsrc ) ; <nl> - if ( abs ( a [ 0 ] - b [ 0 ] ) + abs ( a [ 1 ] - b [ 1 ] ) > src . size ( ) . area ( ) * max_err * 2 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " type : % d , cols : % d , rows : % d , expected : % f , actual : % f \ n " , type , src . cols , src . rows , a [ 0 ] , b [ 0 ] ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return ; <nl> - } <nl> - gen ( 1 + rand ( ) % 200 , 1 + rand ( ) % 200 , CV_MAKETYPE ( type , 3 ) , src ) ; <nl> - b = sqrSum ( GpuMat ( src ) ) ; <nl> - multiply ( src , src , sqrsrc ) ; <nl> - a = sum ( sqrsrc ) ; <nl> - if ( abs ( a [ 0 ] - b [ 0 ] ) + abs ( a [ 1 ] - b [ 1 ] ) + abs ( a [ 2 ] - b [ 2 ] ) > src . size ( ) . area ( ) * max_err * 3 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " type : % d , cols : % d , rows : % d , expected : % f , actual : % f \ n " , type , src . cols , src . rows , a [ 0 ] , b [ 0 ] ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return ; <nl> - } <nl> - gen ( 1 + rand ( ) % 200 , 1 + rand ( ) % 200 , CV_MAKETYPE ( type , 4 ) , src ) ; <nl> - b = sqrSum ( GpuMat ( src ) ) ; <nl> - multiply ( src , src , sqrsrc ) ; <nl> - a = sum ( sqrsrc ) ; <nl> - if ( abs ( a [ 0 ] - b [ 0 ] ) + abs ( a [ 1 ] - b [ 1 ] ) + abs ( a [ 2 ] - b [ 2 ] ) + abs ( a [ 3 ] - b [ 3 ] ) > src . size ( ) . area ( ) * max_err * 4 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " type : % d , cols : % d , rows : % d , expected : % f , actual : % f \ n " , type , src . cols , src . rows , a [ 0 ] , b [ 0 ] ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return ; <nl> - } <nl> - } <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 0 . 0 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( Arithm , BitwiseOr , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : ValuesIn ( all_types ( ) ) ) ) ; <nl> + <nl> + struct BitwiseAnd : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int > > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int type ; <nl> + <nl> + cv : : Size size ; <nl> + cv : : Mat mat1 ; <nl> + cv : : Mat mat2 ; <nl> + <nl> + cv : : Mat dst_gold ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + type = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + size = cv : : Size ( rng . uniform ( 100 , 200 ) , rng . uniform ( 100 , 200 ) ) ; <nl> + <nl> + mat1 . create ( size , type ) ; <nl> + mat2 . create ( size , type ) ; <nl> + <nl> + for ( int i = 0 ; i < mat1 . rows ; + + i ) <nl> + { <nl> + cv : : Mat row1 ( 1 , mat1 . cols * mat1 . elemSize ( ) , CV_8U , ( void * ) mat1 . ptr ( i ) ) ; <nl> + rng . fill ( row1 , cv : : RNG : : UNIFORM , cv : : Scalar ( 0 ) , cv : : Scalar ( 255 ) ) ; <nl> + <nl> + cv : : Mat row2 ( 1 , mat2 . cols * mat2 . elemSize ( ) , CV_8U , ( void * ) mat2 . ptr ( i ) ) ; <nl> + rng . fill ( row2 , cv : : RNG : : UNIFORM , cv : : Scalar ( 0 ) , cv : : Scalar ( 255 ) ) ; <nl> } <nl> + <nl> + dst_gold = mat1 & mat2 ; <nl> } <nl> + } ; <nl> + <nl> + TEST_P ( BitwiseAnd , Accuracy ) <nl> + { <nl> + if ( mat1 . depth ( ) = = CV_64F & & ! supportFeature ( devInfo , cv : : gpu : : NATIVE_DOUBLE ) ) <nl> + return ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) <nl> + PRINT_PARAM ( size ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat dev_dst ; <nl> + <nl> + cv : : gpu : : bitwise_and ( cv : : gpu : : GpuMat ( mat1 ) , cv : : gpu : : GpuMat ( mat2 ) , dev_dst ) ; <nl> + <nl> + dev_dst . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 0 . 0 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( Arithm , BitwiseAnd , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : ValuesIn ( all_types ( ) ) ) ) ; <nl> + <nl> + struct BitwiseXor : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int > > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int type ; <nl> + <nl> + cv : : Size size ; <nl> + cv : : Mat mat1 ; <nl> + cv : : Mat mat2 ; <nl> + <nl> + cv : : Mat dst_gold ; <nl> <nl> - void gen ( int cols , int rows , int type , Mat & m ) <nl> + virtual void SetUp ( ) <nl> { <nl> - m . create ( rows , cols , type ) ; <nl> - RNG rng ; <nl> - rng . fill ( m , RNG : : UNIFORM , Scalar : : all ( 0 ) , Scalar : : all ( 16 ) ) ; <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + type = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + size = cv : : Size ( rng . uniform ( 100 , 200 ) , rng . uniform ( 100 , 200 ) ) ; <nl> + <nl> + mat1 . create ( size , type ) ; <nl> + mat2 . create ( size , type ) ; <nl> + <nl> + for ( int i = 0 ; i < mat1 . rows ; + + i ) <nl> + { <nl> + cv : : Mat row1 ( 1 , mat1 . cols * mat1 . elemSize ( ) , CV_8U , ( void * ) mat1 . ptr ( i ) ) ; <nl> + rng . fill ( row1 , cv : : RNG : : UNIFORM , cv : : Scalar ( 0 ) , cv : : Scalar ( 255 ) ) ; <nl> + <nl> + cv : : Mat row2 ( 1 , mat2 . cols * mat2 . elemSize ( ) , CV_8U , ( void * ) mat2 . ptr ( i ) ) ; <nl> + rng . fill ( row2 , cv : : RNG : : UNIFORM , cv : : Scalar ( 0 ) , cv : : Scalar ( 255 ) ) ; <nl> + } <nl> + <nl> + dst_gold = mat1 ^ mat2 ; <nl> } <nl> } ; <nl> <nl> - TEST ( add , accuracy ) { CV_GpuNppImageAddTest test ; test . safe_run ( ) ; } <nl> - TEST ( subtract , accuracy ) { CV_GpuNppImageSubtractTest test ; test . safe_run ( ) ; } <nl> - TEST ( multiply , accuracy ) { CV_GpuNppImageMultiplyTest test ; test . safe_run ( ) ; } <nl> - TEST ( divide , accuracy ) { CV_GpuNppImageDivideTest test ; test . safe_run ( ) ; } <nl> - TEST ( transpose , accuracy ) { CV_GpuNppImageTransposeTest test ; test . safe_run ( ) ; } <nl> - TEST ( absdiff , accuracy ) { CV_GpuNppImageAbsdiffTest test ; test . safe_run ( ) ; } <nl> - TEST ( compare , accuracy ) { CV_GpuNppImageCompareTest test ; test . safe_run ( ) ; } <nl> - TEST ( meanStdDev , accuracy ) { CV_GpuNppImageMeanStdDevTest test ; test . safe_run ( ) ; } <nl> - TEST ( normDiff , accuracy ) { CV_GpuNppImageNormTest test ; test . safe_run ( ) ; } <nl> - TEST ( flip , accuracy ) { CV_GpuNppImageFlipTest test ; test . safe_run ( ) ; } <nl> - TEST ( LUT , accuracy ) { CV_GpuNppImageLUTTest test ; test . safe_run ( ) ; } <nl> - TEST ( exp , accuracy ) { CV_GpuNppImageExpTest test ; test . safe_run ( ) ; } <nl> - TEST ( log , accuracy ) { CV_GpuNppImageLogTest test ; test . safe_run ( ) ; } <nl> - TEST ( magnitude , accuracy ) { CV_GpuNppImageMagnitudeTest test ; test . safe_run ( ) ; } <nl> - TEST ( phase , accuracy ) { CV_GpuNppImagePhaseTest test ; test . safe_run ( ) ; } <nl> - TEST ( cartToPolar , accuracy ) { CV_GpuNppImageCartToPolarTest test ; test . safe_run ( ) ; } <nl> - TEST ( polarToCart , accuracy ) { CV_GpuNppImagePolarToCartTest test ; test . safe_run ( ) ; } <nl> - TEST ( minMax , accuracy ) { CV_GpuMinMaxTest test ; test . safe_run ( ) ; } <nl> - TEST ( minMaxLoc , accuracy ) { CV_GpuMinMaxLocTest test ; test . safe_run ( ) ; } <nl> - TEST ( countNonZero , accuracy ) { CV_GpuCountNonZeroTest test ; test . safe_run ( ) ; } <nl> - TEST ( sum , accuracy ) { CV_GpuSumTest test ; test . safe_run ( ) ; } <nl> + TEST_P ( BitwiseXor , Accuracy ) <nl> + { <nl> + if ( mat1 . depth ( ) = = CV_64F & & ! supportFeature ( devInfo , cv : : gpu : : NATIVE_DOUBLE ) ) <nl> + return ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) <nl> + PRINT_PARAM ( size ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat dev_dst ; <nl> + <nl> + cv : : gpu : : bitwise_xor ( cv : : gpu : : GpuMat ( mat1 ) , cv : : gpu : : GpuMat ( mat2 ) , dev_dst ) ; <nl> + <nl> + dev_dst . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 0 . 0 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( Arithm , BitwiseXor , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : ValuesIn ( all_types ( ) ) ) ) ; <nl> + <nl> + # endif / / HAVE_CUDA <nl> deleted file mode 100644 <nl> index 6b05053e134 . . 00000000000 <nl> mmm a / modules / gpu / test / test_bitwise_oper . cpp <nl> ppp / dev / null <nl> <nl> - / * M / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / <nl> - / / IMPORTANT : READ BEFORE DOWNLOADING , COPYING , INSTALLING OR USING . <nl> - / / <nl> - / / By downloading , copying , installing or using the software you agree to this license . <nl> - / / If you do not agree to this license , do not download , install , <nl> - / / copy or use the software . <nl> - / / <nl> - / / <nl> - / / Intel License Agreement <nl> - / / For Open Source Computer Vision Library <nl> - / / <nl> - / / Copyright ( C ) 2000 , Intel Corporation , all rights reserved . <nl> - / / Third party copyrights are property of their respective owners . <nl> - / / <nl> - / / Redistribution and use in source and binary forms , with or without modification , <nl> - / / are permitted provided that the following conditions are met : <nl> - / / <nl> - / / * Redistribution ' s of source code must retain the above copyright notice , <nl> - / / this list of conditions and the following disclaimer . <nl> - / / <nl> - / / * Redistribution ' s in binary form must reproduce the above copyright notice , <nl> - / / this list of conditions and the following disclaimer in the documentation <nl> - / / and / or other materials provided with the distribution . <nl> - / / <nl> - / / * The name of Intel Corporation may not be used to endorse or promote products <nl> - / / derived from this software without specific prior written permission . <nl> - / / <nl> - / / This software is provided by the copyright holders and contributors " as is " and <nl> - / / any express or implied warranties , including , but not limited to , the implied <nl> - / / warranties of merchantability and fitness for a particular purpose are disclaimed . <nl> - / / In no event shall the Intel Corporation or contributors be liable for any direct , <nl> - / / indirect , incidental , special , exemplary , or consequential damages <nl> - / / ( including , but not limited to , procurement of substitute goods or services ; <nl> - / / loss of use , data , or profits ; or business interruption ) however caused <nl> - / / and on any theory of liability , whether in contract , strict liability , <nl> - / / or tort ( including negligence or otherwise ) arising in any way out of <nl> - / / the use of this software , even if advised of the possibility of such damage . <nl> - / / <nl> - / / M * / <nl> - <nl> - # include < iostream > <nl> - # include < limits > <nl> - # include " test_precomp . hpp " <nl> - <nl> - # define CHECK ( pred , err ) if ( ! ( pred ) ) { \ <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " Fail : \ " % s \ " at line : % d \ n " , # pred , __LINE__ ) ; \ <nl> - ts - > set_failed_test_info ( err ) ; \ <nl> - return ; } <nl> - <nl> - using namespace cv ; <nl> - using namespace std ; <nl> - <nl> - struct CV_GpuBitwiseTest : public cvtest : : BaseTest <nl> - { <nl> - CV_GpuBitwiseTest ( ) { } <nl> - <nl> - void run ( int ) <nl> - { <nl> - int rows , cols ; <nl> - <nl> - bool double_ok = gpu : : TargetArchs : : builtWith ( gpu : : NATIVE_DOUBLE ) & & <nl> - gpu : : DeviceInfo ( ) . supports ( gpu : : NATIVE_DOUBLE ) ; <nl> - int depth_end = double_ok ? CV_64F : CV_32F ; <nl> - <nl> - for ( int depth = CV_8U ; depth < = depth_end ; + + depth ) <nl> - for ( int cn = 1 ; cn < = 4 ; + + cn ) <nl> - for ( int attempt = 0 ; attempt < 3 ; + + attempt ) <nl> - { <nl> - rows = 1 + rand ( ) % 100 ; <nl> - cols = 1 + rand ( ) % 100 ; <nl> - test_bitwise_not ( rows , cols , CV_MAKETYPE ( depth , cn ) ) ; <nl> - test_bitwise_or ( rows , cols , CV_MAKETYPE ( depth , cn ) ) ; <nl> - test_bitwise_and ( rows , cols , CV_MAKETYPE ( depth , cn ) ) ; <nl> - test_bitwise_xor ( rows , cols , CV_MAKETYPE ( depth , cn ) ) ; <nl> - } <nl> - } <nl> - <nl> - void test_bitwise_not ( int rows , int cols , int type ) <nl> - { <nl> - Mat src ( rows , cols , type ) ; <nl> - <nl> - RNG rng ; <nl> - for ( int i = 0 ; i < src . rows ; + + i ) <nl> - { <nl> - Mat row ( 1 , src . cols * src . elemSize ( ) , CV_8U , src . ptr ( i ) ) ; <nl> - rng . fill ( row , RNG : : UNIFORM , Scalar ( 0 ) , Scalar ( 255 ) ) ; <nl> - } <nl> - <nl> - Mat dst_gold = ~ src ; <nl> - <nl> - gpu : : GpuMat mask ( src . size ( ) , CV_8U ) ; <nl> - mask . setTo ( Scalar ( 1 ) ) ; <nl> - <nl> - gpu : : GpuMat dst ; <nl> - gpu : : bitwise_not ( gpu : : GpuMat ( src ) , dst ) ; <nl> - <nl> - CHECK ( dst_gold . size ( ) = = dst . size ( ) , cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - CHECK ( dst_gold . type ( ) = = dst . type ( ) , cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - <nl> - Mat dsth ( dst ) ; <nl> - for ( int i = 0 ; i < dst_gold . rows ; + + i ) <nl> - CHECK ( memcmp ( dst_gold . ptr ( i ) , dsth . ptr ( i ) , dst_gold . cols * dst_gold . elemSize ( ) ) = = 0 , cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - <nl> - dst . setTo ( Scalar : : all ( 0 ) ) ; <nl> - gpu : : bitwise_not ( gpu : : GpuMat ( src ) , dst , mask ) ; <nl> - <nl> - CHECK ( dst_gold . size ( ) = = dst . size ( ) , cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - CHECK ( dst_gold . type ( ) = = dst . type ( ) , cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - <nl> - dsth = dst ; <nl> - for ( int i = 0 ; i < dst_gold . rows ; + + i ) <nl> - CHECK ( memcmp ( dst_gold . ptr ( i ) , dsth . ptr ( i ) , dst_gold . cols * dst_gold . elemSize ( ) ) = = 0 , cvtest : : TS : : FAIL_INVALID_OUTPUT ) <nl> - } <nl> - <nl> - void test_bitwise_or ( int rows , int cols , int type ) <nl> - { <nl> - Mat src1 ( rows , cols , type ) ; <nl> - Mat src2 ( rows , cols , type ) ; <nl> - <nl> - RNG rng ; <nl> - for ( int i = 0 ; i < src1 . rows ; + + i ) <nl> - { <nl> - Mat row1 ( 1 , src1 . cols * src1 . elemSize ( ) , CV_8U , src1 . ptr ( i ) ) ; <nl> - rng . fill ( row1 , RNG : : UNIFORM , Scalar ( 0 ) , Scalar ( 255 ) ) ; <nl> - Mat row2 ( 1 , src2 . cols * src2 . elemSize ( ) , CV_8U , src2 . ptr ( i ) ) ; <nl> - rng . fill ( row2 , RNG : : UNIFORM , Scalar ( 0 ) , Scalar ( 255 ) ) ; <nl> - } <nl> - <nl> - Mat dst_gold = src1 | src2 ; <nl> - gpu : : GpuMat dst = gpu : : GpuMat ( src1 ) | gpu : : GpuMat ( src2 ) ; <nl> - <nl> - CHECK ( dst_gold . size ( ) = = dst . size ( ) , cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - CHECK ( dst_gold . type ( ) = = dst . type ( ) , cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - Mat dsth ( dst ) ; <nl> - for ( int i = 0 ; i < dst_gold . rows ; + + i ) <nl> - CHECK ( memcmp ( dst_gold . ptr ( i ) , dsth . ptr ( i ) , dst_gold . cols * dst_gold . elemSize ( ) ) = = 0 , cvtest : : TS : : FAIL_INVALID_OUTPUT ) <nl> - <nl> - Mat mask ( src1 . size ( ) , CV_8U ) ; <nl> - randu ( mask , Scalar ( 0 ) , Scalar ( 255 ) ) ; <nl> - <nl> - Mat dst_gold2 ( dst_gold . size ( ) , dst_gold . type ( ) ) ; dst_gold2 . setTo ( Scalar : : all ( 0 ) ) ; <nl> - gpu : : GpuMat dst2 ( dst . size ( ) , dst . type ( ) ) ; dst2 . setTo ( Scalar : : all ( 0 ) ) ; <nl> - bitwise_or ( src1 , src2 , dst_gold2 , mask ) ; <nl> - gpu : : bitwise_or ( gpu : : GpuMat ( src1 ) , gpu : : GpuMat ( src2 ) , dst2 , gpu : : GpuMat ( mask ) ) ; <nl> - <nl> - CHECK ( dst_gold2 . size ( ) = = dst2 . size ( ) , cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - CHECK ( dst_gold2 . type ( ) = = dst2 . type ( ) , cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - dsth = dst2 ; <nl> - for ( int i = 0 ; i < dst_gold . rows ; + + i ) <nl> - CHECK ( memcmp ( dst_gold2 . ptr ( i ) , dsth . ptr ( i ) , dst_gold2 . cols * dst_gold2 . elemSize ( ) ) = = 0 , cvtest : : TS : : FAIL_INVALID_OUTPUT ) <nl> - } <nl> - <nl> - void test_bitwise_and ( int rows , int cols , int type ) <nl> - { <nl> - Mat src1 ( rows , cols , type ) ; <nl> - Mat src2 ( rows , cols , type ) ; <nl> - <nl> - RNG rng ; <nl> - for ( int i = 0 ; i < src1 . rows ; + + i ) <nl> - { <nl> - Mat row1 ( 1 , src1 . cols * src1 . elemSize ( ) , CV_8U , src1 . ptr ( i ) ) ; <nl> - rng . fill ( row1 , RNG : : UNIFORM , Scalar ( 0 ) , Scalar ( 255 ) ) ; <nl> - Mat row2 ( 1 , src2 . cols * src2 . elemSize ( ) , CV_8U , src2 . ptr ( i ) ) ; <nl> - rng . fill ( row2 , RNG : : UNIFORM , Scalar ( 0 ) , Scalar ( 255 ) ) ; <nl> - } <nl> - <nl> - Mat dst_gold = src1 & src2 ; <nl> - <nl> - gpu : : GpuMat dst = gpu : : GpuMat ( src1 ) & gpu : : GpuMat ( src2 ) ; <nl> - <nl> - CHECK ( dst_gold . size ( ) = = dst . size ( ) , cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - CHECK ( dst_gold . type ( ) = = dst . type ( ) , cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - Mat dsth ( dst ) ; <nl> - for ( int i = 0 ; i < dst_gold . rows ; + + i ) <nl> - CHECK ( memcmp ( dst_gold . ptr ( i ) , dsth . ptr ( i ) , dst_gold . cols * dst_gold . elemSize ( ) ) = = 0 , cvtest : : TS : : FAIL_INVALID_OUTPUT ) <nl> - <nl> - <nl> - Mat mask ( src1 . size ( ) , CV_8U ) ; <nl> - randu ( mask , Scalar ( 0 ) , Scalar ( 255 ) ) ; <nl> - <nl> - Mat dst_gold2 ( dst_gold . size ( ) , dst_gold . type ( ) ) ; dst_gold2 . setTo ( Scalar : : all ( 0 ) ) ; <nl> - gpu : : GpuMat dst2 ( dst . size ( ) , dst . type ( ) ) ; dst2 . setTo ( Scalar : : all ( 0 ) ) ; <nl> - bitwise_and ( src1 , src2 , dst_gold2 , mask ) ; <nl> - gpu : : bitwise_and ( gpu : : GpuMat ( src1 ) , gpu : : GpuMat ( src2 ) , dst2 , gpu : : GpuMat ( mask ) ) ; <nl> - <nl> - CHECK ( dst_gold2 . size ( ) = = dst2 . size ( ) , cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - CHECK ( dst_gold2 . type ( ) = = dst2 . type ( ) , cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - dsth = dst2 ; <nl> - for ( int i = 0 ; i < dst_gold . rows ; + + i ) <nl> - CHECK ( memcmp ( dst_gold2 . ptr ( i ) , dsth . ptr ( i ) , dst_gold2 . cols * dst_gold2 . elemSize ( ) ) = = 0 , cvtest : : TS : : FAIL_INVALID_OUTPUT ) <nl> - } <nl> - <nl> - void test_bitwise_xor ( int rows , int cols , int type ) <nl> - { <nl> - Mat src1 ( rows , cols , type ) ; <nl> - Mat src2 ( rows , cols , type ) ; <nl> - <nl> - RNG rng ; <nl> - for ( int i = 0 ; i < src1 . rows ; + + i ) <nl> - { <nl> - Mat row1 ( 1 , src1 . cols * src1 . elemSize ( ) , CV_8U , src1 . ptr ( i ) ) ; <nl> - rng . fill ( row1 , RNG : : UNIFORM , Scalar ( 0 ) , Scalar ( 255 ) ) ; <nl> - Mat row2 ( 1 , src2 . cols * src2 . elemSize ( ) , CV_8U , src2 . ptr ( i ) ) ; <nl> - rng . fill ( row2 , RNG : : UNIFORM , Scalar ( 0 ) , Scalar ( 255 ) ) ; <nl> - } <nl> - <nl> - Mat dst_gold = src1 ^ src2 ; <nl> - <nl> - gpu : : GpuMat dst = gpu : : GpuMat ( src1 ) ^ gpu : : GpuMat ( src2 ) ; <nl> - <nl> - CHECK ( dst_gold . size ( ) = = dst . size ( ) , cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - CHECK ( dst_gold . type ( ) = = dst . type ( ) , cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - Mat dsth ( dst ) ; <nl> - for ( int i = 0 ; i < dst_gold . rows ; + + i ) <nl> - CHECK ( memcmp ( dst_gold . ptr ( i ) , dsth . ptr ( i ) , dst_gold . cols * dst_gold . elemSize ( ) ) = = 0 , cvtest : : TS : : FAIL_INVALID_OUTPUT ) <nl> - <nl> - <nl> - Mat mask ( src1 . size ( ) , CV_8U ) ; <nl> - randu ( mask , Scalar ( 0 ) , Scalar ( 255 ) ) ; <nl> - <nl> - Mat dst_gold2 ( dst_gold . size ( ) , dst_gold . type ( ) ) ; dst_gold2 . setTo ( Scalar : : all ( 0 ) ) ; <nl> - gpu : : GpuMat dst2 ( dst . size ( ) , dst . type ( ) ) ; dst2 . setTo ( Scalar : : all ( 0 ) ) ; <nl> - bitwise_xor ( src1 , src2 , dst_gold2 , mask ) ; <nl> - gpu : : bitwise_xor ( gpu : : GpuMat ( src1 ) , gpu : : GpuMat ( src2 ) , dst2 , gpu : : GpuMat ( mask ) ) ; <nl> - <nl> - CHECK ( dst_gold2 . size ( ) = = dst2 . size ( ) , cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - CHECK ( dst_gold2 . type ( ) = = dst2 . type ( ) , cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - dsth = dst2 ; <nl> - for ( int i = 0 ; i < dst_gold . rows ; + + i ) <nl> - CHECK ( memcmp ( dst_gold2 . ptr ( i ) , dsth . ptr ( i ) , dst_gold2 . cols * dst_gold2 . elemSize ( ) ) = = 0 , cvtest : : TS : : FAIL_INVALID_OUTPUT ) <nl> - } <nl> - } ; <nl> - <nl> - TEST ( BitwiseOperations , accuracy ) { CV_GpuBitwiseTest test ; test . safe_run ( ) ; } <nl> deleted file mode 100644 <nl> index 947969593c5 . . 00000000000 <nl> mmm a / modules / gpu / test / test_blend . cpp <nl> ppp / dev / null <nl> <nl> - / * M / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / <nl> - / / IMPORTANT : READ BEFORE DOWNLOADING , COPYING , INSTALLING OR USING . <nl> - / / <nl> - / / By downloading , copying , installing or using the software you agree to this license . <nl> - / / If you do not agree to this license , do not download , install , <nl> - / / copy or use the software . <nl> - / / <nl> - / / <nl> - / / Intel License Agreement <nl> - / / For Open Source Computer Vision Library <nl> - / / <nl> - / / Copyright ( C ) 2000 , Intel Corporation , all rights reserved . <nl> - / / Third party copyrights are property of their respective owners . <nl> - / / <nl> - / / Redistribution and use in source and binary forms , with or without modification , <nl> - / / are permitted provided that the following conditions are met : <nl> - / / <nl> - / / * Redistribution ' s of source code must retain the above copyright notice , <nl> - / / this list of conditions and the following disclaimer . <nl> - / / <nl> - / / * Redistribution ' s in binary form must reproduce the above copyright notice , <nl> - / / this list of conditions and the following disclaimer in the documentation <nl> - / / and / or other materials provided with the distribution . <nl> - / / <nl> - / / * The name of Intel Corporation may not be used to endorse or promote products <nl> - / / derived from this software without specific prior written permission . <nl> - / / <nl> - / / This software is provided by the copyright holders and contributors " as is " and <nl> - / / any express or implied warranties , including , but not limited to , the implied <nl> - / / warranties of merchantability and fitness for a particular purpose are disclaimed . <nl> - / / In no event shall the Intel Corporation or contributors be liable for any direct , <nl> - / / indirect , incidental , special , exemplary , or consequential damages <nl> - / / ( including , but not limited to , procurement of substitute goods or services ; <nl> - / / loss of use , data , or profits ; or business interruption ) however caused <nl> - / / and on any theory of liability , whether in contract , strict liability , <nl> - / / or tort ( including negligence or otherwise ) arising in any way out of <nl> - / / the use of this software , even if advised of the possibility of such damage . <nl> - / / <nl> - / / M * / <nl> - <nl> - # include " test_precomp . hpp " <nl> - <nl> - using namespace std ; <nl> - using namespace cv ; <nl> - using namespace cv : : gpu ; <nl> - <nl> - TEST ( blendLinear , accuracy_on_8U ) <nl> - { <nl> - RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> - Size size ( 200 + cvtest : : randInt ( rng ) % 1000 , <nl> - 200 + cvtest : : randInt ( rng ) % 1000 ) ; <nl> - for ( int cn = 1 ; cn < = 4 ; + + cn ) <nl> - { <nl> - Mat img1 = cvtest : : randomMat ( rng , size , CV_MAKE_TYPE ( CV_8U , cn ) , 0 , 255 , false ) ; <nl> - Mat img2 = cvtest : : randomMat ( rng , size , CV_MAKE_TYPE ( CV_8U , cn ) , 0 , 255 , false ) ; <nl> - Mat weights1 = cvtest : : randomMat ( rng , size , CV_32F , 0 , 1 , false ) ; <nl> - Mat weights2 = cvtest : : randomMat ( rng , size , CV_32F , 0 , 1 , false ) ; <nl> - Mat result_gold ( size , CV_MAKE_TYPE ( CV_8U , cn ) ) ; <nl> - for ( int y = 0 ; y < size . height ; + + y ) <nl> - for ( int x = 0 ; x < size . width * cn ; + + x ) <nl> - { <nl> - float w1 = weights1 . at < float > ( y , x / cn ) ; <nl> - float w2 = weights2 . at < float > ( y , x / cn ) ; <nl> - result_gold . at < uchar > ( y , x ) = static_cast < uchar > ( <nl> - ( img1 . at < uchar > ( y , x ) * w1 + img2 . at < uchar > ( y , x ) * w2 ) / ( w1 + w2 + 1e - 5f ) ) ; <nl> - } <nl> - GpuMat d_result ; <nl> - blendLinear ( GpuMat ( img1 ) , GpuMat ( img2 ) , GpuMat ( weights1 ) , GpuMat ( weights2 ) , d_result ) ; <nl> - ASSERT_LE ( cvtest : : norm ( result_gold , Mat ( d_result ) , NORM_INF ) , 1 ) <nl> - < < " rows = " < < size . height < < " , cols = " < < size . width < < " , cn = " < < cn ; <nl> - } <nl> - } <nl> - <nl> - TEST ( blendLinear , accuracy_on_32F ) <nl> - { <nl> - RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> - Size size ( 200 + cvtest : : randInt ( rng ) % 1000 , <nl> - 200 + cvtest : : randInt ( rng ) % 1000 ) ; <nl> - for ( int cn = 1 ; cn < = 4 ; + + cn ) <nl> - { <nl> - Mat img1 = cvtest : : randomMat ( rng , size , CV_MAKE_TYPE ( CV_32F , cn ) , 0 , 1 , false ) ; <nl> - Mat img2 = cvtest : : randomMat ( rng , size , CV_MAKE_TYPE ( CV_32F , cn ) , 0 , 1 , false ) ; <nl> - Mat weights1 = cvtest : : randomMat ( rng , size , CV_32F , 0 , 1 , false ) ; <nl> - Mat weights2 = cvtest : : randomMat ( rng , size , CV_32F , 0 , 1 , false ) ; <nl> - Mat result_gold ( size , CV_MAKE_TYPE ( CV_32F , cn ) ) ; <nl> - for ( int y = 0 ; y < size . height ; + + y ) <nl> - for ( int x = 0 ; x < size . width * cn ; + + x ) <nl> - { <nl> - float w1 = weights1 . at < float > ( y , x / cn ) ; <nl> - float w2 = weights2 . at < float > ( y , x / cn ) ; <nl> - result_gold . at < float > ( y , x ) = <nl> - ( img1 . at < float > ( y , x ) * w1 + img2 . at < float > ( y , x ) * w2 ) / ( w1 + w2 + 1e - 5f ) ; <nl> - } <nl> - GpuMat d_result ; <nl> - blendLinear ( GpuMat ( img1 ) , GpuMat ( img2 ) , GpuMat ( weights1 ) , GpuMat ( weights2 ) , d_result ) ; <nl> - ASSERT_LE ( cvtest : : norm ( result_gold , Mat ( d_result ) , NORM_INF ) , 1e - 3 ) <nl> - < < " rows = " < < size . height < < " , cols = " < < size . width < < " , cn = " < < cn ; <nl> - } <nl> - } <nl> deleted file mode 100644 <nl> index 59af9f04f9b . . 00000000000 <nl> mmm a / modules / gpu / test / test_brute_force_matcher . cpp <nl> ppp / dev / null <nl> <nl> - / * M / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / <nl> - / / IMPORTANT : READ BEFORE DOWNLOADING , COPYING , INSTALLING OR USING . <nl> - / / <nl> - / / By downloading , copying , installing or using the software you agree to this license . <nl> - / / If you do not agree to this license , do not download , install , <nl> - / / copy or use the software . <nl> - / / <nl> - / / <nl> - / / Intel License Agreement <nl> - / / For Open Source Computer Vision Library <nl> - / / <nl> - / / Copyright ( C ) 2000 , Intel Corporation , all rights reserved . <nl> - / / Third party copyrights are property of their respective owners . <nl> - / / <nl> - / / Redistribution and use in source and binary forms , with or without modification , <nl> - / / are permitted provided that the following conditions are met : <nl> - / / <nl> - / / * Redistribution ' s of source code must retain the above copyright notice , <nl> - / / this list of conditions and the following disclaimer . <nl> - / / <nl> - / / * Redistribution ' s in binary form must reproduce the above copyright notice , <nl> - / / this list of conditions and the following disclaimer in the documentation <nl> - / / and / or other materials provided with the distribution . <nl> - / / <nl> - / / * The name of Intel Corporation may not be used to endorse or promote products <nl> - / / derived from this software without specific prior written permission . <nl> - / / <nl> - / / This software is provided by the copyright holders and contributors " as is " and <nl> - / / any express or implied warranties , including , but not limited to , the implied <nl> - / / warranties of merchantability and fitness for a particular purpose are disclaimed . <nl> - / / In no event shall the Intel Corporation or contributors be liable for any direct , <nl> - / / indirect , incidental , special , exemplary , or consequential damages <nl> - / / ( including , but not limited to , procurement of substitute goods or services ; <nl> - / / loss of use , data , or profits ; or business interruption ) however caused <nl> - / / and on any theory of liability , whether in contract , strict liability , <nl> - / / or tort ( including negligence or otherwise ) arising in any way out of <nl> - / / the use of this software , even if advised of the possibility of such damage . <nl> - / / <nl> - / / M * / <nl> - <nl> - # include " test_precomp . hpp " <nl> - # include < algorithm > <nl> - # include < iterator > <nl> - <nl> - using namespace cv ; <nl> - using namespace cv : : gpu ; <nl> - using namespace std ; <nl> - <nl> - class CV_GpuBruteForceMatcherTest : public cvtest : : BaseTest <nl> - { <nl> - public : <nl> - CV_GpuBruteForceMatcherTest ( ) <nl> - { <nl> - } <nl> - <nl> - protected : <nl> - virtual void run ( int ) ; <nl> - <nl> - void emptyDataTest ( ) ; <nl> - void dataTest ( int dim ) ; <nl> - <nl> - void generateData ( GpuMat & query , GpuMat & train , int dim ) ; <nl> - <nl> - void matchTest ( const GpuMat & query , const GpuMat & train ) ; <nl> - void knnMatchTest ( const GpuMat & query , const GpuMat & train ) ; <nl> - void radiusMatchTest ( const GpuMat & query , const GpuMat & train ) ; <nl> - <nl> - private : <nl> - BruteForceMatcher_GPU < L2 < float > > dmatcher ; <nl> - <nl> - static const int queryDescCount = 300 ; / / must be even number because we split train data in some cases in two <nl> - static const int countFactor = 4 ; / / do not change it <nl> - } ; <nl> - <nl> - void CV_GpuBruteForceMatcherTest : : emptyDataTest ( ) <nl> - { <nl> - GpuMat queryDescriptors , trainDescriptors , mask ; <nl> - vector < GpuMat > trainDescriptorCollection , masks ; <nl> - vector < DMatch > matches ; <nl> - vector < vector < DMatch > > vmatches ; <nl> - <nl> - try <nl> - { <nl> - dmatcher . match ( queryDescriptors , trainDescriptors , matches , mask ) ; <nl> - } <nl> - catch ( . . . ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " match ( ) on empty descriptors must not generate exception ( 1 ) . \ n " ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - } <nl> - <nl> - try <nl> - { <nl> - dmatcher . knnMatch ( queryDescriptors , trainDescriptors , vmatches , 2 , mask ) ; <nl> - } <nl> - catch ( . . . ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " knnMatch ( ) on empty descriptors must not generate exception ( 1 ) . \ n " ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - } <nl> - <nl> - try <nl> - { <nl> - dmatcher . radiusMatch ( queryDescriptors , trainDescriptors , vmatches , 10 . f , mask ) ; <nl> - } <nl> - catch ( . . . ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " radiusMatch ( ) on empty descriptors must not generate exception ( 1 ) . \ n " ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - } <nl> - <nl> - try <nl> - { <nl> - dmatcher . add ( trainDescriptorCollection ) ; <nl> - } <nl> - catch ( . . . ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " add ( ) on empty descriptors must not generate exception . \ n " ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - } <nl> - <nl> - try <nl> - { <nl> - dmatcher . match ( queryDescriptors , matches , masks ) ; <nl> - } <nl> - catch ( . . . ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " match ( ) on empty descriptors must not generate exception ( 2 ) . \ n " ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - } <nl> - <nl> - try <nl> - { <nl> - dmatcher . knnMatch ( queryDescriptors , vmatches , 2 , masks ) ; <nl> - } <nl> - catch ( . . . ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " knnMatch ( ) on empty descriptors must not generate exception ( 2 ) . \ n " ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - } <nl> - <nl> - try <nl> - { <nl> - dmatcher . radiusMatch ( queryDescriptors , vmatches , 10 . f , masks ) ; <nl> - } <nl> - catch ( . . . ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " radiusMatch ( ) on empty descriptors must not generate exception ( 2 ) . \ n " ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - } <nl> - <nl> - } <nl> - <nl> - void CV_GpuBruteForceMatcherTest : : generateData ( GpuMat & queryGPU , GpuMat & trainGPU , int dim ) <nl> - { <nl> - Mat query , train ; <nl> - RNG & rng = ts - > get_rng ( ) ; <nl> - <nl> - / / Generate query descriptors randomly . <nl> - / / Descriptor vector elements are integer values . <nl> - Mat buf ( queryDescCount , dim , CV_32SC1 ) ; <nl> - rng . fill ( buf , RNG : : UNIFORM , Scalar : : all ( 0 ) , Scalar ( 3 ) ) ; <nl> - buf . convertTo ( query , CV_32FC1 ) ; <nl> - <nl> - / / Generate train decriptors as follows : <nl> - / / copy each query descriptor to train set countFactor times <nl> - / / and perturb some one element of the copied descriptors in <nl> - / / in ascending order . General boundaries of the perturbation <nl> - / / are ( 0 . f , 1 . f ) . <nl> - train . create ( query . rows * countFactor , query . cols , CV_32FC1 ) ; <nl> - float step = 1 . f / countFactor ; <nl> - for ( int qIdx = 0 ; qIdx < query . rows ; qIdx + + ) <nl> - { <nl> - Mat queryDescriptor = query . row ( qIdx ) ; <nl> - for ( int c = 0 ; c < countFactor ; c + + ) <nl> - { <nl> - int tIdx = qIdx * countFactor + c ; <nl> - Mat trainDescriptor = train . row ( tIdx ) ; <nl> - queryDescriptor . copyTo ( trainDescriptor ) ; <nl> - int elem = rng ( dim ) ; <nl> - float diff = rng . uniform ( step * c , step * ( c + 1 ) ) ; <nl> - trainDescriptor . at < float > ( 0 , elem ) + = diff ; <nl> - } <nl> - } <nl> - <nl> - queryGPU . upload ( query ) ; <nl> - trainGPU . upload ( train ) ; <nl> - } <nl> - <nl> - void CV_GpuBruteForceMatcherTest : : matchTest ( const GpuMat & query , const GpuMat & train ) <nl> - { <nl> - dmatcher . clear ( ) ; <nl> - <nl> - / / test const version of match ( ) <nl> - { <nl> - vector < DMatch > matches ; <nl> - dmatcher . match ( query , train , matches ) ; <nl> - <nl> - if ( ( int ) matches . size ( ) ! = queryDescCount ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " Incorrect matches count while test match ( ) function ( 1 ) . \ n " ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - } <nl> - else <nl> - { <nl> - int badCount = 0 ; <nl> - for ( size_t i = 0 ; i < matches . size ( ) ; i + + ) <nl> - { <nl> - DMatch match = matches [ i ] ; <nl> - if ( ( match . queryIdx ! = ( int ) i ) | | ( match . trainIdx ! = ( int ) i * countFactor ) | | ( match . imgIdx ! = 0 ) ) <nl> - badCount + + ; <nl> - } <nl> - if ( badCount > 0 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " % f - too large bad matches part while test match ( ) function ( 1 ) . \ n " , <nl> - ( float ) badCount / ( float ) queryDescCount ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - } <nl> - } <nl> - } <nl> - <nl> - / / test version of match ( ) with add ( ) <nl> - { <nl> - vector < DMatch > matches ; <nl> - / / make add ( ) twice to test such case <nl> - dmatcher . add ( vector < GpuMat > ( 1 , train . rowRange ( 0 , train . rows / 2 ) ) ) ; <nl> - dmatcher . add ( vector < GpuMat > ( 1 , train . rowRange ( train . rows / 2 , train . rows ) ) ) ; <nl> - / / prepare masks ( make first nearest match illegal ) <nl> - vector < GpuMat > masks ( 2 ) ; <nl> - for ( int mi = 0 ; mi < 2 ; mi + + ) <nl> - { <nl> - masks [ mi ] = GpuMat ( query . rows , train . rows / 2 , CV_8UC1 , Scalar : : all ( 1 ) ) ; <nl> - for ( int di = 0 ; di < queryDescCount / 2 ; di + + ) <nl> - masks [ mi ] . col ( di * countFactor ) . setTo ( Scalar : : all ( 0 ) ) ; <nl> - } <nl> - <nl> - dmatcher . match ( query , matches , masks ) ; <nl> - <nl> - if ( ( int ) matches . size ( ) ! = queryDescCount ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " Incorrect matches count while test match ( ) function ( 2 ) . \ n " ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - } <nl> - else <nl> - { <nl> - int badCount = 0 ; <nl> - for ( size_t i = 0 ; i < matches . size ( ) ; i + + ) <nl> - { <nl> - DMatch match = matches [ i ] ; <nl> - int shift = dmatcher . isMaskSupported ( ) ? 1 : 0 ; <nl> - { <nl> - if ( i < queryDescCount / 2 ) <nl> - { <nl> - if ( ( match . queryIdx ! = ( int ) i ) | | ( match . trainIdx ! = ( int ) i * countFactor + shift ) | | ( match . imgIdx ! = 0 ) ) <nl> - badCount + + ; <nl> - } <nl> - else <nl> - { <nl> - if ( ( match . queryIdx ! = ( int ) i ) | | ( match . trainIdx ! = ( ( int ) i - queryDescCount / 2 ) * countFactor + shift ) | | ( match . imgIdx ! = 1 ) ) <nl> - badCount + + ; <nl> - } <nl> - } <nl> - } <nl> - if ( badCount > 0 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " % f - too large bad matches part while test match ( ) function ( 2 ) . \ n " , <nl> - ( float ) badCount / ( float ) queryDescCount ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_BAD_ACCURACY ) ; <nl> - } <nl> - } <nl> - } <nl> - } <nl> - <nl> - void CV_GpuBruteForceMatcherTest : : knnMatchTest ( const GpuMat & query , const GpuMat & train ) <nl> - { <nl> - dmatcher . clear ( ) ; <nl> - <nl> - / / test const version of knnMatch ( ) <nl> - { <nl> - const int knn = 3 ; <nl> - <nl> - vector < vector < DMatch > > matches ; <nl> - dmatcher . knnMatch ( query , train , matches , knn ) ; <nl> - <nl> - if ( ( int ) matches . size ( ) ! = queryDescCount ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " Incorrect matches count while test knnMatch ( ) function ( 1 ) . \ n " ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - } <nl> - else <nl> - { <nl> - int badCount = 0 ; <nl> - for ( size_t i = 0 ; i < matches . size ( ) ; i + + ) <nl> - { <nl> - if ( ( int ) matches [ i ] . size ( ) ! = knn ) <nl> - badCount + + ; <nl> - else <nl> - { <nl> - int localBadCount = 0 ; <nl> - for ( int k = 0 ; k < knn ; k + + ) <nl> - { <nl> - DMatch match = matches [ i ] [ k ] ; <nl> - if ( ( match . queryIdx ! = ( int ) i ) | | ( match . trainIdx ! = ( int ) i * countFactor + k ) | | ( match . imgIdx ! = 0 ) ) <nl> - localBadCount + + ; <nl> - } <nl> - badCount + = localBadCount > 0 ? 1 : 0 ; <nl> - } <nl> - } <nl> - if ( badCount > 0 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " % f - too large bad matches part while test knnMatch ( ) function ( 1 ) . \ n " , <nl> - ( float ) badCount / ( float ) queryDescCount ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - } <nl> - } <nl> - } <nl> - <nl> - / / test version of knnMatch ( ) with add ( ) <nl> - { <nl> - const int knn = 2 ; <nl> - vector < vector < DMatch > > matches ; <nl> - / / make add ( ) twice to test such case <nl> - dmatcher . add ( vector < GpuMat > ( 1 , train . rowRange ( 0 , train . rows / 2 ) ) ) ; <nl> - dmatcher . add ( vector < GpuMat > ( 1 , train . rowRange ( train . rows / 2 , train . rows ) ) ) ; <nl> - / / prepare masks ( make first nearest match illegal ) <nl> - vector < GpuMat > masks ( 2 ) ; <nl> - for ( int mi = 0 ; mi < 2 ; mi + + ) <nl> - { <nl> - masks [ mi ] = GpuMat ( query . rows , train . rows / 2 , CV_8UC1 , Scalar : : all ( 1 ) ) ; <nl> - for ( int di = 0 ; di < queryDescCount / 2 ; di + + ) <nl> - masks [ mi ] . col ( di * countFactor ) . setTo ( Scalar : : all ( 0 ) ) ; <nl> - } <nl> - <nl> - dmatcher . knnMatch ( query , matches , knn , masks ) ; <nl> - <nl> - if ( ( int ) matches . size ( ) ! = queryDescCount ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " Incorrect matches count while test knnMatch ( ) function ( 2 ) . \ n " ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - } <nl> - else <nl> - { <nl> - int badCount = 0 ; <nl> - int shift = dmatcher . isMaskSupported ( ) ? 1 : 0 ; <nl> - for ( size_t i = 0 ; i < matches . size ( ) ; i + + ) <nl> - { <nl> - if ( ( int ) matches [ i ] . size ( ) ! = knn ) <nl> - badCount + + ; <nl> - else <nl> - { <nl> - int localBadCount = 0 ; <nl> - for ( int k = 0 ; k < knn ; k + + ) <nl> - { <nl> - DMatch match = matches [ i ] [ k ] ; <nl> - { <nl> - if ( i < queryDescCount / 2 ) <nl> - { <nl> - if ( ( match . queryIdx ! = ( int ) i ) | | ( match . trainIdx ! = ( int ) i * countFactor + k + shift ) | | <nl> - ( match . imgIdx ! = 0 ) ) <nl> - localBadCount + + ; <nl> - } <nl> - else <nl> - { <nl> - if ( ( match . queryIdx ! = ( int ) i ) | | ( match . trainIdx ! = ( ( int ) i - queryDescCount / 2 ) * countFactor + k + shift ) | | <nl> - ( match . imgIdx ! = 1 ) ) <nl> - localBadCount + + ; <nl> - } <nl> - } <nl> - } <nl> - badCount + = localBadCount > 0 ? 1 : 0 ; <nl> - } <nl> - } <nl> - if ( badCount > 0 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " % f - too large bad matches part while test knnMatch ( ) function ( 2 ) . \ n " , <nl> - ( float ) badCount / ( float ) queryDescCount ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_BAD_ACCURACY ) ; <nl> - } <nl> - } <nl> - } <nl> - } <nl> - <nl> - void CV_GpuBruteForceMatcherTest : : radiusMatchTest ( const GpuMat & query , const GpuMat & train ) <nl> - { <nl> - bool atomics_ok = TargetArchs : : builtWith ( GLOBAL_ATOMICS ) & & DeviceInfo ( ) . supports ( GLOBAL_ATOMICS ) ; <nl> - if ( ! atomics_ok ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " \ nCode and device atomics support is required for radiusMatch ( CC > = 1 . 1 ) " ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_GENERIC ) ; <nl> - return ; <nl> - } <nl> - <nl> - dmatcher . clear ( ) ; <nl> - / / test const version of match ( ) <nl> - { <nl> - const float radius = 1 . f / countFactor ; <nl> - vector < vector < DMatch > > matches ; <nl> - dmatcher . radiusMatch ( query , train , matches , radius ) ; <nl> - <nl> - if ( ( int ) matches . size ( ) ! = queryDescCount ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " Incorrect matches count while test radiusMatch ( ) function ( 1 ) . \ n " ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - } <nl> - else <nl> - { <nl> - int badCount = 0 ; <nl> - for ( size_t i = 0 ; i < matches . size ( ) ; i + + ) <nl> - { <nl> - if ( ( int ) matches [ i ] . size ( ) ! = 1 ) <nl> - badCount + + ; <nl> - else <nl> - { <nl> - DMatch match = matches [ i ] [ 0 ] ; <nl> - if ( ( match . queryIdx ! = ( int ) i ) | | ( match . trainIdx ! = ( int ) i * countFactor ) | | ( match . imgIdx ! = 0 ) ) <nl> - badCount + + ; <nl> - } <nl> - } <nl> - if ( badCount > 0 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " % f - too large bad matches part while test radiusMatch ( ) function ( 1 ) . \ n " , <nl> - ( float ) badCount / ( float ) queryDescCount ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - } <nl> - } <nl> - } <nl> - <nl> - / / test version of match ( ) with add ( ) <nl> - { <nl> - int n = 3 ; <nl> - const float radius = 1 . f / countFactor * n ; <nl> - vector < vector < DMatch > > matches ; <nl> - / / make add ( ) twice to test such case <nl> - dmatcher . add ( vector < GpuMat > ( 1 , train . rowRange ( 0 , train . rows / 2 ) ) ) ; <nl> - dmatcher . add ( vector < GpuMat > ( 1 , train . rowRange ( train . rows / 2 , train . rows ) ) ) ; <nl> - / / prepare masks ( make first nearest match illegal ) <nl> - vector < GpuMat > masks ( 2 ) ; <nl> - for ( int mi = 0 ; mi < 2 ; mi + + ) <nl> - { <nl> - masks [ mi ] = GpuMat ( query . rows , train . rows / 2 , CV_8UC1 , Scalar : : all ( 1 ) ) ; <nl> - for ( int di = 0 ; di < queryDescCount / 2 ; di + + ) <nl> - masks [ mi ] . col ( di * countFactor ) . setTo ( Scalar : : all ( 0 ) ) ; <nl> - } <nl> - <nl> - dmatcher . radiusMatch ( query , matches , radius , masks ) ; <nl> - <nl> - int curRes = cvtest : : TS : : OK ; <nl> - if ( ( int ) matches . size ( ) ! = queryDescCount ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " Incorrect matches count while test radiusMatch ( ) function ( 1 ) . \ n " ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - } <nl> - <nl> - int badCount = 0 ; <nl> - int shift = dmatcher . isMaskSupported ( ) ? 1 : 0 ; <nl> - int needMatchCount = dmatcher . isMaskSupported ( ) ? n - 1 : n ; <nl> - for ( size_t i = 0 ; i < matches . size ( ) ; i + + ) <nl> - { <nl> - if ( ( int ) matches [ i ] . size ( ) ! = needMatchCount ) <nl> - badCount + + ; <nl> - else <nl> - { <nl> - int localBadCount = 0 ; <nl> - for ( int k = 0 ; k < needMatchCount ; k + + ) <nl> - { <nl> - DMatch match = matches [ i ] [ k ] ; <nl> - { <nl> - if ( i < queryDescCount / 2 ) <nl> - { <nl> - if ( ( match . queryIdx ! = ( int ) i ) | | ( match . trainIdx ! = ( int ) i * countFactor + k + shift ) | | <nl> - ( match . imgIdx ! = 0 ) ) <nl> - localBadCount + + ; <nl> - } <nl> - else <nl> - { <nl> - if ( ( match . queryIdx ! = ( int ) i ) | | ( match . trainIdx ! = ( ( int ) i - queryDescCount / 2 ) * countFactor + k + shift ) | | <nl> - ( match . imgIdx ! = 1 ) ) <nl> - localBadCount + + ; <nl> - } <nl> - } <nl> - } <nl> - badCount + = localBadCount > 0 ? 1 : 0 ; <nl> - } <nl> - } <nl> - <nl> - if ( badCount > 0 ) <nl> - { <nl> - curRes = cvtest : : TS : : FAIL_INVALID_OUTPUT ; <nl> - ts - > printf ( cvtest : : TS : : LOG , " % f - too large bad matches part while test radiusMatch ( ) function ( 2 ) . \ n " , <nl> - ( float ) badCount / ( float ) queryDescCount ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_BAD_ACCURACY ) ; <nl> - } <nl> - } <nl> - } <nl> - <nl> - void CV_GpuBruteForceMatcherTest : : dataTest ( int dim ) <nl> - { <nl> - GpuMat query , train ; <nl> - generateData ( query , train , dim ) ; <nl> - <nl> - matchTest ( query , train ) ; <nl> - knnMatchTest ( query , train ) ; <nl> - radiusMatchTest ( query , train ) ; <nl> - <nl> - dmatcher . clear ( ) ; <nl> - } <nl> - <nl> - void CV_GpuBruteForceMatcherTest : : run ( int ) <nl> - { <nl> - emptyDataTest ( ) ; <nl> - <nl> - dataTest ( 50 ) ; <nl> - dataTest ( 64 ) ; <nl> - dataTest ( 100 ) ; <nl> - dataTest ( 128 ) ; <nl> - dataTest ( 200 ) ; <nl> - dataTest ( 256 ) ; <nl> - dataTest ( 300 ) ; <nl> - } <nl> - <nl> - TEST ( BruteForceMatcher , accuracy ) { CV_GpuBruteForceMatcherTest test ; test . safe_run ( ) ; } <nl> mmm a / modules / gpu / test / test_calib3d . cpp <nl> ppp b / modules / gpu / test / test_calib3d . cpp <nl> <nl> - / * M / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / <nl> - / / IMPORTANT : READ BEFORE DOWNLOADING , COPYING , INSTALLING OR USING . <nl> - / / <nl> - / / By downloading , copying , installing or using the software you agree to this license . <nl> - / / If you do not agree to this license , do not download , install , <nl> - / / copy or use the software . <nl> - / / <nl> - / / <nl> - / / Intel License Agreement <nl> - / / For Open Source Computer Vision Library <nl> - / / <nl> - / / Copyright ( C ) 2000 , Intel Corporation , all rights reserved . <nl> - / / Third party copyrights are property of their respective owners . <nl> - / / <nl> - / / Redistribution and use in source and binary forms , with or without modification , <nl> - / / are permitted provided that the following conditions are met : <nl> - / / <nl> - / / * Redistribution ' s of source code must retain the above copyright notice , <nl> - / / this list of conditions and the following disclaimer . <nl> - / / <nl> - / / * Redistribution ' s in binary form must reproduce the above copyright notice , <nl> - / / this list of conditions and the following disclaimer in the documentation <nl> - / / and / or other materials provided with the distribution . <nl> - / / <nl> - / / * The name of Intel Corporation may not be used to endorse or promote products <nl> - / / derived from this software without specific prior written permission . <nl> - / / <nl> - / / This software is provided by the copyright holders and contributors " as is " and <nl> - / / any express or implied warranties , including , but not limited to , the implied <nl> - / / warranties of merchantability and fitness for a particular purpose are disclaimed . <nl> - / / In no event shall the Intel Corporation or contributors be liable for any direct , <nl> - / / indirect , incidental , special , exemplary , or consequential damages <nl> - / / ( including , but not limited to , procurement of substitute goods or services ; <nl> - / / loss of use , data , or profits ; or business interruption ) however caused <nl> - / / and on any theory of liability , whether in contract , strict liability , <nl> - / / or tort ( including negligence or otherwise ) arising in any way out of <nl> - / / the use of this software , even if advised of the possibility of such damage . <nl> - / / <nl> - / / M * / <nl> - <nl> - # include " test_precomp . hpp " <nl> - <nl> - using namespace cv ; <nl> - using namespace cv : : gpu ; <nl> - using namespace cvtest ; <nl> - <nl> - TEST ( projectPoints , accuracy ) <nl> - { <nl> - RNG & rng = TS : : ptr ( ) - > get_rng ( ) ; <nl> - Mat src = randomMat ( rng , Size ( 1000 , 1 ) , CV_32FC3 , 0 , 10 , false ) ; <nl> - Mat rvec = randomMat ( rng , Size ( 3 , 1 ) , CV_32F , 0 , 1 , false ) ; <nl> - Mat tvec = randomMat ( rng , Size ( 3 , 1 ) , CV_32F , 0 , 1 , false ) ; <nl> - Mat camera_mat = randomMat ( rng , Size ( 3 , 3 ) , CV_32F , 0 , 1 , false ) ; <nl> - camera_mat . at < float > ( 0 , 1 ) = 0 . f ; <nl> - camera_mat . at < float > ( 1 , 0 ) = 0 . f ; <nl> - camera_mat . at < float > ( 2 , 0 ) = 0 . f ; <nl> - camera_mat . at < float > ( 2 , 1 ) = 0 . f ; <nl> - <nl> - vector < Point2f > dst ; <nl> - projectPoints ( src , rvec , tvec , camera_mat , Mat ( 1 , 8 , CV_32F , Scalar : : all ( 0 ) ) , dst ) ; <nl> - <nl> - GpuMat d_dst ; <nl> - projectPoints ( GpuMat ( src ) , rvec , tvec , camera_mat , Mat ( ) , d_dst ) ; <nl> - <nl> - ASSERT_EQ ( dst . size ( ) , ( size_t ) d_dst . cols ) ; <nl> - ASSERT_EQ ( 1 , d_dst . rows ) ; <nl> - ASSERT_EQ ( CV_32FC2 , d_dst . type ( ) ) ; <nl> - <nl> - Mat h_dst ( d_dst ) ; <nl> - for ( size_t i = 0 ; i < dst . size ( ) ; + + i ) <nl> - { <nl> - Point2f res_gold = dst [ i ] ; <nl> - Point2f res_actual = h_dst . at < Point2f > ( 0 , i ) ; <nl> - Point2f err = res_actual - res_gold ; <nl> - ASSERT_LT ( err . dot ( err ) / res_gold . dot ( res_gold ) , 1e - 3f ) ; <nl> - } <nl> - } <nl> - <nl> - <nl> - TEST ( transformPoints , accuracy ) <nl> - { <nl> - RNG & rng = TS : : ptr ( ) - > get_rng ( ) ; <nl> - Mat src = randomMat ( rng , Size ( 1000 , 1 ) , CV_32FC3 , 0 , 10 , false ) ; <nl> - Mat rvec = randomMat ( rng , Size ( 3 , 1 ) , CV_32F , 0 , 1 , false ) ; <nl> - Mat tvec = randomMat ( rng , Size ( 3 , 1 ) , CV_32F , 0 , 1 , false ) ; <nl> - <nl> - GpuMat d_dst ; <nl> - transformPoints ( GpuMat ( src ) , rvec , tvec , d_dst ) ; <nl> - ASSERT_TRUE ( src . size ( ) = = d_dst . size ( ) ) ; <nl> - ASSERT_EQ ( src . type ( ) , d_dst . type ( ) ) ; <nl> - <nl> - Mat h_dst ( d_dst ) ; <nl> - Mat rot ; <nl> - Rodrigues ( rvec , rot ) ; <nl> - for ( int i = 0 ; i < h_dst . cols ; + + i ) <nl> - { <nl> - Point3f p = src . at < Point3f > ( 0 , i ) ; <nl> - Point3f res_gold ( <nl> - rot . at < float > ( 0 , 0 ) * p . x + rot . at < float > ( 0 , 1 ) * p . y + rot . at < float > ( 0 , 2 ) * p . z + tvec . at < float > ( 0 , 0 ) , <nl> - rot . at < float > ( 1 , 0 ) * p . x + rot . at < float > ( 1 , 1 ) * p . y + rot . at < float > ( 1 , 2 ) * p . z + tvec . at < float > ( 0 , 1 ) , <nl> - rot . at < float > ( 2 , 0 ) * p . x + rot . at < float > ( 2 , 1 ) * p . y + rot . at < float > ( 2 , 2 ) * p . z + tvec . at < float > ( 0 , 2 ) ) ; <nl> - Point3f res_actual = h_dst . at < Point3f > ( 0 , i ) ; <nl> - Point3f err = res_actual - res_gold ; <nl> - ASSERT_LT ( err . dot ( err ) / res_gold . dot ( res_gold ) , 1e - 3f ) ; <nl> - } <nl> - } <nl> - <nl> - <nl> - TEST ( solvePnPRansac , accuracy ) <nl> - { <nl> - RNG & rng = TS : : ptr ( ) - > get_rng ( ) ; <nl> - <nl> - const int num_points = 5000 ; <nl> - Mat object = randomMat ( rng , Size ( num_points , 1 ) , CV_32FC3 , 0 , 100 , false ) ; <nl> - Mat camera_mat = randomMat ( rng , Size ( 3 , 3 ) , CV_32F , 0 . 5 , 1 , false ) ; <nl> - camera_mat . at < float > ( 0 , 1 ) = 0 . f ; <nl> - camera_mat . at < float > ( 1 , 0 ) = 0 . f ; <nl> - camera_mat . at < float > ( 2 , 0 ) = 0 . f ; <nl> - camera_mat . at < float > ( 2 , 1 ) = 0 . f ; <nl> - <nl> - Mat rvec_gold = randomMat ( rng , Size ( 3 , 1 ) , CV_32F , 0 , 1 , false ) ; <nl> - Mat tvec_gold = randomMat ( rng , Size ( 3 , 1 ) , CV_32F , 0 , 1 , false ) ; <nl> - <nl> - vector < Point2f > image_vec ; <nl> - projectPoints ( object , rvec_gold , tvec_gold , camera_mat , Mat ( 1 , 8 , CV_32F , Scalar : : all ( 0 ) ) , image_vec ) ; <nl> - Mat image ( 1 , image_vec . size ( ) , CV_32FC2 , & image_vec [ 0 ] ) ; <nl> - <nl> - Mat rvec , tvec ; <nl> - vector < int > inliers ; <nl> - gpu : : solvePnPRansac ( object , image , camera_mat , Mat ( 1 , 8 , CV_32F , Scalar : : all ( 0 ) ) , rvec , tvec , false , 200 , 2 . f , 100 , & inliers ) ; <nl> - <nl> - ASSERT_LE ( norm ( rvec - rvec_gold ) , 1e - 3f ) ; <nl> - ASSERT_LE ( norm ( tvec - tvec_gold ) , 1e - 3f ) ; <nl> - } <nl> + / * M / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / <nl> + / / IMPORTANT : READ BEFORE DOWNLOADING , COPYING , INSTALLING OR USING . <nl> + / / <nl> + / / By downloading , copying , installing or using the software you agree to this license . <nl> + / / If you do not agree to this license , do not download , install , <nl> + / / copy or use the software . <nl> + / / <nl> + / / <nl> + / / Intel License Agreement <nl> + / / For Open Source Computer Vision Library <nl> + / / <nl> + / / Copyright ( C ) 2000 , Intel Corporation , all rights reserved . <nl> + / / Third party copyrights are property of their respective owners . <nl> + / / <nl> + / / Redistribution and use in source and binary forms , with or without modification , <nl> + / / are permitted provided that the following conditions are met : <nl> + / / <nl> + / / * Redistribution ' s of source code must retain the above copyright notice , <nl> + / / this list of conditions and the following disclaimer . <nl> + / / <nl> + / / * Redistribution ' s in binary form must reproduce the above copyright notice , <nl> + / / this list of conditions and the following disclaimer in the documentation <nl> + / / and / or other materials provided with the distribution . <nl> + / / <nl> + / / * The name of Intel Corporation may not be used to endorse or promote products <nl> + / / derived from this software without specific prior written permission . <nl> + / / <nl> + / / This software is provided by the copyright holders and contributors " as is " and <nl> + / / any express or implied warranties , including , but not limited to , the implied <nl> + / / warranties of merchantability and fitness for a particular purpose are disclaimed . <nl> + / / In no event shall the Intel Corporation or contributors be liable for any direct , <nl> + / / indirect , incidental , special , exemplary , or consequential damages <nl> + / / ( including , but not limited to , procurement of substitute goods or services ; <nl> + / / loss of use , data , or profits ; or business interruption ) however caused <nl> + / / and on any theory of liability , whether in contract , strict liability , <nl> + / / or tort ( including negligence or otherwise ) arising in any way out of <nl> + / / the use of this software , even if advised of the possibility of such damage . <nl> + / / <nl> + / / M * / <nl> + <nl> + # include " test_precomp . hpp " <nl> + <nl> + # ifdef HAVE_CUDA <nl> + <nl> + struct StereoTest : testing : : TestWithParam < cv : : gpu : : DeviceInfo > <nl> + { <nl> + static cv : : Mat img_l ; <nl> + static cv : : Mat img_r ; <nl> + static cv : : Mat img_template ; <nl> + <nl> + static void TearDownTestCase ( ) <nl> + { <nl> + img_l . release ( ) ; <nl> + img_r . release ( ) ; <nl> + img_template . release ( ) ; <nl> + } <nl> + <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = GetParam ( ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + } <nl> + } ; <nl> + <nl> + cv : : Mat StereoTest : : img_l ; <nl> + cv : : Mat StereoTest : : img_r ; <nl> + cv : : Mat StereoTest : : img_template ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / BlockMatching <nl> + <nl> + struct StereoBlockMatching : StereoTest <nl> + { <nl> + static void SetUpTestCase ( ) <nl> + { <nl> + img_l = readImage ( " stereobm / aloe - L . png " , CV_LOAD_IMAGE_GRAYSCALE ) ; <nl> + img_r = readImage ( " stereobm / aloe - R . png " , CV_LOAD_IMAGE_GRAYSCALE ) ; <nl> + img_template = readImage ( " stereobm / aloe - disp . png " , CV_LOAD_IMAGE_GRAYSCALE ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( StereoBlockMatching , Regression ) <nl> + { <nl> + ASSERT_TRUE ( ! img_l . empty ( ) & & ! img_r . empty ( ) & & ! img_template . empty ( ) ) ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + <nl> + cv : : gpu : : GpuMat disp ; <nl> + cv : : gpu : : StereoBM_GPU bm ( 0 , 128 , 19 ) ; <nl> + <nl> + bm ( cv : : gpu : : GpuMat ( img_l ) , cv : : gpu : : GpuMat ( img_r ) , disp ) ; <nl> + <nl> + disp . convertTo ( disp , img_template . type ( ) ) ; <nl> + <nl> + ASSERT_EQ ( img_template . size ( ) , disp . size ( ) ) ; <nl> + double norm = cv : : norm ( img_template , ( cv : : Mat ) disp , cv : : NORM_INF ) ; <nl> + ASSERT_EQ ( 0 . 0 , norm ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( Calib3D , StereoBlockMatching , testing : : ValuesIn ( devices ( ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / BeliefPropagation <nl> + <nl> + struct StereoBeliefPropagation : StereoTest <nl> + { <nl> + static void SetUpTestCase ( ) <nl> + { <nl> + img_l = readImage ( " stereobp / aloe - L . png " ) ; <nl> + img_r = readImage ( " stereobp / aloe - R . png " ) ; <nl> + img_template = readImage ( " stereobp / aloe - disp . png " , CV_LOAD_IMAGE_GRAYSCALE ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( StereoBeliefPropagation , Regression ) <nl> + { <nl> + ASSERT_TRUE ( ! img_l . empty ( ) & & ! img_r . empty ( ) & & ! img_template . empty ( ) ) ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + <nl> + cv : : gpu : : GpuMat disp ; <nl> + cv : : gpu : : StereoBeliefPropagation bpm ( 64 , 8 , 2 , 25 , 0 . 1f , 15 , 1 , CV_16S ) ; <nl> + <nl> + bpm ( cv : : gpu : : GpuMat ( img_l ) , cv : : gpu : : GpuMat ( img_r ) , disp ) ; <nl> + <nl> + disp . convertTo ( disp , img_template . type ( ) ) ; <nl> + <nl> + ASSERT_EQ ( img_template . size ( ) , disp . size ( ) ) ; <nl> + double norm = cv : : norm ( img_template , ( cv : : Mat ) disp , cv : : NORM_INF ) ; <nl> + ASSERT_EQ ( 0 . 0 , norm ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( Calib3D , StereoBeliefPropagation , testing : : ValuesIn ( devices ( ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / ConstantSpaceBP <nl> + <nl> + struct StereoConstantSpaceBP : StereoTest <nl> + { <nl> + static void SetUpTestCase ( ) <nl> + { <nl> + img_l = readImage ( " csstereobp / aloe - L . png " ) ; <nl> + img_r = readImage ( " csstereobp / aloe - R . png " ) ; <nl> + } <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + StereoTest : : SetUp ( ) ; <nl> + <nl> + if ( supportFeature ( GetParam ( ) , cv : : gpu : : FEATURE_SET_COMPUTE_20 ) ) <nl> + img_template = readImage ( " csstereobp / aloe - disp . png " , CV_LOAD_IMAGE_GRAYSCALE ) ; <nl> + else <nl> + img_template = readImage ( " csstereobp / aloe - disp_CC1X . png " , CV_LOAD_IMAGE_GRAYSCALE ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( StereoConstantSpaceBP , Regression ) <nl> + { <nl> + ASSERT_TRUE ( ! img_l . empty ( ) & & ! img_r . empty ( ) & & ! img_template . empty ( ) ) ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + <nl> + cv : : gpu : : GpuMat disp ; <nl> + cv : : gpu : : StereoConstantSpaceBP bpm ( 128 , 16 , 4 , 4 ) ; <nl> + <nl> + bpm ( cv : : gpu : : GpuMat ( img_l ) , cv : : gpu : : GpuMat ( img_r ) , disp ) ; <nl> + <nl> + disp . convertTo ( disp , img_template . type ( ) ) ; <nl> + <nl> + ASSERT_EQ ( img_template . size ( ) , disp . size ( ) ) ; <nl> + double norm = cv : : norm ( img_template , ( cv : : Mat ) disp , cv : : NORM_INF ) ; <nl> + ASSERT_EQ ( 0 . 0 , norm ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( Calib3D , StereoConstantSpaceBP , testing : : ValuesIn ( devices ( ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / projectPoints <nl> + <nl> + struct ProjectPoints : testing : : TestWithParam < cv : : gpu : : DeviceInfo > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + <nl> + cv : : Mat src ; <nl> + cv : : Mat rvec ; <nl> + cv : : Mat tvec ; <nl> + cv : : Mat camera_mat ; <nl> + <nl> + std : : vector < cv : : Point2f > dst_gold ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = GetParam ( ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + src = cvtest : : randomMat ( rng , cv : : Size ( 1000 , 1 ) , CV_32FC3 , 0 , 10 , false ) ; <nl> + rvec = cvtest : : randomMat ( rng , cv : : Size ( 3 , 1 ) , CV_32F , 0 , 1 , false ) ; <nl> + tvec = cvtest : : randomMat ( rng , cv : : Size ( 3 , 1 ) , CV_32F , 0 , 1 , false ) ; <nl> + camera_mat = cvtest : : randomMat ( rng , cv : : Size ( 3 , 3 ) , CV_32F , 0 , 1 , false ) ; <nl> + camera_mat . at < float > ( 0 , 1 ) = 0 . f ; <nl> + camera_mat . at < float > ( 1 , 0 ) = 0 . f ; <nl> + camera_mat . at < float > ( 2 , 0 ) = 0 . f ; <nl> + camera_mat . at < float > ( 2 , 1 ) = 0 . f ; <nl> + <nl> + cv : : projectPoints ( src , rvec , tvec , camera_mat , cv : : Mat ( 1 , 8 , CV_32F , cv : : Scalar : : all ( 0 ) ) , dst_gold ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( ProjectPoints , Accuracy ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat d_dst ; <nl> + <nl> + cv : : gpu : : projectPoints ( cv : : gpu : : GpuMat ( src ) , rvec , tvec , camera_mat , cv : : Mat ( ) , d_dst ) ; <nl> + <nl> + d_dst . download ( dst ) ; <nl> + ) ; <nl> + <nl> + ASSERT_EQ ( dst_gold . size ( ) , dst . cols ) ; <nl> + ASSERT_EQ ( 1 , dst . rows ) ; <nl> + ASSERT_EQ ( CV_32FC2 , dst . type ( ) ) ; <nl> + <nl> + for ( size_t i = 0 ; i < dst_gold . size ( ) ; + + i ) <nl> + { <nl> + cv : : Point2f res_gold = dst_gold [ i ] ; <nl> + cv : : Point2f res_actual = dst . at < cv : : Point2f > ( 0 , i ) ; <nl> + cv : : Point2f err = res_actual - res_gold ; <nl> + <nl> + ASSERT_LE ( err . dot ( err ) / res_gold . dot ( res_gold ) , 1e - 3f ) ; <nl> + } <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( Calib3D , ProjectPoints , testing : : ValuesIn ( devices ( ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / transformPoints <nl> + <nl> + struct TransformPoints : testing : : TestWithParam < cv : : gpu : : DeviceInfo > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + <nl> + cv : : Mat src ; <nl> + cv : : Mat rvec ; <nl> + cv : : Mat tvec ; <nl> + cv : : Mat rot ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = GetParam ( ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + src = cvtest : : randomMat ( rng , cv : : Size ( 1000 , 1 ) , CV_32FC3 , 0 , 10 , false ) ; <nl> + rvec = cvtest : : randomMat ( rng , cv : : Size ( 3 , 1 ) , CV_32F , 0 , 1 , false ) ; <nl> + tvec = cvtest : : randomMat ( rng , cv : : Size ( 3 , 1 ) , CV_32F , 0 , 1 , false ) ; <nl> + <nl> + cv : : Rodrigues ( rvec , rot ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( TransformPoints , Accuracy ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat d_dst ; <nl> + <nl> + cv : : gpu : : transformPoints ( cv : : gpu : : GpuMat ( src ) , rvec , tvec , d_dst ) ; <nl> + <nl> + d_dst . download ( dst ) ; <nl> + ) ; <nl> + <nl> + ASSERT_EQ ( src . size ( ) , dst . size ( ) ) ; <nl> + ASSERT_EQ ( src . type ( ) , dst . type ( ) ) ; <nl> + <nl> + for ( int i = 0 ; i < dst . cols ; + + i ) <nl> + { <nl> + cv : : Point3f p = src . at < cv : : Point3f > ( 0 , i ) ; <nl> + cv : : Point3f res_gold ( <nl> + rot . at < float > ( 0 , 0 ) * p . x + rot . at < float > ( 0 , 1 ) * p . y + rot . at < float > ( 0 , 2 ) * p . z + tvec . at < float > ( 0 , 0 ) , <nl> + rot . at < float > ( 1 , 0 ) * p . x + rot . at < float > ( 1 , 1 ) * p . y + rot . at < float > ( 1 , 2 ) * p . z + tvec . at < float > ( 0 , 1 ) , <nl> + rot . at < float > ( 2 , 0 ) * p . x + rot . at < float > ( 2 , 1 ) * p . y + rot . at < float > ( 2 , 2 ) * p . z + tvec . at < float > ( 0 , 2 ) ) ; <nl> + cv : : Point3f res_actual = dst . at < cv : : Point3f > ( 0 , i ) ; <nl> + cv : : Point3f err = res_actual - res_gold ; <nl> + <nl> + ASSERT_LE ( err . dot ( err ) / res_gold . dot ( res_gold ) , 1e - 3f ) ; <nl> + } <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( Calib3D , TransformPoints , testing : : ValuesIn ( devices ( ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / solvePnPRansac <nl> + <nl> + struct SolvePnPRansac : testing : : TestWithParam < cv : : gpu : : DeviceInfo > <nl> + { <nl> + static const int num_points = 5000 ; <nl> + <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + <nl> + cv : : Mat object ; <nl> + cv : : Mat camera_mat ; <nl> + std : : vector < cv : : Point2f > image_vec ; <nl> + <nl> + cv : : Mat rvec_gold ; <nl> + cv : : Mat tvec_gold ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = GetParam ( ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + object = cvtest : : randomMat ( rng , cv : : Size ( num_points , 1 ) , CV_32FC3 , 0 , 100 , false ) ; <nl> + camera_mat = cvtest : : randomMat ( rng , cv : : Size ( 3 , 3 ) , CV_32F , 0 . 5 , 1 , false ) ; <nl> + camera_mat . at < float > ( 0 , 1 ) = 0 . f ; <nl> + camera_mat . at < float > ( 1 , 0 ) = 0 . f ; <nl> + camera_mat . at < float > ( 2 , 0 ) = 0 . f ; <nl> + camera_mat . at < float > ( 2 , 1 ) = 0 . f ; <nl> + <nl> + rvec_gold = cvtest : : randomMat ( rng , cv : : Size ( 3 , 1 ) , CV_32F , 0 , 1 , false ) ; <nl> + tvec_gold = cvtest : : randomMat ( rng , cv : : Size ( 3 , 1 ) , CV_32F , 0 , 1 , false ) ; <nl> + <nl> + cv : : projectPoints ( object , rvec_gold , tvec_gold , camera_mat , cv : : Mat ( 1 , 8 , CV_32F , cv : : Scalar : : all ( 0 ) ) , image_vec ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( SolvePnPRansac , Accuracy ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + <nl> + cv : : Mat rvec , tvec ; <nl> + std : : vector < int > inliers ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : solvePnPRansac ( object , cv : : Mat ( 1 , image_vec . size ( ) , CV_32FC2 , & image_vec [ 0 ] ) , camera_mat , <nl> + cv : : Mat ( 1 , 8 , CV_32F , cv : : Scalar : : all ( 0 ) ) , rvec , tvec , false , 200 , 2 . f , 100 , & inliers ) ; <nl> + ) ; <nl> + <nl> + ASSERT_LE ( cv : : norm ( rvec - rvec_gold ) , 1e - 3f ) ; <nl> + ASSERT_LE ( cv : : norm ( tvec - tvec_gold ) , 1e - 3f ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( Calib3D , SolvePnPRansac , testing : : ValuesIn ( devices ( ) ) ) ; <nl> + <nl> + # endif / / HAVE_CUDA <nl> deleted file mode 100644 <nl> index f346bef428e . . 00000000000 <nl> mmm a / modules / gpu / test / test_dft_routines . cpp <nl> ppp / dev / null <nl> <nl> - / * M / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / <nl> - / / IMPORTANT : READ BEFORE DOWNLOADING , COPYING , INSTALLING OR USING . <nl> - / / <nl> - / / By downloading , copying , installing or using the software you agree to this license . <nl> - / / If you do not agree to this license , do not download , install , <nl> - / / copy or use the software . <nl> - / / <nl> - / / <nl> - / / Intel License Agreement <nl> - / / For Open Source Computer Vision Library <nl> - / / <nl> - / / Copyright ( C ) 2000 , Intel Corporation , all rights reserved . <nl> - / / Third party copyrights are property of their respective owners . <nl> - / / <nl> - / / Redistribution and use in source and binary forms , with or without modification , <nl> - / / are permitted provided that the following conditions are met : <nl> - / / <nl> - / / * Redistribution ' s of source code must retain the above copyright notice , <nl> - / / this list of conditions and the following disclaimer . <nl> - / / <nl> - / / * Redistribution ' s in binary form must reproduce the above copyright notice , <nl> - / / this list of conditions and the following disclaimer in the documentation <nl> - / / and / or other materials provided with the distribution . <nl> - / / <nl> - / / * The name of Intel Corporation may not be used to endorse or promote products <nl> - / / derived from this software without specific prior written permission . <nl> - / / <nl> - / / This software is provided by the copyright holders and contributors " as is " and <nl> - / / any express or implied warranties , including , but not limited to , the implied <nl> - / / warranties of merchantability and fitness for a particular purpose are disclaimed . <nl> - / / In no event shall the Intel Corporation or contributors be liable for any direct , <nl> - / / indirect , incidental , special , exemplary , or consequential damages <nl> - / / ( including , but not limited to , procurement of substitute goods or services ; <nl> - / / loss of use , data , or profits ; or business interruption ) however caused <nl> - / / and on any theory of liability , whether in contract , strict liability , <nl> - / / or tort ( including negligence or otherwise ) arising in any way out of <nl> - / / the use of this software , even if advised of the possibility of such damage . <nl> - / / <nl> - / / M * / <nl> - <nl> - # include " test_precomp . hpp " <nl> - <nl> - using namespace cv ; <nl> - using namespace cv : : gpu ; <nl> - using namespace std ; <nl> - <nl> - struct CV_GpuMulSpectrumsTest : cvtest : : BaseTest <nl> - { <nl> - CV_GpuMulSpectrumsTest ( ) { } <nl> - <nl> - void run ( int ) <nl> - { <nl> - test ( 0 ) ; <nl> - testConj ( 0 ) ; <nl> - testScaled ( 0 ) ; <nl> - testScaledConj ( 0 ) ; <nl> - test ( DFT_ROWS ) ; <nl> - testConj ( DFT_ROWS ) ; <nl> - testScaled ( DFT_ROWS ) ; <nl> - testScaledConj ( DFT_ROWS ) ; <nl> - } <nl> - <nl> - void gen ( int cols , int rows , Mat & mat ) <nl> - { <nl> - RNG rng ; <nl> - mat . create ( rows , cols , CV_32FC2 ) ; <nl> - rng . fill ( mat , RNG : : UNIFORM , Scalar : : all ( 0 . f ) , Scalar : : all ( 10 . f ) ) ; <nl> - } <nl> - <nl> - bool cmp ( const Mat & gold , const Mat & mine , float max_err = 1e - 3f ) <nl> - { <nl> - if ( gold . size ( ) ! = mine . size ( ) ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " bad sizes : gold : % d d % , mine : % d % d \ n " , gold . cols , gold . rows , mine . cols , mine . rows ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return false ; <nl> - } <nl> - if ( gold . type ( ) ! = mine . type ( ) ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " bad types : gold = % d , mine = % d \ n " , gold . type ( ) , mine . type ( ) ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return false ; <nl> - } <nl> - for ( int i = 0 ; i < gold . rows ; + + i ) <nl> - { <nl> - for ( int j = 0 ; j < gold . cols * 2 ; + + j ) <nl> - { <nl> - float gold_ = gold . at < float > ( i , j ) ; <nl> - float mine_ = mine . at < float > ( i , j ) ; <nl> - if ( fabs ( gold_ - mine_ ) > max_err ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " bad values at % d % d : gold = % f , mine = % f \ n " , j , i , gold_ , mine_ ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return false ; <nl> - } <nl> - } <nl> - } <nl> - return true ; <nl> - } <nl> - <nl> - bool cmpScaled ( const Mat & gold , const Mat & mine , float scale , float max_err = 1e - 3f ) <nl> - { <nl> - if ( gold . size ( ) ! = mine . size ( ) ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " bad sizes : gold : % d d % , mine : % d % d \ n " , gold . cols , gold . rows , mine . cols , mine . rows ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return false ; <nl> - } <nl> - if ( gold . type ( ) ! = mine . type ( ) ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " bad types : gold = % d , mine = % d \ n " , gold . type ( ) , mine . type ( ) ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return false ; <nl> - } <nl> - for ( int i = 0 ; i < gold . rows ; + + i ) <nl> - { <nl> - for ( int j = 0 ; j < gold . cols * 2 ; + + j ) <nl> - { <nl> - float gold_ = gold . at < float > ( i , j ) * scale ; <nl> - float mine_ = mine . at < float > ( i , j ) ; <nl> - if ( fabs ( gold_ - mine_ ) > max_err ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " bad values at % d % d : gold = % f , mine = % f \ n " , j , i , gold_ , mine_ ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return false ; <nl> - } <nl> - } <nl> - } <nl> - return true ; <nl> - } <nl> - <nl> - void test ( int flags ) <nl> - { <nl> - int cols = 1 + rand ( ) % 100 , rows = 1 + rand ( ) % 1000 ; <nl> - <nl> - Mat a , b ; <nl> - gen ( cols , rows , a ) ; <nl> - gen ( cols , rows , b ) ; <nl> - <nl> - Mat c_gold ; <nl> - mulSpectrums ( a , b , c_gold , flags , false ) ; <nl> - <nl> - GpuMat d_c ; <nl> - mulSpectrums ( GpuMat ( a ) , GpuMat ( b ) , d_c , flags , false ) ; <nl> - <nl> - if ( ! cmp ( c_gold , Mat ( d_c ) ) ) <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " test failed : cols = % d , rows = % d , flags = % d \ n " , cols , rows , flags ) ; <nl> - } <nl> - <nl> - void testConj ( int flags ) <nl> - { <nl> - int cols = 1 + rand ( ) % 100 , rows = 1 + rand ( ) % 1000 ; <nl> - <nl> - Mat a , b ; <nl> - gen ( cols , rows , a ) ; <nl> - gen ( cols , rows , b ) ; <nl> - <nl> - Mat c_gold ; <nl> - mulSpectrums ( a , b , c_gold , flags , true ) ; <nl> - <nl> - GpuMat d_c ; <nl> - mulSpectrums ( GpuMat ( a ) , GpuMat ( b ) , d_c , flags , true ) ; <nl> - <nl> - if ( ! cmp ( c_gold , Mat ( d_c ) ) ) <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " testConj failed : cols = % d , rows = % d , flags = % d \ n " , cols , rows , flags ) ; <nl> - } <nl> - <nl> - void testScaled ( int flags ) <nl> - { <nl> - int cols = 1 + rand ( ) % 100 , rows = 1 + rand ( ) % 1000 ; <nl> - <nl> - Mat a , b ; <nl> - gen ( cols , rows , a ) ; <nl> - gen ( cols , rows , b ) ; <nl> - float scale = 1 . f / a . size ( ) . area ( ) ; <nl> - <nl> - Mat c_gold ; <nl> - mulSpectrums ( a , b , c_gold , flags , false ) ; <nl> - <nl> - GpuMat d_c ; <nl> - mulAndScaleSpectrums ( GpuMat ( a ) , GpuMat ( b ) , d_c , flags , scale , false ) ; <nl> - <nl> - if ( ! cmpScaled ( c_gold , Mat ( d_c ) , scale ) ) <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " testScaled failed : cols = % d , rows = % d , flags = % d \ n " , cols , rows , flags ) ; <nl> - } <nl> - <nl> - void testScaledConj ( int flags ) <nl> - { <nl> - int cols = 1 + rand ( ) % 100 , rows = 1 + rand ( ) % 1000 ; <nl> - <nl> - Mat a , b ; <nl> - gen ( cols , rows , a ) ; <nl> - gen ( cols , rows , b ) ; <nl> - float scale = 1 . f / a . size ( ) . area ( ) ; <nl> - <nl> - Mat c_gold ; <nl> - mulSpectrums ( a , b , c_gold , flags , true ) ; <nl> - <nl> - GpuMat d_c ; <nl> - mulAndScaleSpectrums ( GpuMat ( a ) , GpuMat ( b ) , d_c , flags , scale , true ) ; <nl> - <nl> - if ( ! cmpScaled ( c_gold , Mat ( d_c ) , scale ) ) <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " testScaledConj failed : cols = % d , rows = % d , flags = % D \ n " , cols , rows , flags ) ; <nl> - } <nl> - } CV_GpuMulSpectrumsTest_inst ; <nl> - <nl> - <nl> - struct CV_GpuDftTest : cvtest : : BaseTest <nl> - { <nl> - CV_GpuDftTest ( ) { } <nl> - <nl> - void run ( int ) <nl> - { <nl> - srand ( 0 ) ; <nl> - int cols = 2 + rand ( ) % 100 , rows = 2 + rand ( ) % 100 ; <nl> - <nl> - for ( int i = 0 ; i < 2 ; + + i ) <nl> - { <nl> - bool inplace = i ! = 0 ; <nl> - testC2C ( " no flags " , cols , rows , 0 , inplace ) ; <nl> - testC2C ( " no flags 0 1 " , cols , rows + 1 , 0 , inplace ) ; <nl> - testC2C ( " no flags 1 0 " , cols , rows + 1 , 0 , inplace ) ; <nl> - testC2C ( " no flags 1 1 " , cols + 1 , rows , 0 , inplace ) ; <nl> - testC2C ( " DFT_INVERSE " , cols , rows , DFT_INVERSE , inplace ) ; <nl> - testC2C ( " DFT_ROWS " , cols , rows , DFT_ROWS , inplace ) ; <nl> - testC2C ( " single col " , 1 , rows , 0 , inplace ) ; <nl> - testC2C ( " single row " , cols , 1 , 0 , inplace ) ; <nl> - testC2C ( " single col inversed " , 1 , rows , DFT_INVERSE , inplace ) ; <nl> - testC2C ( " single row inversed " , cols , 1 , DFT_INVERSE , inplace ) ; <nl> - testC2C ( " single row DFT_ROWS " , cols , 1 , DFT_ROWS , inplace ) ; <nl> - testC2C ( " size 1 2 " , 1 , 2 , 0 , inplace ) ; <nl> - testC2C ( " size 2 1 " , 2 , 1 , 0 , inplace ) ; <nl> - } <nl> - <nl> - testR2CThenC2R ( " sanity " , cols , rows ) ; <nl> - testR2CThenC2R ( " sanity 0 1 " , cols , rows + 1 ) ; <nl> - testR2CThenC2R ( " sanity 1 0 " , cols + 1 , rows ) ; <nl> - testR2CThenC2R ( " sanity 1 1 " , cols + 1 , rows + 1 ) ; <nl> - testR2CThenC2R ( " single col " , 1 , rows ) ; <nl> - testR2CThenC2R ( " single col 1 " , 1 , rows + 1 ) ; <nl> - testR2CThenC2R ( " single row " , cols , 1 ) ; <nl> - testR2CThenC2R ( " single row 1 " , cols + 1 , 1 ) ; <nl> - <nl> - testR2CThenC2R ( " sanity " , cols , rows , true ) ; <nl> - testR2CThenC2R ( " sanity 0 1 " , cols , rows + 1 , true ) ; <nl> - testR2CThenC2R ( " sanity 1 0 " , cols + 1 , rows , true ) ; <nl> - testR2CThenC2R ( " sanity 1 1 " , cols + 1 , rows + 1 , true ) ; <nl> - testR2CThenC2R ( " single row " , cols , 1 , true ) ; <nl> - testR2CThenC2R ( " single row 1 " , cols + 1 , 1 , true ) ; <nl> - } <nl> - <nl> - void gen ( int cols , int rows , int cn , Mat & mat ) <nl> - { <nl> - RNG rng ( 1 ) ; <nl> - mat . create ( rows , cols , CV_MAKETYPE ( CV_32F , cn ) ) ; <nl> - rng . fill ( mat , RNG : : UNIFORM , Scalar : : all ( 0 . f ) , Scalar : : all ( 10 . f ) ) ; <nl> - } <nl> - <nl> - bool cmp ( const Mat & gold , const Mat & mine , float max_err = 1e - 3f ) <nl> - { <nl> - if ( gold . size ( ) ! = mine . size ( ) ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " bad sizes : gold : % d % d , mine : % d % d \ n " , gold . cols , gold . rows , mine . cols , mine . rows ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return false ; <nl> - } <nl> - if ( gold . depth ( ) ! = mine . depth ( ) ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " bad depth : gold = % d , mine = % d \ n " , gold . depth ( ) , mine . depth ( ) ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return false ; <nl> - } <nl> - if ( gold . channels ( ) ! = mine . channels ( ) ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " bad channel count : gold = % d , mine = % d \ n " , gold . channels ( ) , mine . channels ( ) ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return false ; <nl> - } <nl> - for ( int i = 0 ; i < gold . rows ; + + i ) <nl> - { <nl> - for ( int j = 0 ; j < gold . cols * gold . channels ( ) ; + + j ) <nl> - { <nl> - float gold_ = gold . at < float > ( i , j ) ; <nl> - float mine_ = mine . at < float > ( i , j ) ; <nl> - if ( fabs ( gold_ - mine_ ) > max_err ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " bad values at % d % d : gold = % f , mine = % f \ n " , j / gold . channels ( ) , i , gold_ , mine_ ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return false ; <nl> - } <nl> - } <nl> - } <nl> - return true ; <nl> - } <nl> - <nl> - void testC2C ( const std : : string & hint , int cols , int rows , int flags , bool inplace = false ) <nl> - { <nl> - Mat a ; <nl> - gen ( cols , rows , 2 , a ) ; <nl> - <nl> - Mat b_gold ; <nl> - dft ( a , b_gold , flags ) ; <nl> - <nl> - GpuMat d_b ; <nl> - GpuMat d_b_data ; <nl> - if ( inplace ) <nl> - { <nl> - d_b_data . create ( 1 , a . size ( ) . area ( ) , CV_32FC2 ) ; <nl> - d_b = GpuMat ( a . rows , a . cols , CV_32FC2 , d_b_data . ptr ( ) , a . cols * d_b_data . elemSize ( ) ) ; <nl> - } <nl> - <nl> - dft ( GpuMat ( a ) , d_b , Size ( cols , rows ) , flags ) ; <nl> - <nl> - bool ok = true ; <nl> - if ( ok & & inplace & & d_b . ptr ( ) ! = d_b_data . ptr ( ) ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " unnecessary reallocation was done \ n " ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - ok = false ; <nl> - } <nl> - if ( ok & & d_b . depth ( ) ! = CV_32F ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " bad depth : % d \ n " , d_b . depth ( ) ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - ok = false ; <nl> - } <nl> - if ( ok & & d_b . channels ( ) ! = 2 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " bad channel count : % d \ n " , d_b . channels ( ) ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - ok = false ; <nl> - } <nl> - if ( ok ) ok = cmp ( b_gold , Mat ( d_b ) , rows * cols * 1e - 4f ) ; <nl> - if ( ! ok ) <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " testC2C failed : hint = % s , cols = % d , rows = % d , flags = % d , inplace = % d \ n " , <nl> - hint . c_str ( ) , cols , rows , flags , inplace ) ; <nl> - } <nl> - <nl> - void testR2CThenC2R ( const std : : string & hint , int cols , int rows , bool inplace = false ) <nl> - { <nl> - Mat a ; <nl> - gen ( cols , rows , 1 , a ) ; <nl> - <nl> - bool ok = true ; <nl> - <nl> - GpuMat d_b , d_c ; <nl> - GpuMat d_b_data , d_c_data ; <nl> - if ( inplace ) <nl> - { <nl> - if ( a . cols = = 1 ) <nl> - { <nl> - d_b_data . create ( 1 , ( a . rows / 2 + 1 ) * a . cols , CV_32FC2 ) ; <nl> - d_b = GpuMat ( a . rows / 2 + 1 , a . cols , CV_32FC2 , d_b_data . ptr ( ) , a . cols * d_b_data . elemSize ( ) ) ; <nl> - } <nl> - else <nl> - { <nl> - d_b_data . create ( 1 , a . rows * ( a . cols / 2 + 1 ) , CV_32FC2 ) ; <nl> - d_b = GpuMat ( a . rows , a . cols / 2 + 1 , CV_32FC2 , d_b_data . ptr ( ) , ( a . cols / 2 + 1 ) * d_b_data . elemSize ( ) ) ; <nl> - } <nl> - d_c_data . create ( 1 , a . size ( ) . area ( ) , CV_32F ) ; <nl> - d_c = GpuMat ( a . rows , a . cols , CV_32F , d_c_data . ptr ( ) , a . cols * d_c_data . elemSize ( ) ) ; <nl> - } <nl> - <nl> - dft ( GpuMat ( a ) , d_b , Size ( cols , rows ) , 0 ) ; <nl> - dft ( d_b , d_c , Size ( cols , rows ) , DFT_REAL_OUTPUT | DFT_SCALE ) ; <nl> - <nl> - if ( ok & & inplace & & d_b . ptr ( ) ! = d_b_data . ptr ( ) ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " unnecessary reallocation was done for b \ n " ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - ok = false ; <nl> - } <nl> - if ( ok & & inplace & & d_c . ptr ( ) ! = d_c_data . ptr ( ) ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " unnecessary reallocation was done for c \ n " ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - ok = false ; <nl> - } <nl> - if ( ok & & d_c . depth ( ) ! = CV_32F ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " bad depth : % d \ n " , d_c . depth ( ) ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - ok = false ; <nl> - } <nl> - if ( ok & & d_c . channels ( ) ! = 1 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " bad channel count : % d \ n " , d_c . channels ( ) ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - ok = false ; <nl> - } <nl> - if ( ok ) ok = cmp ( a , Mat ( d_c ) , rows * cols * 1e - 5f ) ; <nl> - if ( ! ok ) <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " testR2CThenC2R failed : hint = % s , cols = % d , rows = % d , inplace = % d \ n " , <nl> - hint . c_str ( ) , cols , rows , inplace ) ; <nl> - } <nl> - } ; <nl> - <nl> - TEST ( dft , accuracy ) { CV_GpuDftTest test ; test . safe_run ( ) ; } <nl> mmm a / modules / gpu / test / test_features2d . cpp <nl> ppp b / modules / gpu / test / test_features2d . cpp <nl> <nl> / / M * / <nl> <nl> # include " test_precomp . hpp " <nl> - # include < string > <nl> <nl> - using namespace cv ; <nl> - using namespace cv : : gpu ; <nl> - using namespace std ; <nl> + # ifdef HAVE_CUDA <nl> <nl> - const string FEATURES2D_DIR = " features2d " ; <nl> - const string IMAGE_FILENAME = " aloe . png " ; <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / SURF <nl> <nl> - class CV_GPU_SURFTest : public cvtest : : BaseTest <nl> + struct SURF : testing : : TestWithParam < cv : : gpu : : DeviceInfo > <nl> { <nl> - public : <nl> - CV_GPU_SURFTest ( ) <nl> + static cv : : Mat image ; <nl> + static cv : : Mat mask ; <nl> + static std : : vector < cv : : KeyPoint > keypoints_gold ; <nl> + static std : : vector < float > descriptors_gold ; <nl> + <nl> + static void SetUpTestCase ( ) <nl> + { <nl> + image = readImage ( " features2d / aloe . png " , CV_LOAD_IMAGE_GRAYSCALE ) ; <nl> + <nl> + mask = cv : : Mat ( image . size ( ) , CV_8UC1 , cv : : Scalar : : all ( 1 ) ) ; <nl> + mask ( cv : : Range ( 0 , image . rows / 2 ) , cv : : Range ( 0 , image . cols / 2 ) ) . setTo ( cv : : Scalar : : all ( 0 ) ) ; <nl> + <nl> + cv : : SURF fdetector_gold ; fdetector_gold . extended = false ; <nl> + fdetector_gold ( image , mask , keypoints_gold , descriptors_gold ) ; <nl> + } <nl> + <nl> + static void TearDownTestCase ( ) <nl> { <nl> + image . release ( ) ; <nl> + mask . release ( ) ; <nl> + keypoints_gold . clear ( ) ; <nl> + descriptors_gold . clear ( ) ; <nl> } <nl> <nl> - protected : <nl> - bool isSimilarKeypoints ( const KeyPoint & p1 , const KeyPoint & p2 ) ; <nl> - int getValidCount ( const vector < KeyPoint > & keypoints1 , const vector < KeyPoint > & keypoints2 , const vector < DMatch > & matches ) ; <nl> - void compareKeypointSets ( const vector < KeyPoint > & validKeypoints , const vector < KeyPoint > & calcKeypoints , <nl> - const Mat & validDescriptors , const Mat & calcDescriptors ) ; <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = GetParam ( ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + } <nl> <nl> - void emptyDataTest ( ) ; <nl> - void accuracyTest ( ) ; <nl> + bool isSimilarKeypoints ( const cv : : KeyPoint & p1 , const cv : : KeyPoint & p2 ) <nl> + { <nl> + const float maxPtDif = 1 . f ; <nl> + const float maxSizeDif = 1 . f ; <nl> + const float maxAngleDif = 2 . f ; <nl> + const float maxResponseDif = 0 . 1f ; <nl> <nl> - virtual void run ( int ) ; <nl> + float dist = ( float ) cv : : norm ( p1 . pt - p2 . pt ) ; <nl> + return ( dist < maxPtDif & & <nl> + fabs ( p1 . size - p2 . size ) < maxSizeDif & & <nl> + abs ( p1 . angle - p2 . angle ) < maxAngleDif & & <nl> + abs ( p1 . response - p2 . response ) < maxResponseDif & & <nl> + p1 . octave = = p2 . octave & & <nl> + p1 . class_id = = p2 . class_id ) ; <nl> + } <nl> } ; <nl> <nl> - void CV_GPU_SURFTest : : emptyDataTest ( ) <nl> + cv : : Mat SURF : : image ; <nl> + cv : : Mat SURF : : mask ; <nl> + std : : vector < cv : : KeyPoint > SURF : : keypoints_gold ; <nl> + std : : vector < float > SURF : : descriptors_gold ; <nl> + <nl> + TEST_P ( SURF , EmptyDataTest ) <nl> { <nl> - SURF_GPU fdetector ; <nl> + PRINT_PARAM ( devInfo ) ; <nl> <nl> - GpuMat image ; <nl> - vector < KeyPoint > keypoints ; <nl> - vector < float > descriptors ; <nl> - try <nl> - { <nl> - fdetector ( image , GpuMat ( ) , keypoints , descriptors ) ; <nl> - } <nl> - catch ( . . . ) <nl> + cv : : gpu : : SURF_GPU fdetector ; <nl> + <nl> + cv : : gpu : : GpuMat image ; <nl> + std : : vector < cv : : KeyPoint > keypoints ; <nl> + std : : vector < float > descriptors ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + fdetector ( image , cv : : gpu : : GpuMat ( ) , keypoints , descriptors ) ; <nl> + ) ; <nl> + <nl> + EXPECT_TRUE ( keypoints . empty ( ) ) ; <nl> + EXPECT_TRUE ( descriptors . empty ( ) ) ; <nl> + } <nl> + <nl> + TEST_P ( SURF , Accuracy ) <nl> + { <nl> + ASSERT_TRUE ( ! image . empty ( ) ) ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + <nl> + / / Compute keypoints . <nl> + std : : vector < cv : : KeyPoint > keypoints ; <nl> + cv : : Mat descriptors ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat dev_descriptors ; <nl> + cv : : gpu : : SURF_GPU fdetector ; fdetector . extended = false ; <nl> + <nl> + fdetector ( cv : : gpu : : GpuMat ( image ) , cv : : gpu : : GpuMat ( mask ) , keypoints , dev_descriptors ) ; <nl> + <nl> + dev_descriptors . download ( descriptors ) ; <nl> + ) ; <nl> + <nl> + cv : : BruteForceMatcher < cv : : L2 < float > > matcher ; <nl> + std : : vector < cv : : DMatch > matches ; <nl> + <nl> + matcher . match ( cv : : Mat ( keypoints_gold . size ( ) , 64 , CV_32FC1 , & descriptors_gold [ 0 ] ) , descriptors , matches ) ; <nl> + <nl> + int validCount = 0 ; <nl> + <nl> + for ( size_t i = 0 ; i < matches . size ( ) ; + + i ) <nl> { <nl> - ts - > printf ( cvtest : : TS : : LOG , " detect ( ) on empty image must not generate exception ( 1 ) . \ n " ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> + const cv : : DMatch & m = matches [ i ] ; <nl> + <nl> + const cv : : KeyPoint & p1 = keypoints_gold [ m . queryIdx ] ; <nl> + const cv : : KeyPoint & p2 = keypoints [ m . trainIdx ] ; <nl> + <nl> + const float maxPtDif = 1 . f ; <nl> + const float maxSizeDif = 1 . f ; <nl> + const float maxAngleDif = 2 . f ; <nl> + const float maxResponseDif = 0 . 1f ; <nl> + <nl> + float dist = ( float ) cv : : norm ( p1 . pt - p2 . pt ) ; <nl> + if ( dist < maxPtDif & & <nl> + fabs ( p1 . size - p2 . size ) < maxSizeDif & & <nl> + abs ( p1 . angle - p2 . angle ) < maxAngleDif & & <nl> + abs ( p1 . response - p2 . response ) < maxResponseDif & & <nl> + p1 . octave = = p2 . octave & & <nl> + p1 . class_id = = p2 . class_id ) <nl> + { <nl> + + + validCount ; <nl> + } <nl> } <nl> <nl> - if ( ! keypoints . empty ( ) ) <nl> + double validRatio = ( double ) validCount / matches . size ( ) ; <nl> + <nl> + EXPECT_GT ( validRatio , 0 . 5 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( Features2D , SURF , testing : : ValuesIn ( devices ( cv : : gpu : : GLOBAL_ATOMICS ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / BruteForceMatcher <nl> + <nl> + static const char * dists [ ] = { " L1Dist " , " L2Dist " , " HammingDist " } ; <nl> + <nl> + struct BruteForceMatcher : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , cv : : gpu : : BruteForceMatcher_GPU_base : : DistType , int > > <nl> + { <nl> + static const int queryDescCount = 300 ; / / must be even number because we split train data in some cases in two <nl> + static const int countFactor = 4 ; / / do not change it <nl> + <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + cv : : gpu : : BruteForceMatcher_GPU_base : : DistType distType ; <nl> + int dim ; <nl> + <nl> + cv : : Mat query , train ; <nl> + <nl> + virtual void SetUp ( ) <nl> { <nl> - ts - > printf ( cvtest : : TS : : LOG , " detect ( ) on empty image must return empty keypoints vector ( 1 ) . \ n " ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return ; <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + distType = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> + dim = std : : tr1 : : get < 2 > ( GetParam ( ) ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + cv : : Mat queryBuf , trainBuf ; <nl> + <nl> + / / Generate query descriptors randomly . <nl> + / / Descriptor vector elements are integer values . <nl> + queryBuf . create ( queryDescCount , dim , CV_32SC1 ) ; <nl> + rng . fill ( queryBuf , cv : : RNG : : UNIFORM , cv : : Scalar : : all ( 0 ) , cv : : Scalar : : all ( 3 ) ) ; <nl> + queryBuf . convertTo ( queryBuf , CV_32FC1 ) ; <nl> + <nl> + / / Generate train decriptors as follows : <nl> + / / copy each query descriptor to train set countFactor times <nl> + / / and perturb some one element of the copied descriptors in <nl> + / / in ascending order . General boundaries of the perturbation <nl> + / / are ( 0 . f , 1 . f ) . <nl> + trainBuf . create ( queryDescCount * countFactor , dim , CV_32FC1 ) ; <nl> + float step = 1 . f / countFactor ; <nl> + for ( int qIdx = 0 ; qIdx < queryDescCount ; qIdx + + ) <nl> + { <nl> + cv : : Mat queryDescriptor = queryBuf . row ( qIdx ) ; <nl> + for ( int c = 0 ; c < countFactor ; c + + ) <nl> + { <nl> + int tIdx = qIdx * countFactor + c ; <nl> + cv : : Mat trainDescriptor = trainBuf . row ( tIdx ) ; <nl> + queryDescriptor . copyTo ( trainDescriptor ) ; <nl> + int elem = rng ( dim ) ; <nl> + float diff = rng . uniform ( step * c , step * ( c + 1 ) ) ; <nl> + trainDescriptor . at < float > ( 0 , elem ) + = diff ; <nl> + } <nl> + } <nl> + <nl> + queryBuf . convertTo ( query , CV_32F ) ; <nl> + trainBuf . convertTo ( train , CV_32F ) ; <nl> } <nl> + } ; <nl> + <nl> + TEST_P ( BruteForceMatcher , Match ) <nl> + { <nl> + const char * distStr = dists [ distType ] ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_PARAM ( distStr ) ; <nl> + PRINT_PARAM ( dim ) ; <nl> <nl> - if ( ! descriptors . empty ( ) ) <nl> + std : : vector < cv : : DMatch > matches ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : BruteForceMatcher_GPU_base matcher ( distType ) ; <nl> + <nl> + matcher . match ( cv : : gpu : : GpuMat ( query ) , cv : : gpu : : GpuMat ( train ) , matches ) ; <nl> + ) ; <nl> + <nl> + ASSERT_EQ ( queryDescCount , matches . size ( ) ) ; <nl> + <nl> + int badCount = 0 ; <nl> + for ( size_t i = 0 ; i < matches . size ( ) ; i + + ) <nl> { <nl> - ts - > printf ( cvtest : : TS : : LOG , " detect ( ) on empty image must return empty descriptors vector ( 1 ) . \ n " ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return ; <nl> + cv : : DMatch match = matches [ i ] ; <nl> + if ( ( match . queryIdx ! = ( int ) i ) | | ( match . trainIdx ! = ( int ) i * countFactor ) | | ( match . imgIdx ! = 0 ) ) <nl> + badCount + + ; <nl> } <nl> + <nl> + ASSERT_EQ ( 0 , badCount ) ; <nl> } <nl> <nl> - bool CV_GPU_SURFTest : : isSimilarKeypoints ( const KeyPoint & p1 , const KeyPoint & p2 ) <nl> + TEST_P ( BruteForceMatcher , MatchAdd ) <nl> { <nl> - const float maxPtDif = 1 . f ; <nl> - const float maxSizeDif = 1 . f ; <nl> - const float maxAngleDif = 2 . f ; <nl> - const float maxResponseDif = 0 . 1f ; <nl> - <nl> - float dist = ( float ) norm ( p1 . pt - p2 . pt ) ; <nl> - return ( dist < maxPtDif & & <nl> - fabs ( p1 . size - p2 . size ) < maxSizeDif & & <nl> - abs ( p1 . angle - p2 . angle ) < maxAngleDif & & <nl> - abs ( p1 . response - p2 . response ) < maxResponseDif & & <nl> - p1 . octave = = p2 . octave & & <nl> - p1 . class_id = = p2 . class_id ) ; <nl> + const char * distStr = dists [ distType ] ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_PARAM ( distStr ) ; <nl> + PRINT_PARAM ( dim ) ; <nl> + <nl> + std : : vector < cv : : DMatch > matches ; <nl> + <nl> + bool isMaskSupported ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : BruteForceMatcher_GPU_base matcher ( distType ) ; <nl> + <nl> + cv : : gpu : : GpuMat d_train ( train ) ; <nl> + <nl> + / / make add ( ) twice to test such case <nl> + matcher . add ( std : : vector < cv : : gpu : : GpuMat > ( 1 , d_train . rowRange ( 0 , train . rows / 2 ) ) ) ; <nl> + matcher . add ( std : : vector < cv : : gpu : : GpuMat > ( 1 , d_train . rowRange ( train . rows / 2 , train . rows ) ) ) ; <nl> + <nl> + / / prepare masks ( make first nearest match illegal ) <nl> + std : : vector < cv : : gpu : : GpuMat > masks ( 2 ) ; <nl> + for ( int mi = 0 ; mi < 2 ; mi + + ) <nl> + { <nl> + masks [ mi ] = cv : : gpu : : GpuMat ( query . rows , train . rows / 2 , CV_8UC1 , cv : : Scalar : : all ( 1 ) ) ; <nl> + for ( int di = 0 ; di < queryDescCount / 2 ; di + + ) <nl> + masks [ mi ] . col ( di * countFactor ) . setTo ( cv : : Scalar : : all ( 0 ) ) ; <nl> + } <nl> + <nl> + matcher . match ( cv : : gpu : : GpuMat ( query ) , matches , masks ) ; <nl> + <nl> + isMaskSupported = matcher . isMaskSupported ( ) ; <nl> + ) ; <nl> + <nl> + ASSERT_EQ ( queryDescCount , matches . size ( ) ) ; <nl> + <nl> + int badCount = 0 ; <nl> + for ( size_t i = 0 ; i < matches . size ( ) ; i + + ) <nl> + { <nl> + cv : : DMatch match = matches [ i ] ; <nl> + int shift = isMaskSupported ? 1 : 0 ; <nl> + { <nl> + if ( i < queryDescCount / 2 ) <nl> + { <nl> + if ( ( match . queryIdx ! = ( int ) i ) | | ( match . trainIdx ! = ( int ) i * countFactor + shift ) | | ( match . imgIdx ! = 0 ) ) <nl> + badCount + + ; <nl> + } <nl> + else <nl> + { <nl> + if ( ( match . queryIdx ! = ( int ) i ) | | ( match . trainIdx ! = ( ( int ) i - queryDescCount / 2 ) * countFactor + shift ) | | ( match . imgIdx ! = 1 ) ) <nl> + badCount + + ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + ASSERT_EQ ( 0 , badCount ) ; <nl> } <nl> <nl> - int CV_GPU_SURFTest : : getValidCount ( const vector < KeyPoint > & keypoints1 , const vector < KeyPoint > & keypoints2 , <nl> - const vector < DMatch > & matches ) <nl> + TEST_P ( BruteForceMatcher , KnnMatch ) <nl> { <nl> - int count = 0 ; <nl> + const char * distStr = dists [ distType ] ; <nl> <nl> - for ( size_t i = 0 ; i < matches . size ( ) ; + + i ) <nl> - { <nl> - const DMatch & m = matches [ i ] ; <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_PARAM ( distStr ) ; <nl> + PRINT_PARAM ( dim ) ; <nl> + <nl> + const int knn = 3 ; <nl> + <nl> + std : : vector < std : : vector < cv : : DMatch > > matches ; <nl> <nl> - const KeyPoint & kp1 = keypoints1 [ m . queryIdx ] ; <nl> - const KeyPoint & kp2 = keypoints2 [ m . trainIdx ] ; <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : BruteForceMatcher_GPU_base matcher ( distType ) ; <nl> + matcher . knnMatch ( cv : : gpu : : GpuMat ( query ) , cv : : gpu : : GpuMat ( train ) , matches , knn ) ; <nl> + ) ; <nl> <nl> - if ( isSimilarKeypoints ( kp1 , kp2 ) ) <nl> - + + count ; <nl> + ASSERT_EQ ( queryDescCount , matches . size ( ) ) ; <nl> + <nl> + int badCount = 0 ; <nl> + for ( size_t i = 0 ; i < matches . size ( ) ; i + + ) <nl> + { <nl> + if ( ( int ) matches [ i ] . size ( ) ! = knn ) <nl> + badCount + + ; <nl> + else <nl> + { <nl> + int localBadCount = 0 ; <nl> + for ( int k = 0 ; k < knn ; k + + ) <nl> + { <nl> + cv : : DMatch match = matches [ i ] [ k ] ; <nl> + if ( ( match . queryIdx ! = ( int ) i ) | | ( match . trainIdx ! = ( int ) i * countFactor + k ) | | ( match . imgIdx ! = 0 ) ) <nl> + localBadCount + + ; <nl> + } <nl> + badCount + = localBadCount > 0 ? 1 : 0 ; <nl> + } <nl> } <nl> <nl> - return count ; <nl> + ASSERT_EQ ( 0 , badCount ) ; <nl> } <nl> <nl> - void CV_GPU_SURFTest : : compareKeypointSets ( const vector < KeyPoint > & validKeypoints , const vector < KeyPoint > & calcKeypoints , <nl> - const Mat & validDescriptors , const Mat & calcDescriptors ) <nl> + TEST_P ( BruteForceMatcher , KnnMatchAdd ) <nl> { <nl> - BruteForceMatcher < L2 < float > > matcher ; <nl> - vector < DMatch > matches ; <nl> + const char * distStr = dists [ distType ] ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_PARAM ( distStr ) ; <nl> + PRINT_PARAM ( dim ) ; <nl> <nl> - matcher . match ( validDescriptors , calcDescriptors , matches ) ; <nl> + const int knn = 2 ; <nl> + std : : vector < std : : vector < cv : : DMatch > > matches ; <nl> <nl> - int validCount = getValidCount ( validKeypoints , calcKeypoints , matches ) ; <nl> - float validRatio = ( float ) validCount / matches . size ( ) ; <nl> + bool isMaskSupported ; <nl> <nl> - if ( validRatio < 0 . 5f ) <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : BruteForceMatcher_GPU_base matcher ( distType ) ; <nl> + <nl> + cv : : gpu : : GpuMat d_train ( train ) ; <nl> + <nl> + / / make add ( ) twice to test such case <nl> + matcher . add ( std : : vector < cv : : gpu : : GpuMat > ( 1 , d_train . rowRange ( 0 , train . rows / 2 ) ) ) ; <nl> + matcher . add ( std : : vector < cv : : gpu : : GpuMat > ( 1 , d_train . rowRange ( train . rows / 2 , train . rows ) ) ) ; <nl> + <nl> + / / prepare masks ( make first nearest match illegal ) <nl> + std : : vector < cv : : gpu : : GpuMat > masks ( 2 ) ; <nl> + for ( int mi = 0 ; mi < 2 ; mi + + ) <nl> + { <nl> + masks [ mi ] = cv : : gpu : : GpuMat ( query . rows , train . rows / 2 , CV_8UC1 , cv : : Scalar : : all ( 1 ) ) ; <nl> + for ( int di = 0 ; di < queryDescCount / 2 ; di + + ) <nl> + masks [ mi ] . col ( di * countFactor ) . setTo ( cv : : Scalar : : all ( 0 ) ) ; <nl> + } <nl> + <nl> + matcher . knnMatch ( cv : : gpu : : GpuMat ( query ) , matches , knn , masks ) ; <nl> + <nl> + isMaskSupported = matcher . isMaskSupported ( ) ; <nl> + ) ; <nl> + <nl> + ASSERT_EQ ( queryDescCount , matches . size ( ) ) ; <nl> + <nl> + int badCount = 0 ; <nl> + int shift = isMaskSupported ? 1 : 0 ; <nl> + for ( size_t i = 0 ; i < matches . size ( ) ; i + + ) <nl> { <nl> - ts - > printf ( cvtest : : TS : : LOG , " Bad accuracy - % f . \ n " , validRatio ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_BAD_ACCURACY ) ; <nl> - return ; <nl> + if ( ( int ) matches [ i ] . size ( ) ! = knn ) <nl> + badCount + + ; <nl> + else <nl> + { <nl> + int localBadCount = 0 ; <nl> + for ( int k = 0 ; k < knn ; k + + ) <nl> + { <nl> + cv : : DMatch match = matches [ i ] [ k ] ; <nl> + { <nl> + if ( i < queryDescCount / 2 ) <nl> + { <nl> + if ( ( match . queryIdx ! = ( int ) i ) | | ( match . trainIdx ! = ( int ) i * countFactor + k + shift ) | | ( match . imgIdx ! = 0 ) ) <nl> + localBadCount + + ; <nl> + } <nl> + else <nl> + { <nl> + if ( ( match . queryIdx ! = ( int ) i ) | | ( match . trainIdx ! = ( ( int ) i - queryDescCount / 2 ) * countFactor + k + shift ) | | ( match . imgIdx ! = 1 ) ) <nl> + localBadCount + + ; <nl> + } <nl> + } <nl> + } <nl> + badCount + = localBadCount > 0 ? 1 : 0 ; <nl> + } <nl> } <nl> + <nl> + ASSERT_EQ ( 0 , badCount ) ; <nl> } <nl> <nl> - void CV_GPU_SURFTest : : accuracyTest ( ) <nl> + TEST_P ( BruteForceMatcher , RadiusMatch ) <nl> { <nl> - string imgFilename = string ( ts - > get_data_path ( ) ) + FEATURES2D_DIR + " / " + IMAGE_FILENAME ; <nl> + if ( ! supportFeature ( devInfo , cv : : gpu : : GLOBAL_ATOMICS ) ) <nl> + return ; <nl> + <nl> + const char * distStr = dists [ distType ] ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_PARAM ( distStr ) ; <nl> + PRINT_PARAM ( dim ) ; <nl> + <nl> + const float radius = 1 . f / countFactor ; <nl> + <nl> + std : : vector < std : : vector < cv : : DMatch > > matches ; <nl> <nl> - / / Read the test image . <nl> - Mat image = imread ( imgFilename , 0 ) ; <nl> - if ( image . empty ( ) ) <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : BruteForceMatcher_GPU_base matcher ( distType ) ; <nl> + <nl> + matcher . radiusMatch ( cv : : gpu : : GpuMat ( query ) , cv : : gpu : : GpuMat ( train ) , matches , radius ) ; <nl> + ) ; <nl> + <nl> + ASSERT_EQ ( queryDescCount , matches . size ( ) ) ; <nl> + <nl> + int badCount = 0 ; <nl> + for ( size_t i = 0 ; i < matches . size ( ) ; i + + ) <nl> { <nl> - ts - > printf ( cvtest : : TS : : LOG , " Image % s can not be read . \ n " , imgFilename . c_str ( ) ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_TEST_DATA ) ; <nl> - return ; <nl> + if ( ( int ) matches [ i ] . size ( ) ! = 1 ) <nl> + badCount + + ; <nl> + else <nl> + { <nl> + cv : : DMatch match = matches [ i ] [ 0 ] ; <nl> + if ( ( match . queryIdx ! = ( int ) i ) | | ( match . trainIdx ! = ( int ) i * countFactor ) | | ( match . imgIdx ! = 0 ) ) <nl> + badCount + + ; <nl> + } <nl> } <nl> - <nl> - Mat mask ( image . size ( ) , CV_8UC1 , Scalar : : all ( 1 ) ) ; <nl> - mask ( Range ( 0 , image . rows / 2 ) , Range ( 0 , image . cols / 2 ) ) . setTo ( Scalar : : all ( 0 ) ) ; <nl> <nl> - / / Compute keypoints . <nl> - vector < KeyPoint > calcKeypoints ; <nl> - GpuMat calcDescriptors ; <nl> - SURF_GPU fdetector ; fdetector . extended = false ; <nl> - fdetector ( GpuMat ( image ) , GpuMat ( mask ) , calcKeypoints , calcDescriptors ) ; <nl> - <nl> - / / Calc validation keypoints set . <nl> - vector < KeyPoint > validKeypoints ; <nl> - vector < float > validDescriptors ; <nl> - SURF fdetector_gold ; fdetector_gold . extended = false ; <nl> - fdetector_gold ( image , mask , validKeypoints , validDescriptors ) ; <nl> - <nl> - compareKeypointSets ( validKeypoints , calcKeypoints , <nl> - Mat ( validKeypoints . size ( ) , fdetector_gold . descriptorSize ( ) , CV_32F , & validDescriptors [ 0 ] ) , calcDescriptors ) ; <nl> + ASSERT_EQ ( 0 , badCount ) ; <nl> } <nl> <nl> - void CV_GPU_SURFTest : : run ( int / * start_from * / ) <nl> + TEST_P ( BruteForceMatcher , RadiusMatchAdd ) <nl> { <nl> - emptyDataTest ( ) ; <nl> - accuracyTest ( ) ; <nl> + if ( ! supportFeature ( devInfo , cv : : gpu : : GLOBAL_ATOMICS ) ) <nl> + return ; <nl> + <nl> + const char * distStr = dists [ distType ] ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_PARAM ( distStr ) ; <nl> + PRINT_PARAM ( dim ) ; <nl> + <nl> + int n = 3 ; <nl> + const float radius = 1 . f / countFactor * n ; <nl> + <nl> + std : : vector < std : : vector < cv : : DMatch > > matches ; <nl> + <nl> + bool isMaskSupported ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : BruteForceMatcher_GPU_base matcher ( distType ) ; <nl> + <nl> + cv : : gpu : : GpuMat d_train ( train ) ; <nl> + <nl> + / / make add ( ) twice to test such case <nl> + matcher . add ( std : : vector < cv : : gpu : : GpuMat > ( 1 , d_train . rowRange ( 0 , train . rows / 2 ) ) ) ; <nl> + matcher . add ( std : : vector < cv : : gpu : : GpuMat > ( 1 , d_train . rowRange ( train . rows / 2 , train . rows ) ) ) ; <nl> + <nl> + / / prepare masks ( make first nearest match illegal ) <nl> + std : : vector < cv : : gpu : : GpuMat > masks ( 2 ) ; <nl> + for ( int mi = 0 ; mi < 2 ; mi + + ) <nl> + { <nl> + masks [ mi ] = cv : : gpu : : GpuMat ( query . rows , train . rows / 2 , CV_8UC1 , cv : : Scalar : : all ( 1 ) ) ; <nl> + for ( int di = 0 ; di < queryDescCount / 2 ; di + + ) <nl> + masks [ mi ] . col ( di * countFactor ) . setTo ( cv : : Scalar : : all ( 0 ) ) ; <nl> + } <nl> + <nl> + matcher . radiusMatch ( cv : : gpu : : GpuMat ( query ) , matches , radius , masks ) ; <nl> + <nl> + isMaskSupported = matcher . isMaskSupported ( ) ; <nl> + ) ; <nl> + <nl> + ASSERT_EQ ( queryDescCount , matches . size ( ) ) ; <nl> + <nl> + int badCount = 0 ; <nl> + int shift = isMaskSupported ? 1 : 0 ; <nl> + int needMatchCount = isMaskSupported ? n - 1 : n ; <nl> + for ( size_t i = 0 ; i < matches . size ( ) ; i + + ) <nl> + { <nl> + if ( ( int ) matches [ i ] . size ( ) ! = needMatchCount ) <nl> + badCount + + ; <nl> + else <nl> + { <nl> + int localBadCount = 0 ; <nl> + for ( int k = 0 ; k < needMatchCount ; k + + ) <nl> + { <nl> + cv : : DMatch match = matches [ i ] [ k ] ; <nl> + { <nl> + if ( i < queryDescCount / 2 ) <nl> + { <nl> + if ( ( match . queryIdx ! = ( int ) i ) | | ( match . trainIdx ! = ( int ) i * countFactor + k + shift ) | | ( match . imgIdx ! = 0 ) ) <nl> + localBadCount + + ; <nl> + } <nl> + else <nl> + { <nl> + if ( ( match . queryIdx ! = ( int ) i ) | | ( match . trainIdx ! = ( ( int ) i - queryDescCount / 2 ) * countFactor + k + shift ) | | ( match . imgIdx ! = 1 ) ) <nl> + localBadCount + + ; <nl> + } <nl> + } <nl> + } <nl> + badCount + = localBadCount > 0 ? 1 : 0 ; <nl> + } <nl> + } <nl> + <nl> + ASSERT_EQ ( 0 , badCount ) ; <nl> } <nl> <nl> - TEST ( SURF , empty_data_and_accuracy ) { CV_GPU_SURFTest test ; test . safe_run ( ) ; } <nl> + INSTANTIATE_TEST_CASE_P ( Features2D , BruteForceMatcher , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( cv : : gpu : : BruteForceMatcher_GPU_base : : L1Dist , cv : : gpu : : BruteForceMatcher_GPU_base : : L2Dist ) , <nl> + testing : : Values ( 57 , 64 , 83 , 128 , 179 , 256 , 304 ) ) ) ; <nl> + <nl> + # endif / / HAVE_CUDA <nl> + <nl> + <nl> + <nl> + <nl> + <nl> + <nl> + <nl> + <nl> + <nl> + <nl> + <nl> + <nl> + <nl> + <nl> + <nl> + <nl> + <nl> + / / struct CV_GpuBFMTest : CV_GpuTestBase <nl> + / / { <nl> + / / void run_gpu_test ( ) ; <nl> + / / <nl> + / / void generateData ( GpuMat & query , GpuMat & train , int dim , int depth ) ; <nl> + / / <nl> + / / virtual void test ( const GpuMat & query , const GpuMat & train , BruteForceMatcher_GPU_base & matcher ) = 0 ; <nl> + / / <nl> + / / static const int queryDescCount = 300 ; / / must be even number because we split train data in some cases in two <nl> + / / static const int countFactor = 4 ; / / do not change it <nl> + / / } ; <nl> + / / <nl> + / / void CV_GpuBFMTest : : run_gpu_test ( ) <nl> + / / { <nl> + / / BruteForceMatcher_GPU_base : : DistType dists [ ] = { BruteForceMatcher_GPU_base : : L1Dist , BruteForceMatcher_GPU_base : : L2Dist , BruteForceMatcher_GPU_base : : HammingDist } ; <nl> + / / const char * dists_str [ ] = { " L1Dist " , " L2Dist " , " HammingDist " } ; <nl> + / / int dists_count = sizeof ( dists ) / sizeof ( dists [ 0 ] ) ; <nl> + / / <nl> + / / RNG rng = ts - > get_rng ( ) ; <nl> + / / <nl> + / / int dims [ ] = { rng . uniform ( 30 , 60 ) , 64 , rng . uniform ( 70 , 110 ) , 128 , rng . uniform ( 130 , 250 ) , 256 , rng . uniform ( 260 , 350 ) } ; <nl> + / / int dims_count = sizeof ( dims ) / sizeof ( dims [ 0 ] ) ; <nl> + / / <nl> + / / for ( int dist = 0 ; dist < dists_count ; + + dist ) <nl> + / / { <nl> + / / int depth_end = dists [ dist ] = = BruteForceMatcher_GPU_base : : HammingDist ? CV_32S : CV_32F ; <nl> + / / <nl> + / / for ( int depth = CV_8U ; depth < = depth_end ; + + depth ) <nl> + / / { <nl> + / / for ( int dim = 0 ; dim < dims_count ; + + dim ) <nl> + / / { <nl> + / / PRINT_ARGS ( " dist = % s depth = % s dim = % d " , dists_str [ dist ] , getTypeName ( depth ) , dims [ dim ] ) ; <nl> + / / <nl> + / / BruteForceMatcher_GPU_base matcher ( dists [ dist ] ) ; <nl> + / / <nl> + / / GpuMat query , train ; <nl> + / / generateData ( query , train , dim , depth ) ; <nl> + / / <nl> + / / test ( query , train , matcher ) ; <nl> + / / } <nl> + / / } <nl> + / / } <nl> + / / } <nl> + / / <nl> + / / void CV_GpuBFMTest : : generateData ( GpuMat & queryGPU , GpuMat & trainGPU , int dim , int depth ) <nl> + / / { <nl> + / / RNG & rng = ts - > get_rng ( ) ; <nl> + / / <nl> + / / Mat queryBuf , trainBuf ; <nl> + / / <nl> + / / / / Generate query descriptors randomly . <nl> + / / / / Descriptor vector elements are integer values . <nl> + / / queryBuf . create ( queryDescCount , dim , CV_32SC1 ) ; <nl> + / / rng . fill ( queryBuf , RNG : : UNIFORM , Scalar : : all ( 0 ) , Scalar ( 3 ) ) ; <nl> + / / queryBuf . convertTo ( queryBuf , CV_32FC1 ) ; <nl> + / / <nl> + / / / / Generate train decriptors as follows : <nl> + / / / / copy each query descriptor to train set countFactor times <nl> + / / / / and perturb some one element of the copied descriptors in <nl> + / / / / in ascending order . General boundaries of the perturbation <nl> + / / / / are ( 0 . f , 1 . f ) . <nl> + / / trainBuf . create ( queryDescCount * countFactor , dim , CV_32FC1 ) ; <nl> + / / float step = 1 . f / countFactor ; <nl> + / / for ( int qIdx = 0 ; qIdx < queryDescCount ; qIdx + + ) <nl> + / / { <nl> + / / Mat queryDescriptor = queryBuf . row ( qIdx ) ; <nl> + / / for ( int c = 0 ; c < countFactor ; c + + ) <nl> + / / { <nl> + / / int tIdx = qIdx * countFactor + c ; <nl> + / / Mat trainDescriptor = trainBuf . row ( tIdx ) ; <nl> + / / queryDescriptor . copyTo ( trainDescriptor ) ; <nl> + / / int elem = rng ( dim ) ; <nl> + / / float diff = rng . uniform ( step * c , step * ( c + 1 ) ) ; <nl> + / / trainDescriptor . at < float > ( 0 , elem ) + = diff ; <nl> + / / } <nl> + / / } <nl> + / / <nl> + / / Mat query , train ; <nl> + / / queryBuf . convertTo ( query , depth ) ; <nl> + / / trainBuf . convertTo ( train , depth ) ; <nl> + / / <nl> + / / queryGPU . upload ( query ) ; <nl> + / / trainGPU . upload ( train ) ; <nl> + / / } <nl> + / / <nl> + / / # define GPU_BFM_TEST ( test_name ) \ <nl> + / / struct CV_GpuBFM_ # # test_name # # _Test : CV_GpuBFMTest \ <nl> + / / { \ <nl> + / / void test ( const GpuMat & query , const GpuMat & train , BruteForceMatcher_GPU_base & matcher ) ; \ <nl> + / / } ; \ <nl> + / / TEST ( BruteForceMatcher , test_name ) { CV_GpuBFM_ # # test_name # # _Test test ; test . safe_run ( ) ; } \ <nl> + / / void CV_GpuBFM_ # # test_name # # _Test : : test ( const GpuMat & query , const GpuMat & train , BruteForceMatcher_GPU_base & matcher ) <nl> + / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / / / match <nl> + / / <nl> + / / GPU_BFM_TEST ( match ) <nl> + / / { <nl> + / / vector < DMatch > matches ; <nl> + / / <nl> + / / matcher . match ( query , train , matches ) ; <nl> + / / <nl> + / / CHECK ( ( int ) matches . size ( ) = = queryDescCount , TS : : FAIL_INVALID_OUTPUT ) ; <nl> + / / <nl> + / / int badCount = 0 ; <nl> + / / for ( size_t i = 0 ; i < matches . size ( ) ; i + + ) <nl> + / / { <nl> + / / DMatch match = matches [ i ] ; <nl> + / / if ( ( match . queryIdx ! = ( int ) i ) | | ( match . trainIdx ! = ( int ) i * countFactor ) | | ( match . imgIdx ! = 0 ) ) <nl> + / / badCount + + ; <nl> + / / } <nl> + / / <nl> + / / CHECK ( badCount = = 0 , TS : : FAIL_INVALID_OUTPUT ) ; <nl> + / / } <nl> + / / <nl> + / / GPU_BFM_TEST ( match_add ) <nl> + / / { <nl> + / / vector < DMatch > matches ; <nl> + / / <nl> + / / / / make add ( ) twice to test such case <nl> + / / matcher . add ( vector < GpuMat > ( 1 , train . rowRange ( 0 , train . rows / 2 ) ) ) ; <nl> + / / matcher . add ( vector < GpuMat > ( 1 , train . rowRange ( train . rows / 2 , train . rows ) ) ) ; <nl> + / / <nl> + / / / / prepare masks ( make first nearest match illegal ) <nl> + / / vector < GpuMat > masks ( 2 ) ; <nl> + / / for ( int mi = 0 ; mi < 2 ; mi + + ) <nl> + / / { <nl> + / / masks [ mi ] = GpuMat ( query . rows , train . rows / 2 , CV_8UC1 , Scalar : : all ( 1 ) ) ; <nl> + / / for ( int di = 0 ; di < queryDescCount / 2 ; di + + ) <nl> + / / masks [ mi ] . col ( di * countFactor ) . setTo ( Scalar : : all ( 0 ) ) ; <nl> + / / } <nl> + / / <nl> + / / matcher . match ( query , matches , masks ) ; <nl> + / / <nl> + / / CHECK ( ( int ) matches . size ( ) = = queryDescCount , TS : : FAIL_INVALID_OUTPUT ) ; <nl> + / / <nl> + / / int badCount = 0 ; <nl> + / / for ( size_t i = 0 ; i < matches . size ( ) ; i + + ) <nl> + / / { <nl> + / / DMatch match = matches [ i ] ; <nl> + / / int shift = matcher . isMaskSupported ( ) ? 1 : 0 ; <nl> + / / { <nl> + / / if ( i < queryDescCount / 2 ) <nl> + / / { <nl> + / / if ( ( match . queryIdx ! = ( int ) i ) | | ( match . trainIdx ! = ( int ) i * countFactor + shift ) | | ( match . imgIdx ! = 0 ) ) <nl> + / / badCount + + ; <nl> + / / } <nl> + / / else <nl> + / / { <nl> + / / if ( ( match . queryIdx ! = ( int ) i ) | | ( match . trainIdx ! = ( ( int ) i - queryDescCount / 2 ) * countFactor + shift ) | | ( match . imgIdx ! = 1 ) ) <nl> + / / badCount + + ; <nl> + / / } <nl> + / / } <nl> + / / } <nl> + / / <nl> + / / CHECK ( badCount = = 0 , TS : : FAIL_INVALID_OUTPUT ) ; <nl> + / / } <nl> + / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / / / knnMatch <nl> + / / <nl> + / / GPU_BFM_TEST ( knnMatch ) <nl> + / / { <nl> + / / const int knn = 3 ; <nl> + / / <nl> + / / vector < vector < DMatch > > matches ; <nl> + / / <nl> + / / matcher . knnMatch ( query , train , matches , knn ) ; <nl> + / / <nl> + / / CHECK ( ( int ) matches . size ( ) = = queryDescCount , TS : : FAIL_INVALID_OUTPUT ) ; <nl> + / / <nl> + / / int badCount = 0 ; <nl> + / / for ( size_t i = 0 ; i < matches . size ( ) ; i + + ) <nl> + / / { <nl> + / / if ( ( int ) matches [ i ] . size ( ) ! = knn ) <nl> + / / badCount + + ; <nl> + / / else <nl> + / / { <nl> + / / int localBadCount = 0 ; <nl> + / / for ( int k = 0 ; k < knn ; k + + ) <nl> + / / { <nl> + / / DMatch match = matches [ i ] [ k ] ; <nl> + / / if ( ( match . queryIdx ! = ( int ) i ) | | ( match . trainIdx ! = ( int ) i * countFactor + k ) | | ( match . imgIdx ! = 0 ) ) <nl> + / / localBadCount + + ; <nl> + / / } <nl> + / / badCount + = localBadCount > 0 ? 1 : 0 ; <nl> + / / } <nl> + / / } <nl> + / / <nl> + / / CHECK ( badCount = = 0 , TS : : FAIL_INVALID_OUTPUT ) ; <nl> + / / } <nl> + / / <nl> + / / GPU_BFM_TEST ( knnMatch_add ) <nl> + / / { <nl> + / / const int knn = 2 ; <nl> + / / vector < vector < DMatch > > matches ; <nl> + / / <nl> + / / / / make add ( ) twice to test such case <nl> + / / matcher . add ( vector < GpuMat > ( 1 , train . rowRange ( 0 , train . rows / 2 ) ) ) ; <nl> + / / matcher . add ( vector < GpuMat > ( 1 , train . rowRange ( train . rows / 2 , train . rows ) ) ) ; <nl> + / / <nl> + / / / / prepare masks ( make first nearest match illegal ) <nl> + / / vector < GpuMat > masks ( 2 ) ; <nl> + / / for ( int mi = 0 ; mi < 2 ; mi + + ) <nl> + / / { <nl> + / / masks [ mi ] = GpuMat ( query . rows , train . rows / 2 , CV_8UC1 , Scalar : : all ( 1 ) ) ; <nl> + / / for ( int di = 0 ; di < queryDescCount / 2 ; di + + ) <nl> + / / masks [ mi ] . col ( di * countFactor ) . setTo ( Scalar : : all ( 0 ) ) ; <nl> + / / } <nl> + / / <nl> + / / matcher . knnMatch ( query , matches , knn , masks ) ; <nl> + / / <nl> + / / CHECK ( ( int ) matches . size ( ) = = queryDescCount , TS : : FAIL_INVALID_OUTPUT ) ; <nl> + / / <nl> + / / int badCount = 0 ; <nl> + / / int shift = matcher . isMaskSupported ( ) ? 1 : 0 ; <nl> + / / for ( size_t i = 0 ; i < matches . size ( ) ; i + + ) <nl> + / / { <nl> + / / if ( ( int ) matches [ i ] . size ( ) ! = knn ) <nl> + / / badCount + + ; <nl> + / / else <nl> + / / { <nl> + / / int localBadCount = 0 ; <nl> + / / for ( int k = 0 ; k < knn ; k + + ) <nl> + / / { <nl> + / / DMatch match = matches [ i ] [ k ] ; <nl> + / / { <nl> + / / if ( i < queryDescCount / 2 ) <nl> + / / { <nl> + / / if ( ( match . queryIdx ! = ( int ) i ) | | ( match . trainIdx ! = ( int ) i * countFactor + k + shift ) | | ( match . imgIdx ! = 0 ) ) <nl> + / / localBadCount + + ; <nl> + / / } <nl> + / / else <nl> + / / { <nl> + / / if ( ( match . queryIdx ! = ( int ) i ) | | ( match . trainIdx ! = ( ( int ) i - queryDescCount / 2 ) * countFactor + k + shift ) | | ( match . imgIdx ! = 1 ) ) <nl> + / / localBadCount + + ; <nl> + / / } <nl> + / / } <nl> + / / } <nl> + / / badCount + = localBadCount > 0 ? 1 : 0 ; <nl> + / / } <nl> + / / } <nl> + / / <nl> + / / CHECK ( badCount = = 0 , TS : : FAIL_INVALID_OUTPUT ) ; <nl> + / / } <nl> + / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / / / radiusMatch <nl> + / / <nl> + / / GPU_BFM_TEST ( radiusMatch ) <nl> + / / { <nl> + / / CHECK_RETURN ( support ( GLOBAL_ATOMICS ) , TS : : SKIPPED ) ; <nl> + / / <nl> + / / const float radius = 1 . f / countFactor ; <nl> + / / <nl> + / / vector < vector < DMatch > > matches ; <nl> + / / <nl> + / / matcher . radiusMatch ( query , train , matches , radius ) ; <nl> + / / <nl> + / / CHECK ( ( int ) matches . size ( ) = = queryDescCount , TS : : FAIL_INVALID_OUTPUT ) ; <nl> + / / <nl> + / / int badCount = 0 ; <nl> + / / for ( size_t i = 0 ; i < matches . size ( ) ; i + + ) <nl> + / / { <nl> + / / if ( ( int ) matches [ i ] . size ( ) ! = 1 ) <nl> + / / badCount + + ; <nl> + / / else <nl> + / / { <nl> + / / DMatch match = matches [ i ] [ 0 ] ; <nl> + / / if ( ( match . queryIdx ! = ( int ) i ) | | ( match . trainIdx ! = ( int ) i * countFactor ) | | ( match . imgIdx ! = 0 ) ) <nl> + / / badCount + + ; <nl> + / / } <nl> + / / } <nl> + / / <nl> + / / CHECK ( badCount = = 0 , TS : : FAIL_INVALID_OUTPUT ) ; <nl> + / / } <nl> + / / <nl> + / / GPU_BFM_TEST ( radiusMatch_add ) <nl> + / / { <nl> + / / CHECK_RETURN ( support ( GLOBAL_ATOMICS ) , TS : : SKIPPED ) ; <nl> + / / <nl> + / / int n = 3 ; <nl> + / / const float radius = 1 . f / countFactor * n ; <nl> + / / vector < vector < DMatch > > matches ; <nl> + / / <nl> + / / / / make add ( ) twice to test such case <nl> + / / matcher . add ( vector < GpuMat > ( 1 , train . rowRange ( 0 , train . rows / 2 ) ) ) ; <nl> + / / matcher . add ( vector < GpuMat > ( 1 , train . rowRange ( train . rows / 2 , train . rows ) ) ) ; <nl> + / / <nl> + / / / / prepare masks ( make first nearest match illegal ) <nl> + / / vector < GpuMat > masks ( 2 ) ; <nl> + / / for ( int mi = 0 ; mi < 2 ; mi + + ) <nl> + / / { <nl> + / / masks [ mi ] = GpuMat ( query . rows , train . rows / 2 , CV_8UC1 , Scalar : : all ( 1 ) ) ; <nl> + / / for ( int di = 0 ; di < queryDescCount / 2 ; di + + ) <nl> + / / masks [ mi ] . col ( di * countFactor ) . setTo ( Scalar : : all ( 0 ) ) ; <nl> + / / } <nl> + / / <nl> + / / matcher . radiusMatch ( query , matches , radius , masks ) ; <nl> + / / <nl> + / / CHECK ( ( int ) matches . size ( ) = = queryDescCount , TS : : FAIL_INVALID_OUTPUT ) ; <nl> + / / <nl> + / / int badCount = 0 ; <nl> + / / int shift = matcher . isMaskSupported ( ) ? 1 : 0 ; <nl> + / / int needMatchCount = matcher . isMaskSupported ( ) ? n - 1 : n ; <nl> + / / for ( size_t i = 0 ; i < matches . size ( ) ; i + + ) <nl> + / / { <nl> + / / if ( ( int ) matches [ i ] . size ( ) ! = needMatchCount ) <nl> + / / badCount + + ; <nl> + / / else <nl> + / / { <nl> + / / int localBadCount = 0 ; <nl> + / / for ( int k = 0 ; k < needMatchCount ; k + + ) <nl> + / / { <nl> + / / DMatch match = matches [ i ] [ k ] ; <nl> + / / { <nl> + / / if ( i < queryDescCount / 2 ) <nl> + / / { <nl> + / / if ( ( match . queryIdx ! = ( int ) i ) | | ( match . trainIdx ! = ( int ) i * countFactor + k + shift ) | | ( match . imgIdx ! = 0 ) ) <nl> + / / localBadCount + + ; <nl> + / / } <nl> + / / else <nl> + / / { <nl> + / / if ( ( match . queryIdx ! = ( int ) i ) | | ( match . trainIdx ! = ( ( int ) i - queryDescCount / 2 ) * countFactor + k + shift ) | | ( match . imgIdx ! = 1 ) ) <nl> + / / localBadCount + + ; <nl> + / / } <nl> + / / } <nl> + / / } <nl> + / / badCount + = localBadCount > 0 ? 1 : 0 ; <nl> + / / } <nl> + / / } <nl> + / / <nl> + / / CHECK ( badCount = = 0 , TS : : FAIL_INVALID_OUTPUT ) ; <nl> + / / } <nl> + / / <nl> + / / <nl> + / / <nl> + / / <nl> + / / <nl> + / / <nl> + / / <nl> + / / <nl> + / / <nl> + / / <nl> + / / <nl> + / / <nl> + / / <nl> + / / <nl> + / / <nl> + / / <nl> + / / <nl> + / / <nl> + / / <nl> + / / <nl> + / / <nl> + / / / / struct CV_GpuBruteForceMatcherTest : CV_GpuTestBase <nl> + / / / / { <nl> + / / / / void run_gpu_test ( ) ; <nl> + / / / / <nl> + / / / / void emptyDataTest ( ) ; <nl> + / / / / void dataTest ( int dim ) ; <nl> + / / / / <nl> + / / / / void generateData ( GpuMat & query , GpuMat & train , int dim ) ; <nl> + / / / / <nl> + / / / / void matchTest ( const GpuMat & query , const GpuMat & train ) ; <nl> + / / / / void knnMatchTest ( const GpuMat & query , const GpuMat & train ) ; <nl> + / / / / void radiusMatchTest ( const GpuMat & query , const GpuMat & train ) ; <nl> + / / / / <nl> + / / / / BruteForceMatcher_GPU < L2 < float > > dmatcher ; <nl> + / / / / <nl> + / / / / static const int queryDescCount = 300 ; / / must be even number because we split train data in some cases in two <nl> + / / / / static const int countFactor = 4 ; / / do not change it <nl> + / / / / } ; <nl> + / / / / <nl> + / / / / void CV_GpuBruteForceMatcherTest : : emptyDataTest ( ) <nl> + / / / / { <nl> + / / / / GpuMat queryDescriptors , trainDescriptors , mask ; <nl> + / / / / vector < GpuMat > trainDescriptorCollection , masks ; <nl> + / / / / vector < DMatch > matches ; <nl> + / / / / vector < vector < DMatch > > vmatches ; <nl> + / / / / <nl> + / / / / try <nl> + / / / / { <nl> + / / / / dmatcher . match ( queryDescriptors , trainDescriptors , matches , mask ) ; <nl> + / / / / } <nl> + / / / / catch ( . . . ) <nl> + / / / / { <nl> + / / / / PRINTLN ( " match ( ) on empty descriptors must not generate exception ( 1 ) " ) ; <nl> + / / / / ts - > set_failed_test_info ( TS : : FAIL_EXCEPTION ) ; <nl> + / / / / } <nl> + / / / / <nl> + / / / / try <nl> + / / / / { <nl> + / / / / dmatcher . knnMatch ( queryDescriptors , trainDescriptors , vmatches , 2 , mask ) ; <nl> + / / / / } <nl> + / / / / catch ( . . . ) <nl> + / / / / { <nl> + / / / / PRINTLN ( " knnMatch ( ) on empty descriptors must not generate exception ( 1 ) " ) ; <nl> + / / / / ts - > set_failed_test_info ( TS : : FAIL_EXCEPTION ) ; <nl> + / / / / } <nl> + / / / / <nl> + / / / / try <nl> + / / / / { <nl> + / / / / dmatcher . radiusMatch ( queryDescriptors , trainDescriptors , vmatches , 10 . f , mask ) ; <nl> + / / / / } <nl> + / / / / catch ( . . . ) <nl> + / / / / { <nl> + / / / / PRINTLN ( " radiusMatch ( ) on empty descriptors must not generate exception ( 1 ) " ) ; <nl> + / / / / ts - > set_failed_test_info ( TS : : FAIL_EXCEPTION ) ; <nl> + / / / / } <nl> + / / / / <nl> + / / / / try <nl> + / / / / { <nl> + / / / / dmatcher . add ( trainDescriptorCollection ) ; <nl> + / / / / } <nl> + / / / / catch ( . . . ) <nl> + / / / / { <nl> + / / / / PRINTLN ( " add ( ) on empty descriptors must not generate exception " ) ; <nl> + / / / / ts - > set_failed_test_info ( TS : : FAIL_EXCEPTION ) ; <nl> + / / / / } <nl> + / / / / <nl> + / / / / try <nl> + / / / / { <nl> + / / / / dmatcher . match ( queryDescriptors , matches , masks ) ; <nl> + / / / / } <nl> + / / / / catch ( . . . ) <nl> + / / / / { <nl> + / / / / PRINTLN ( " match ( ) on empty descriptors must not generate exception ( 2 ) " ) ; <nl> + / / / / ts - > set_failed_test_info ( TS : : FAIL_EXCEPTION ) ; <nl> + / / / / } <nl> + / / / / <nl> + / / / / try <nl> + / / / / { <nl> + / / / / dmatcher . knnMatch ( queryDescriptors , vmatches , 2 , masks ) ; <nl> + / / / / } <nl> + / / / / catch ( . . . ) <nl> + / / / / { <nl> + / / / / PRINTLN ( " knnMatch ( ) on empty descriptors must not generate exception ( 2 ) " ) ; <nl> + / / / / ts - > set_failed_test_info ( TS : : FAIL_EXCEPTION ) ; <nl> + / / / / } <nl> + / / / / <nl> + / / / / try <nl> + / / / / { <nl> + / / / / dmatcher . radiusMatch ( queryDescriptors , vmatches , 10 . f , masks ) ; <nl> + / / / / } <nl> + / / / / catch ( . . . ) <nl> + / / / / { <nl> + / / / / PRINTLN ( " radiusMatch ( ) on empty descriptors must not generate exception ( 2 ) " ) ; <nl> + / / / / ts - > set_failed_test_info ( TS : : FAIL_EXCEPTION ) ; <nl> + / / / / } <nl> + / / / / <nl> + / / / / } <nl> + / / / / <nl> + / / / / void CV_GpuBruteForceMatcherTest : : generateData ( GpuMat & queryGPU , GpuMat & trainGPU , int dim ) <nl> + / / / / { <nl> + / / / / Mat query , train ; <nl> + / / / / RNG & rng = ts - > get_rng ( ) ; <nl> + / / / / <nl> + / / / / / / Generate query descriptors randomly . <nl> + / / / / / / Descriptor vector elements are integer values . <nl> + / / / / Mat buf ( queryDescCount , dim , CV_32SC1 ) ; <nl> + / / / / rng . fill ( buf , RNG : : UNIFORM , Scalar : : all ( 0 ) , Scalar ( 3 ) ) ; <nl> + / / / / buf . convertTo ( query , CV_32FC1 ) ; <nl> + / / / / <nl> + / / / / / / Generate train decriptors as follows : <nl> + / / / / / / copy each query descriptor to train set countFactor times <nl> + / / / / / / and perturb some one element of the copied descriptors in <nl> + / / / / / / in ascending order . General boundaries of the perturbation <nl> + / / / / / / are ( 0 . f , 1 . f ) . <nl> + / / / / train . create ( query . rows * countFactor , query . cols , CV_32FC1 ) ; <nl> + / / / / float step = 1 . f / countFactor ; <nl> + / / / / for ( int qIdx = 0 ; qIdx < query . rows ; qIdx + + ) <nl> + / / / / { <nl> + / / / / Mat queryDescriptor = query . row ( qIdx ) ; <nl> + / / / / for ( int c = 0 ; c < countFactor ; c + + ) <nl> + / / / / { <nl> + / / / / int tIdx = qIdx * countFactor + c ; <nl> + / / / / Mat trainDescriptor = train . row ( tIdx ) ; <nl> + / / / / queryDescriptor . copyTo ( trainDescriptor ) ; <nl> + / / / / int elem = rng ( dim ) ; <nl> + / / / / float diff = rng . uniform ( step * c , step * ( c + 1 ) ) ; <nl> + / / / / trainDescriptor . at < float > ( 0 , elem ) + = diff ; <nl> + / / / / } <nl> + / / / / } <nl> + / / / / <nl> + / / / / queryGPU . upload ( query ) ; <nl> + / / / / trainGPU . upload ( train ) ; <nl> + / / / / } <nl> + / / / / <nl> + / / / / void CV_GpuBruteForceMatcherTest : : matchTest ( const GpuMat & query , const GpuMat & train ) <nl> + / / / / { <nl> + / / / / dmatcher . clear ( ) ; <nl> + / / / / <nl> + / / / / / / test const version of match ( ) <nl> + / / / / { <nl> + / / / / vector < DMatch > matches ; <nl> + / / / / dmatcher . match ( query , train , matches ) ; <nl> + / / / / <nl> + / / / / CHECK ( ( int ) matches . size ( ) = = queryDescCount , TS : : FAIL_INVALID_OUTPUT ) ; <nl> + / / / / <nl> + / / / / int badCount = 0 ; <nl> + / / / / for ( size_t i = 0 ; i < matches . size ( ) ; i + + ) <nl> + / / / / { <nl> + / / / / DMatch match = matches [ i ] ; <nl> + / / / / if ( ( match . queryIdx ! = ( int ) i ) | | ( match . trainIdx ! = ( int ) i * countFactor ) | | ( match . imgIdx ! = 0 ) ) <nl> + / / / / badCount + + ; <nl> + / / / / } <nl> + / / / / <nl> + / / / / CHECK ( badCount = = 0 , TS : : FAIL_INVALID_OUTPUT ) ; <nl> + / / / / } <nl> + / / / / <nl> + / / / / / / test version of match ( ) with add ( ) <nl> + / / / / { <nl> + / / / / vector < DMatch > matches ; <nl> + / / / / <nl> + / / / / / / make add ( ) twice to test such case <nl> + / / / / dmatcher . add ( vector < GpuMat > ( 1 , train . rowRange ( 0 , train . rows / 2 ) ) ) ; <nl> + / / / / dmatcher . add ( vector < GpuMat > ( 1 , train . rowRange ( train . rows / 2 , train . rows ) ) ) ; <nl> + / / / / <nl> + / / / / / / prepare masks ( make first nearest match illegal ) <nl> + / / / / vector < GpuMat > masks ( 2 ) ; <nl> + / / / / for ( int mi = 0 ; mi < 2 ; mi + + ) <nl> + / / / / { <nl> + / / / / masks [ mi ] = GpuMat ( query . rows , train . rows / 2 , CV_8UC1 , Scalar : : all ( 1 ) ) ; <nl> + / / / / for ( int di = 0 ; di < queryDescCount / 2 ; di + + ) <nl> + / / / / masks [ mi ] . col ( di * countFactor ) . setTo ( Scalar : : all ( 0 ) ) ; <nl> + / / / / } <nl> + / / / / <nl> + / / / / dmatcher . match ( query , matches , masks ) ; <nl> + / / / / <nl> + / / / / CHECK ( ( int ) matches . size ( ) = = queryDescCount , TS : : FAIL_INVALID_OUTPUT ) ; <nl> + / / / / <nl> + / / / / int badCount = 0 ; <nl> + / / / / for ( size_t i = 0 ; i < matches . size ( ) ; i + + ) <nl> + / / / / { <nl> + / / / / DMatch match = matches [ i ] ; <nl> + / / / / int shift = dmatcher . isMaskSupported ( ) ? 1 : 0 ; <nl> + / / / / { <nl> + / / / / if ( i < queryDescCount / 2 ) <nl> + / / / / { <nl> + / / / / if ( ( match . queryIdx ! = ( int ) i ) | | ( match . trainIdx ! = ( int ) i * countFactor + shift ) | | ( match . imgIdx ! = 0 ) ) <nl> + / / / / badCount + + ; <nl> + / / / / } <nl> + / / / / else <nl> + / / / / { <nl> + / / / / if ( ( match . queryIdx ! = ( int ) i ) | | ( match . trainIdx ! = ( ( int ) i - queryDescCount / 2 ) * countFactor + shift ) | | ( match . imgIdx ! = 1 ) ) <nl> + / / / / badCount + + ; <nl> + / / / / } <nl> + / / / / } <nl> + / / / / } <nl> + / / / / <nl> + / / / / CHECK ( badCount = = 0 , TS : : FAIL_INVALID_OUTPUT ) ; <nl> + / / / / } <nl> + / / / / } <nl> + / / / / <nl> + / / / / void CV_GpuBruteForceMatcherTest : : knnMatchTest ( const GpuMat & query , const GpuMat & train ) <nl> + / / / / { <nl> + / / / / dmatcher . clear ( ) ; <nl> + / / / / <nl> + / / / / / / test const version of knnMatch ( ) <nl> + / / / / { <nl> + / / / / const int knn = 3 ; <nl> + / / / / <nl> + / / / / vector < vector < DMatch > > matches ; <nl> + / / / / dmatcher . knnMatch ( query , train , matches , knn ) ; <nl> + / / / / <nl> + / / / / CHECK ( ( int ) matches . size ( ) = = queryDescCount , TS : : FAIL_INVALID_OUTPUT ) ; <nl> + / / / / <nl> + / / / / int badCount = 0 ; <nl> + / / / / for ( size_t i = 0 ; i < matches . size ( ) ; i + + ) <nl> + / / / / { <nl> + / / / / if ( ( int ) matches [ i ] . size ( ) ! = knn ) <nl> + / / / / badCount + + ; <nl> + / / / / else <nl> + / / / / { <nl> + / / / / int localBadCount = 0 ; <nl> + / / / / for ( int k = 0 ; k < knn ; k + + ) <nl> + / / / / { <nl> + / / / / DMatch match = matches [ i ] [ k ] ; <nl> + / / / / if ( ( match . queryIdx ! = ( int ) i ) | | ( match . trainIdx ! = ( int ) i * countFactor + k ) | | ( match . imgIdx ! = 0 ) ) <nl> + / / / / localBadCount + + ; <nl> + / / / / } <nl> + / / / / badCount + = localBadCount > 0 ? 1 : 0 ; <nl> + / / / / } <nl> + / / / / } <nl> + / / / / <nl> + / / / / CHECK ( badCount = = 0 , TS : : FAIL_INVALID_OUTPUT ) ; <nl> + / / / / } <nl> + / / / / <nl> + / / / / / / test version of knnMatch ( ) with add ( ) <nl> + / / / / { <nl> + / / / / const int knn = 2 ; <nl> + / / / / vector < vector < DMatch > > matches ; <nl> + / / / / <nl> + / / / / / / make add ( ) twice to test such case <nl> + / / / / dmatcher . add ( vector < GpuMat > ( 1 , train . rowRange ( 0 , train . rows / 2 ) ) ) ; <nl> + / / / / dmatcher . add ( vector < GpuMat > ( 1 , train . rowRange ( train . rows / 2 , train . rows ) ) ) ; <nl> + / / / / <nl> + / / / / / / prepare masks ( make first nearest match illegal ) <nl> + / / / / vector < GpuMat > masks ( 2 ) ; <nl> + / / / / for ( int mi = 0 ; mi < 2 ; mi + + ) <nl> + / / / / { <nl> + / / / / masks [ mi ] = GpuMat ( query . rows , train . rows / 2 , CV_8UC1 , Scalar : : all ( 1 ) ) ; <nl> + / / / / for ( int di = 0 ; di < queryDescCount / 2 ; di + + ) <nl> + / / / / masks [ mi ] . col ( di * countFactor ) . setTo ( Scalar : : all ( 0 ) ) ; <nl> + / / / / } <nl> + / / / / <nl> + / / / / dmatcher . knnMatch ( query , matches , knn , masks ) ; <nl> + / / / / <nl> + / / / / CHECK ( ( int ) matches . size ( ) = = queryDescCount , TS : : FAIL_INVALID_OUTPUT ) ; <nl> + / / / / <nl> + / / / / int badCount = 0 ; <nl> + / / / / int shift = dmatcher . isMaskSupported ( ) ? 1 : 0 ; <nl> + / / / / for ( size_t i = 0 ; i < matches . size ( ) ; i + + ) <nl> + / / / / { <nl> + / / / / if ( ( int ) matches [ i ] . size ( ) ! = knn ) <nl> + / / / / badCount + + ; <nl> + / / / / else <nl> + / / / / { <nl> + / / / / int localBadCount = 0 ; <nl> + / / / / for ( int k = 0 ; k < knn ; k + + ) <nl> + / / / / { <nl> + / / / / DMatch match = matches [ i ] [ k ] ; <nl> + / / / / { <nl> + / / / / if ( i < queryDescCount / 2 ) <nl> + / / / / { <nl> + / / / / if ( ( match . queryIdx ! = ( int ) i ) | | ( match . trainIdx ! = ( int ) i * countFactor + k + shift ) | | ( match . imgIdx ! = 0 ) ) <nl> + / / / / localBadCount + + ; <nl> + / / / / } <nl> + / / / / else <nl> + / / / / { <nl> + / / / / if ( ( match . queryIdx ! = ( int ) i ) | | ( match . trainIdx ! = ( ( int ) i - queryDescCount / 2 ) * countFactor + k + shift ) | | ( match . imgIdx ! = 1 ) ) <nl> + / / / / localBadCount + + ; <nl> + / / / / } <nl> + / / / / } <nl> + / / / / } <nl> + / / / / badCount + = localBadCount > 0 ? 1 : 0 ; <nl> + / / / / } <nl> + / / / / } <nl> + / / / / <nl> + / / / / CHECK ( badCount = = 0 , TS : : FAIL_INVALID_OUTPUT ) ; <nl> + / / / / } <nl> + / / / / } <nl> + / / / / <nl> + / / / / void CV_GpuBruteForceMatcherTest : : radiusMatchTest ( const GpuMat & query , const GpuMat & train ) <nl> + / / / / { <nl> + / / / / CHECK_RETURN ( support ( GLOBAL_ATOMICS ) , TS : : SKIPPED ) ; <nl> + / / / / <nl> + / / / / dmatcher . clear ( ) ; <nl> + / / / / <nl> + / / / / / / test const version of match ( ) <nl> + / / / / { <nl> + / / / / const float radius = 1 . f / countFactor ; <nl> + / / / / <nl> + / / / / vector < vector < DMatch > > matches ; <nl> + / / / / dmatcher . radiusMatch ( query , train , matches , radius ) ; <nl> + / / / / <nl> + / / / / CHECK ( ( int ) matches . size ( ) = = queryDescCount , TS : : FAIL_INVALID_OUTPUT ) ; <nl> + / / / / <nl> + / / / / int badCount = 0 ; <nl> + / / / / for ( size_t i = 0 ; i < matches . size ( ) ; i + + ) <nl> + / / / / { <nl> + / / / / if ( ( int ) matches [ i ] . size ( ) ! = 1 ) <nl> + / / / / badCount + + ; <nl> + / / / / else <nl> + / / / / { <nl> + / / / / DMatch match = matches [ i ] [ 0 ] ; <nl> + / / / / if ( ( match . queryIdx ! = ( int ) i ) | | ( match . trainIdx ! = ( int ) i * countFactor ) | | ( match . imgIdx ! = 0 ) ) <nl> + / / / / badCount + + ; <nl> + / / / / } <nl> + / / / / } <nl> + / / / / <nl> + / / / / CHECK ( badCount = = 0 , TS : : FAIL_INVALID_OUTPUT ) ; <nl> + / / / / } <nl> + / / / / <nl> + / / / / / / test version of match ( ) with add ( ) <nl> + / / / / { <nl> + / / / / int n = 3 ; <nl> + / / / / const float radius = 1 . f / countFactor * n ; <nl> + / / / / vector < vector < DMatch > > matches ; <nl> + / / / / <nl> + / / / / / / make add ( ) twice to test such case <nl> + / / / / dmatcher . add ( vector < GpuMat > ( 1 , train . rowRange ( 0 , train . rows / 2 ) ) ) ; <nl> + / / / / dmatcher . add ( vector < GpuMat > ( 1 , train . rowRange ( train . rows / 2 , train . rows ) ) ) ; <nl> + / / / / <nl> + / / / / / / prepare masks ( make first nearest match illegal ) <nl> + / / / / vector < GpuMat > masks ( 2 ) ; <nl> + / / / / for ( int mi = 0 ; mi < 2 ; mi + + ) <nl> + / / / / { <nl> + / / / / masks [ mi ] = GpuMat ( query . rows , train . rows / 2 , CV_8UC1 , Scalar : : all ( 1 ) ) ; <nl> + / / / / for ( int di = 0 ; di < queryDescCount / 2 ; di + + ) <nl> + / / / / masks [ mi ] . col ( di * countFactor ) . setTo ( Scalar : : all ( 0 ) ) ; <nl> + / / / / } <nl> + / / / / <nl> + / / / / dmatcher . radiusMatch ( query , matches , radius , masks ) ; <nl> + / / / / <nl> + / / / / CHECK ( ( int ) matches . size ( ) = = queryDescCount , TS : : FAIL_INVALID_OUTPUT ) ; <nl> + / / / / <nl> + / / / / int badCount = 0 ; <nl> + / / / / int shift = dmatcher . isMaskSupported ( ) ? 1 : 0 ; <nl> + / / / / int needMatchCount = dmatcher . isMaskSupported ( ) ? n - 1 : n ; <nl> + / / / / for ( size_t i = 0 ; i < matches . size ( ) ; i + + ) <nl> + / / / / { <nl> + / / / / if ( ( int ) matches [ i ] . size ( ) ! = needMatchCount ) <nl> + / / / / badCount + + ; <nl> + / / / / else <nl> + / / / / { <nl> + / / / / int localBadCount = 0 ; <nl> + / / / / for ( int k = 0 ; k < needMatchCount ; k + + ) <nl> + / / / / { <nl> + / / / / DMatch match = matches [ i ] [ k ] ; <nl> + / / / / { <nl> + / / / / if ( i < queryDescCount / 2 ) <nl> + / / / / { <nl> + / / / / if ( ( match . queryIdx ! = ( int ) i ) | | ( match . trainIdx ! = ( int ) i * countFactor + k + shift ) | | ( match . imgIdx ! = 0 ) ) <nl> + / / / / localBadCount + + ; <nl> + / / / / } <nl> + / / / / else <nl> + / / / / { <nl> + / / / / if ( ( match . queryIdx ! = ( int ) i ) | | ( match . trainIdx ! = ( ( int ) i - queryDescCount / 2 ) * countFactor + k + shift ) | | ( match . imgIdx ! = 1 ) ) <nl> + / / / / localBadCount + + ; <nl> + / / / / } <nl> + / / / / } <nl> + / / / / } <nl> + / / / / badCount + = localBadCount > 0 ? 1 : 0 ; <nl> + / / / / } <nl> + / / / / } <nl> + / / / / <nl> + / / / / CHECK ( badCount = = 0 , TS : : FAIL_INVALID_OUTPUT ) ; <nl> + / / / / } <nl> + / / / / } <nl> + / / / / <nl> + / / / / void CV_GpuBruteForceMatcherTest : : dataTest ( int dim ) <nl> + / / / / { <nl> + / / / / GpuMat query , train ; <nl> + / / / / generateData ( query , train , dim ) ; <nl> + / / / / <nl> + / / / / matchTest ( query , train ) ; <nl> + / / / / knnMatchTest ( query , train ) ; <nl> + / / / / radiusMatchTest ( query , train ) ; <nl> + / / / / <nl> + / / / / dmatcher . clear ( ) ; <nl> + / / / / } <nl> + / / / / <nl> + / / / / void CV_GpuBruteForceMatcherTest : : run_gpu_test ( ) <nl> + / / / / { <nl> + / / / / emptyDataTest ( ) ; <nl> + / / / / <nl> + / / / / dataTest ( 50 ) ; <nl> + / / / / dataTest ( 64 ) ; <nl> + / / / / dataTest ( 100 ) ; <nl> + / / / / dataTest ( 128 ) ; <nl> + / / / / dataTest ( 200 ) ; <nl> + / / / / dataTest ( 256 ) ; <nl> + / / / / dataTest ( 300 ) ; <nl> + / / / / } <nl> + / / / / <nl> + / / / / TEST ( BruteForceMatcher , accuracy ) { CV_GpuBruteForceMatcherTest test ; test . safe_run ( ) ; } <nl> mmm a / modules / gpu / test / test_filters . cpp <nl> ppp b / modules / gpu / test / test_filters . cpp <nl> <nl> / / <nl> / / M * / <nl> <nl> - # include < iostream > <nl> - # include < cmath > <nl> - # include < limits > <nl> # include " test_precomp . hpp " <nl> <nl> - using namespace cv ; <nl> - using namespace std ; <nl> - using namespace gpu ; <nl> + # ifdef HAVE_CUDA <nl> <nl> - class CV_GpuNppFilterTest : public cvtest : : BaseTest <nl> + struct FilterTest <nl> { <nl> - public : <nl> - CV_GpuNppFilterTest ( const char * / * test_name * / , const char * / * test_funcs * / ) { } <nl> - virtual ~ CV_GpuNppFilterTest ( ) { } <nl> + static cv : : Mat img_rgba ; <nl> + static cv : : Mat img_gray ; <nl> <nl> - protected : <nl> - void run ( int ) ; <nl> - virtual int test ( const Mat & img ) = 0 ; <nl> - <nl> - int test8UC1 ( const Mat & img ) <nl> + static void SetUpTestCase ( ) <nl> { <nl> - cv : : Mat img_C1 ; <nl> - cvtColor ( img , img_C1 , CV_BGR2GRAY ) ; <nl> - return test ( img_C1 ) ; <nl> + cv : : Mat img = readImage ( " stereobp / aloe - L . png " ) ; <nl> + cv : : cvtColor ( img , img_rgba , CV_BGR2BGRA ) ; <nl> + cv : : cvtColor ( img , img_gray , CV_BGR2GRAY ) ; <nl> } <nl> <nl> - int test8UC4 ( const Mat & img ) <nl> + static void TearDownTestCase ( ) <nl> { <nl> - cv : : Mat img_C4 ; <nl> - cvtColor ( img , img_C4 , CV_BGR2BGRA ) ; <nl> - return test ( img_C4 ) ; <nl> + img_rgba . release ( ) ; <nl> + img_gray . release ( ) ; <nl> } <nl> - <nl> - int CheckNorm ( const Mat & m1 , const Mat & m2 , const Size & ksize ) <nl> - { <nl> - Rect roi = Rect ( ksize . width , ksize . height , m1 . cols - 2 * ksize . width , m1 . rows - 2 * ksize . height ) ; <nl> - Mat m1ROI = m1 ( roi ) ; <nl> - Mat m2ROI = m2 ( roi ) ; <nl> + } ; <nl> <nl> - double res = norm ( m1ROI , m2ROI , NORM_INF ) ; <nl> + cv : : Mat FilterTest : : img_rgba ; <nl> + cv : : Mat FilterTest : : img_gray ; <nl> <nl> - / / Max difference ( 2 . 0 ) in GaussianBlur <nl> - if ( res < = 2 ) <nl> - return cvtest : : TS : : OK ; <nl> - <nl> - ts - > printf ( cvtest : : TS : : LOG , " Norm : % f \ n " , res ) ; <nl> - return cvtest : : TS : : FAIL_GENERIC ; <nl> + static double checkNorm ( const cv : : Mat & m1 , const cv : : Mat & m2 , const cv : : Size & ksize ) <nl> + { <nl> + cv : : Rect roi ( ksize . width , ksize . height , m1 . cols - 2 * ksize . width , m1 . rows - 2 * ksize . height ) ; <nl> + cv : : Mat m1ROI = m1 ( roi ) ; <nl> + cv : : Mat m2ROI = m2 ( roi ) ; <nl> + return checkNorm ( m1ROI , m2ROI ) ; <nl> + } <nl> + <nl> + static double checkNorm ( const cv : : Mat & m1 , const cv : : Mat & m2 , int ksize ) <nl> + { <nl> + return checkNorm ( m1 , m2 , cv : : Size ( ksize , ksize ) ) ; <nl> + } <nl> + <nl> + # define EXPECT_MAT_NEAR_KSIZE ( mat1 , mat2 , ksize , eps ) \ <nl> + { \ <nl> + ASSERT_EQ ( mat1 . type ( ) , mat2 . type ( ) ) ; \ <nl> + ASSERT_EQ ( mat1 . size ( ) , mat2 . size ( ) ) ; \ <nl> + EXPECT_LE ( checkNorm ( mat1 , mat2 , ksize ) , eps ) ; \ <nl> } <nl> - } ; <nl> <nl> - void CV_GpuNppFilterTest : : run ( int ) <nl> - { <nl> - cv : : Mat img = cv : : imread ( std : : string ( ts - > get_data_path ( ) ) + " stereobp / aloe - L . png " ) ; <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / blur <nl> + <nl> + struct Blur : FilterTest , testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int , int > > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + cv : : Size ksize ; <nl> + <nl> + cv : : Mat dst_gold_rgba ; <nl> + cv : : Mat dst_gold_gray ; <nl> + <nl> + using FilterTest : : SetUpTestCase ; <nl> + using FilterTest : : TearDownTestCase ; <nl> <nl> - if ( img . empty ( ) ) <nl> + virtual void SetUp ( ) <nl> { <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_MISSING_TEST_DATA ) ; <nl> - return ; <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + ksize = cv : : Size ( std : : tr1 : : get < 1 > ( GetParam ( ) ) , std : : tr1 : : get < 2 > ( GetParam ( ) ) ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : blur ( img_rgba , dst_gold_rgba , ksize ) ; <nl> + cv : : blur ( img_gray , dst_gold_gray , ksize ) ; <nl> } <nl> + } ; <nl> + <nl> + TEST_P ( Blur , Accuracy ) <nl> + { <nl> + ASSERT_TRUE ( ! img_rgba . empty ( ) & & ! img_gray . empty ( ) ) ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_PARAM ( ksize ) ; <nl> <nl> - / / run tests <nl> - int testResult = cvtest : : TS : : OK ; <nl> + cv : : Mat dst_rgba ; <nl> + cv : : Mat dst_gray ; <nl> <nl> - if ( test8UC1 ( img ) ! = cvtest : : TS : : OK ) <nl> - testResult = cvtest : : TS : : FAIL_GENERIC ; <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat dev_dst_rgba ; <nl> + cv : : gpu : : GpuMat dev_dst_gray ; <nl> <nl> - if ( test8UC4 ( img ) ! = cvtest : : TS : : OK ) <nl> - testResult = cvtest : : TS : : FAIL_GENERIC ; <nl> + cv : : gpu : : blur ( cv : : gpu : : GpuMat ( img_rgba ) , dev_dst_rgba , ksize ) ; <nl> + cv : : gpu : : blur ( cv : : gpu : : GpuMat ( img_gray ) , dev_dst_gray , ksize ) ; <nl> <nl> - ts - > set_failed_test_info ( testResult ) ; <nl> + dev_dst_rgba . download ( dst_rgba ) ; <nl> + dev_dst_gray . download ( dst_gray ) ; <nl> + ) ; <nl> <nl> - ts - > set_failed_test_info ( cvtest : : TS : : OK ) ; <nl> + EXPECT_MAT_NEAR_KSIZE ( dst_gold_rgba , dst_rgba , ksize , 1 . 0 ) ; <nl> + EXPECT_MAT_NEAR_KSIZE ( dst_gold_gray , dst_gray , ksize , 1 . 0 ) ; <nl> } <nl> <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / blur <nl> - struct CV_GpuNppImageBlurTest : public CV_GpuNppFilterTest <nl> + INSTANTIATE_TEST_CASE_P ( Filter , Blur , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( 3 , 5 , 7 ) , <nl> + testing : : Values ( 3 , 5 , 7 ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / sobel <nl> + <nl> + struct Sobel : FilterTest , testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int , std : : pair < int , int > > > <nl> { <nl> - CV_GpuNppImageBlurTest ( ) : CV_GpuNppFilterTest ( " GPU - NppImageBlur " , " blur " ) { } <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int ksize ; <nl> + int dx , dy ; <nl> + <nl> + cv : : Mat dst_gold_rgba ; <nl> + cv : : Mat dst_gold_gray ; <nl> <nl> - int test ( const Mat & img ) <nl> + using FilterTest : : SetUpTestCase ; <nl> + using FilterTest : : TearDownTestCase ; <nl> + <nl> + virtual void SetUp ( ) <nl> { <nl> - int ksizes [ ] = { 3 , 5 , 7 } ; <nl> - int ksizes_num = sizeof ( ksizes ) / sizeof ( int ) ; <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + ksize = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> + std : : pair < int , int > d = std : : tr1 : : get < 2 > ( GetParam ( ) ) ; <nl> + dx = d . first ; dy = d . second ; <nl> <nl> - int test_res = cvtest : : TS : : OK ; <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : Sobel ( img_rgba , dst_gold_rgba , - 1 , dx , dy , ksize ) ; <nl> + cv : : Sobel ( img_gray , dst_gold_gray , - 1 , dx , dy , ksize ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( Sobel , Accuracy ) <nl> + { <nl> + ASSERT_TRUE ( ! img_rgba . empty ( ) & & ! img_gray . empty ( ) ) ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_PARAM ( ksize ) ; <nl> + PRINT_PARAM ( dx ) ; <nl> + PRINT_PARAM ( dy ) ; <nl> + <nl> + cv : : Mat dst_rgba ; <nl> + cv : : Mat dst_gray ; <nl> <nl> - for ( int i = 0 ; i < ksizes_num ; + + i ) <nl> - { <nl> - for ( int j = 0 ; j < ksizes_num ; + + j ) <nl> - { <nl> - Size ksize ( ksizes [ i ] , ksizes [ j ] ) ; <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat dev_dst_rgba ; <nl> + cv : : gpu : : GpuMat dev_dst_gray ; <nl> <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ nksize = ( % dx % d ) \ n " , ksizes [ i ] , ksizes [ j ] ) ; <nl> + cv : : gpu : : Sobel ( cv : : gpu : : GpuMat ( img_rgba ) , dev_dst_rgba , - 1 , dx , dy , ksize ) ; <nl> + cv : : gpu : : Sobel ( cv : : gpu : : GpuMat ( img_gray ) , dev_dst_gray , - 1 , dx , dy , ksize ) ; <nl> <nl> - Mat cpudst ; <nl> - cv : : blur ( img , cpudst , ksize ) ; <nl> + dev_dst_rgba . download ( dst_rgba ) ; <nl> + dev_dst_gray . download ( dst_gray ) ; <nl> + ) ; <nl> <nl> - GpuMat gpu1 ( img ) ; <nl> - GpuMat gpudst ; <nl> - cv : : gpu : : blur ( gpu1 , gpudst , ksize ) ; <nl> + EXPECT_MAT_NEAR_KSIZE ( dst_gold_rgba , dst_rgba , ksize , 0 . 0 ) ; <nl> + EXPECT_MAT_NEAR_KSIZE ( dst_gold_gray , dst_gray , ksize , 0 . 0 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( Filter , Sobel , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( 3 , 5 , 7 ) , <nl> + testing : : Values ( std : : make_pair ( 1 , 0 ) , std : : make_pair ( 0 , 1 ) , std : : make_pair ( 1 , 1 ) , std : : make_pair ( 2 , 0 ) , std : : make_pair ( 2 , 1 ) , std : : make_pair ( 0 , 2 ) , std : : make_pair ( 1 , 2 ) , std : : make_pair ( 2 , 2 ) ) ) ) ; <nl> <nl> - if ( CheckNorm ( cpudst , gpudst , ksize ) ! = cvtest : : TS : : OK ) <nl> - test_res = cvtest : : TS : : FAIL_GENERIC ; <nl> - } <nl> - } <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / scharr <nl> + <nl> + struct Scharr : FilterTest , testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , std : : pair < int , int > > > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int dx , dy ; <nl> <nl> - return test_res ; <nl> + cv : : Mat dst_gold_rgba ; <nl> + cv : : Mat dst_gold_gray ; <nl> + <nl> + using FilterTest : : SetUpTestCase ; <nl> + using FilterTest : : TearDownTestCase ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + std : : pair < int , int > d = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> + dx = d . first ; dy = d . second ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : Scharr ( img_rgba , dst_gold_rgba , - 1 , dx , dy ) ; <nl> + cv : : Scharr ( img_gray , dst_gold_gray , - 1 , dx , dy ) ; <nl> } <nl> } ; <nl> <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / Sobel <nl> - struct CV_GpuNppImageSobelTest : public CV_GpuNppFilterTest <nl> + TEST_P ( Scharr , Accuracy ) <nl> { <nl> - CV_GpuNppImageSobelTest ( ) : CV_GpuNppFilterTest ( " GPU - NppImageSobel " , " Sobel " ) { } <nl> + ASSERT_TRUE ( ! img_rgba . empty ( ) & & ! img_gray . empty ( ) ) ; <nl> <nl> - int test ( const Mat & img ) <nl> - { <nl> - int ksizes [ ] = { 3 , 5 , 7 } ; <nl> - int ksizes_num = sizeof ( ksizes ) / sizeof ( int ) ; <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_PARAM ( dx ) ; <nl> + PRINT_PARAM ( dy ) ; <nl> <nl> - int dx = 1 , dy = 0 ; <nl> + cv : : Mat dst_rgba ; <nl> + cv : : Mat dst_gray ; <nl> <nl> - int test_res = cvtest : : TS : : OK ; <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat dev_dst_rgba ; <nl> + cv : : gpu : : GpuMat dev_dst_gray ; <nl> <nl> - for ( int i = 0 ; i < ksizes_num ; + + i ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ nksize = % d \ n " , ksizes [ i ] ) ; <nl> + cv : : gpu : : Scharr ( cv : : gpu : : GpuMat ( img_rgba ) , dev_dst_rgba , - 1 , dx , dy ) ; <nl> + cv : : gpu : : Scharr ( cv : : gpu : : GpuMat ( img_gray ) , dev_dst_gray , - 1 , dx , dy ) ; <nl> <nl> - Mat cpudst ; <nl> - cv : : Sobel ( img , cpudst , - 1 , dx , dy , ksizes [ i ] ) ; <nl> + dev_dst_rgba . download ( dst_rgba ) ; <nl> + dev_dst_gray . download ( dst_gray ) ; <nl> + ) ; <nl> <nl> - GpuMat gpu1 ( img ) ; <nl> - GpuMat gpudst ; <nl> - cv : : gpu : : Sobel ( gpu1 , gpudst , - 1 , dx , dy , ksizes [ i ] ) ; <nl> + EXPECT_MAT_NEAR_KSIZE ( dst_gold_rgba , dst_rgba , 3 , 0 . 0 ) ; <nl> + EXPECT_MAT_NEAR_KSIZE ( dst_gold_gray , dst_gray , 3 , 0 . 0 ) ; <nl> + } <nl> <nl> - if ( CheckNorm ( cpudst , gpudst , Size ( ksizes [ i ] , ksizes [ i ] ) ) ! = cvtest : : TS : : OK ) <nl> - test_res = cvtest : : TS : : FAIL_GENERIC ; <nl> - } <nl> + INSTANTIATE_TEST_CASE_P ( Filter , Scharr , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( std : : make_pair ( 1 , 0 ) , std : : make_pair ( 0 , 1 ) ) ) ) ; <nl> <nl> - return test_res ; <nl> - } <nl> - } ; <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / gaussianBlur <nl> <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / Scharr <nl> - struct CV_GpuNppImageScharrTest : public CV_GpuNppFilterTest <nl> + struct GaussianBlur : FilterTest , testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int , int > > <nl> { <nl> - CV_GpuNppImageScharrTest ( ) : CV_GpuNppFilterTest ( " GPU - NppImageScharr " , " Scharr " ) { } <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + cv : : Size ksize ; <nl> + <nl> + double sigma1 , sigma2 ; <nl> <nl> - int test ( const Mat & img ) <nl> + cv : : Mat dst_gold_rgba ; <nl> + cv : : Mat dst_gold_gray ; <nl> + <nl> + using FilterTest : : SetUpTestCase ; <nl> + using FilterTest : : TearDownTestCase ; <nl> + <nl> + virtual void SetUp ( ) <nl> { <nl> - int dx = 1 , dy = 0 ; <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + ksize = cv : : Size ( std : : tr1 : : get < 1 > ( GetParam ( ) ) , std : : tr1 : : get < 2 > ( GetParam ( ) ) ) ; <nl> <nl> - Mat cpudst ; <nl> - cv : : Scharr ( img , cpudst , - 1 , dx , dy ) ; <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> <nl> - GpuMat gpu1 ( img ) ; <nl> - GpuMat gpudst ; <nl> - cv : : gpu : : Scharr ( gpu1 , gpudst , - 1 , dx , dy ) ; <nl> - <nl> - return CheckNorm ( cpudst , gpudst , Size ( 3 , 3 ) ) ; <nl> + sigma1 = rng . uniform ( 0 . 1 , 1 . 0 ) ; <nl> + sigma2 = rng . uniform ( 0 . 1 , 1 . 0 ) ; <nl> + <nl> + cv : : GaussianBlur ( img_rgba , dst_gold_rgba , ksize , sigma1 , sigma2 ) ; <nl> + cv : : GaussianBlur ( img_gray , dst_gold_gray , ksize , sigma1 , sigma2 ) ; <nl> } <nl> } ; <nl> <nl> - <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / GaussianBlur <nl> - struct CV_GpuNppImageGaussianBlurTest : public CV_GpuNppFilterTest <nl> + TEST_P ( GaussianBlur , Accuracy ) <nl> { <nl> - CV_GpuNppImageGaussianBlurTest ( ) : CV_GpuNppFilterTest ( " GPU - NppImageGaussianBlur " , " GaussianBlur " ) { } <nl> + ASSERT_TRUE ( ! img_rgba . empty ( ) & & ! img_gray . empty ( ) ) ; <nl> <nl> - int test ( const Mat & img ) <nl> - { <nl> - int ksizes [ ] = { 3 , 5 , 7 } ; <nl> - int ksizes_num = sizeof ( ksizes ) / sizeof ( int ) ; <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_PARAM ( ksize ) ; <nl> + PRINT_PARAM ( sigma1 ) ; <nl> + PRINT_PARAM ( sigma2 ) ; <nl> <nl> - int test_res = cvtest : : TS : : OK ; <nl> + cv : : Mat dst_rgba ; <nl> + cv : : Mat dst_gray ; <nl> <nl> - const double sigma1 = 3 . 0 ; <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat dev_dst_rgba ; <nl> + cv : : gpu : : GpuMat dev_dst_gray ; <nl> <nl> - for ( int i = 0 ; i < ksizes_num ; + + i ) <nl> - { <nl> - for ( int j = 0 ; j < ksizes_num ; + + j ) <nl> - { <nl> - cv : : Size ksize ( ksizes [ i ] , ksizes [ j ] ) ; <nl> + cv : : gpu : : GaussianBlur ( cv : : gpu : : GpuMat ( img_rgba ) , dev_dst_rgba , ksize , sigma1 , sigma2 ) ; <nl> + cv : : gpu : : GaussianBlur ( cv : : gpu : : GpuMat ( img_gray ) , dev_dst_gray , ksize , sigma1 , sigma2 ) ; <nl> <nl> - ts - > printf ( cvtest : : TS : : LOG , " ksize = ( % dx % d ) \ t \ n " , ksizes [ i ] , ksizes [ j ] ) ; <nl> + dev_dst_rgba . download ( dst_rgba ) ; <nl> + dev_dst_gray . download ( dst_gray ) ; <nl> + ) ; <nl> <nl> - Mat cpudst ; <nl> - cv : : GaussianBlur ( img , cpudst , ksize , sigma1 ) ; <nl> + EXPECT_MAT_NEAR_KSIZE ( dst_gold_rgba , dst_rgba , ksize , 3 . 0 ) ; <nl> + EXPECT_MAT_NEAR_KSIZE ( dst_gold_gray , dst_gray , ksize , 3 . 0 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( Filter , GaussianBlur , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( 3 , 5 , 7 ) , <nl> + testing : : Values ( 3 , 5 , 7 ) ) ) ; <nl> <nl> - GpuMat gpu1 ( img ) ; <nl> - GpuMat gpudst ; <nl> - cv : : gpu : : GaussianBlur ( gpu1 , gpudst , ksize , sigma1 ) ; <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / laplacian <nl> + <nl> + struct Laplacian : FilterTest , testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int > > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int ksize ; <nl> + <nl> + cv : : Mat dst_gold_rgba ; <nl> + cv : : Mat dst_gold_gray ; <nl> + <nl> + using FilterTest : : SetUpTestCase ; <nl> + using FilterTest : : TearDownTestCase ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + ksize = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> <nl> - if ( CheckNorm ( cpudst , gpudst , ksize ) ! = cvtest : : TS : : OK ) <nl> - test_res = cvtest : : TS : : FAIL_GENERIC ; <nl> - } <nl> - } <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> <nl> - return test_res ; <nl> + cv : : Laplacian ( img_rgba , dst_gold_rgba , - 1 , ksize ) ; <nl> + cv : : Laplacian ( img_gray , dst_gold_gray , - 1 , ksize ) ; <nl> } <nl> } ; <nl> <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / Laplacian <nl> - struct CV_GpuNppImageLaplacianTest : public CV_GpuNppFilterTest <nl> + TEST_P ( Laplacian , Accuracy ) <nl> { <nl> - CV_GpuNppImageLaplacianTest ( ) : CV_GpuNppFilterTest ( " GPU - NppImageLaplacian " , " Laplacian " ) { } <nl> + ASSERT_TRUE ( ! img_rgba . empty ( ) & & ! img_gray . empty ( ) ) ; <nl> <nl> - int test ( const Mat & img ) <nl> - { <nl> - int ksizes [ ] = { 1 , 3 } ; <nl> - int ksizes_num = sizeof ( ksizes ) / sizeof ( int ) ; <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_PARAM ( ksize ) ; <nl> <nl> - int test_res = cvtest : : TS : : OK ; <nl> + cv : : Mat dst_rgba ; <nl> + cv : : Mat dst_gray ; <nl> <nl> - for ( int i = 0 ; i < ksizes_num ; + + i ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ nksize = % d \ n " , ksizes [ i ] ) ; <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat dev_dst_rgba ; <nl> + cv : : gpu : : GpuMat dev_dst_gray ; <nl> <nl> - Mat cpudst ; <nl> - cv : : Laplacian ( img , cpudst , - 1 , ksizes [ i ] ) ; <nl> + cv : : gpu : : Laplacian ( cv : : gpu : : GpuMat ( img_rgba ) , dev_dst_rgba , - 1 , ksize ) ; <nl> + cv : : gpu : : Laplacian ( cv : : gpu : : GpuMat ( img_gray ) , dev_dst_gray , - 1 , ksize ) ; <nl> <nl> - GpuMat gpu1 ( img ) ; <nl> - GpuMat gpudst ; <nl> - cv : : gpu : : Laplacian ( gpu1 , gpudst , - 1 , ksizes [ i ] ) ; <nl> + dev_dst_rgba . download ( dst_rgba ) ; <nl> + dev_dst_gray . download ( dst_gray ) ; <nl> + ) ; <nl> <nl> - if ( CheckNorm ( cpudst , gpudst , Size ( 3 , 3 ) ) ! = cvtest : : TS : : OK ) <nl> - test_res = cvtest : : TS : : FAIL_GENERIC ; <nl> - } <nl> + EXPECT_MAT_NEAR_KSIZE ( dst_gold_rgba , dst_rgba , 3 , 0 . 0 ) ; <nl> + EXPECT_MAT_NEAR_KSIZE ( dst_gold_gray , dst_gray , 3 , 0 . 0 ) ; <nl> + } <nl> <nl> - return test_res ; <nl> - } <nl> - } ; <nl> + INSTANTIATE_TEST_CASE_P ( Filter , Laplacian , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( 1 , 3 ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / erode <nl> <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / Erode <nl> - class CV_GpuErodeTest : public CV_GpuNppFilterTest <nl> + struct Erode : FilterTest , testing : : TestWithParam < cv : : gpu : : DeviceInfo > <nl> { <nl> - public : <nl> - CV_GpuErodeTest ( ) : CV_GpuNppFilterTest ( " GPU - NppErode " , " erode " ) { } <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + <nl> + cv : : Mat kernel ; <nl> <nl> - protected : <nl> - virtual int test ( const Mat & img ) <nl> + cv : : Mat dst_gold_rgba ; <nl> + cv : : Mat dst_gold_gray ; <nl> + <nl> + using FilterTest : : SetUpTestCase ; <nl> + using FilterTest : : TearDownTestCase ; <nl> + <nl> + virtual void SetUp ( ) <nl> { <nl> - Mat kernel ( Mat : : ones ( 3 , 3 , CV_8U ) ) ; <nl> + devInfo = GetParam ( ) ; <nl> <nl> - cv : : Mat cpuRes ; <nl> - cv : : erode ( img , cpuRes , kernel ) ; <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> <nl> - GpuMat gpuRes ; <nl> - cv : : gpu : : erode ( GpuMat ( img ) , gpuRes , kernel ) ; <nl> + kernel = cv : : Mat : : ones ( 3 , 3 , CV_8U ) ; <nl> <nl> - return CheckNorm ( cpuRes , gpuRes , Size ( 3 , 3 ) ) ; <nl> + cv : : erode ( img_rgba , dst_gold_rgba , kernel ) ; <nl> + cv : : erode ( img_gray , dst_gold_gray , kernel ) ; <nl> } <nl> } ; <nl> <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / Dilate <nl> - class CV_GpuDilateTest : public CV_GpuNppFilterTest <nl> + TEST_P ( Erode , Accuracy ) <nl> + { <nl> + ASSERT_TRUE ( ! img_rgba . empty ( ) & & ! img_gray . empty ( ) ) ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + <nl> + cv : : Mat dst_rgba ; <nl> + cv : : Mat dst_gray ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat dev_dst_rgba ; <nl> + cv : : gpu : : GpuMat dev_dst_gray ; <nl> + <nl> + cv : : gpu : : erode ( cv : : gpu : : GpuMat ( img_rgba ) , dev_dst_rgba , kernel ) ; <nl> + cv : : gpu : : erode ( cv : : gpu : : GpuMat ( img_gray ) , dev_dst_gray , kernel ) ; <nl> + <nl> + dev_dst_rgba . download ( dst_rgba ) ; <nl> + dev_dst_gray . download ( dst_gray ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR_KSIZE ( dst_gold_rgba , dst_rgba , 3 , 0 . 0 ) ; <nl> + EXPECT_MAT_NEAR_KSIZE ( dst_gold_gray , dst_gray , 3 , 0 . 0 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( Filter , Erode , testing : : ValuesIn ( devices ( ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / dilate <nl> + <nl> + struct Dilate : FilterTest , testing : : TestWithParam < cv : : gpu : : DeviceInfo > <nl> { <nl> - public : <nl> - CV_GpuDilateTest ( ) : CV_GpuNppFilterTest ( " GPU - NppDilate " , " dilate " ) { } <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + <nl> + cv : : Mat kernel ; <nl> <nl> - protected : <nl> - virtual int test ( const Mat & img ) <nl> + cv : : Mat dst_gold_rgba ; <nl> + cv : : Mat dst_gold_gray ; <nl> + <nl> + using FilterTest : : SetUpTestCase ; <nl> + using FilterTest : : TearDownTestCase ; <nl> + <nl> + virtual void SetUp ( ) <nl> { <nl> - Mat kernel ( Mat : : ones ( 3 , 3 , CV_8U ) ) ; <nl> + devInfo = GetParam ( ) ; <nl> <nl> - cv : : Mat cpuRes ; <nl> - cv : : dilate ( img , cpuRes , kernel ) ; <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> <nl> - GpuMat gpuRes ; <nl> - cv : : gpu : : dilate ( GpuMat ( img ) , gpuRes , kernel ) ; <nl> - <nl> - return CheckNorm ( cpuRes , gpuRes , Size ( 3 , 3 ) ) ; <nl> + kernel = cv : : Mat : : ones ( 3 , 3 , CV_8U ) ; <nl> + <nl> + cv : : dilate ( img_rgba , dst_gold_rgba , kernel ) ; <nl> + cv : : dilate ( img_gray , dst_gold_gray , kernel ) ; <nl> } <nl> } ; <nl> <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / MorphologyEx <nl> - class CV_GpuMorphExTest : public CV_GpuNppFilterTest <nl> + TEST_P ( Dilate , Accuracy ) <nl> { <nl> - public : <nl> - CV_GpuMorphExTest ( ) : CV_GpuNppFilterTest ( " GPU - NppMorphologyEx " , " morphologyEx " ) { } <nl> + ASSERT_TRUE ( ! img_rgba . empty ( ) & & ! img_gray . empty ( ) ) ; <nl> <nl> - protected : <nl> - virtual int test ( const Mat & img ) <nl> - { <nl> - static int ops [ ] = { MORPH_OPEN , CV_MOP_CLOSE , CV_MOP_GRADIENT , CV_MOP_TOPHAT , CV_MOP_BLACKHAT } ; <nl> - const char * names [ ] = { " MORPH_OPEN " , " CV_MOP_CLOSE " , " CV_MOP_GRADIENT " , " CV_MOP_TOPHAT " , " CV_MOP_BLACKHAT " } ; <nl> - int num = sizeof ( ops ) / sizeof ( ops [ 0 ] ) ; <nl> + PRINT_PARAM ( devInfo ) ; <nl> + <nl> + cv : : Mat dst_rgba ; <nl> + cv : : Mat dst_gray ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat dev_dst_rgba ; <nl> + cv : : gpu : : GpuMat dev_dst_gray ; <nl> + <nl> + cv : : gpu : : dilate ( cv : : gpu : : GpuMat ( img_rgba ) , dev_dst_rgba , kernel ) ; <nl> + cv : : gpu : : dilate ( cv : : gpu : : GpuMat ( img_gray ) , dev_dst_gray , kernel ) ; <nl> <nl> - GpuMat kernel ( Mat : : ones ( 3 , 3 , CV_8U ) ) ; <nl> + dev_dst_rgba . download ( dst_rgba ) ; <nl> + dev_dst_gray . download ( dst_gray ) ; <nl> + ) ; <nl> <nl> - int res = cvtest : : TS : : OK ; <nl> + EXPECT_MAT_NEAR_KSIZE ( dst_gold_rgba , dst_rgba , 3 , 0 . 0 ) ; <nl> + EXPECT_MAT_NEAR_KSIZE ( dst_gold_gray , dst_gray , 3 , 0 . 0 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( Filter , Dilate , testing : : ValuesIn ( devices ( ) ) ) ; <nl> <nl> - for ( int i = 0 ; i < num ; + + i ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " Tesing % s \ n " , names [ i ] ) ; <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / morphEx <nl> <nl> - cv : : Mat cpuRes ; <nl> - cv : : morphologyEx ( img , cpuRes , ops [ i ] , ( Mat ) kernel ) ; <nl> + static const int morphOps [ ] = { cv : : MORPH_OPEN , CV_MOP_CLOSE , CV_MOP_GRADIENT , CV_MOP_TOPHAT , CV_MOP_BLACKHAT } ; <nl> + static const char * morphOps_str [ ] = { " MORPH_OPEN " , " MOP_CLOSE " , " MOP_GRADIENT " , " MOP_TOPHAT " , " MOP_BLACKHAT " } ; <nl> + <nl> + struct MorphEx : FilterTest , testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int > > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int morphOpsIdx ; <nl> <nl> - GpuMat gpuRes ; <nl> - cv : : gpu : : morphologyEx ( GpuMat ( img ) , gpuRes , ops [ i ] , kernel ) ; <nl> + cv : : Mat kernel ; <nl> <nl> - if ( cvtest : : TS : : OK ! = CheckNorm ( cpuRes , gpuRes , Size ( 4 , 4 ) ) ) <nl> - res = cvtest : : TS : : FAIL_GENERIC ; <nl> - } <nl> - return res ; <nl> + cv : : Mat dst_gold_rgba ; <nl> + cv : : Mat dst_gold_gray ; <nl> + <nl> + using FilterTest : : SetUpTestCase ; <nl> + using FilterTest : : TearDownTestCase ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + morphOpsIdx = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + kernel = cv : : Mat : : ones ( 3 , 3 , CV_8U ) ; <nl> + <nl> + cv : : morphologyEx ( img_rgba , dst_gold_rgba , morphOps [ morphOpsIdx ] , kernel ) ; <nl> + cv : : morphologyEx ( img_gray , dst_gold_gray , morphOps [ morphOpsIdx ] , kernel ) ; <nl> } <nl> } ; <nl> <nl> + TEST_P ( MorphEx , Accuracy ) <nl> + { <nl> + ASSERT_TRUE ( ! img_rgba . empty ( ) & & ! img_gray . empty ( ) ) ; <nl> + <nl> + const char * morphOpStr = morphOps_str [ morphOpsIdx ] ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_PARAM ( morphOpStr ) ; <nl> + <nl> + cv : : Mat dst_rgba ; <nl> + cv : : Mat dst_gray ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat dev_dst_rgba ; <nl> + cv : : gpu : : GpuMat dev_dst_gray ; <nl> + <nl> + cv : : gpu : : morphologyEx ( cv : : gpu : : GpuMat ( img_rgba ) , dev_dst_rgba , morphOps [ morphOpsIdx ] , cv : : gpu : : GpuMat ( kernel ) ) ; <nl> + cv : : gpu : : morphologyEx ( cv : : gpu : : GpuMat ( img_gray ) , dev_dst_gray , morphOps [ morphOpsIdx ] , cv : : gpu : : GpuMat ( kernel ) ) ; <nl> + <nl> + dev_dst_rgba . download ( dst_rgba ) ; <nl> + dev_dst_gray . download ( dst_gray ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR_KSIZE ( dst_gold_rgba , dst_rgba , 4 , 0 . 0 ) ; <nl> + EXPECT_MAT_NEAR_KSIZE ( dst_gold_gray , dst_gray , 4 , 0 . 0 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( Filter , MorphEx , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Range ( 0 , 5 ) ) ) ; <nl> <nl> - TEST ( blur , accuracy ) { CV_GpuNppImageBlurTest test ; test . safe_run ( ) ; } <nl> - TEST ( sobel , accuracy ) { CV_GpuNppImageSobelTest test ; test . safe_run ( ) ; } <nl> - TEST ( scharr , accuracy ) { CV_GpuNppImageScharrTest test ; test . safe_run ( ) ; } <nl> - TEST ( gaussianBlur , accuracy ) { CV_GpuNppImageGaussianBlurTest test ; test . safe_run ( ) ; } <nl> - TEST ( laplcaian , accuracy ) { CV_GpuNppImageLaplacianTest test ; test . safe_run ( ) ; } <nl> - TEST ( erode , accuracy ) { CV_GpuErodeTest test ; test . safe_run ( ) ; } <nl> - TEST ( dilate , accuracy ) { CV_GpuDilateTest test ; test . safe_run ( ) ; } <nl> - TEST ( morphEx , accuracy ) { CV_GpuMorphExTest test ; test . safe_run ( ) ; } <nl> + # endif / / HAVE_CUDA <nl> new file mode 100644 <nl> index 00000000000 . . f035d7a3caa <nl> mmm / dev / null <nl> ppp b / modules / gpu / test / test_gpu_base . cpp <nl> <nl> + / * M / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / <nl> + / / IMPORTANT : READ BEFORE DOWNLOADING , COPYING , INSTALLING OR USING . <nl> + / / <nl> + / / By downloading , copying , installing or using the software you agree to this license . <nl> + / / If you do not agree to this license , do not download , install , <nl> + / / copy or use the software . <nl> + / / <nl> + / / <nl> + / / Intel License Agreement <nl> + / / For Open Source Computer Vision Library <nl> + / / <nl> + / / Copyright ( C ) 2000 , Intel Corporation , all rights reserved . <nl> + / / Third party copyrights are property of their respective owners . <nl> + / / <nl> + / / Redistribution and use in source and binary forms , with or without modification , <nl> + / / are permitted provided that the following conditions are met : <nl> + / / <nl> + / / * Redistribution ' s of source code must retain the above copyright notice , <nl> + / / this list of conditions and the following disclaimer . <nl> + / / <nl> + / / * Redistribution ' s in binary form must reproduce the above copyright notice , <nl> + / / this list of conditions and the following disclaimer in the documentation <nl> + / / and / or other materials provided with the distribution . <nl> + / / <nl> + / / * The name of Intel Corporation may not be used to endorse or promote products <nl> + / / derived from this software without specific prior written permission . <nl> + / / <nl> + / / This software is provided by the copyright holders and contributors " as is " and <nl> + / / any express or implied warranties , including , but not limited to , the implied <nl> + / / warranties of merchantability and fitness for a particular purpose are disclaimed . <nl> + / / In no event shall the Intel Corporation or contributors be liable for any direct , <nl> + / / indirect , incidental , special , exemplary , or consequential damages <nl> + / / ( including , but not limited to , procurement of substitute goods or services ; <nl> + / / loss of use , data , or profits ; or business interruption ) however caused <nl> + / / and on any theory of liability , whether in contract , strict liability , <nl> + / / or tort ( including negligence or otherwise ) arising in any way out of <nl> + / / the use of this software , even if advised of the possibility of such damage . <nl> + / / <nl> + / / M * / <nl> + <nl> + # include " test_precomp . hpp " <nl> + <nl> + bool supportFeature ( const cv : : gpu : : DeviceInfo & info , cv : : gpu : : FeatureSet feature ) <nl> + { <nl> + return cv : : gpu : : TargetArchs : : builtWith ( feature ) & & info . supports ( feature ) ; <nl> + } <nl> + <nl> + const std : : vector < cv : : gpu : : DeviceInfo > & devices ( ) <nl> + { <nl> + static std : : vector < cv : : gpu : : DeviceInfo > devs ; <nl> + static bool first = true ; <nl> + <nl> + if ( first ) <nl> + { <nl> + int deviceCount = cv : : gpu : : getCudaEnabledDeviceCount ( ) ; <nl> + <nl> + devs . reserve ( deviceCount ) ; <nl> + <nl> + for ( int i = 0 ; i < deviceCount ; + + i ) <nl> + { <nl> + cv : : gpu : : DeviceInfo info ( i ) ; <nl> + if ( info . isCompatible ( ) ) <nl> + devs . push_back ( info ) ; <nl> + } <nl> + <nl> + first = false ; <nl> + } <nl> + <nl> + return devs ; <nl> + } <nl> + <nl> + std : : vector < cv : : gpu : : DeviceInfo > devices ( cv : : gpu : : FeatureSet feature ) <nl> + { <nl> + const std : : vector < cv : : gpu : : DeviceInfo > & d = devices ( ) ; <nl> + <nl> + std : : vector < cv : : gpu : : DeviceInfo > devs_filtered ; <nl> + <nl> + if ( cv : : gpu : : TargetArchs : : builtWith ( feature ) ) <nl> + { <nl> + devs_filtered . reserve ( d . size ( ) ) ; <nl> + <nl> + for ( size_t i = 0 , size = d . size ( ) ; i < size ; + + i ) <nl> + { <nl> + const cv : : gpu : : DeviceInfo & info = d [ i ] ; <nl> + <nl> + if ( info . supports ( feature ) ) <nl> + devs_filtered . push_back ( info ) ; <nl> + } <nl> + } <nl> + <nl> + return devs_filtered ; <nl> + } <nl> + <nl> + std : : vector < int > types ( int depth_start , int depth_end , int cn_start , int cn_end ) <nl> + { <nl> + std : : vector < int > v ; <nl> + <nl> + v . reserve ( ( depth_end - depth_start + 1 ) * ( cn_end - cn_start + 1 ) ) ; <nl> + <nl> + for ( int depth = depth_start ; depth < = depth_end ; + + depth ) <nl> + { <nl> + for ( int cn = cn_start ; cn < = cn_end ; + + cn ) <nl> + { <nl> + v . push_back ( CV_MAKETYPE ( depth , cn ) ) ; <nl> + } <nl> + } <nl> + <nl> + return v ; <nl> + } <nl> + <nl> + const std : : vector < int > & all_types ( ) <nl> + { <nl> + static std : : vector < int > v = types ( CV_8U , CV_64F , 1 , 4 ) ; <nl> + return v ; <nl> + } <nl> + <nl> + cv : : Mat readImage ( const std : : string & fileName , int flags ) <nl> + { <nl> + return cv : : imread ( std : : string ( cvtest : : TS : : ptr ( ) - > get_data_path ( ) ) + fileName , flags ) ; <nl> + } <nl> + <nl> + double checkNorm ( const cv : : Mat & m1 , const cv : : Mat & m2 ) <nl> + { <nl> + return cv : : norm ( m1 , m2 , cv : : NORM_INF ) ; <nl> + } <nl> + <nl> + double checkSimilarity ( const cv : : Mat & m1 , const cv : : Mat & m2 ) <nl> + { <nl> + cv : : Mat diff ; <nl> + cv : : matchTemplate ( m1 , m2 , diff , CV_TM_CCORR_NORMED ) ; <nl> + return std : : abs ( diff . at < float > ( 0 , 0 ) - 1 . f ) ; <nl> + } <nl> + <nl> + namespace cv <nl> + { <nl> + std : : ostream & operator < < ( std : : ostream & os , const Size & sz ) <nl> + { <nl> + return os < < sz . width < < " x " < < sz . height ; <nl> + } <nl> + <nl> + std : : ostream & operator < < ( std : : ostream & os , const Scalar & s ) <nl> + { <nl> + return os < < " [ " < < s [ 0 ] < < " , " < < s [ 1 ] < < " , " < < s [ 2 ] < < " , " < < s [ 3 ] < < " ] " ; <nl> + } <nl> + <nl> + namespace gpu <nl> + { <nl> + std : : ostream & operator < < ( std : : ostream & os , const DeviceInfo & info ) <nl> + { <nl> + return os < < info . name ( ) ; <nl> + } <nl> + } <nl> + } <nl> new file mode 100644 <nl> index 00000000000 . . 25bf163a3d0 <nl> mmm / dev / null <nl> ppp b / modules / gpu / test / test_gpu_base . hpp <nl> <nl> + / * M / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / <nl> + / / IMPORTANT : READ BEFORE DOWNLOADING , COPYING , INSTALLING OR USING . <nl> + / / <nl> + / / By downloading , copying , installing or using the software you agree to this license . <nl> + / / If you do not agree to this license , do not download , install , <nl> + / / copy or use the software . <nl> + / / <nl> + / / <nl> + / / Intel License Agreement <nl> + / / For Open Source Computer Vision Library <nl> + / / <nl> + / / Copyright ( C ) 2000 , Intel Corporation , all rights reserved . <nl> + / / Third party copyrights are property of their respective owners . <nl> + / / <nl> + / / Redistribution and use in source and binary forms , with or without modification , <nl> + / / are permitted provided that the following conditions are met : <nl> + / / <nl> + / / * Redistribution ' s of source code must retain the above copyright notice , <nl> + / / this list of conditions and the following disclaimer . <nl> + / / <nl> + / / * Redistribution ' s in binary form must reproduce the above copyright notice , <nl> + / / this list of conditions and the following disclaimer in the documentation <nl> + / / and / or other materials provided with the distribution . <nl> + / / <nl> + / / * The name of Intel Corporation may not be used to endorse or promote products <nl> + / / derived from this software without specific prior written permission . <nl> + / / <nl> + / / This software is provided by the copyright holders and contributors " as is " and <nl> + / / any express or implied warranties , including , but not limited to , the implied <nl> + / / warranties of merchantability and fitness for a particular purpose are disclaimed . <nl> + / / In no event shall the Intel Corporation or contributors be liable for any direct , <nl> + / / indirect , incidental , special , exemplary , or consequential damages <nl> + / / ( including , but not limited to , procurement of substitute goods or services ; <nl> + / / loss of use , data , or profits ; or business interruption ) however caused <nl> + / / and on any theory of liability , whether in contract , strict liability , <nl> + / / or tort ( including negligence or otherwise ) arising in any way out of <nl> + / / the use of this software , even if advised of the possibility of such damage . <nl> + / / <nl> + / / M * / <nl> + <nl> + # ifndef __OPENCV_TEST_GPU_BASE_HPP__ <nl> + # define __OPENCV_TEST_GPU_BASE_HPP__ <nl> + <nl> + / / ! return true if device supports specified feature and gpu module was built with support the feature . <nl> + bool supportFeature ( const cv : : gpu : : DeviceInfo & info , cv : : gpu : : FeatureSet feature ) ; <nl> + <nl> + / / ! return all devices compatible with current gpu module build . <nl> + const std : : vector < cv : : gpu : : DeviceInfo > & devices ( ) ; <nl> + / / ! return all devices compatible with current gpu module build which support specified feature . <nl> + std : : vector < cv : : gpu : : DeviceInfo > devices ( cv : : gpu : : FeatureSet feature ) ; <nl> + <nl> + / / ! return vector with types from specified range . <nl> + std : : vector < int > types ( int depth_start , int depth_end , int cn_start , int cn_end ) ; <nl> + <nl> + / / ! return vector with all types ( depth : CV_8U - CV_64F , channels : 1 - 4 ) . <nl> + const std : : vector < int > & all_types ( ) ; <nl> + <nl> + / / ! read image from testdata folder . <nl> + cv : : Mat readImage ( const std : : string & fileName , int flags = CV_LOAD_IMAGE_COLOR ) ; <nl> + <nl> + double checkNorm ( const cv : : Mat & m1 , const cv : : Mat & m2 ) ; <nl> + double checkSimilarity ( const cv : : Mat & m1 , const cv : : Mat & m2 ) ; <nl> + <nl> + # define OSTR_NAME ( suf ) ostr_ # # suf <nl> + <nl> + # define PRINT_PARAM ( name ) \ <nl> + std : : ostringstream OSTR_NAME ( name ) ; \ <nl> + OSTR_NAME ( name ) < < # name < < " : " < < name ; \ <nl> + SCOPED_TRACE ( OSTR_NAME ( name ) . str ( ) ) ; <nl> + <nl> + # define PRINT_TYPE ( type ) \ <nl> + std : : ostringstream OSTR_NAME ( type ) ; \ <nl> + OSTR_NAME ( type ) < < # type < < " : " < < cvtest : : getTypeName ( type ) < < " c " < < CV_MAT_CN ( type ) ; \ <nl> + SCOPED_TRACE ( OSTR_NAME ( type ) . str ( ) ) ; <nl> + <nl> + # define EXPECT_MAT_NEAR ( mat1 , mat2 , eps ) \ <nl> + { \ <nl> + ASSERT_EQ ( mat1 . type ( ) , mat2 . type ( ) ) ; \ <nl> + ASSERT_EQ ( mat1 . size ( ) , mat2 . size ( ) ) ; \ <nl> + EXPECT_LE ( checkNorm ( mat1 , mat2 ) , eps ) ; \ <nl> + } <nl> + <nl> + # define EXPECT_MAT_SIMILAR ( mat1 , mat2 , eps ) \ <nl> + { \ <nl> + ASSERT_EQ ( mat1 . type ( ) , mat2 . type ( ) ) ; \ <nl> + ASSERT_EQ ( mat1 . size ( ) , mat2 . size ( ) ) ; \ <nl> + EXPECT_LE ( checkSimilarity ( mat1 , mat2 ) , eps ) ; \ <nl> + } <nl> + <nl> + <nl> + / / ! for gtest ASSERT <nl> + namespace cv <nl> + { <nl> + std : : ostream & operator < < ( std : : ostream & os , const Size & sz ) ; <nl> + std : : ostream & operator < < ( std : : ostream & os , const Scalar & s ) ; <nl> + namespace gpu <nl> + { <nl> + std : : ostream & operator < < ( std : : ostream & os , const DeviceInfo & info ) ; <nl> + } <nl> + } <nl> + <nl> + # endif / / __OPENCV_TEST_GPU_BASE_HPP__ <nl> mmm a / modules / gpu / test / test_hog . cpp <nl> ppp b / modules / gpu / test / test_hog . cpp <nl> <nl> / / M * / <nl> <nl> # include " test_precomp . hpp " <nl> - # include < fstream > <nl> <nl> - using namespace std ; <nl> + # ifdef HAVE_CUDA <nl> <nl> / / # define DUMP <nl> <nl> - # define CHECK ( pred , err ) if ( ! ( pred ) ) { \ <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " Fail : \ " % s \ " at line : % d \ n " , # pred , __LINE__ ) ; \ <nl> - ts - > set_failed_test_info ( err ) ; \ <nl> - return ; } <nl> - <nl> - struct CV_GpuHogDetectTestRunner : cv : : gpu : : HOGDescriptor <nl> + struct CV_GpuHogDetectTestRunner : cv : : gpu : : HOGDescriptor <nl> { <nl> - CV_GpuHogDetectTestRunner ( cvtest : : TS * ts_ ) : ts ( ts_ ) { } <nl> - <nl> - void run ( int ) <nl> + void run ( ) <nl> { <nl> - cv : : Mat img_rgb = cv : : imread ( std : : string ( ts - > get_data_path ( ) ) + " hog / road . png " ) ; <nl> - CHECK ( ! img_rgb . empty ( ) , cvtest : : TS : : FAIL_MISSING_TEST_DATA ) ; <nl> + cv : : Mat img_rgb = readImage ( " hog / road . png " ) ; <nl> + ASSERT_TRUE ( ! img_rgb . empty ( ) ) ; <nl> <nl> # ifdef DUMP <nl> - f . open ( ( std : : string ( ts - > get_data_path ( ) ) + " hog / expected_output . bin " ) . c_str ( ) , std : : ios_base : : binary ) ; <nl> - CHECK ( f . is_open ( ) , cvtest : : TS : : FAIL_GENERIC ) ; <nl> + f . open ( ( std : : string ( cvtest : : TS : : ptr ( ) - > get_data_path ( ) ) + " hog / expected_output . bin " ) . c_str ( ) , std : : ios_base : : binary ) ; <nl> + ASSERT_TRUE ( f . is_open ( ) ) ; <nl> # else <nl> - f . open ( ( std : : string ( ts - > get_data_path ( ) ) + " hog / expected_output . bin " ) . c_str ( ) , std : : ios_base : : binary ) ; <nl> - CHECK ( f . is_open ( ) , cvtest : : TS : : FAIL_MISSING_TEST_DATA ) ; <nl> + f . open ( ( std : : string ( cvtest : : TS : : ptr ( ) - > get_data_path ( ) ) + " hog / expected_output . bin " ) . c_str ( ) , std : : ios_base : : binary ) ; <nl> + ASSERT_TRUE ( f . is_open ( ) ) ; <nl> # endif <nl> <nl> / / Test on color image <nl> struct CV_GpuHogDetectTestRunner : cv : : gpu : : HOGDescriptor <nl> test ( img ) ; <nl> <nl> f . close ( ) ; <nl> - <nl> } <nl> <nl> # ifdef DUMP <nl> struct CV_GpuHogDetectTestRunner : cv : : gpu : : HOGDescriptor <nl> <nl> f . read ( ( char * ) & rows , sizeof ( rows ) ) ; <nl> f . read ( ( char * ) & cols , sizeof ( cols ) ) ; <nl> - CHECK ( rows = = block_hists . rows , cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - CHECK ( cols = = block_hists . cols , cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> + ASSERT_EQ ( rows , block_hists . rows ) ; <nl> + ASSERT_EQ ( cols , block_hists . cols ) ; <nl> for ( int i = 0 ; i < block_hists . rows ; + + i ) <nl> { <nl> for ( int j = 0 ; j < block_hists . cols ; + + j ) <nl> { <nl> float val ; <nl> f . read ( ( char * ) & val , sizeof ( val ) ) ; <nl> - CHECK ( fabs ( val - block_hists . at < float > ( i , j ) ) < 1e - 3f , cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> + ASSERT_NEAR ( val , block_hists . at < float > ( i , j ) , 1e - 3 ) ; <nl> } <nl> } <nl> f . read ( ( char * ) & nlocations , sizeof ( nlocations ) ) ; <nl> - CHECK ( nlocations = = static_cast < int > ( locations . size ( ) ) , cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> + ASSERT_EQ ( nlocations , static_cast < int > ( locations . size ( ) ) ) ; <nl> for ( int i = 0 ; i < nlocations ; + + i ) <nl> { <nl> cv : : Point location ; <nl> f . read ( ( char * ) & location , sizeof ( location ) ) ; <nl> - CHECK ( location = = locations [ i ] , cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> + ASSERT_EQ ( location , locations [ i ] ) ; <nl> } <nl> } <nl> # endif <nl> struct CV_GpuHogDetectTestRunner : cv : : gpu : : HOGDescriptor <nl> # else <nl> std : : ifstream f ; <nl> # endif <nl> - <nl> - cvtest : : TS * ts ; <nl> } ; <nl> <nl> - <nl> - struct CV_GpuHogDetectTest : cvtest : : BaseTest <nl> + struct HogDetect : testing : : TestWithParam < cv : : gpu : : DeviceInfo > <nl> { <nl> - CV_GpuHogDetectTest ( ) { } <nl> - <nl> - void run ( int i ) <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + <nl> + virtual void SetUp ( ) <nl> { <nl> - CV_GpuHogDetectTestRunner runner ( ts ) ; <nl> - runner . run ( i ) ; <nl> + devInfo = GetParam ( ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> } <nl> } ; <nl> <nl> - TEST ( HOG , detect_accuracy ) { CV_GpuHogDetectTest test ; test . safe_run ( ) ; } <nl> + TEST_P ( HogDetect , Accuracy ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + CV_GpuHogDetectTestRunner runner ; <nl> + runner . run ( ) ; <nl> + ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( HOG , HogDetect , testing : : ValuesIn ( devices ( ) ) ) ; <nl> <nl> - struct CV_GpuHogGetDescriptorsTestRunner : cv : : gpu : : HOGDescriptor <nl> + struct CV_GpuHogGetDescriptorsTestRunner : cv : : gpu : : HOGDescriptor <nl> { <nl> - CV_GpuHogGetDescriptorsTestRunner ( cvtest : : TS * ts_ ) : HOGDescriptor ( cv : : Size ( 64 , 128 ) ) , ts ( ts_ ) { } <nl> + CV_GpuHogGetDescriptorsTestRunner ( ) : cv : : gpu : : HOGDescriptor ( cv : : Size ( 64 , 128 ) ) { } <nl> <nl> - void run ( int ) <nl> + void run ( ) <nl> { <nl> / / Load image ( e . g . train data , composed from windows ) <nl> - cv : : Mat img_rgb = cv : : imread ( std : : string ( ts - > get_data_path ( ) ) + " hog / train_data . png " ) ; <nl> - CHECK ( ! img_rgb . empty ( ) , cvtest : : TS : : FAIL_MISSING_TEST_DATA ) ; <nl> + cv : : Mat img_rgb = readImage ( " hog / train_data . png " ) ; <nl> + ASSERT_TRUE ( ! img_rgb . empty ( ) ) ; <nl> <nl> / / Convert to C4 <nl> cv : : Mat img ; <nl> cv : : cvtColor ( img_rgb , img , CV_BGR2BGRA ) ; <nl> - cv : : gpu : : GpuMat d_img ( img ) ; <nl> <nl> + cv : : gpu : : GpuMat d_img ( img ) ; <nl> <nl> / / Convert train images into feature vectors ( train table ) <nl> cv : : gpu : : GpuMat descriptors , descriptors_by_cols ; <nl> struct CV_GpuHogGetDescriptorsTestRunner : cv : : gpu : : HOGDescriptor <nl> block_hist_size = 36 ; <nl> cv : : Size descr_size_expected = cv : : Size ( blocks_per_win_x * blocks_per_win_y * block_hist_size , <nl> wins_per_img_x * wins_per_img_y ) ; <nl> - CHECK ( descriptors . size ( ) = = descr_size_expected , cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> + ASSERT_EQ ( descr_size_expected , descriptors . size ( ) ) ; <nl> <nl> / / Check both formats of output descriptors are handled correctly <nl> cv : : Mat dr ( descriptors ) ; <nl> struct CV_GpuHogGetDescriptorsTestRunner : cv : : gpu : : HOGDescriptor <nl> for ( int y = 0 ; y < blocks_per_win_y ; + + y ) <nl> for ( int x = 0 ; x < blocks_per_win_x ; + + x ) <nl> for ( int k = 0 ; k < block_hist_size ; + + k ) <nl> - CHECK ( l [ ( y * blocks_per_win_x + x ) * block_hist_size + k ] = = <nl> - r [ ( x * blocks_per_win_y + y ) * block_hist_size + k ] , cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> + ASSERT_EQ ( l [ ( y * blocks_per_win_x + x ) * block_hist_size + k ] , <nl> + r [ ( x * blocks_per_win_y + y ) * block_hist_size + k ] ) ; <nl> } <nl> <nl> / * Now we want to extract the same feature vectors , but from single images . NOTE : results will <nl> struct CV_GpuHogGetDescriptorsTestRunner : cv : : gpu : : HOGDescriptor <nl> wont ' t call getDescriptors and will use computeBlockHistograms instead of . computeBlockHistograms <nl> works good , it can be checked in the gpu_hog sample * / <nl> <nl> - img_rgb = cv : : imread ( std : : string ( ts - > get_data_path ( ) ) + " hog / positive1 . png " ) ; <nl> - CHECK ( ! img_rgb . empty ( ) , cvtest : : TS : : FAIL_MISSING_TEST_DATA ) ; <nl> + img_rgb = readImage ( " hog / positive1 . png " ) ; <nl> + ASSERT_TRUE ( ! img_rgb . empty ( ) ) ; <nl> cv : : cvtColor ( img_rgb , img , CV_BGR2BGRA ) ; <nl> computeBlockHistograms ( cv : : gpu : : GpuMat ( img ) ) ; <nl> / / Everything is fine with interpolation for left top subimage <nl> - CHECK ( cv : : norm ( ( cv : : Mat ) block_hists , ( cv : : Mat ) descriptors . rowRange ( 0 , 1 ) ) = = 0 . f , cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> + ASSERT_EQ ( 0 . 0 , cv : : norm ( ( cv : : Mat ) block_hists , ( cv : : Mat ) descriptors . rowRange ( 0 , 1 ) ) ) ; <nl> <nl> - img_rgb = cv : : imread ( std : : string ( ts - > get_data_path ( ) ) + " hog / positive2 . png " ) ; <nl> - CHECK ( ! img_rgb . empty ( ) , cvtest : : TS : : FAIL_MISSING_TEST_DATA ) ; <nl> + img_rgb = readImage ( " hog / positive2 . png " ) ; <nl> + ASSERT_TRUE ( ! img_rgb . empty ( ) ) ; <nl> cv : : cvtColor ( img_rgb , img , CV_BGR2BGRA ) ; <nl> computeBlockHistograms ( cv : : gpu : : GpuMat ( img ) ) ; <nl> compare_inner_parts ( block_hists , descriptors . rowRange ( 1 , 2 ) ) ; <nl> <nl> - img_rgb = cv : : imread ( std : : string ( ts - > get_data_path ( ) ) + " hog / negative1 . png " ) ; <nl> - CHECK ( ! img_rgb . empty ( ) , cvtest : : TS : : FAIL_MISSING_TEST_DATA ) ; <nl> + img_rgb = readImage ( " hog / negative1 . png " ) ; <nl> + ASSERT_TRUE ( ! img_rgb . empty ( ) ) ; <nl> cv : : cvtColor ( img_rgb , img , CV_BGR2BGRA ) ; <nl> computeBlockHistograms ( cv : : gpu : : GpuMat ( img ) ) ; <nl> compare_inner_parts ( block_hists , descriptors . rowRange ( 2 , 3 ) ) ; <nl> <nl> - img_rgb = cv : : imread ( std : : string ( ts - > get_data_path ( ) ) + " hog / negative2 . png " ) ; <nl> - CHECK ( ! img_rgb . empty ( ) , cvtest : : TS : : FAIL_MISSING_TEST_DATA ) ; <nl> + img_rgb = readImage ( " hog / negative2 . png " ) ; <nl> + ASSERT_TRUE ( ! img_rgb . empty ( ) ) ; <nl> cv : : cvtColor ( img_rgb , img , CV_BGR2BGRA ) ; <nl> computeBlockHistograms ( cv : : gpu : : GpuMat ( img ) ) ; <nl> compare_inner_parts ( block_hists , descriptors . rowRange ( 3 , 4 ) ) ; <nl> <nl> - img_rgb = cv : : imread ( std : : string ( ts - > get_data_path ( ) ) + " hog / positive3 . png " ) ; <nl> - CHECK ( ! img_rgb . empty ( ) , cvtest : : TS : : FAIL_MISSING_TEST_DATA ) ; <nl> + img_rgb = readImage ( " hog / positive3 . png " ) ; <nl> + ASSERT_TRUE ( ! img_rgb . empty ( ) ) ; <nl> cv : : cvtColor ( img_rgb , img , CV_BGR2BGRA ) ; <nl> computeBlockHistograms ( cv : : gpu : : GpuMat ( img ) ) ; <nl> compare_inner_parts ( block_hists , descriptors . rowRange ( 4 , 5 ) ) ; <nl> <nl> - img_rgb = cv : : imread ( std : : string ( ts - > get_data_path ( ) ) + " hog / negative3 . png " ) ; <nl> - CHECK ( ! img_rgb . empty ( ) , cvtest : : TS : : FAIL_MISSING_TEST_DATA ) ; <nl> + img_rgb = readImage ( " hog / negative3 . png " ) ; <nl> + ASSERT_TRUE ( ! img_rgb . empty ( ) ) ; <nl> cv : : cvtColor ( img_rgb , img , CV_BGR2BGRA ) ; <nl> computeBlockHistograms ( cv : : gpu : : GpuMat ( img ) ) ; <nl> compare_inner_parts ( block_hists , descriptors . rowRange ( 5 , 6 ) ) ; <nl> struct CV_GpuHogGetDescriptorsTestRunner : cv : : gpu : : HOGDescriptor <nl> { <nl> float a = d1 . at < float > ( 0 , ( i * blocks_per_win_x + j ) * block_hist_size ) ; <nl> float b = d2 . at < float > ( 0 , ( i * blocks_per_win_x + j ) * block_hist_size ) ; <nl> - CHECK ( a = = b , cvtest : : TS : : FAIL_INVALID_OUTPUT ) <nl> + ASSERT_FLOAT_EQ ( a , b ) ; <nl> } <nl> } <nl> <nl> struct CV_GpuHogGetDescriptorsTestRunner : cv : : gpu : : HOGDescriptor <nl> int blocks_per_win_x ; <nl> int blocks_per_win_y ; <nl> int block_hist_size ; <nl> - <nl> - cvtest : : TS * ts ; <nl> } ; <nl> <nl> - <nl> - struct CV_GpuHogGetDescriptorsTest : cvtest : : BaseTest <nl> + struct HogGetDescriptors : testing : : TestWithParam < cv : : gpu : : DeviceInfo > <nl> { <nl> - CV_GpuHogGetDescriptorsTest ( ) { } <nl> - <nl> - void run ( int i ) <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + <nl> + virtual void SetUp ( ) <nl> { <nl> - CV_GpuHogGetDescriptorsTestRunner runner ( ts ) ; <nl> - runner . run ( i ) ; <nl> + devInfo = GetParam ( ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> } <nl> } ; <nl> <nl> - TEST ( HOG , descriptors_accuracy ) { CV_GpuHogGetDescriptorsTest test ; test . safe_run ( ) ; } <nl> + TEST_P ( HogGetDescriptors , Accuracy ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + CV_GpuHogGetDescriptorsTestRunner runner ; <nl> + runner . run ( ) ; <nl> + ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( HOG , HogGetDescriptors , testing : : ValuesIn ( devices ( ) ) ) ; <nl> + <nl> + # endif / / HAVE_CUDA <nl> new file mode 100644 <nl> index 00000000000 . . 219b73e4aba <nl> mmm / dev / null <nl> ppp b / modules / gpu / test / test_imgproc . cpp <nl> <nl> + / * M / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / <nl> + / / IMPORTANT : READ BEFORE DOWNLOADING , COPYING , INSTALLING OR USING . <nl> + / / <nl> + / / By downloading , copying , installing or using the software you agree to this license . <nl> + / / If you do not agree to this license , do not download , install , <nl> + / / copy or use the software . <nl> + / / <nl> + / / <nl> + / / Intel License Agreement <nl> + / / For Open Source Computer Vision Library <nl> + / / <nl> + / / Copyright ( C ) 2000 , Intel Corporation , all rights reserved . <nl> + / / Third party copyrights are property of their respective owners . <nl> + / / <nl> + / / Redistribution and use in source and binary forms , with or without modification , <nl> + / / are permitted provided that the following conditions are met : <nl> + / / <nl> + / / * Redistribution ' s of source code must retain the above copyright notice , <nl> + / / this list of conditions and the following disclaimer . <nl> + / / <nl> + / / * Redistribution ' s in binary form must reproduce the above copyright notice , <nl> + / / this list of conditions and the following disclaimer in the documentation <nl> + / / and / or other materials provided with the distribution . <nl> + / / <nl> + / / * The name of Intel Corporation may not be used to endorse or promote products <nl> + / / derived from this software without specific prior written permission . <nl> + / / <nl> + / / This software is provided by the copyright holders and contributors " as is " and <nl> + / / any express or implied warranties , including , but not limited to , the implied <nl> + / / warranties of merchantability and fitness for a particular purpose are disclaimed . <nl> + / / In no event shall the Intel Corporation or contributors be liable for any direct , <nl> + / / indirect , incidental , special , exemplary , or consequential damages <nl> + / / ( including , but not limited to , procurement of substitute goods or services ; <nl> + / / loss of use , data , or profits ; or business interruption ) however caused <nl> + / / and on any theory of liability , whether in contract , strict liability , <nl> + / / or tort ( including negligence or otherwise ) arising in any way out of <nl> + / / the use of this software , even if advised of the possibility of such damage . <nl> + / / <nl> + / / M * / <nl> + <nl> + # include " test_precomp . hpp " <nl> + <nl> + # ifdef HAVE_CUDA <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / threshold <nl> + <nl> + struct Threshold : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int , int > > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int type ; <nl> + int threshOp ; <nl> + <nl> + cv : : Size size ; <nl> + cv : : Mat src ; <nl> + double maxVal ; <nl> + double thresh ; <nl> + <nl> + cv : : Mat dst_gold ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + type = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> + threshOp = std : : tr1 : : get < 2 > ( GetParam ( ) ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + size = cv : : Size ( rng . uniform ( 20 , 150 ) , rng . uniform ( 20 , 150 ) ) ; <nl> + <nl> + src = cvtest : : randomMat ( rng , size , type , 0 . 0 , 127 . 0 , false ) ; <nl> + <nl> + maxVal = rng . uniform ( 20 . 0 , 127 . 0 ) ; <nl> + thresh = rng . uniform ( 0 . 0 , maxVal ) ; <nl> + <nl> + cv : : threshold ( src , dst_gold , thresh , maxVal , threshOp ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( Threshold , Accuracy ) <nl> + { <nl> + static const char * ops [ ] = { " THRESH_BINARY " , " THRESH_BINARY_INV " , " THRESH_TRUNC " , " THRESH_TOZERO " , " THRESH_TOZERO_INV " } ; <nl> + const char * threshOpStr = ops [ threshOp ] ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + PRINT_PARAM ( threshOpStr ) ; <nl> + PRINT_PARAM ( maxVal ) ; <nl> + PRINT_PARAM ( thresh ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuRes ; <nl> + <nl> + cv : : gpu : : threshold ( cv : : gpu : : GpuMat ( src ) , gpuRes , thresh , maxVal , threshOp ) ; <nl> + <nl> + gpuRes . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 0 . 0 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( ImgProc , Threshold , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( CV_8U , CV_32F ) , <nl> + testing : : Values ( ( int ) cv : : THRESH_BINARY , ( int ) cv : : THRESH_BINARY_INV , ( int ) cv : : THRESH_TRUNC , ( int ) cv : : THRESH_TOZERO , ( int ) cv : : THRESH_TOZERO_INV ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / resize <nl> + <nl> + struct Resize : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int , int > > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int type ; <nl> + int interpolation ; <nl> + <nl> + cv : : Size size ; <nl> + cv : : Mat src ; <nl> + <nl> + cv : : Mat dst_gold1 ; <nl> + cv : : Mat dst_gold2 ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + type = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> + interpolation = std : : tr1 : : get < 2 > ( GetParam ( ) ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + size = cv : : Size ( rng . uniform ( 20 , 150 ) , rng . uniform ( 20 , 150 ) ) ; <nl> + <nl> + src = cvtest : : randomMat ( rng , size , type , 0 . 0 , 127 . 0 , false ) ; <nl> + <nl> + cv : : resize ( src , dst_gold1 , cv : : Size ( ) , 2 . 0 , 2 . 0 , interpolation ) ; <nl> + cv : : resize ( src , dst_gold2 , cv : : Size ( ) , 0 . 5 , 0 . 5 , interpolation ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( Resize , Accuracy ) <nl> + { <nl> + static const char * interpolations [ ] = { " INTER_NEAREST " , " INTER_LINEAR " } ; <nl> + const char * interpolationStr = interpolations [ interpolation ] ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + PRINT_PARAM ( interpolationStr ) ; <nl> + <nl> + cv : : Mat dst1 ; <nl> + cv : : Mat dst2 ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat dev_src ( src ) ; <nl> + cv : : gpu : : GpuMat gpuRes1 ; <nl> + cv : : gpu : : GpuMat gpuRes2 ; <nl> + <nl> + cv : : gpu : : resize ( dev_src , gpuRes1 , cv : : Size ( ) , 2 . 0 , 2 . 0 , interpolation ) ; <nl> + cv : : gpu : : resize ( dev_src , gpuRes2 , cv : : Size ( ) , 0 . 5 , 0 . 5 , interpolation ) ; <nl> + <nl> + gpuRes1 . download ( dst1 ) ; <nl> + gpuRes2 . download ( dst2 ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_SIMILAR ( dst_gold1 , dst1 , 0 . 5 ) ; <nl> + EXPECT_MAT_SIMILAR ( dst_gold2 , dst2 , 0 . 5 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( ImgProc , Resize , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( CV_8UC1 , CV_8UC4 ) , <nl> + testing : : Values ( ( int ) cv : : INTER_NEAREST , ( int ) cv : : INTER_LINEAR ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / copyMakeBorder <nl> + <nl> + struct CopyMakeBorder : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int > > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int type ; <nl> + <nl> + cv : : Size size ; <nl> + cv : : Mat src ; <nl> + int top ; <nl> + int botton ; <nl> + int left ; <nl> + int right ; <nl> + cv : : Scalar val ; <nl> + <nl> + cv : : Mat dst_gold ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + type = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + size = cv : : Size ( rng . uniform ( 20 , 150 ) , rng . uniform ( 20 , 150 ) ) ; <nl> + <nl> + src = cvtest : : randomMat ( rng , size , type , 0 . 0 , 127 . 0 , false ) ; <nl> + <nl> + top = rng . uniform ( 1 , 10 ) ; <nl> + botton = rng . uniform ( 1 , 10 ) ; <nl> + left = rng . uniform ( 1 , 10 ) ; <nl> + right = rng . uniform ( 1 , 10 ) ; <nl> + val = cv : : Scalar ( rng . uniform ( 0 , 255 ) , rng . uniform ( 0 , 255 ) , rng . uniform ( 0 , 255 ) , rng . uniform ( 0 , 255 ) ) ; <nl> + <nl> + cv : : copyMakeBorder ( src , dst_gold , top , botton , left , right , cv : : BORDER_CONSTANT , val ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( CopyMakeBorder , Accuracy ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + PRINT_PARAM ( top ) ; <nl> + PRINT_PARAM ( botton ) ; <nl> + PRINT_PARAM ( left ) ; <nl> + PRINT_PARAM ( right ) ; <nl> + PRINT_PARAM ( val ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuRes ; <nl> + <nl> + cv : : gpu : : copyMakeBorder ( cv : : gpu : : GpuMat ( src ) , gpuRes , top , botton , left , right , val ) ; <nl> + <nl> + gpuRes . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 0 . 0 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( ImgProc , CopyMakeBorder , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( CV_8UC1 , CV_8UC4 , CV_32SC1 ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / warpAffine & warpPerspective <nl> + <nl> + static const int warpFlags [ ] = { cv : : INTER_NEAREST , cv : : INTER_LINEAR , cv : : INTER_CUBIC , cv : : INTER_NEAREST | cv : : WARP_INVERSE_MAP , cv : : INTER_LINEAR | cv : : WARP_INVERSE_MAP , cv : : INTER_CUBIC | cv : : WARP_INVERSE_MAP } ; <nl> + static const char * warpFlags_str [ ] = { " INTER_NEAREST " , " INTER_LINEAR " , " INTER_CUBIC " , " INTER_NEAREST | WARP_INVERSE_MAP " , " INTER_LINEAR | WARP_INVERSE_MAP " , " INTER_CUBIC | WARP_INVERSE_MAP " } ; <nl> + <nl> + struct WarpAffine : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int , int > > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int type ; <nl> + int flagIdx ; <nl> + <nl> + cv : : Size size ; <nl> + cv : : Mat src ; <nl> + cv : : Mat M ; <nl> + <nl> + cv : : Mat dst_gold ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + type = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> + flagIdx = std : : tr1 : : get < 2 > ( GetParam ( ) ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + size = cv : : Size ( rng . uniform ( 20 , 150 ) , rng . uniform ( 20 , 150 ) ) ; <nl> + <nl> + src = cvtest : : randomMat ( rng , size , type , 0 . 0 , 127 . 0 , false ) ; <nl> + <nl> + static double reflect [ 2 ] [ 3 ] = { { - 1 , 0 , 0 } , <nl> + { 0 , - 1 , 0 } } ; <nl> + reflect [ 0 ] [ 2 ] = size . width ; <nl> + reflect [ 1 ] [ 2 ] = size . height ; <nl> + M = cv : : Mat ( 2 , 3 , CV_64F , ( void * ) reflect ) ; <nl> + <nl> + cv : : warpAffine ( src , dst_gold , M , src . size ( ) , warpFlags [ flagIdx ] ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( WarpAffine , Accuracy ) <nl> + { <nl> + const char * warpFlagStr = warpFlags_str [ flagIdx ] ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + PRINT_PARAM ( warpFlagStr ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuRes ; <nl> + <nl> + cv : : gpu : : warpAffine ( cv : : gpu : : GpuMat ( src ) , gpuRes , M , src . size ( ) , warpFlags [ flagIdx ] ) ; <nl> + <nl> + gpuRes . download ( dst ) ; <nl> + ) ; <nl> + <nl> + / / Check inner parts ( ignoring 1 pixel width border ) <nl> + cv : : Mat dst_gold_roi = dst_gold . rowRange ( 1 , dst_gold . rows - 1 ) . colRange ( 1 , dst_gold . cols - 1 ) ; <nl> + cv : : Mat dst_roi = dst . rowRange ( 1 , dst . rows - 1 ) . colRange ( 1 , dst . cols - 1 ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold_roi , dst_roi , 1e - 3 ) ; <nl> + } <nl> + <nl> + struct WarpPerspective : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int , int > > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int type ; <nl> + int flagIdx ; <nl> + <nl> + cv : : Size size ; <nl> + cv : : Mat src ; <nl> + cv : : Mat M ; <nl> + <nl> + cv : : Mat dst_gold ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + type = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> + flagIdx = std : : tr1 : : get < 2 > ( GetParam ( ) ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + size = cv : : Size ( rng . uniform ( 20 , 150 ) , rng . uniform ( 20 , 150 ) ) ; <nl> + <nl> + src = cvtest : : randomMat ( rng , size , type , 0 . 0 , 127 . 0 , false ) ; <nl> + <nl> + static double reflect [ 3 ] [ 3 ] = { { - 1 , 0 , 0 } , <nl> + { 0 , - 1 , 0 } , <nl> + { 0 , 0 , 1 } } ; <nl> + reflect [ 0 ] [ 2 ] = size . width ; <nl> + reflect [ 1 ] [ 2 ] = size . height ; <nl> + M = cv : : Mat ( 3 , 3 , CV_64F , ( void * ) reflect ) ; <nl> + <nl> + cv : : warpPerspective ( src , dst_gold , M , src . size ( ) , warpFlags [ flagIdx ] ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( WarpPerspective , Accuracy ) <nl> + { <nl> + const char * warpFlagStr = warpFlags_str [ flagIdx ] ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + PRINT_PARAM ( warpFlagStr ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuRes ; <nl> + <nl> + cv : : gpu : : warpPerspective ( cv : : gpu : : GpuMat ( src ) , gpuRes , M , src . size ( ) , warpFlags [ flagIdx ] ) ; <nl> + <nl> + gpuRes . download ( dst ) ; <nl> + ) ; <nl> + <nl> + / / Check inner parts ( ignoring 1 pixel width border ) <nl> + cv : : Mat dst_gold_roi = dst_gold . rowRange ( 1 , dst_gold . rows - 1 ) . colRange ( 1 , dst_gold . cols - 1 ) ; <nl> + cv : : Mat dst_roi = dst . rowRange ( 1 , dst . rows - 1 ) . colRange ( 1 , dst . cols - 1 ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold_roi , dst_roi , 1e - 3 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( ImgProc , WarpAffine , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( CV_8UC1 , CV_8UC3 , CV_8UC4 , CV_32FC1 , CV_32FC3 , CV_32FC4 ) , <nl> + testing : : Range ( 0 , 6 ) ) ) ; <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( ImgProc , WarpPerspective , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( CV_8UC1 , CV_8UC3 , CV_8UC4 , CV_32FC1 , CV_32FC3 , CV_32FC4 ) , <nl> + testing : : Range ( 0 , 6 ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / integral <nl> + <nl> + struct Integral : testing : : TestWithParam < cv : : gpu : : DeviceInfo > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + <nl> + cv : : Size size ; <nl> + cv : : Mat src ; <nl> + <nl> + cv : : Mat dst_gold ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = GetParam ( ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + size = cv : : Size ( rng . uniform ( 20 , 150 ) , rng . uniform ( 20 , 150 ) ) ; <nl> + <nl> + src = cvtest : : randomMat ( rng , size , CV_8UC1 , 0 . 0 , 255 . 0 , false ) ; <nl> + <nl> + cv : : integral ( src , dst_gold , CV_32S ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( Integral , Accuracy ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuRes ; <nl> + <nl> + cv : : gpu : : integral ( cv : : gpu : : GpuMat ( src ) , gpuRes ) ; <nl> + <nl> + gpuRes . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 0 . 0 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( ImgProc , Integral , testing : : ValuesIn ( devices ( ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / cvtColor <nl> + <nl> + struct CvtColor : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int > > <nl> + { <nl> + static cv : : Mat imgBase ; <nl> + <nl> + static void SetUpTestCase ( ) <nl> + { <nl> + imgBase = readImage ( " stereobm / aloe - L . png " ) ; <nl> + } <nl> + <nl> + static void TearDownTestCase ( ) <nl> + { <nl> + imgBase . release ( ) ; <nl> + } <nl> + <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int type ; <nl> + <nl> + cv : : Mat img ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + type = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + imgBase . convertTo ( img , type , type = = CV_32F ? 1 . 0 / 255 . 0 : 1 . 0 ) ; <nl> + } <nl> + } ; <nl> + <nl> + cv : : Mat CvtColor : : imgBase ; <nl> + <nl> + TEST_P ( CvtColor , BGR2RGB ) <nl> + { <nl> + ASSERT_TRUE ( ! img . empty ( ) ) ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + <nl> + cv : : Mat src = img ; <nl> + cv : : Mat dst_gold ; <nl> + cv : : cvtColor ( src , dst_gold , CV_BGR2RGB ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuRes ; <nl> + <nl> + cv : : gpu : : cvtColor ( cv : : gpu : : GpuMat ( src ) , gpuRes , CV_BGR2RGB ) ; <nl> + <nl> + gpuRes . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 0 . 0 ) ; <nl> + } <nl> + <nl> + TEST_P ( CvtColor , BGR2RGBA ) <nl> + { <nl> + ASSERT_TRUE ( ! img . empty ( ) ) ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + <nl> + cv : : Mat src = img ; <nl> + cv : : Mat dst_gold ; <nl> + cv : : cvtColor ( src , dst_gold , CV_BGR2RGBA ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuRes ; <nl> + <nl> + cv : : gpu : : cvtColor ( cv : : gpu : : GpuMat ( src ) , gpuRes , CV_BGR2RGBA ) ; <nl> + <nl> + gpuRes . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 0 . 0 ) ; <nl> + } <nl> + <nl> + TEST_P ( CvtColor , BGRA2RGB ) <nl> + { <nl> + ASSERT_TRUE ( ! img . empty ( ) ) ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + <nl> + cv : : Mat src ; <nl> + cv : : cvtColor ( img , src , CV_BGR2BGRA ) ; <nl> + cv : : Mat dst_gold ; <nl> + cv : : cvtColor ( src , dst_gold , CV_BGRA2RGB ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuRes ; <nl> + <nl> + cv : : gpu : : cvtColor ( cv : : gpu : : GpuMat ( src ) , gpuRes , CV_BGRA2RGB ) ; <nl> + <nl> + gpuRes . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 0 . 0 ) ; <nl> + } <nl> + <nl> + TEST_P ( CvtColor , BGR2YCrCb ) <nl> + { <nl> + ASSERT_TRUE ( ! img . empty ( ) ) ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + <nl> + cv : : Mat src = img ; <nl> + cv : : Mat dst_gold ; <nl> + cv : : cvtColor ( src , dst_gold , CV_BGR2YCrCb ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuRes ; <nl> + <nl> + cv : : gpu : : cvtColor ( cv : : gpu : : GpuMat ( src ) , gpuRes , CV_BGR2YCrCb ) ; <nl> + <nl> + gpuRes . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 1e - 5 ) ; <nl> + } <nl> + <nl> + TEST_P ( CvtColor , YCrCb2RGB ) <nl> + { <nl> + ASSERT_TRUE ( ! img . empty ( ) ) ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + <nl> + cv : : Mat src ; <nl> + cv : : cvtColor ( img , src , CV_BGR2YCrCb ) ; <nl> + cv : : Mat dst_gold ; <nl> + cv : : cvtColor ( src , dst_gold , CV_YCrCb2RGB ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuRes ; <nl> + <nl> + cv : : gpu : : cvtColor ( cv : : gpu : : GpuMat ( src ) , gpuRes , CV_YCrCb2RGB ) ; <nl> + <nl> + gpuRes . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 1e - 5 ) ; <nl> + } <nl> + <nl> + TEST_P ( CvtColor , BGR2YUV ) <nl> + { <nl> + ASSERT_TRUE ( ! img . empty ( ) ) ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + <nl> + cv : : Mat src = img ; <nl> + cv : : Mat dst_gold ; <nl> + cv : : cvtColor ( src , dst_gold , CV_BGR2YUV ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuRes ; <nl> + <nl> + cv : : gpu : : cvtColor ( cv : : gpu : : GpuMat ( src ) , gpuRes , CV_BGR2YUV ) ; <nl> + <nl> + gpuRes . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 1e - 5 ) ; <nl> + } <nl> + <nl> + TEST_P ( CvtColor , YUV2BGR ) <nl> + { <nl> + ASSERT_TRUE ( ! img . empty ( ) ) ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + <nl> + cv : : Mat src ; <nl> + cv : : cvtColor ( img , src , CV_BGR2YUV ) ; <nl> + cv : : Mat dst_gold ; <nl> + cv : : cvtColor ( src , dst_gold , CV_YUV2BGR ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuRes ; <nl> + <nl> + cv : : gpu : : cvtColor ( cv : : gpu : : GpuMat ( src ) , gpuRes , CV_YUV2BGR ) ; <nl> + <nl> + gpuRes . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 1e - 5 ) ; <nl> + } <nl> + <nl> + TEST_P ( CvtColor , BGR2XYZ ) <nl> + { <nl> + ASSERT_TRUE ( ! img . empty ( ) ) ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + <nl> + cv : : Mat src = img ; <nl> + cv : : Mat dst_gold ; <nl> + cv : : cvtColor ( src , dst_gold , CV_BGR2XYZ ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuRes ; <nl> + <nl> + cv : : gpu : : cvtColor ( cv : : gpu : : GpuMat ( src ) , gpuRes , CV_BGR2XYZ ) ; <nl> + <nl> + gpuRes . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 1e - 5 ) ; <nl> + } <nl> + <nl> + TEST_P ( CvtColor , XYZ2BGR ) <nl> + { <nl> + ASSERT_TRUE ( ! img . empty ( ) ) ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + <nl> + cv : : Mat src ; <nl> + cv : : cvtColor ( img , src , CV_BGR2XYZ ) ; <nl> + cv : : Mat dst_gold ; <nl> + cv : : cvtColor ( src , dst_gold , CV_XYZ2BGR ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuRes ; <nl> + <nl> + cv : : gpu : : cvtColor ( cv : : gpu : : GpuMat ( src ) , gpuRes , CV_XYZ2BGR ) ; <nl> + <nl> + gpuRes . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 1e - 5 ) ; <nl> + } <nl> + <nl> + TEST_P ( CvtColor , BGR2HSV ) <nl> + { <nl> + if ( type = = CV_16U ) <nl> + return ; <nl> + <nl> + ASSERT_TRUE ( ! img . empty ( ) ) ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + <nl> + cv : : Mat src = img ; <nl> + cv : : Mat dst_gold ; <nl> + cv : : cvtColor ( src , dst_gold , CV_BGR2HSV ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuRes ; <nl> + <nl> + cv : : gpu : : cvtColor ( cv : : gpu : : GpuMat ( src ) , gpuRes , CV_BGR2HSV ) ; <nl> + <nl> + gpuRes . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , type = = CV_32F ? 1e - 2 : 1 ) ; <nl> + } <nl> + <nl> + TEST_P ( CvtColor , HSV2BGR ) <nl> + { <nl> + if ( type = = CV_16U ) <nl> + return ; <nl> + <nl> + ASSERT_TRUE ( ! img . empty ( ) ) ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + <nl> + cv : : Mat src ; <nl> + cv : : cvtColor ( img , src , CV_BGR2HSV ) ; <nl> + cv : : Mat dst_gold ; <nl> + cv : : cvtColor ( src , dst_gold , CV_HSV2BGR ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuRes ; <nl> + <nl> + cv : : gpu : : cvtColor ( cv : : gpu : : GpuMat ( src ) , gpuRes , CV_HSV2BGR ) ; <nl> + <nl> + gpuRes . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , type = = CV_32F ? 1e - 2 : 1 ) ; <nl> + } <nl> + <nl> + TEST_P ( CvtColor , BGR2HSV_FULL ) <nl> + { <nl> + if ( type = = CV_16U ) <nl> + return ; <nl> + <nl> + ASSERT_TRUE ( ! img . empty ( ) ) ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + <nl> + cv : : Mat src = img ; <nl> + cv : : Mat dst_gold ; <nl> + cv : : cvtColor ( src , dst_gold , CV_BGR2HSV_FULL ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuRes ; <nl> + <nl> + cv : : gpu : : cvtColor ( cv : : gpu : : GpuMat ( src ) , gpuRes , CV_BGR2HSV_FULL ) ; <nl> + <nl> + gpuRes . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , type = = CV_32F ? 1e - 2 : 1 ) ; <nl> + } <nl> + <nl> + TEST_P ( CvtColor , HSV2BGR_FULL ) <nl> + { <nl> + if ( type = = CV_16U ) <nl> + return ; <nl> + <nl> + ASSERT_TRUE ( ! img . empty ( ) ) ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + <nl> + cv : : Mat src ; <nl> + cv : : cvtColor ( img , src , CV_BGR2HSV_FULL ) ; <nl> + cv : : Mat dst_gold ; <nl> + cv : : cvtColor ( src , dst_gold , CV_HSV2BGR_FULL ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuRes ; <nl> + <nl> + cv : : gpu : : cvtColor ( cv : : gpu : : GpuMat ( src ) , gpuRes , CV_HSV2BGR_FULL ) ; <nl> + <nl> + gpuRes . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , type = = CV_32F ? 1e - 2 : 1 ) ; <nl> + } <nl> + <nl> + TEST_P ( CvtColor , BGR2HLS ) <nl> + { <nl> + if ( type = = CV_16U ) <nl> + return ; <nl> + <nl> + ASSERT_TRUE ( ! img . empty ( ) ) ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + <nl> + cv : : Mat src = img ; <nl> + cv : : Mat dst_gold ; <nl> + cv : : cvtColor ( src , dst_gold , CV_BGR2HLS ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuRes ; <nl> + <nl> + cv : : gpu : : cvtColor ( cv : : gpu : : GpuMat ( src ) , gpuRes , CV_BGR2HLS ) ; <nl> + <nl> + gpuRes . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , type = = CV_32F ? 1e - 2 : 1 ) ; <nl> + } <nl> + <nl> + TEST_P ( CvtColor , HLS2BGR ) <nl> + { <nl> + if ( type = = CV_16U ) <nl> + return ; <nl> + <nl> + ASSERT_TRUE ( ! img . empty ( ) ) ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + <nl> + cv : : Mat src ; <nl> + cv : : cvtColor ( img , src , CV_BGR2HLS ) ; <nl> + cv : : Mat dst_gold ; <nl> + cv : : cvtColor ( src , dst_gold , CV_HLS2BGR ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuRes ; <nl> + <nl> + cv : : gpu : : cvtColor ( cv : : gpu : : GpuMat ( src ) , gpuRes , CV_HLS2BGR ) ; <nl> + <nl> + gpuRes . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , type = = CV_32F ? 1e - 2 : 1 ) ; <nl> + } <nl> + <nl> + TEST_P ( CvtColor , BGR2HLS_FULL ) <nl> + { <nl> + if ( type = = CV_16U ) <nl> + return ; <nl> + <nl> + ASSERT_TRUE ( ! img . empty ( ) ) ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + <nl> + cv : : Mat src = img ; <nl> + cv : : Mat dst_gold ; <nl> + cv : : cvtColor ( src , dst_gold , CV_BGR2HLS_FULL ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuRes ; <nl> + <nl> + cv : : gpu : : cvtColor ( cv : : gpu : : GpuMat ( src ) , gpuRes , CV_BGR2HLS_FULL ) ; <nl> + <nl> + gpuRes . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , type = = CV_32F ? 1e - 2 : 1 ) ; <nl> + } <nl> + <nl> + TEST_P ( CvtColor , HLS2BGR_FULL ) <nl> + { <nl> + if ( type = = CV_16U ) <nl> + return ; <nl> + <nl> + ASSERT_TRUE ( ! img . empty ( ) ) ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + <nl> + cv : : Mat src ; <nl> + cv : : cvtColor ( img , src , CV_BGR2HLS_FULL ) ; <nl> + cv : : Mat dst_gold ; <nl> + cv : : cvtColor ( src , dst_gold , CV_HLS2BGR_FULL ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuRes ; <nl> + <nl> + cv : : gpu : : cvtColor ( cv : : gpu : : GpuMat ( src ) , gpuRes , CV_HLS2BGR_FULL ) ; <nl> + <nl> + gpuRes . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , type = = CV_32F ? 1e - 2 : 1 ) ; <nl> + } <nl> + <nl> + TEST_P ( CvtColor , BGR2GRAY ) <nl> + { <nl> + ASSERT_TRUE ( ! img . empty ( ) ) ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + <nl> + cv : : Mat src = img ; <nl> + cv : : Mat dst_gold ; <nl> + cv : : cvtColor ( src , dst_gold , CV_BGR2GRAY ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuRes ; <nl> + <nl> + cv : : gpu : : cvtColor ( cv : : gpu : : GpuMat ( src ) , gpuRes , CV_BGR2GRAY ) ; <nl> + <nl> + gpuRes . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 1e - 5 ) ; <nl> + } <nl> + <nl> + TEST_P ( CvtColor , GRAY2RGB ) <nl> + { <nl> + ASSERT_TRUE ( ! img . empty ( ) ) ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + <nl> + cv : : Mat src ; <nl> + cv : : cvtColor ( img , src , CV_BGR2GRAY ) ; <nl> + cv : : Mat dst_gold ; <nl> + cv : : cvtColor ( src , dst_gold , CV_GRAY2RGB ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpuRes ; <nl> + <nl> + cv : : gpu : : cvtColor ( cv : : gpu : : GpuMat ( src ) , gpuRes , CV_GRAY2RGB ) ; <nl> + <nl> + gpuRes . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 0 . 0 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( ImgProc , CvtColor , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( CV_8U , CV_16U , CV_32F ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / histograms <nl> + <nl> + struct Histograms : testing : : TestWithParam < cv : : gpu : : DeviceInfo > <nl> + { <nl> + static cv : : Mat hsv ; <nl> + <nl> + static void SetUpTestCase ( ) <nl> + { <nl> + cv : : Mat img = readImage ( " stereobm / aloe - L . png " ) ; <nl> + cv : : cvtColor ( img , hsv , CV_BGR2HSV ) ; <nl> + } <nl> + <nl> + static void TearDownTestCase ( ) <nl> + { <nl> + hsv . release ( ) ; <nl> + } <nl> + <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + <nl> + int hbins ; <nl> + float hranges [ 2 ] ; <nl> + <nl> + cv : : Mat hist_gold ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = GetParam ( ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + hbins = 30 ; <nl> + <nl> + hranges [ 0 ] = 0 ; <nl> + hranges [ 1 ] = 180 ; <nl> + <nl> + int histSize [ ] = { hbins } ; <nl> + const float * ranges [ ] = { hranges } ; <nl> + <nl> + cv : : MatND histnd ; <nl> + <nl> + int channels [ ] = { 0 } ; <nl> + cv : : calcHist ( & hsv , 1 , channels , cv : : Mat ( ) , histnd , 1 , histSize , ranges ) ; <nl> + <nl> + hist_gold = histnd ; <nl> + hist_gold = hist_gold . t ( ) ; <nl> + hist_gold . convertTo ( hist_gold , CV_32S ) ; <nl> + } <nl> + } ; <nl> + <nl> + cv : : Mat Histograms : : hsv ; <nl> + <nl> + TEST_P ( Histograms , Accuracy ) <nl> + { <nl> + ASSERT_TRUE ( ! hsv . empty ( ) ) ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + <nl> + cv : : Mat hist ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + std : : vector < cv : : gpu : : GpuMat > srcs ; <nl> + cv : : gpu : : split ( cv : : gpu : : GpuMat ( hsv ) , srcs ) ; <nl> + <nl> + cv : : gpu : : GpuMat gpuHist ; <nl> + <nl> + cv : : gpu : : histEven ( srcs [ 0 ] , gpuHist , hbins , ( int ) hranges [ 0 ] , ( int ) hranges [ 1 ] ) ; <nl> + <nl> + gpuHist . download ( hist ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( hist_gold , hist , 0 . 0 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( ImgProc , Histograms , testing : : ValuesIn ( devices ( ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / cornerHarris <nl> + <nl> + static const int borderTypes [ ] = { cv : : BORDER_REPLICATE , cv : : BORDER_CONSTANT , cv : : BORDER_REFLECT , cv : : BORDER_WRAP , cv : : BORDER_REFLECT101 , cv : : BORDER_TRANSPARENT } ; <nl> + static const char * borderTypes_str [ ] = { " BORDER_REPLICATE " , " BORDER_CONSTANT " , " BORDER_REFLECT " , " BORDER_WRAP " , " BORDER_REFLECT101 " , " BORDER_TRANSPARENT " } ; <nl> + <nl> + struct CornerHarris : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int , int > > <nl> + { <nl> + static cv : : Mat img ; <nl> + <nl> + static void SetUpTestCase ( ) <nl> + { <nl> + img = readImage ( " stereobm / aloe - L . png " , CV_LOAD_IMAGE_GRAYSCALE ) ; <nl> + } <nl> + <nl> + static void TearDownTestCase ( ) <nl> + { <nl> + img . release ( ) ; <nl> + } <nl> + <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int type ; <nl> + int borderTypeIdx ; <nl> + <nl> + cv : : Mat src ; <nl> + int blockSize ; <nl> + int apertureSize ; <nl> + double k ; <nl> + <nl> + cv : : Mat dst_gold ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + type = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> + borderTypeIdx = std : : tr1 : : get < 2 > ( GetParam ( ) ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + img . convertTo ( src , type , type = = CV_32F ? 1 . 0 / 255 . 0 : 1 . 0 ) ; <nl> + <nl> + blockSize = 1 + rng . next ( ) % 5 ; <nl> + apertureSize = 1 + 2 * ( rng . next ( ) % 4 ) ; <nl> + k = rng . uniform ( 0 . 1 , 0 . 9 ) ; <nl> + <nl> + cv : : cornerHarris ( src , dst_gold , blockSize , apertureSize , k , borderTypes [ borderTypeIdx ] ) ; <nl> + } <nl> + } ; <nl> + <nl> + cv : : Mat CornerHarris : : img ; <nl> + <nl> + TEST_P ( CornerHarris , Accuracy ) <nl> + { <nl> + const char * borderTypeStr = borderTypes_str [ borderTypeIdx ] ; <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + PRINT_PARAM ( borderTypeStr ) ; <nl> + PRINT_PARAM ( blockSize ) ; <nl> + PRINT_PARAM ( apertureSize ) ; <nl> + PRINT_PARAM ( k ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat dev_dst ; <nl> + cv : : gpu : : cornerHarris ( cv : : gpu : : GpuMat ( src ) , dev_dst , blockSize , apertureSize , k , borderTypes [ borderTypeIdx ] ) ; <nl> + dev_dst . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 1e - 3 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( ImgProc , CornerHarris , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( CV_8UC1 , CV_32FC1 ) , <nl> + testing : : Values ( 0 , 4 ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / cornerMinEigen <nl> + <nl> + struct CornerMinEigen : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int , int > > <nl> + { <nl> + static cv : : Mat img ; <nl> + <nl> + static void SetUpTestCase ( ) <nl> + { <nl> + img = readImage ( " stereobm / aloe - L . png " , CV_LOAD_IMAGE_GRAYSCALE ) ; <nl> + } <nl> + <nl> + static void TearDownTestCase ( ) <nl> + { <nl> + img . release ( ) ; <nl> + } <nl> + <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int type ; <nl> + int borderTypeIdx ; <nl> + <nl> + cv : : Mat src ; <nl> + int blockSize ; <nl> + int apertureSize ; <nl> + <nl> + cv : : Mat dst_gold ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + type = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> + borderTypeIdx = std : : tr1 : : get < 2 > ( GetParam ( ) ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + img . convertTo ( src , type , type = = CV_32F ? 1 . 0 / 255 . 0 : 1 . 0 ) ; <nl> + <nl> + blockSize = 1 + rng . next ( ) % 5 ; <nl> + apertureSize = 1 + 2 * ( rng . next ( ) % 4 ) ; <nl> + <nl> + cv : : cornerMinEigenVal ( src , dst_gold , blockSize , apertureSize , borderTypes [ borderTypeIdx ] ) ; <nl> + } <nl> + } ; <nl> + <nl> + cv : : Mat CornerMinEigen : : img ; <nl> + <nl> + TEST_P ( CornerMinEigen , Accuracy ) <nl> + { <nl> + const char * borderTypeStr = borderTypes_str [ borderTypeIdx ] ; <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + PRINT_PARAM ( borderTypeStr ) ; <nl> + PRINT_PARAM ( blockSize ) ; <nl> + PRINT_PARAM ( apertureSize ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat dev_dst ; <nl> + cv : : gpu : : cornerMinEigenVal ( cv : : gpu : : GpuMat ( src ) , dev_dst , blockSize , apertureSize , borderTypes [ borderTypeIdx ] ) ; <nl> + dev_dst . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 1e - 2 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( ImgProc , CornerMinEigen , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( CV_8UC1 , CV_32FC1 ) , <nl> + testing : : Values ( 0 , 4 ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / ColumnSum <nl> + <nl> + struct ColumnSum : testing : : TestWithParam < cv : : gpu : : DeviceInfo > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + <nl> + cv : : Size size ; <nl> + cv : : Mat src ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = GetParam ( ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + size = cv : : Size ( rng . uniform ( 100 , 400 ) , rng . uniform ( 100 , 400 ) ) ; <nl> + <nl> + src = cvtest : : randomMat ( rng , size , CV_32F , 0 . 0 , 1 . 0 , false ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( ColumnSum , Accuracy ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat dev_dst ; <nl> + cv : : gpu : : columnSum ( cv : : gpu : : GpuMat ( src ) , dev_dst ) ; <nl> + dev_dst . download ( dst ) ; <nl> + ) ; <nl> + <nl> + for ( int j = 0 ; j < src . cols ; + + j ) <nl> + { <nl> + float gold = src . at < float > ( 0 , j ) ; <nl> + float res = dst . at < float > ( 0 , j ) ; <nl> + ASSERT_NEAR ( res , gold , 0 . 5 ) ; <nl> + } <nl> + <nl> + for ( int i = 1 ; i < src . rows ; + + i ) <nl> + { <nl> + for ( int j = 0 ; j < src . cols ; + + j ) <nl> + { <nl> + float gold = src . at < float > ( i , j ) + = src . at < float > ( i - 1 , j ) ; <nl> + float res = dst . at < float > ( i , j ) ; <nl> + ASSERT_NEAR ( res , gold , 0 . 5 ) ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( ImgProc , ColumnSum , testing : : ValuesIn ( devices ( ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / Norm <nl> + <nl> + static const int normTypes [ ] = { cv : : NORM_INF , cv : : NORM_L1 , cv : : NORM_L2 } ; <nl> + static const char * normTypes_str [ ] = { " NORM_INF " , " NORM_L1 " , " NORM_L2 " } ; <nl> + <nl> + struct Norm : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int , int > > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int type ; <nl> + int normTypeIdx ; <nl> + <nl> + cv : : Size size ; <nl> + cv : : Mat src ; <nl> + <nl> + double gold ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + type = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> + normTypeIdx = std : : tr1 : : get < 2 > ( GetParam ( ) ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + size = cv : : Size ( rng . uniform ( 100 , 400 ) , rng . uniform ( 100 , 400 ) ) ; <nl> + <nl> + src = cvtest : : randomMat ( rng , size , type , 0 . 0 , 10 . 0 , false ) ; <nl> + <nl> + gold = cv : : norm ( src , normTypes [ normTypeIdx ] ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( Norm , Accuracy ) <nl> + { <nl> + const char * normTypeStr = normTypes_str [ normTypeIdx ] ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + PRINT_PARAM ( normTypeStr ) ; <nl> + <nl> + double res ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + res = cv : : gpu : : norm ( cv : : gpu : : GpuMat ( src ) , normTypes [ normTypeIdx ] ) ; <nl> + ) ; <nl> + <nl> + ASSERT_NEAR ( res , gold , 0 . 5 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( ImgProc , Norm , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : ValuesIn ( types ( CV_8U , CV_32F , 1 , 1 ) ) , <nl> + testing : : Range ( 0 , 3 ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / reprojectImageTo3D <nl> + <nl> + struct ReprojectImageTo3D : testing : : TestWithParam < cv : : gpu : : DeviceInfo > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + <nl> + cv : : Size size ; <nl> + cv : : Mat disp ; <nl> + cv : : Mat Q ; <nl> + <nl> + cv : : Mat dst_gold ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = GetParam ( ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + size = cv : : Size ( rng . uniform ( 100 , 500 ) , rng . uniform ( 100 , 500 ) ) ; <nl> + <nl> + disp = cvtest : : randomMat ( rng , size , CV_8UC1 , 5 . 0 , 30 . 0 , false ) ; <nl> + <nl> + Q = cvtest : : randomMat ( rng , cv : : Size ( 4 , 4 ) , CV_32FC1 , 0 . 1 , 1 . 0 , false ) ; <nl> + <nl> + cv : : reprojectImageTo3D ( disp , dst_gold , Q , false ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( ReprojectImageTo3D , Accuracy ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpures ; <nl> + cv : : gpu : : reprojectImageTo3D ( cv : : gpu : : GpuMat ( disp ) , gpures , Q ) ; <nl> + gpures . download ( dst ) ; <nl> + ) ; <nl> + <nl> + ASSERT_EQ ( dst_gold . size ( ) , dst . size ( ) ) ; <nl> + <nl> + for ( int y = 0 ; y < dst_gold . rows ; + + y ) <nl> + { <nl> + const cv : : Vec3f * cpu_row = dst_gold . ptr < cv : : Vec3f > ( y ) ; <nl> + const cv : : Vec4f * gpu_row = dst . ptr < cv : : Vec4f > ( y ) ; <nl> + <nl> + for ( int x = 0 ; x < dst_gold . cols ; + + x ) <nl> + { <nl> + cv : : Vec3f gold = cpu_row [ x ] ; <nl> + cv : : Vec4f res = gpu_row [ x ] ; <nl> + <nl> + ASSERT_NEAR ( res [ 0 ] , gold [ 0 ] , 1e - 5 ) ; <nl> + ASSERT_NEAR ( res [ 1 ] , gold [ 1 ] , 1e - 5 ) ; <nl> + ASSERT_NEAR ( res [ 2 ] , gold [ 2 ] , 1e - 5 ) ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( ImgProc , ReprojectImageTo3D , testing : : ValuesIn ( devices ( ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / Downsample <nl> + <nl> + struct Downsample : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int > > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int k ; <nl> + <nl> + cv : : Size size ; <nl> + <nl> + cv : : Size dst_gold_size ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + k = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + size = cv : : Size ( 200 + cvtest : : randInt ( rng ) % 1000 , 200 + cvtest : : randInt ( rng ) % 1000 ) ; <nl> + <nl> + dst_gold_size = cv : : Size ( ( size . width + k - 1 ) / k , ( size . height + k - 1 ) / k ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( Downsample , Accuracy8U ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + PRINT_PARAM ( k ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + cv : : Mat src = cvtest : : randomMat ( rng , size , CV_8U , 0 , 255 , false ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpures ; <nl> + cv : : gpu : : downsample ( cv : : gpu : : GpuMat ( src ) , gpures , k ) ; <nl> + gpures . download ( dst ) ; <nl> + ) ; <nl> + <nl> + ASSERT_EQ ( dst_gold_size , dst . size ( ) ) ; <nl> + <nl> + for ( int y = 0 ; y < dst . rows ; + + y ) <nl> + { <nl> + for ( int x = 0 ; x < dst . cols ; + + x ) <nl> + { <nl> + int gold = src . at < uchar > ( y * k , x * k ) ; <nl> + int res = dst . at < uchar > ( y , x ) ; <nl> + ASSERT_EQ ( gold , res ) ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + TEST_P ( Downsample , Accuracy32F ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + PRINT_PARAM ( k ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + cv : : Mat src = cvtest : : randomMat ( rng , size , CV_32F , 0 , 1 . 0 , false ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat gpures ; <nl> + cv : : gpu : : downsample ( cv : : gpu : : GpuMat ( src ) , gpures , k ) ; <nl> + gpures . download ( dst ) ; <nl> + ) ; <nl> + <nl> + ASSERT_EQ ( dst_gold_size , dst . size ( ) ) ; <nl> + <nl> + for ( int y = 0 ; y < dst . rows ; + + y ) <nl> + { <nl> + for ( int x = 0 ; x < dst . cols ; + + x ) <nl> + { <nl> + float gold = src . at < float > ( y * k , x * k ) ; <nl> + float res = dst . at < float > ( y , x ) ; <nl> + ASSERT_FLOAT_EQ ( gold , res ) ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( ImgProc , Downsample , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Range ( 2 , 6 ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / meanShift <nl> + <nl> + struct MeanShift : testing : : TestWithParam < cv : : gpu : : DeviceInfo > <nl> + { <nl> + static cv : : Mat rgba ; <nl> + <nl> + static void SetUpTestCase ( ) <nl> + { <nl> + cv : : Mat img = readImage ( " meanshift / cones . png " ) ; <nl> + cv : : cvtColor ( img , rgba , CV_BGR2BGRA ) ; <nl> + } <nl> + <nl> + static void TearDownTestCase ( ) <nl> + { <nl> + rgba . release ( ) ; <nl> + } <nl> + <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + <nl> + int spatialRad ; <nl> + int colorRad ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = GetParam ( ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + spatialRad = 30 ; <nl> + colorRad = 30 ; <nl> + } <nl> + } ; <nl> + <nl> + cv : : Mat MeanShift : : rgba ; <nl> + <nl> + TEST_P ( MeanShift , Filtering ) <nl> + { <nl> + cv : : Mat img_template ; <nl> + <nl> + if ( supportFeature ( devInfo , cv : : gpu : : FEATURE_SET_COMPUTE_20 ) ) <nl> + img_template = readImage ( " meanshift / con_result . png " ) ; <nl> + else <nl> + img_template = readImage ( " meanshift / con_result_CC1X . png " ) ; <nl> + <nl> + ASSERT_TRUE ( ! rgba . empty ( ) & & ! img_template . empty ( ) ) ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat dev_dst ; <nl> + cv : : gpu : : meanShiftFiltering ( cv : : gpu : : GpuMat ( rgba ) , dev_dst , spatialRad , colorRad ) ; <nl> + dev_dst . download ( dst ) ; <nl> + ) ; <nl> + <nl> + ASSERT_EQ ( CV_8UC4 , dst . type ( ) ) ; <nl> + <nl> + cv : : Mat result ; <nl> + cv : : cvtColor ( dst , result , CV_BGRA2BGR ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( img_template , result , 0 . 0 ) ; <nl> + } <nl> + <nl> + TEST_P ( MeanShift , Proc ) <nl> + { <nl> + cv : : Mat spmap_template ; <nl> + cv : : FileStorage fs ; <nl> + <nl> + if ( supportFeature ( devInfo , cv : : gpu : : FEATURE_SET_COMPUTE_20 ) ) <nl> + fs . open ( std : : string ( cvtest : : TS : : ptr ( ) - > get_data_path ( ) ) + " meanshift / spmap . yaml " , cv : : FileStorage : : READ ) ; <nl> + else <nl> + fs . open ( std : : string ( cvtest : : TS : : ptr ( ) - > get_data_path ( ) ) + " meanshift / spmap_CC1X . yaml " , cv : : FileStorage : : READ ) ; <nl> + <nl> + ASSERT_TRUE ( fs . isOpened ( ) ) ; <nl> + <nl> + fs [ " spmap " ] > > spmap_template ; <nl> + <nl> + ASSERT_TRUE ( ! rgba . empty ( ) & & ! spmap_template . empty ( ) ) ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + <nl> + cv : : Mat rmap_filtered ; <nl> + cv : : Mat rmap ; <nl> + cv : : Mat spmap ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat d_rmap_filtered ; <nl> + cv : : gpu : : meanShiftFiltering ( cv : : gpu : : GpuMat ( rgba ) , d_rmap_filtered , spatialRad , colorRad ) ; <nl> + <nl> + cv : : gpu : : GpuMat d_rmap ; <nl> + cv : : gpu : : GpuMat d_spmap ; <nl> + cv : : gpu : : meanShiftProc ( cv : : gpu : : GpuMat ( rgba ) , d_rmap , d_spmap , spatialRad , colorRad ) ; <nl> + <nl> + d_rmap_filtered . download ( rmap_filtered ) ; <nl> + d_rmap . download ( rmap ) ; <nl> + d_spmap . download ( spmap ) ; <nl> + ) ; <nl> + <nl> + ASSERT_EQ ( CV_8UC4 , rmap . type ( ) ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( rmap_filtered , rmap , 0 . 0 ) ; <nl> + EXPECT_MAT_NEAR ( spmap_template , spmap , 0 . 0 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( ImgProc , MeanShift , testing : : ValuesIn ( devices ( cv : : gpu : : FEATURE_SET_COMPUTE_12 ) ) ) ; <nl> + <nl> + struct MeanShiftSegmentation : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int > > <nl> + { <nl> + static cv : : Mat rgba ; <nl> + <nl> + static void SetUpTestCase ( ) <nl> + { <nl> + cv : : Mat img = readImage ( " meanshift / cones . png " ) ; <nl> + cv : : cvtColor ( img , rgba , CV_BGR2BGRA ) ; <nl> + } <nl> + <nl> + static void TearDownTestCase ( ) <nl> + { <nl> + rgba . release ( ) ; <nl> + } <nl> + <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int minsize ; <nl> + <nl> + cv : : Mat dst_gold ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + minsize = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + std : : ostringstream path ; <nl> + path < < " meanshift / cones_segmented_sp10_sr10_minsize " < < minsize ; <nl> + if ( supportFeature ( devInfo , cv : : gpu : : FEATURE_SET_COMPUTE_20 ) ) <nl> + path < < " . png " ; <nl> + else <nl> + path < < " _CC1X . png " ; <nl> + <nl> + dst_gold = readImage ( path . str ( ) ) ; <nl> + } <nl> + } ; <nl> + <nl> + cv : : Mat MeanShiftSegmentation : : rgba ; <nl> + <nl> + TEST_P ( MeanShiftSegmentation , Regression ) <nl> + { <nl> + ASSERT_TRUE ( ! rgba . empty ( ) & & ! dst_gold . empty ( ) ) ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_PARAM ( minsize ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : meanShiftSegmentation ( cv : : gpu : : GpuMat ( rgba ) , dst , 10 , 10 , minsize ) ; <nl> + ) ; <nl> + <nl> + cv : : Mat dst_rgb ; <nl> + cv : : cvtColor ( dst , dst_rgb , CV_BGRA2BGR ) ; <nl> + <nl> + EXPECT_MAT_SIMILAR ( dst_gold , dst_rgb , 1e - 5 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( ImgProc , MeanShiftSegmentation , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( cv : : gpu : : FEATURE_SET_COMPUTE_12 ) ) , <nl> + testing : : Values ( 0 , 4 , 20 , 84 , 340 , 1364 ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / matchTemplate <nl> + <nl> + static const char * matchTemplateMethods [ ] = { " SQDIFF " , " SQDIFF_NORMED " , " CCORR " , " CCORR_NORMED " , " CCOEFF " , " CCOEFF_NORMED " } ; <nl> + <nl> + struct MatchTemplate8U : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int , int > > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int cn ; <nl> + int method ; <nl> + <nl> + int n , m , h , w ; <nl> + cv : : Mat image , templ ; <nl> + <nl> + cv : : Mat dst_gold ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + cn = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> + method = std : : tr1 : : get < 2 > ( GetParam ( ) ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + n = rng . uniform ( 30 , 100 ) ; <nl> + m = rng . uniform ( 30 , 100 ) ; <nl> + h = rng . uniform ( 5 , n - 1 ) ; <nl> + w = rng . uniform ( 5 , m - 1 ) ; <nl> + <nl> + image = cvtest : : randomMat ( rng , cv : : Size ( m , n ) , CV_MAKETYPE ( CV_8U , cn ) , 1 . 0 , 10 . 0 , false ) ; <nl> + templ = cvtest : : randomMat ( rng , cv : : Size ( w , h ) , CV_MAKETYPE ( CV_8U , cn ) , 1 . 0 , 10 . 0 , false ) ; <nl> + <nl> + cv : : matchTemplate ( image , templ , dst_gold , method ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( MatchTemplate8U , Regression ) <nl> + { <nl> + const char * matchTemplateMethodStr = matchTemplateMethods [ method ] ; <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_PARAM ( cn ) ; <nl> + PRINT_PARAM ( matchTemplateMethodStr ) ; <nl> + PRINT_PARAM ( n ) ; <nl> + PRINT_PARAM ( m ) ; <nl> + PRINT_PARAM ( h ) ; <nl> + PRINT_PARAM ( w ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat dev_dst ; <nl> + cv : : gpu : : matchTemplate ( cv : : gpu : : GpuMat ( image ) , cv : : gpu : : GpuMat ( templ ) , dev_dst , method ) ; <nl> + dev_dst . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 5 * h * w * 1e - 4 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( ImgProc , MatchTemplate8U , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Range ( 1 , 5 ) , <nl> + testing : : Values ( ( int ) CV_TM_SQDIFF , ( int ) CV_TM_SQDIFF_NORMED , ( int ) CV_TM_CCORR , ( int ) CV_TM_CCORR_NORMED , ( int ) CV_TM_CCOEFF , ( int ) CV_TM_CCOEFF_NORMED ) ) ) ; <nl> + <nl> + struct MatchTemplate32F : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int , int > > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int cn ; <nl> + int method ; <nl> + <nl> + int n , m , h , w ; <nl> + cv : : Mat image , templ ; <nl> + <nl> + cv : : Mat dst_gold ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + cn = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> + method = std : : tr1 : : get < 2 > ( GetParam ( ) ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + n = rng . uniform ( 30 , 100 ) ; <nl> + m = rng . uniform ( 30 , 100 ) ; <nl> + h = rng . uniform ( 5 , n - 1 ) ; <nl> + w = rng . uniform ( 5 , m - 1 ) ; <nl> + <nl> + image = cvtest : : randomMat ( rng , cv : : Size ( m , n ) , CV_MAKETYPE ( CV_32F , cn ) , 0 . 001 , 1 . 0 , false ) ; <nl> + templ = cvtest : : randomMat ( rng , cv : : Size ( w , h ) , CV_MAKETYPE ( CV_32F , cn ) , 0 . 001 , 1 . 0 , false ) ; <nl> + <nl> + cv : : matchTemplate ( image , templ , dst_gold , method ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( MatchTemplate32F , Regression ) <nl> + { <nl> + const char * matchTemplateMethodStr = matchTemplateMethods [ method ] ; <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_PARAM ( cn ) ; <nl> + PRINT_PARAM ( matchTemplateMethodStr ) ; <nl> + PRINT_PARAM ( n ) ; <nl> + PRINT_PARAM ( m ) ; <nl> + PRINT_PARAM ( h ) ; <nl> + PRINT_PARAM ( w ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat dev_dst ; <nl> + cv : : gpu : : matchTemplate ( cv : : gpu : : GpuMat ( image ) , cv : : gpu : : GpuMat ( templ ) , dev_dst , method ) ; <nl> + dev_dst . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 0 . 25 * h * w * 1e - 4 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( ImgProc , MatchTemplate32F , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Range ( 1 , 5 ) , <nl> + testing : : Values ( ( int ) CV_TM_SQDIFF , ( int ) CV_TM_CCORR ) ) ) ; <nl> + <nl> + struct MatchTemplate : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int > > <nl> + { <nl> + static cv : : Mat image ; <nl> + static cv : : Mat pattern ; <nl> + <nl> + static cv : : Point maxLocGold ; <nl> + <nl> + static void SetUpTestCase ( ) <nl> + { <nl> + image = readImage ( " matchtemplate / black . png " ) ; <nl> + pattern = readImage ( " matchtemplate / cat . png " ) ; <nl> + <nl> + maxLocGold = cv : : Point ( 284 , 12 ) ; <nl> + } <nl> + <nl> + static void TearDownTestCase ( ) <nl> + { <nl> + image . release ( ) ; <nl> + pattern . release ( ) ; <nl> + } <nl> + <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int method ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + method = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + } <nl> + } ; <nl> + <nl> + cv : : Mat MatchTemplate : : image ; <nl> + cv : : Mat MatchTemplate : : pattern ; <nl> + cv : : Point MatchTemplate : : maxLocGold ; <nl> + <nl> + TEST_P ( MatchTemplate , FindPatternInBlack ) <nl> + { <nl> + ASSERT_TRUE ( ! image . empty ( ) & & ! pattern . empty ( ) ) ; <nl> + <nl> + const char * matchTemplateMethodStr = matchTemplateMethods [ method ] ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_PARAM ( matchTemplateMethodStr ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat dev_dst ; <nl> + cv : : gpu : : matchTemplate ( cv : : gpu : : GpuMat ( image ) , cv : : gpu : : GpuMat ( pattern ) , dev_dst , method ) ; <nl> + dev_dst . download ( dst ) ; <nl> + ) ; <nl> + <nl> + double maxValue ; <nl> + cv : : Point maxLoc ; <nl> + cv : : minMaxLoc ( dst , NULL , & maxValue , NULL , & maxLoc ) ; <nl> + <nl> + ASSERT_EQ ( maxLocGold , maxLoc ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( ImgProc , MatchTemplate , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( ( int ) CV_TM_CCOEFF_NORMED , ( int ) CV_TM_CCORR_NORMED ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / MulSpectrums <nl> + <nl> + struct MulSpectrums : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int > > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int flag ; <nl> + <nl> + cv : : Mat a , b ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + flag = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + a = cvtest : : randomMat ( rng , cv : : Size ( rng . uniform ( 100 , 200 ) , rng . uniform ( 100 , 200 ) ) , CV_32FC2 , 0 . 0 , 10 . 0 , false ) ; <nl> + b = cvtest : : randomMat ( rng , a . size ( ) , CV_32FC2 , 0 . 0 , 10 . 0 , false ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( MulSpectrums , Simple ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_PARAM ( flag ) ; <nl> + <nl> + cv : : Mat c_gold ; <nl> + cv : : mulSpectrums ( a , b , c_gold , flag , false ) ; <nl> + <nl> + cv : : Mat c ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat d_c ; <nl> + <nl> + cv : : gpu : : mulSpectrums ( cv : : gpu : : GpuMat ( a ) , cv : : gpu : : GpuMat ( b ) , d_c , flag , false ) ; <nl> + <nl> + d_c . download ( c ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( c_gold , c , 1e - 4 ) ; <nl> + } <nl> + <nl> + TEST_P ( MulSpectrums , Scaled ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_PARAM ( flag ) ; <nl> + <nl> + float scale = 1 . f / a . size ( ) . area ( ) ; <nl> + <nl> + cv : : Mat c_gold ; <nl> + cv : : mulSpectrums ( a , b , c_gold , flag , false ) ; <nl> + c_gold . convertTo ( c_gold , c_gold . type ( ) , scale ) ; <nl> + <nl> + cv : : Mat c ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat d_c ; <nl> + <nl> + cv : : gpu : : mulAndScaleSpectrums ( cv : : gpu : : GpuMat ( a ) , cv : : gpu : : GpuMat ( b ) , d_c , flag , scale , false ) ; <nl> + <nl> + d_c . download ( c ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( c_gold , c , 1e - 4 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( ImgProc , MulSpectrums , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( 0 , ( int ) cv : : DFT_ROWS ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / Dft <nl> + <nl> + struct Dft : testing : : TestWithParam < cv : : gpu : : DeviceInfo > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = GetParam ( ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + } <nl> + } ; <nl> + <nl> + static void testC2C ( const std : : string & hint , int cols , int rows , int flags , bool inplace ) <nl> + { <nl> + PRINT_PARAM ( hint ) ; <nl> + PRINT_PARAM ( cols ) ; <nl> + PRINT_PARAM ( rows ) ; <nl> + PRINT_PARAM ( flags ) ; <nl> + PRINT_PARAM ( inplace ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + cv : : Mat a = cvtest : : randomMat ( rng , cv : : Size ( cols , rows ) , CV_32FC2 , 0 . 0 , 10 . 0 , false ) ; <nl> + <nl> + cv : : Mat b_gold ; <nl> + cv : : dft ( a , b_gold , flags ) ; <nl> + <nl> + cv : : gpu : : GpuMat d_b ; <nl> + cv : : gpu : : GpuMat d_b_data ; <nl> + if ( inplace ) <nl> + { <nl> + d_b_data . create ( 1 , a . size ( ) . area ( ) , CV_32FC2 ) ; <nl> + d_b = cv : : gpu : : GpuMat ( a . rows , a . cols , CV_32FC2 , d_b_data . ptr ( ) , a . cols * d_b_data . elemSize ( ) ) ; <nl> + } <nl> + cv : : gpu : : dft ( cv : : gpu : : GpuMat ( a ) , d_b , cv : : Size ( cols , rows ) , flags ) ; <nl> + <nl> + EXPECT_TRUE ( ! inplace | | d_b . ptr ( ) = = d_b_data . ptr ( ) ) ; <nl> + ASSERT_EQ ( CV_32F , d_b . depth ( ) ) ; <nl> + ASSERT_EQ ( 2 , d_b . channels ( ) ) ; <nl> + EXPECT_MAT_NEAR ( b_gold , d_b , rows * cols * 1e - 4 ) ; <nl> + } <nl> + <nl> + TEST_P ( Dft , C2C ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + int cols = 2 + rng . next ( ) % 100 , rows = 2 + rng . next ( ) % 100 ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + for ( int i = 0 ; i < 2 ; + + i ) <nl> + { <nl> + bool inplace = i ! = 0 ; <nl> + <nl> + testC2C ( " no flags " , cols , rows , 0 , inplace ) ; <nl> + testC2C ( " no flags 0 1 " , cols , rows + 1 , 0 , inplace ) ; <nl> + testC2C ( " no flags 1 0 " , cols , rows + 1 , 0 , inplace ) ; <nl> + testC2C ( " no flags 1 1 " , cols + 1 , rows , 0 , inplace ) ; <nl> + testC2C ( " DFT_INVERSE " , cols , rows , cv : : DFT_INVERSE , inplace ) ; <nl> + testC2C ( " DFT_ROWS " , cols , rows , cv : : DFT_ROWS , inplace ) ; <nl> + testC2C ( " single col " , 1 , rows , 0 , inplace ) ; <nl> + testC2C ( " single row " , cols , 1 , 0 , inplace ) ; <nl> + testC2C ( " single col inversed " , 1 , rows , cv : : DFT_INVERSE , inplace ) ; <nl> + testC2C ( " single row inversed " , cols , 1 , cv : : DFT_INVERSE , inplace ) ; <nl> + testC2C ( " single row DFT_ROWS " , cols , 1 , cv : : DFT_ROWS , inplace ) ; <nl> + testC2C ( " size 1 2 " , 1 , 2 , 0 , inplace ) ; <nl> + testC2C ( " size 2 1 " , 2 , 1 , 0 , inplace ) ; <nl> + } <nl> + ) ; <nl> + } <nl> + <nl> + static void testR2CThenC2R ( const std : : string & hint , int cols , int rows , bool inplace ) <nl> + { <nl> + PRINT_PARAM ( hint ) ; <nl> + PRINT_PARAM ( cols ) ; <nl> + PRINT_PARAM ( rows ) ; <nl> + PRINT_PARAM ( inplace ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + cv : : Mat a = cvtest : : randomMat ( rng , cv : : Size ( cols , rows ) , CV_32FC1 , 0 . 0 , 10 . 0 , false ) ; <nl> + <nl> + cv : : gpu : : GpuMat d_b , d_c ; <nl> + cv : : gpu : : GpuMat d_b_data , d_c_data ; <nl> + if ( inplace ) <nl> + { <nl> + if ( a . cols = = 1 ) <nl> + { <nl> + d_b_data . create ( 1 , ( a . rows / 2 + 1 ) * a . cols , CV_32FC2 ) ; <nl> + d_b = cv : : gpu : : GpuMat ( a . rows / 2 + 1 , a . cols , CV_32FC2 , d_b_data . ptr ( ) , a . cols * d_b_data . elemSize ( ) ) ; <nl> + } <nl> + else <nl> + { <nl> + d_b_data . create ( 1 , a . rows * ( a . cols / 2 + 1 ) , CV_32FC2 ) ; <nl> + d_b = cv : : gpu : : GpuMat ( a . rows , a . cols / 2 + 1 , CV_32FC2 , d_b_data . ptr ( ) , ( a . cols / 2 + 1 ) * d_b_data . elemSize ( ) ) ; <nl> + } <nl> + d_c_data . create ( 1 , a . size ( ) . area ( ) , CV_32F ) ; <nl> + d_c = cv : : gpu : : GpuMat ( a . rows , a . cols , CV_32F , d_c_data . ptr ( ) , a . cols * d_c_data . elemSize ( ) ) ; <nl> + } <nl> + <nl> + cv : : gpu : : dft ( cv : : gpu : : GpuMat ( a ) , d_b , cv : : Size ( cols , rows ) , 0 ) ; <nl> + cv : : gpu : : dft ( d_b , d_c , cv : : Size ( cols , rows ) , cv : : DFT_REAL_OUTPUT | cv : : DFT_SCALE ) ; <nl> + <nl> + EXPECT_TRUE ( ! inplace | | d_b . ptr ( ) = = d_b_data . ptr ( ) ) ; <nl> + EXPECT_TRUE ( ! inplace | | d_c . ptr ( ) = = d_c_data . ptr ( ) ) ; <nl> + ASSERT_EQ ( CV_32F , d_c . depth ( ) ) ; <nl> + ASSERT_EQ ( 1 , d_c . channels ( ) ) ; <nl> + <nl> + cv : : Mat c ( d_c ) ; <nl> + EXPECT_MAT_NEAR ( a , c , rows * cols * 1e - 5 ) ; <nl> + } <nl> + <nl> + TEST_P ( Dft , R2CThenC2R ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + int cols = 2 + rng . next ( ) % 100 , rows = 2 + rng . next ( ) % 100 ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + testR2CThenC2R ( " sanity " , cols , rows , false ) ; <nl> + testR2CThenC2R ( " sanity 0 1 " , cols , rows + 1 , false ) ; <nl> + testR2CThenC2R ( " sanity 1 0 " , cols + 1 , rows , false ) ; <nl> + testR2CThenC2R ( " sanity 1 1 " , cols + 1 , rows + 1 , false ) ; <nl> + testR2CThenC2R ( " single col " , 1 , rows , false ) ; <nl> + testR2CThenC2R ( " single col 1 " , 1 , rows + 1 , false ) ; <nl> + testR2CThenC2R ( " single row " , cols , 1 , false ) ; <nl> + testR2CThenC2R ( " single row 1 " , cols + 1 , 1 , false ) ; <nl> + <nl> + testR2CThenC2R ( " sanity " , cols , rows , true ) ; <nl> + testR2CThenC2R ( " sanity 0 1 " , cols , rows + 1 , true ) ; <nl> + testR2CThenC2R ( " sanity 1 0 " , cols + 1 , rows , true ) ; <nl> + testR2CThenC2R ( " sanity 1 1 " , cols + 1 , rows + 1 , true ) ; <nl> + testR2CThenC2R ( " single row " , cols , 1 , true ) ; <nl> + testR2CThenC2R ( " single row 1 " , cols + 1 , 1 , true ) ; <nl> + ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( ImgProc , Dft , testing : : ValuesIn ( devices ( ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / blend <nl> + <nl> + template < typename T > static void blendLinearGold ( const cv : : Mat & img1 , const cv : : Mat & img2 , const cv : : Mat & weights1 , const cv : : Mat & weights2 , cv : : Mat & result_gold ) <nl> + { <nl> + result_gold . create ( img1 . size ( ) , img1 . type ( ) ) ; <nl> + <nl> + int cn = img1 . channels ( ) ; <nl> + <nl> + for ( int y = 0 ; y < img1 . rows ; + + y ) <nl> + { <nl> + const float * weights1_row = weights1 . ptr < float > ( y ) ; <nl> + const float * weights2_row = weights2 . ptr < float > ( y ) ; <nl> + const T * img1_row = img1 . ptr < T > ( y ) ; <nl> + const T * img2_row = img2 . ptr < T > ( y ) ; <nl> + T * result_gold_row = result_gold . ptr < T > ( y ) ; <nl> + for ( int x = 0 ; x < img1 . cols * cn ; + + x ) <nl> + { <nl> + float w1 = weights1_row [ x / cn ] ; <nl> + float w2 = weights2_row [ x / cn ] ; <nl> + result_gold_row [ x ] = static_cast < T > ( ( img1_row [ x ] * w1 + img2_row [ x ] * w2 ) / ( w1 + w2 + 1e - 5f ) ) ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + struct Blend : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int , int > > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int depth ; <nl> + int cn ; <nl> + <nl> + int type ; <nl> + cv : : Size size ; <nl> + cv : : Mat img1 ; <nl> + cv : : Mat img2 ; <nl> + cv : : Mat weights1 ; <nl> + cv : : Mat weights2 ; <nl> + <nl> + cv : : Mat result_gold ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + depth = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> + cn = std : : tr1 : : get < 2 > ( GetParam ( ) ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + type = CV_MAKETYPE ( depth , cn ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + size = cv : : Size ( 200 + cvtest : : randInt ( rng ) % 1000 , 200 + cvtest : : randInt ( rng ) % 1000 ) ; <nl> + <nl> + img1 = cvtest : : randomMat ( rng , size , type , 0 . 0 , depth = = CV_8U ? 255 . 0 : 1 . 0 , false ) ; <nl> + img2 = cvtest : : randomMat ( rng , size , type , 0 . 0 , depth = = CV_8U ? 255 . 0 : 1 . 0 , false ) ; <nl> + weights1 = cvtest : : randomMat ( rng , size , CV_32F , 0 , 1 , false ) ; <nl> + weights2 = cvtest : : randomMat ( rng , size , CV_32F , 0 , 1 , false ) ; <nl> + <nl> + if ( depth = = CV_8U ) <nl> + blendLinearGold < uchar > ( img1 , img2 , weights1 , weights2 , result_gold ) ; <nl> + else <nl> + blendLinearGold < float > ( img1 , img2 , weights1 , weights2 , result_gold ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( Blend , Accuracy ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + <nl> + cv : : Mat result ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat d_result ; <nl> + <nl> + cv : : gpu : : blendLinear ( cv : : gpu : : GpuMat ( img1 ) , cv : : gpu : : GpuMat ( img2 ) , cv : : gpu : : GpuMat ( weights1 ) , cv : : gpu : : GpuMat ( weights2 ) , d_result ) ; <nl> + <nl> + d_result . download ( result ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( result_gold , result , depth = = CV_8U ? 1 . 0 : 1e - 5 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( ImgProc , Blend , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : Values ( CV_8U , CV_32F ) , <nl> + testing : : Range ( 1 , 5 ) ) ) ; <nl> + <nl> + # endif / / HAVE_CUDA <nl> deleted file mode 100644 <nl> index d45d7c77bbf . . 00000000000 <nl> mmm a / modules / gpu / test / test_imgproc_gpu . cpp <nl> ppp / dev / null <nl> <nl> - / * M / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / <nl> - / / IMPORTANT : READ BEFORE DOWNLOADING , COPYING , INSTALLING OR USING . <nl> - / / <nl> - / / By downloading , copying , installing or using the software you agree to this license . <nl> - / / If you do not agree to this license , do not download , install , <nl> - / / copy or use the software . <nl> - / / <nl> - / / <nl> - / / Intel License Agreement <nl> - / / For Open Source Computer Vision Library <nl> - / / <nl> - / / Copyright ( C ) 2000 , Intel Corporation , all rights reserved . <nl> - / / Third party copyrights are property of their respective owners . <nl> - / / <nl> - / / Redistribution and use in source and binary forms , with or without modification , <nl> - / / are permitted provided that the following conditions are met : <nl> - / / <nl> - / / * Redistribution ' s of source code must retain the above copyright notice , <nl> - / / this list of conditions and the following disclaimer . <nl> - / / <nl> - / / * Redistribution ' s in binary form must reproduce the above copyright notice , <nl> - / / this list of conditions and the following disclaimer in the documentation <nl> - / / and / or other materials provided with the distribution . <nl> - / / <nl> - / / * The name of Intel Corporation may not be used to endorse or promote products <nl> - / / derived from this software without specific prior written permission . <nl> - / / <nl> - / / This software is provided by the copyright holders and contributors " as is " and <nl> - / / any express or implied warranties , including , but not limited to , the implied <nl> - / / warranties of merchantability and fitness for a particular purpose are disclaimed . <nl> - / / In no event shall the Intel Corporation or contributors be liable for any direct , <nl> - / / indirect , incidental , special , exemplary , or consequential damages <nl> - / / ( including , but not limited to , procurement of substitute goods or services ; <nl> - / / loss of use , data , or profits ; or business interruption ) however caused <nl> - / / and on any theory of liability , whether in contract , strict liability , <nl> - / / or tort ( including negligence or otherwise ) arising in any way out of <nl> - / / the use of this software , even if advised of the possibility of such damage . <nl> - / / <nl> - / / M * / <nl> - <nl> - # include < cmath > <nl> - # include < limits > <nl> - # include " test_precomp . hpp " <nl> - <nl> - using namespace cv ; <nl> - using namespace std ; <nl> - using namespace gpu ; <nl> - <nl> - class CV_GpuImageProcTest : public cvtest : : BaseTest <nl> - { <nl> - public : <nl> - virtual ~ CV_GpuImageProcTest ( ) { } <nl> - <nl> - protected : <nl> - void run ( int ) ; <nl> - <nl> - int test8UC1 ( const Mat & img ) ; <nl> - int test8UC4 ( const Mat & img ) ; <nl> - int test32SC1 ( const Mat & img ) ; <nl> - int test32FC1 ( const Mat & img ) ; <nl> - <nl> - virtual int test ( const Mat & img ) = 0 ; <nl> - <nl> - int CheckNorm ( const Mat & m1 , const Mat & m2 ) ; <nl> - <nl> - / / Checks whether two images are similar enough using normalized <nl> - / / cross - correlation as an error measure <nl> - int CheckSimilarity ( const Mat & m1 , const Mat & m2 , float max_err = 1e - 3f ) ; <nl> - } ; <nl> - <nl> - <nl> - int CV_GpuImageProcTest : : test8UC1 ( const Mat & img ) <nl> - { <nl> - cv : : Mat img_C1 ; <nl> - cvtColor ( img , img_C1 , CV_BGR2GRAY ) ; <nl> - <nl> - return test ( img_C1 ) ; <nl> - } <nl> - <nl> - int CV_GpuImageProcTest : : test8UC4 ( const Mat & img ) <nl> - { <nl> - cv : : Mat img_C4 ; <nl> - cvtColor ( img , img_C4 , CV_BGR2BGRA ) ; <nl> - <nl> - return test ( img_C4 ) ; <nl> - } <nl> - <nl> - int CV_GpuImageProcTest : : test32SC1 ( const Mat & img ) <nl> - { <nl> - cv : : Mat img_C1 ; <nl> - cvtColor ( img , img_C1 , CV_BGR2GRAY ) ; <nl> - img_C1 . convertTo ( img_C1 , CV_32S ) ; <nl> - <nl> - return test ( img_C1 ) ; <nl> - } <nl> - <nl> - int CV_GpuImageProcTest : : test32FC1 ( const Mat & img ) <nl> - { <nl> - cv : : Mat temp , img_C1 ; <nl> - img . convertTo ( temp , CV_32F , 1 . f / 255 . f ) ; <nl> - cvtColor ( temp , img_C1 , CV_BGR2GRAY ) ; <nl> - <nl> - return test ( img_C1 ) ; <nl> - } <nl> - <nl> - int CV_GpuImageProcTest : : CheckNorm ( const Mat & m1 , const Mat & m2 ) <nl> - { <nl> - double ret = norm ( m1 , m2 , NORM_INF ) ; <nl> - <nl> - if ( ret < std : : numeric_limits < double > : : epsilon ( ) ) <nl> - { <nl> - return cvtest : : TS : : OK ; <nl> - } <nl> - else <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " Norm : % f \ n " , ret ) ; <nl> - return cvtest : : TS : : FAIL_GENERIC ; <nl> - } <nl> - } <nl> - <nl> - int CV_GpuImageProcTest : : CheckSimilarity ( const Mat & m1 , const Mat & m2 , float max_err ) <nl> - { <nl> - Mat diff ; <nl> - cv : : matchTemplate ( m1 , m2 , diff , CV_TM_CCORR_NORMED ) ; <nl> - <nl> - float err = abs ( diff . at < float > ( 0 , 0 ) - 1 . f ) ; <nl> - <nl> - if ( err > max_err ) <nl> - return cvtest : : TS : : FAIL_INVALID_OUTPUT ; <nl> - <nl> - return cvtest : : TS : : OK ; <nl> - } <nl> - <nl> - void CV_GpuImageProcTest : : run ( int ) <nl> - { <nl> - / / load image <nl> - cv : : Mat img = cv : : imread ( std : : string ( ts - > get_data_path ( ) ) + " stereobp / aloe - L . png " ) ; <nl> - <nl> - if ( img . empty ( ) ) <nl> - { <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_MISSING_TEST_DATA ) ; <nl> - return ; <nl> - } <nl> - <nl> - int testResult = cvtest : : TS : : OK ; <nl> - / / run tests <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ n = = = = = = = = Start test 8UC1 = = = = = = = = \ n " ) ; <nl> - if ( test8UC1 ( img ) = = cvtest : : TS : : OK ) <nl> - ts - > printf ( cvtest : : TS : : LOG , " SUCCESS \ n " ) ; <nl> - else <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " FAIL \ n " ) ; <nl> - testResult = cvtest : : TS : : FAIL_GENERIC ; <nl> - } <nl> - <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ n = = = = = = = = Start test 8UC4 = = = = = = = = \ n " ) ; <nl> - if ( test8UC4 ( img ) = = cvtest : : TS : : OK ) <nl> - ts - > printf ( cvtest : : TS : : LOG , " SUCCESS \ n " ) ; <nl> - else <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " FAIL \ n " ) ; <nl> - testResult = cvtest : : TS : : FAIL_GENERIC ; <nl> - } <nl> - <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ n = = = = = = = = Start test 32SC1 = = = = = = = = \ n " ) ; <nl> - if ( test32SC1 ( img ) = = cvtest : : TS : : OK ) <nl> - ts - > printf ( cvtest : : TS : : LOG , " SUCCESS \ n " ) ; <nl> - else <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " FAIL \ n " ) ; <nl> - testResult = cvtest : : TS : : FAIL_GENERIC ; <nl> - } <nl> - <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ n = = = = = = = = Start test 32FC1 = = = = = = = = \ n " ) ; <nl> - if ( test32FC1 ( img ) = = cvtest : : TS : : OK ) <nl> - ts - > printf ( cvtest : : TS : : LOG , " SUCCESS \ n " ) ; <nl> - else <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " FAIL \ n " ) ; <nl> - testResult = cvtest : : TS : : FAIL_GENERIC ; <nl> - } <nl> - <nl> - ts - > set_failed_test_info ( testResult ) ; <nl> - } <nl> - <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / threshold <nl> - struct CV_GpuImageThresholdTest : public CV_GpuImageProcTest <nl> - { <nl> - public : <nl> - CV_GpuImageThresholdTest ( ) { } <nl> - <nl> - int test ( const Mat & img ) <nl> - { <nl> - if ( img . type ( ) ! = CV_8UC1 & & img . type ( ) ! = CV_32FC1 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ nUnsupported type \ n " ) ; <nl> - return cvtest : : TS : : OK ; <nl> - } <nl> - <nl> - const double maxVal = img . type ( ) = = CV_8UC1 ? 255 : 1 . 0 ; <nl> - <nl> - cv : : RNG & rng = ts - > get_rng ( ) ; <nl> - <nl> - int res = cvtest : : TS : : OK ; <nl> - <nl> - for ( int type = THRESH_BINARY ; type < = THRESH_TOZERO_INV ; + + type ) <nl> - { <nl> - const double thresh = rng . uniform ( 0 . 0 , maxVal ) ; <nl> - <nl> - cv : : Mat cpuRes ; <nl> - cv : : threshold ( img , cpuRes , thresh , maxVal , type ) ; <nl> - <nl> - GpuMat gpu1 ( img ) ; <nl> - GpuMat gpuRes ; <nl> - cv : : gpu : : threshold ( gpu1 , gpuRes , thresh , maxVal , type ) ; <nl> - <nl> - if ( CheckNorm ( cpuRes , gpuRes ) ! = cvtest : : TS : : OK ) <nl> - res = cvtest : : TS : : FAIL_GENERIC ; <nl> - } <nl> - <nl> - return res ; <nl> - } <nl> - } ; <nl> - <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / resize <nl> - struct CV_GpuNppImageResizeTest : public CV_GpuImageProcTest <nl> - { <nl> - CV_GpuNppImageResizeTest ( ) { } <nl> - int test ( const Mat & img ) <nl> - { <nl> - if ( img . type ( ) ! = CV_8UC1 & & img . type ( ) ! = CV_8UC4 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " Unsupported type \ n " ) ; <nl> - return cvtest : : TS : : OK ; <nl> - } <nl> - <nl> - int interpolations [ ] = { INTER_NEAREST , INTER_LINEAR , / * INTER_CUBIC , * / / * INTER_LANCZOS4 * / } ; <nl> - const char * interpolations_str [ ] = { " INTER_NEAREST " , " INTER_LINEAR " , / * " INTER_CUBIC " , * / / * " INTER_LANCZOS4 " * / } ; <nl> - int interpolations_num = sizeof ( interpolations ) / sizeof ( int ) ; <nl> - <nl> - int test_res = cvtest : : TS : : OK ; <nl> - <nl> - for ( int i = 0 ; i < interpolations_num ; + + i ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " Interpolation : % s \ n " , interpolations_str [ i ] ) ; <nl> - <nl> - Mat cpu_res1 , cpu_res2 ; <nl> - cv : : resize ( img , cpu_res1 , Size ( ) , 2 . 0 , 2 . 0 , interpolations [ i ] ) ; <nl> - cv : : resize ( cpu_res1 , cpu_res2 , Size ( ) , 0 . 5 , 0 . 5 , interpolations [ i ] ) ; <nl> - <nl> - GpuMat gpu1 ( img ) , gpu_res1 , gpu_res2 ; <nl> - cv : : gpu : : resize ( gpu1 , gpu_res1 , Size ( ) , 2 . 0 , 2 . 0 , interpolations [ i ] ) ; <nl> - cv : : gpu : : resize ( gpu_res1 , gpu_res2 , Size ( ) , 0 . 5 , 0 . 5 , interpolations [ i ] ) ; <nl> - <nl> - if ( CheckSimilarity ( cpu_res2 , gpu_res2 ) ! = cvtest : : TS : : OK ) <nl> - test_res = cvtest : : TS : : FAIL_GENERIC ; <nl> - } <nl> - <nl> - return test_res ; <nl> - } <nl> - } ; <nl> - <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / copyMakeBorder <nl> - struct CV_GpuNppImageCopyMakeBorderTest : public CV_GpuImageProcTest <nl> - { <nl> - CV_GpuNppImageCopyMakeBorderTest ( ) { } <nl> - <nl> - int test ( const Mat & img ) <nl> - { <nl> - if ( img . type ( ) ! = CV_8UC1 & & img . type ( ) ! = CV_8UC4 & & img . type ( ) ! = CV_32SC1 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ nUnsupported type \ n " ) ; <nl> - return cvtest : : TS : : OK ; <nl> - } <nl> - <nl> - cv : : RNG & rng = ts - > get_rng ( ) ; <nl> - int top = rng . uniform ( 1 , 10 ) ; <nl> - int botton = rng . uniform ( 1 , 10 ) ; <nl> - int left = rng . uniform ( 1 , 10 ) ; <nl> - int right = rng . uniform ( 1 , 10 ) ; <nl> - cv : : Scalar val ( rng . uniform ( 0 , 255 ) , rng . uniform ( 0 , 255 ) , rng . uniform ( 0 , 255 ) , rng . uniform ( 0 , 255 ) ) ; <nl> - <nl> - Mat cpudst ; <nl> - cv : : copyMakeBorder ( img , cpudst , top , botton , left , right , BORDER_CONSTANT , val ) ; <nl> - <nl> - GpuMat gpu1 ( img ) ; <nl> - GpuMat gpudst ; <nl> - cv : : gpu : : copyMakeBorder ( gpu1 , gpudst , top , botton , left , right , val ) ; <nl> - <nl> - return CheckNorm ( cpudst , gpudst ) ; <nl> - } <nl> - } ; <nl> - <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / warpAffine <nl> - struct CV_GpuNppImageWarpAffineTest : public CV_GpuImageProcTest <nl> - { <nl> - CV_GpuNppImageWarpAffineTest ( ) { } <nl> - <nl> - int test ( const Mat & img ) <nl> - { <nl> - if ( img . type ( ) = = CV_32SC1 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ nUnsupported type \ n " ) ; <nl> - return cvtest : : TS : : OK ; <nl> - } <nl> - <nl> - static double reflect [ 2 ] [ 3 ] = { { - 1 , 0 , 0 } , <nl> - { 0 , - 1 , 0 } } ; <nl> - reflect [ 0 ] [ 2 ] = img . cols ; <nl> - reflect [ 1 ] [ 2 ] = img . rows ; <nl> - <nl> - Mat M ( 2 , 3 , CV_64F , ( void * ) reflect ) ; <nl> - <nl> - int flags [ ] = { INTER_NEAREST , INTER_LINEAR , INTER_CUBIC , INTER_NEAREST | WARP_INVERSE_MAP , INTER_LINEAR | WARP_INVERSE_MAP , INTER_CUBIC | WARP_INVERSE_MAP } ; <nl> - const char * flags_str [ ] = { " INTER_NEAREST " , " INTER_LINEAR " , " INTER_CUBIC " , " INTER_NEAREST | WARP_INVERSE_MAP " , " INTER_LINEAR | WARP_INVERSE_MAP " , " INTER_CUBIC | WARP_INVERSE_MAP " } ; <nl> - int flags_num = sizeof ( flags ) / sizeof ( int ) ; <nl> - <nl> - int test_res = cvtest : : TS : : OK ; <nl> - <nl> - for ( int i = 0 ; i < flags_num ; + + i ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ nFlags : % s \ n " , flags_str [ i ] ) ; <nl> - <nl> - Mat cpudst ; <nl> - cv : : warpAffine ( img , cpudst , M , img . size ( ) , flags [ i ] ) ; <nl> - <nl> - GpuMat gpu1 ( img ) ; <nl> - GpuMat gpudst ; <nl> - cv : : gpu : : warpAffine ( gpu1 , gpudst , M , gpu1 . size ( ) , flags [ i ] ) ; <nl> - <nl> - / / Check inner parts ( ignoring 1 pixel width border ) <nl> - if ( CheckSimilarity ( cpudst . rowRange ( 1 , cpudst . rows - 1 ) . colRange ( 1 , cpudst . cols - 1 ) , <nl> - gpudst . rowRange ( 1 , gpudst . rows - 1 ) . colRange ( 1 , gpudst . cols - 1 ) ) ! = cvtest : : TS : : OK ) <nl> - test_res = cvtest : : TS : : FAIL_GENERIC ; <nl> - } <nl> - <nl> - return test_res ; <nl> - } <nl> - } ; <nl> - <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / warpPerspective <nl> - struct CV_GpuNppImageWarpPerspectiveTest : public CV_GpuImageProcTest <nl> - { <nl> - CV_GpuNppImageWarpPerspectiveTest ( ) { } <nl> - <nl> - <nl> - int test ( const Mat & img ) <nl> - { <nl> - if ( img . type ( ) = = CV_32SC1 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ nUnsupported type \ n " ) ; <nl> - return cvtest : : TS : : OK ; <nl> - } <nl> - <nl> - static double reflect [ 3 ] [ 3 ] = { { - 1 , 0 , 0 } , <nl> - { 0 , - 1 , 0 } , <nl> - { 0 , 0 , 1 } } ; <nl> - reflect [ 0 ] [ 2 ] = img . cols ; <nl> - reflect [ 1 ] [ 2 ] = img . rows ; <nl> - Mat M ( 3 , 3 , CV_64F , ( void * ) reflect ) ; <nl> - <nl> - int flags [ ] = { INTER_NEAREST , INTER_LINEAR , INTER_CUBIC , INTER_NEAREST | WARP_INVERSE_MAP , INTER_LINEAR | WARP_INVERSE_MAP , INTER_CUBIC | WARP_INVERSE_MAP } ; <nl> - const char * flags_str [ ] = { " INTER_NEAREST " , " INTER_LINEAR " , " INTER_CUBIC " , " INTER_NEAREST | WARP_INVERSE_MAP " , " INTER_LINEAR | WARP_INVERSE_MAP " , " INTER_CUBIC | WARP_INVERSE_MAP " } ; <nl> - int flags_num = sizeof ( flags ) / sizeof ( int ) ; <nl> - <nl> - int test_res = cvtest : : TS : : OK ; <nl> - <nl> - for ( int i = 0 ; i < flags_num ; + + i ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ nFlags : % s \ n " , flags_str [ i ] ) ; <nl> - <nl> - Mat cpudst ; <nl> - cv : : warpPerspective ( img , cpudst , M , img . size ( ) , flags [ i ] ) ; <nl> - <nl> - GpuMat gpu1 ( img ) ; <nl> - GpuMat gpudst ; <nl> - cv : : gpu : : warpPerspective ( gpu1 , gpudst , M , gpu1 . size ( ) , flags [ i ] ) ; <nl> - <nl> - / / Check inner parts ( ignoring 1 pixel width border ) <nl> - if ( CheckSimilarity ( cpudst . rowRange ( 1 , cpudst . rows - 1 ) . colRange ( 1 , cpudst . cols - 1 ) , <nl> - gpudst . rowRange ( 1 , gpudst . rows - 1 ) . colRange ( 1 , gpudst . cols - 1 ) ) ! = cvtest : : TS : : OK ) <nl> - test_res = cvtest : : TS : : FAIL_GENERIC ; <nl> - } <nl> - <nl> - return test_res ; <nl> - } <nl> - } ; <nl> - <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / integral <nl> - struct CV_GpuNppImageIntegralTest : public CV_GpuImageProcTest <nl> - { <nl> - CV_GpuNppImageIntegralTest ( ) { } <nl> - <nl> - int test ( const Mat & img ) <nl> - { <nl> - if ( img . type ( ) ! = CV_8UC1 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ nUnsupported type \ n " ) ; <nl> - return cvtest : : TS : : OK ; <nl> - } <nl> - <nl> - Mat cpusum ; <nl> - cv : : integral ( img , cpusum , CV_32S ) ; <nl> - <nl> - GpuMat gpu1 ( img ) ; <nl> - GpuMat gpusum ; <nl> - cv : : gpu : : integral ( gpu1 , gpusum ) ; <nl> - <nl> - return CheckNorm ( cpusum , gpusum ) = = cvtest : : TS : : OK ? cvtest : : TS : : OK : cvtest : : TS : : FAIL_GENERIC ; <nl> - } <nl> - } ; <nl> - <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / Canny <nl> - / / struct CV_GpuNppImageCannyTest : public CV_GpuImageProcTest <nl> - / / { <nl> - / / CV_GpuNppImageCannyTest ( ) : CV_GpuImageProcTest ( " GPU - NppImageCanny " , " Canny " ) { } <nl> - / / <nl> - / / int test ( const Mat & img ) <nl> - / / { <nl> - / / if ( img . type ( ) ! = CV_8UC1 ) <nl> - / / { <nl> - / / ts - > printf ( cvtest : : TS : : LOG , " \ nUnsupported type \ n " ) ; <nl> - / / return cvtest : : TS : : OK ; <nl> - / / } <nl> - / / <nl> - / / const double threshold1 = 1 . 0 , threshold2 = 10 . 0 ; <nl> - / / <nl> - / / Mat cpudst ; <nl> - / / cv : : Canny ( img , cpudst , threshold1 , threshold2 ) ; <nl> - / / <nl> - / / GpuMat gpu1 ( img ) ; <nl> - / / GpuMat gpudst ; <nl> - / / cv : : gpu : : Canny ( gpu1 , gpudst , threshold1 , threshold2 ) ; <nl> - / / <nl> - / / return CheckNorm ( cpudst , gpudst ) ; <nl> - / / } <nl> - / / } ; <nl> - <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / cvtColor <nl> - class CV_GpuCvtColorTest : public cvtest : : BaseTest <nl> - { <nl> - public : <nl> - CV_GpuCvtColorTest ( ) { } <nl> - ~ CV_GpuCvtColorTest ( ) { } ; <nl> - <nl> - protected : <nl> - void run ( int ) ; <nl> - <nl> - int CheckNorm ( const Mat & m1 , const Mat & m2 ) ; <nl> - } ; <nl> - <nl> - <nl> - int CV_GpuCvtColorTest : : CheckNorm ( const Mat & m1 , const Mat & m2 ) <nl> - { <nl> - float max_err = 1e - 2f ; <nl> - <nl> - Mat diff ; <nl> - cv : : matchTemplate ( m1 , m2 , diff , CV_TM_CCORR_NORMED ) ; <nl> - <nl> - float err = abs ( diff . at < float > ( 0 , 0 ) - 1 . f ) ; <nl> - <nl> - if ( err > max_err ) <nl> - return cvtest : : TS : : FAIL_INVALID_OUTPUT ; <nl> - <nl> - return cvtest : : TS : : OK ; <nl> - } <nl> - <nl> - void CV_GpuCvtColorTest : : run ( int ) <nl> - { <nl> - cv : : Mat img = cv : : imread ( std : : string ( ts - > get_data_path ( ) ) + " stereobp / aloe - L . png " ) ; <nl> - <nl> - if ( img . empty ( ) ) <nl> - { <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_MISSING_TEST_DATA ) ; <nl> - return ; <nl> - } <nl> - <nl> - int testResult = cvtest : : TS : : OK ; <nl> - cv : : Mat cpuRes ; <nl> - cv : : gpu : : GpuMat gpuImg ( img ) , gpuRes ; <nl> - <nl> - int codes [ ] = { CV_BGR2RGB , CV_RGB2BGRA , CV_BGRA2RGB , <nl> - CV_RGB2BGR555 , CV_BGR5552BGR , CV_BGR2BGR565 , CV_BGR5652RGB , <nl> - CV_RGB2YCrCb , CV_YCrCb2BGR , CV_BGR2YUV , CV_YUV2RGB , <nl> - CV_RGB2XYZ , CV_XYZ2BGR , CV_BGR2XYZ , CV_XYZ2RGB , <nl> - CV_RGB2HSV , CV_HSV2BGR , CV_BGR2HSV_FULL , CV_HSV2RGB_FULL , <nl> - CV_RGB2HLS , CV_HLS2BGR , CV_BGR2HLS_FULL , CV_HLS2RGB_FULL , <nl> - CV_RGB2GRAY , CV_GRAY2BGRA , CV_BGRA2GRAY , <nl> - CV_GRAY2BGR555 , CV_BGR5552GRAY , CV_GRAY2BGR565 , CV_BGR5652GRAY } ; <nl> - const char * codes_str [ ] = { " CV_BGR2RGB " , " CV_RGB2BGRA " , " CV_BGRA2RGB " , <nl> - " CV_RGB2BGR555 " , " CV_BGR5552BGR " , " CV_BGR2BGR565 " , " CV_BGR5652RGB " , <nl> - " CV_RGB2YCrCb " , " CV_YCrCb2BGR " , " CV_BGR2YUV " , " CV_YUV2RGB " , <nl> - " CV_RGB2XYZ " , " CV_XYZ2BGR " , " CV_BGR2XYZ " , " CV_XYZ2RGB " , <nl> - " CV_RGB2HSV " , " CV_HSV2RGB " , " CV_BGR2HSV_FULL " , " CV_HSV2RGB_FULL " , <nl> - " CV_RGB2HLS " , " CV_HLS2RGB " , " CV_BGR2HLS_FULL " , " CV_HLS2RGB_FULL " , <nl> - " CV_RGB2GRAY " , " CV_GRAY2BGRA " , " CV_BGRA2GRAY " , <nl> - " CV_GRAY2BGR555 " , " CV_BGR5552GRAY " , " CV_GRAY2BGR565 " , " CV_BGR5652GRAY " } ; <nl> - int codes_num = sizeof ( codes ) / sizeof ( int ) ; <nl> - <nl> - for ( int i = 0 ; i < codes_num ; + + i ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ n % s \ n " , codes_str [ i ] ) ; <nl> - <nl> - cv : : cvtColor ( img , cpuRes , codes [ i ] ) ; <nl> - cv : : gpu : : cvtColor ( gpuImg , gpuRes , codes [ i ] ) ; <nl> - <nl> - if ( CheckNorm ( cpuRes , gpuRes ) = = cvtest : : TS : : OK ) <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ nSUCCESS \ n " ) ; <nl> - else <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ nFAIL \ n " ) ; <nl> - testResult = cvtest : : TS : : FAIL_GENERIC ; <nl> - } <nl> - <nl> - img = cpuRes ; <nl> - gpuImg = gpuRes ; <nl> - } <nl> - <nl> - ts - > set_failed_test_info ( testResult ) ; <nl> - } <nl> - <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / Histograms <nl> - class CV_GpuHistogramsTest : public cvtest : : BaseTest <nl> - { <nl> - public : <nl> - CV_GpuHistogramsTest ( ) { } <nl> - ~ CV_GpuHistogramsTest ( ) { } ; <nl> - <nl> - protected : <nl> - void run ( int ) ; <nl> - <nl> - int CheckNorm ( const Mat & m1 , const Mat & m2 ) <nl> - { <nl> - double ret = norm ( m1 , m2 , NORM_INF ) ; <nl> - <nl> - if ( ret < std : : numeric_limits < double > : : epsilon ( ) ) <nl> - { <nl> - return cvtest : : TS : : OK ; <nl> - } <nl> - else <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ nNorm : % f \ n " , ret ) ; <nl> - return cvtest : : TS : : FAIL_GENERIC ; <nl> - } <nl> - } <nl> - } ; <nl> - <nl> - void CV_GpuHistogramsTest : : run ( int ) <nl> - { <nl> - / / load image <nl> - cv : : Mat img = cv : : imread ( std : : string ( ts - > get_data_path ( ) ) + " stereobp / aloe - L . png " ) ; <nl> - <nl> - if ( img . empty ( ) ) <nl> - { <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_MISSING_TEST_DATA ) ; <nl> - return ; <nl> - } <nl> - <nl> - Mat hsv ; <nl> - cv : : cvtColor ( img , hsv , CV_BGR2HSV ) ; <nl> - <nl> - int hbins = 30 ; <nl> - int histSize [ ] = { hbins } ; <nl> - <nl> - float hranges [ ] = { 0 , 180 } ; <nl> - const float * ranges [ ] = { hranges } ; <nl> - <nl> - MatND hist ; <nl> - <nl> - int channels [ ] = { 0 } ; <nl> - calcHist ( & hsv , 1 , channels , Mat ( ) , hist , 1 , histSize , ranges ) ; <nl> - <nl> - GpuMat gpuHsv ( hsv ) ; <nl> - std : : vector < GpuMat > srcs ; <nl> - cv : : gpu : : split ( gpuHsv , srcs ) ; <nl> - GpuMat gpuHist ; <nl> - histEven ( srcs [ 0 ] , gpuHist , hbins , ( int ) hranges [ 0 ] , ( int ) hranges [ 1 ] ) ; <nl> - <nl> - Mat cpuHist = hist ; <nl> - cpuHist = cpuHist . t ( ) ; <nl> - cpuHist . convertTo ( cpuHist , CV_32S ) ; <nl> - <nl> - ts - > set_failed_test_info ( CheckNorm ( cpuHist , gpuHist ) ) ; <nl> - } <nl> - <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / Corner Harris feature detector <nl> - <nl> - struct CV_GpuCornerHarrisTest : cvtest : : BaseTest <nl> - { <nl> - CV_GpuCornerHarrisTest ( ) { } <nl> - <nl> - void run ( int ) <nl> - { <nl> - for ( int i = 0 ; i < 5 ; + + i ) <nl> - { <nl> - int rows = 25 + rand ( ) % 300 , cols = 25 + rand ( ) % 300 ; <nl> - if ( ! compareToCpuTest ( rows , cols , CV_32F , 1 + rand ( ) % 5 , 1 + 2 * ( rand ( ) % 4 ) ) ) return ; <nl> - if ( ! compareToCpuTest ( rows , cols , CV_32F , 1 + rand ( ) % 5 , - 1 ) ) return ; <nl> - if ( ! compareToCpuTest ( rows , cols , CV_8U , 1 + rand ( ) % 5 , 1 + 2 * ( rand ( ) % 4 ) ) ) return ; <nl> - if ( ! compareToCpuTest ( rows , cols , CV_8U , 1 + rand ( ) % 5 , - 1 ) ) return ; <nl> - } <nl> - } <nl> - <nl> - bool compareToCpuTest ( int rows , int cols , int depth , int blockSize , int apertureSize ) <nl> - { <nl> - RNG rng ; <nl> - cv : : Mat src ( rows , cols , depth ) ; <nl> - if ( depth = = CV_32F ) <nl> - rng . fill ( src , RNG : : UNIFORM , cv : : Scalar ( 0 ) , cv : : Scalar ( 1 ) ) ; <nl> - else if ( depth = = CV_8U ) <nl> - rng . fill ( src , RNG : : UNIFORM , cv : : Scalar ( 0 ) , cv : : Scalar ( 256 ) ) ; <nl> - <nl> - double k = 0 . 1 ; <nl> - <nl> - cv : : Mat dst_gold ; <nl> - cv : : gpu : : GpuMat dst ; <nl> - cv : : Mat dsth ; <nl> - int borderType ; <nl> - <nl> - borderType = BORDER_REFLECT101 ; <nl> - cv : : cornerHarris ( src , dst_gold , blockSize , apertureSize , k , borderType ) ; <nl> - cv : : gpu : : cornerHarris ( cv : : gpu : : GpuMat ( src ) , dst , blockSize , apertureSize , k , borderType ) ; <nl> - <nl> - dsth = dst ; <nl> - for ( int i = 0 ; i < dst . rows ; + + i ) <nl> - { <nl> - for ( int j = 0 ; j < dst . cols ; + + j ) <nl> - { <nl> - float a = dst_gold . at < float > ( i , j ) ; <nl> - float b = dsth . at < float > ( i , j ) ; <nl> - if ( fabs ( a - b ) > 1e - 3f ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " % d % d % f % f % d \ n " , i , j , a , b , apertureSize ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return false ; <nl> - } ; <nl> - } <nl> - } <nl> - <nl> - borderType = BORDER_REPLICATE ; <nl> - cv : : cornerHarris ( src , dst_gold , blockSize , apertureSize , k , borderType ) ; <nl> - cv : : gpu : : cornerHarris ( cv : : gpu : : GpuMat ( src ) , dst , blockSize , apertureSize , k , borderType ) ; <nl> - <nl> - dsth = dst ; <nl> - for ( int i = 0 ; i < dst . rows ; + + i ) <nl> - { <nl> - for ( int j = 0 ; j < dst . cols ; + + j ) <nl> - { <nl> - float a = dst_gold . at < float > ( i , j ) ; <nl> - float b = dsth . at < float > ( i , j ) ; <nl> - if ( fabs ( a - b ) > 1e - 3f ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " % d % d % f % f % d \ n " , i , j , a , b , apertureSize ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return false ; <nl> - } ; <nl> - } <nl> - } <nl> - return true ; <nl> - } <nl> - } ; <nl> - <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / Corner Min Eigen Val <nl> - <nl> - struct CV_GpuCornerMinEigenValTest : cvtest : : BaseTest <nl> - { <nl> - CV_GpuCornerMinEigenValTest ( ) { } <nl> - <nl> - void run ( int ) <nl> - { <nl> - for ( int i = 0 ; i < 3 ; + + i ) <nl> - { <nl> - int rows = 25 + rand ( ) % 300 , cols = 25 + rand ( ) % 300 ; <nl> - if ( ! compareToCpuTest ( rows , cols , CV_32F , 1 + rand ( ) % 5 , - 1 ) ) return ; <nl> - if ( ! compareToCpuTest ( rows , cols , CV_32F , 1 + rand ( ) % 5 , 1 + 2 * ( rand ( ) % 4 ) ) ) return ; <nl> - if ( ! compareToCpuTest ( rows , cols , CV_8U , 1 + rand ( ) % 5 , - 1 ) ) return ; <nl> - if ( ! compareToCpuTest ( rows , cols , CV_8U , 1 + rand ( ) % 5 , 1 + 2 * ( rand ( ) % 4 ) ) ) return ; <nl> - } <nl> - } <nl> - <nl> - bool compareToCpuTest ( int rows , int cols , int depth , int blockSize , int apertureSize ) <nl> - { <nl> - RNG rng ; <nl> - cv : : Mat src ( rows , cols , depth ) ; <nl> - if ( depth = = CV_32F ) <nl> - rng . fill ( src , RNG : : UNIFORM , cv : : Scalar ( 0 ) , cv : : Scalar ( 1 ) ) ; <nl> - else if ( depth = = CV_8U ) <nl> - rng . fill ( src , RNG : : UNIFORM , cv : : Scalar ( 0 ) , cv : : Scalar ( 256 ) ) ; <nl> - <nl> - cv : : Mat dst_gold ; <nl> - cv : : gpu : : GpuMat dst ; <nl> - cv : : Mat dsth ; <nl> - <nl> - int borderType ; <nl> - <nl> - borderType = BORDER_REFLECT101 ; <nl> - cv : : cornerMinEigenVal ( src , dst_gold , blockSize , apertureSize , borderType ) ; <nl> - cv : : gpu : : cornerMinEigenVal ( cv : : gpu : : GpuMat ( src ) , dst , blockSize , apertureSize , borderType ) ; <nl> - <nl> - dsth = dst ; <nl> - for ( int i = 0 ; i < dst . rows ; + + i ) <nl> - { <nl> - for ( int j = 0 ; j < dst . cols ; + + j ) <nl> - { <nl> - float a = dst_gold . at < float > ( i , j ) ; <nl> - float b = dsth . at < float > ( i , j ) ; <nl> - if ( fabs ( a - b ) > 1e - 2f ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " % d % d % f % f % d % d \ n " , i , j , a , b , apertureSize , blockSize ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return false ; <nl> - } ; <nl> - } <nl> - } <nl> - <nl> - borderType = BORDER_REPLICATE ; <nl> - cv : : cornerMinEigenVal ( src , dst_gold , blockSize , apertureSize , borderType ) ; <nl> - cv : : gpu : : cornerMinEigenVal ( cv : : gpu : : GpuMat ( src ) , dst , blockSize , apertureSize , borderType ) ; <nl> - <nl> - dsth = dst ; <nl> - for ( int i = 0 ; i < dst . rows ; + + i ) <nl> - { <nl> - for ( int j = 0 ; j < dst . cols ; + + j ) <nl> - { <nl> - float a = dst_gold . at < float > ( i , j ) ; <nl> - float b = dsth . at < float > ( i , j ) ; <nl> - if ( fabs ( a - b ) > 1e - 2f ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " % d % d % f % f % d % d \ n " , i , j , a , b , apertureSize , blockSize ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return false ; <nl> - } ; <nl> - } <nl> - } <nl> - <nl> - return true ; <nl> - } <nl> - } ; <nl> - <nl> - struct CV_GpuColumnSumTest : cvtest : : BaseTest <nl> - { <nl> - CV_GpuColumnSumTest ( ) { } <nl> - <nl> - void run ( int ) <nl> - { <nl> - int cols = 375 ; <nl> - int rows = 1072 ; <nl> - <nl> - Mat src ( rows , cols , CV_32F ) ; <nl> - RNG rng ( 1 ) ; <nl> - rng . fill ( src , RNG : : UNIFORM , Scalar ( 0 ) , Scalar ( 1 ) ) ; <nl> - <nl> - GpuMat d_dst ; <nl> - columnSum ( GpuMat ( src ) , d_dst ) ; <nl> - <nl> - Mat dst = d_dst ; <nl> - for ( int j = 0 ; j < src . cols ; + + j ) <nl> - { <nl> - float a = src . at < float > ( 0 , j ) ; <nl> - float b = dst . at < float > ( 0 , j ) ; <nl> - if ( fabs ( a - b ) > 0 . 5f ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " big diff at % d % d : % f % f \ n " , 0 , j , a , b ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return ; <nl> - } <nl> - } <nl> - for ( int i = 1 ; i < src . rows ; + + i ) <nl> - { <nl> - for ( int j = 0 ; j < src . cols ; + + j ) <nl> - { <nl> - float a = src . at < float > ( i , j ) + = src . at < float > ( i - 1 , j ) ; <nl> - float b = dst . at < float > ( i , j ) ; <nl> - if ( fabs ( a - b ) > 0 . 5f ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " big diff at % d % d : % f % f \ n " , i , j , a , b ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return ; <nl> - } <nl> - } <nl> - } <nl> - } <nl> - } ; <nl> - <nl> - struct CV_GpuNormTest : cvtest : : BaseTest <nl> - { <nl> - CV_GpuNormTest ( ) { } <nl> - <nl> - void run ( int ) <nl> - { <nl> - RNG rng ( 0 ) ; <nl> - <nl> - int rows = rng . uniform ( 1 , 500 ) ; <nl> - int cols = rng . uniform ( 1 , 500 ) ; <nl> - <nl> - for ( int cn = 1 ; cn < = 4 ; + + cn ) <nl> - { <nl> - test ( NORM_L1 , rows , cols , CV_8U , cn , Scalar : : all ( 0 ) , Scalar : : all ( 10 ) ) ; <nl> - test ( NORM_L1 , rows , cols , CV_8S , cn , Scalar : : all ( - 10 ) , Scalar : : all ( 10 ) ) ; <nl> - test ( NORM_L1 , rows , cols , CV_16U , cn , Scalar : : all ( 0 ) , Scalar : : all ( 10 ) ) ; <nl> - test ( NORM_L1 , rows , cols , CV_16S , cn , Scalar : : all ( - 10 ) , Scalar : : all ( 10 ) ) ; <nl> - test ( NORM_L1 , rows , cols , CV_32S , cn , Scalar : : all ( - 10 ) , Scalar : : all ( 10 ) ) ; <nl> - test ( NORM_L1 , rows , cols , CV_32F , cn , Scalar : : all ( 0 ) , Scalar : : all ( 1 ) ) ; <nl> - <nl> - test ( NORM_L2 , rows , cols , CV_8U , cn , Scalar : : all ( 0 ) , Scalar : : all ( 10 ) ) ; <nl> - test ( NORM_L2 , rows , cols , CV_8S , cn , Scalar : : all ( - 10 ) , Scalar : : all ( 10 ) ) ; <nl> - test ( NORM_L2 , rows , cols , CV_16U , cn , Scalar : : all ( 0 ) , Scalar : : all ( 10 ) ) ; <nl> - test ( NORM_L2 , rows , cols , CV_16S , cn , Scalar : : all ( - 10 ) , Scalar : : all ( 10 ) ) ; <nl> - test ( NORM_L2 , rows , cols , CV_32S , cn , Scalar : : all ( - 10 ) , Scalar : : all ( 10 ) ) ; <nl> - test ( NORM_L2 , rows , cols , CV_32F , cn , Scalar : : all ( 0 ) , Scalar : : all ( 1 ) ) ; <nl> - <nl> - test ( NORM_INF , rows , cols , CV_8U , cn , Scalar : : all ( 0 ) , Scalar : : all ( 10 ) ) ; <nl> - test ( NORM_INF , rows , cols , CV_8S , cn , Scalar : : all ( - 10 ) , Scalar : : all ( 10 ) ) ; <nl> - test ( NORM_INF , rows , cols , CV_16U , cn , Scalar : : all ( 0 ) , Scalar : : all ( 10 ) ) ; <nl> - test ( NORM_INF , rows , cols , CV_16S , cn , Scalar : : all ( - 10 ) , Scalar : : all ( 10 ) ) ; <nl> - test ( NORM_INF , rows , cols , CV_32S , cn , Scalar : : all ( - 10 ) , Scalar : : all ( 10 ) ) ; <nl> - test ( NORM_INF , rows , cols , CV_32F , cn , Scalar : : all ( 0 ) , Scalar : : all ( 1 ) ) ; <nl> - } <nl> - } <nl> - <nl> - void gen ( Mat & mat , int rows , int cols , int type , Scalar low , Scalar high ) <nl> - { <nl> - mat . create ( rows , cols , type ) ; <nl> - RNG rng ( 0 ) ; <nl> - rng . fill ( mat , RNG : : UNIFORM , low , high ) ; <nl> - } <nl> - <nl> - void test ( int norm_type , int rows , int cols , int depth , int cn , Scalar low , Scalar high ) <nl> - { <nl> - int type = CV_MAKE_TYPE ( depth , cn ) ; <nl> - <nl> - Mat src ; <nl> - gen ( src , rows , cols , type , low , high ) ; <nl> - <nl> - double gold = norm ( src , norm_type ) ; <nl> - double mine = norm ( GpuMat ( src ) , norm_type ) ; <nl> - <nl> - if ( abs ( gold - mine ) > 1e - 3 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " failed test : gold = % f , mine = % f , norm_type = % d , rows = % d , " <nl> - " cols = % d , depth = % d , cn = % d \ n " , gold , mine , norm_type , rows , cols , depth , cn ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - } <nl> - } <nl> - } ; <nl> - <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / reprojectImageTo3D <nl> - class CV_GpuReprojectImageTo3DTest : public cvtest : : BaseTest <nl> - { <nl> - public : <nl> - CV_GpuReprojectImageTo3DTest ( ) { } <nl> - <nl> - protected : <nl> - void run ( int ) <nl> - { <nl> - Mat disp ( 320 , 240 , CV_8UC1 ) ; <nl> - <nl> - RNG & rng = ts - > get_rng ( ) ; <nl> - rng . fill ( disp , RNG : : UNIFORM , Scalar ( 5 ) , Scalar ( 30 ) ) ; <nl> - <nl> - Mat Q ( 4 , 4 , CV_32FC1 ) ; <nl> - rng . fill ( Q , RNG : : UNIFORM , Scalar ( 0 . 1 ) , Scalar ( 1 ) ) ; <nl> - <nl> - Mat cpures ; <nl> - GpuMat gpures ; <nl> - <nl> - reprojectImageTo3D ( disp , cpures , Q , false ) ; <nl> - reprojectImageTo3D ( GpuMat ( disp ) , gpures , Q ) ; <nl> - <nl> - Mat temp = gpures ; <nl> - <nl> - for ( int y = 0 ; y < cpures . rows ; + + y ) <nl> - { <nl> - const Vec3f * cpu_row = cpures . ptr < Vec3f > ( y ) ; <nl> - const Vec4f * gpu_row = temp . ptr < Vec4f > ( y ) ; <nl> - for ( int x = 0 ; x < cpures . cols ; + + x ) <nl> - { <nl> - Vec3f a = cpu_row [ x ] ; <nl> - Vec4f b = gpu_row [ x ] ; <nl> - <nl> - if ( fabs ( a [ 0 ] - b [ 0 ] ) > 1e - 5 | | fabs ( a [ 1 ] - b [ 1 ] ) > 1e - 5 | | fabs ( a [ 2 ] - b [ 2 ] ) > 1e - 5 ) <nl> - { <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return ; <nl> - } <nl> - } <nl> - } <nl> - } <nl> - } ; <nl> - <nl> - TEST ( threshold , accuracy ) { CV_GpuImageThresholdTest test ; test . safe_run ( ) ; } <nl> - TEST ( resize , accuracy ) { CV_GpuNppImageResizeTest test ; test . safe_run ( ) ; } <nl> - TEST ( copyMakeBorder , accuracy ) { CV_GpuNppImageCopyMakeBorderTest test ; test . safe_run ( ) ; } <nl> - TEST ( warpAffine , accuracy ) { CV_GpuNppImageWarpAffineTest test ; test . safe_run ( ) ; } <nl> - TEST ( warpPerspective , accuracy ) { CV_GpuNppImageWarpPerspectiveTest test ; test . safe_run ( ) ; } <nl> - TEST ( integral , accuracy ) { CV_GpuNppImageIntegralTest test ; test . safe_run ( ) ; } <nl> - TEST ( cvtColor , accuracy ) { CV_GpuCvtColorTest test ; test . safe_run ( ) ; } <nl> - TEST ( histograms , accuracy ) { CV_GpuHistogramsTest test ; test . safe_run ( ) ; } <nl> - TEST ( cornerHearris , accuracy ) { CV_GpuCornerHarrisTest test ; test . safe_run ( ) ; } <nl> - TEST ( minEigen , accuracy ) { CV_GpuCornerMinEigenValTest test ; test . safe_run ( ) ; } <nl> - TEST ( columnSum , accuracy ) { CV_GpuColumnSumTest test ; test . safe_run ( ) ; } <nl> - TEST ( norm , accuracy ) { CV_GpuNormTest test ; test . safe_run ( ) ; } <nl> - TEST ( reprojectImageTo3D , accuracy ) { CV_GpuReprojectImageTo3DTest test ; test . safe_run ( ) ; } <nl> - <nl> - TEST ( downsample , accuracy_on_8U ) <nl> - { <nl> - RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> - Size size ( 200 + cvtest : : randInt ( rng ) % 1000 , 200 + cvtest : : randInt ( rng ) % 1000 ) ; <nl> - Mat src = cvtest : : randomMat ( rng , size , CV_8U , 0 , 255 , false ) ; <nl> - <nl> - for ( int k = 2 ; k < = 5 ; + + k ) <nl> - { <nl> - GpuMat d_dst ; <nl> - downsample ( GpuMat ( src ) , d_dst , k ) ; <nl> - <nl> - Size dst_gold_size ( ( src . cols + k - 1 ) / k , ( src . rows + k - 1 ) / k ) ; <nl> - ASSERT_EQ ( dst_gold_size . width , d_dst . cols ) <nl> - < < " rows = " < < size . height < < " , cols = " < < size . width < < " , k = " < < k ; <nl> - ASSERT_EQ ( dst_gold_size . height , d_dst . rows ) <nl> - < < " rows = " < < size . height < < " , cols = " < < size . width < < " , k = " < < k ; <nl> - <nl> - Mat dst = d_dst ; <nl> - for ( int y = 0 ; y < dst . rows ; + + y ) <nl> - for ( int x = 0 ; x < dst . cols ; + + x ) <nl> - ASSERT_EQ ( src . at < uchar > ( y * k , x * k ) , dst . at < uchar > ( y , x ) ) <nl> - < < " rows = " < < size . height < < " , cols = " < < size . width < < " , k = " < < k ; <nl> - } <nl> - } <nl> - <nl> - TEST ( downsample , accuracy_on_32F ) <nl> - { <nl> - RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> - Size size ( 200 + cvtest : : randInt ( rng ) % 1000 , 200 + cvtest : : randInt ( rng ) % 1000 ) ; <nl> - Mat src = cvtest : : randomMat ( rng , size , CV_32F , 0 , 1 , false ) ; <nl> - <nl> - for ( int k = 2 ; k < = 5 ; + + k ) <nl> - { <nl> - GpuMat d_dst ; <nl> - downsample ( GpuMat ( src ) , d_dst , k ) ; <nl> - <nl> - Size dst_gold_size ( ( src . cols + k - 1 ) / k , ( src . rows + k - 1 ) / k ) ; <nl> - ASSERT_EQ ( dst_gold_size . width , d_dst . cols ) <nl> - < < " rows = " < < size . height < < " , cols = " < < size . width < < " , k = " < < k ; <nl> - ASSERT_EQ ( dst_gold_size . height , d_dst . rows ) <nl> - < < " rows = " < < size . height < < " , cols = " < < size . width < < " , k = " < < k ; <nl> - <nl> - Mat dst = d_dst ; <nl> - for ( int y = 0 ; y < dst . rows ; + + y ) <nl> - for ( int x = 0 ; x < dst . cols ; + + x ) <nl> - ASSERT_FLOAT_EQ ( src . at < float > ( y * k , x * k ) , dst . at < float > ( y , x ) ) <nl> - < < " rows = " < < size . height < < " , cols = " < < size . width < < " , k = " < < k ; <nl> - } <nl> - } <nl> mmm a / modules / gpu / test / test_main . cpp <nl> ppp b / modules / gpu / test / test_main . cpp <nl> <nl> + / * M / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / <nl> + / / IMPORTANT : READ BEFORE DOWNLOADING , COPYING , INSTALLING OR USING . <nl> + / / <nl> + / / By downloading , copying , installing or using the software you agree to this license . <nl> + / / If you do not agree to this license , do not download , install , <nl> + / / copy or use the software . <nl> + / / <nl> + / / <nl> + / / Intel License Agreement <nl> + / / For Open Source Computer Vision Library <nl> + / / <nl> + / / Copyright ( C ) 2000 , Intel Corporation , all rights reserved . <nl> + / / Third party copyrights are property of their respective owners . <nl> + / / <nl> + / / Redistribution and use in source and binary forms , with or without modification , <nl> + / / are permitted provided that the following conditions are met : <nl> + / / <nl> + / / * Redistribution ' s of source code must retain the above copyright notice , <nl> + / / this list of conditions and the following disclaimer . <nl> + / / <nl> + / / * Redistribution ' s in binary form must reproduce the above copyright notice , <nl> + / / this list of conditions and the following disclaimer in the documentation <nl> + / / and / or other materials provided with the distribution . <nl> + / / <nl> + / / * The name of Intel Corporation may not be used to endorse or promote products <nl> + / / derived from this software without specific prior written permission . <nl> + / / <nl> + / / This software is provided by the copyright holders and contributors " as is " and <nl> + / / any express or implied warranties , including , but not limited to , the implied <nl> + / / warranties of merchantability and fitness for a particular purpose are disclaimed . <nl> + / / In no event shall the Intel Corporation or contributors be liable for any direct , <nl> + / / indirect , incidental , special , exemplary , or consequential damages <nl> + / / ( including , but not limited to , procurement of substitute goods or services ; <nl> + / / loss of use , data , or profits ; or business interruption ) however caused <nl> + / / and on any theory of liability , whether in contract , strict liability , <nl> + / / or tort ( including negligence or otherwise ) arising in any way out of <nl> + / / the use of this software , even if advised of the possibility of such damage . <nl> + / / <nl> + / / M * / <nl> + <nl> # include " test_precomp . hpp " <nl> <nl> - int main ( int argc , char * * argv ) <nl> + # ifdef HAVE_CUDA <nl> + <nl> + void print_info ( ) <nl> + { <nl> + int deviceCount = cv : : gpu : : getCudaEnabledDeviceCount ( ) ; <nl> + <nl> + printf ( " Found % d CUDA devices \ n \ n " , deviceCount ) ; <nl> + <nl> + for ( int i = 0 ; i < deviceCount ; + + i ) <nl> + { <nl> + cv : : gpu : : DeviceInfo info ( i ) ; <nl> + printf ( " Device % d : \ n " , i ) ; <nl> + printf ( " \ tName : % s \ n " , info . name ( ) . c_str ( ) ) ; <nl> + printf ( " \ tCompute capability version : % d . % d \ n " , info . majorVersion ( ) , info . minorVersion ( ) ) ; <nl> + printf ( " \ tTotal memory : % d Mb \ n " , static_cast < int > ( static_cast < int > ( info . totalMemory ( ) / 1024 . 0 ) / 1024 . 0 ) ) ; <nl> + printf ( " \ tFree memory : % d Mb \ n " , static_cast < int > ( static_cast < int > ( info . freeMemory ( ) / 1024 . 0 ) / 1024 . 0 ) ) ; <nl> + if ( ! info . isCompatible ( ) ) <nl> + printf ( " \ tThis device is not compatible with current GPU module build \ n " ) ; <nl> + printf ( " \ n " ) ; <nl> + } <nl> + <nl> + printf ( " GPU module was compiled for next GPU archs : \ n " ) ; <nl> + printf ( " \ tBIN : % s \ n " , CUDA_ARCH_BIN ) ; <nl> + printf ( " \ tPTX : % s \ n \ n " , CUDA_ARCH_PTX ) ; <nl> + } <nl> + <nl> + enum OutputLevel <nl> + { <nl> + OutputLevelNone , <nl> + OutputLevelCompact , <nl> + OutputLevelFull <nl> + } ; <nl> + <nl> + extern OutputLevel nvidiaTestOutputLevel ; <nl> + <nl> + int main ( int argc , char * * argv ) <nl> { <nl> cvtest : : TS : : ptr ( ) - > init ( " gpu " ) ; <nl> - : : testing : : InitGoogleTest ( & argc , argv ) ; <nl> - # ifdef HAVE_CUDA <nl> + testing : : InitGoogleTest ( & argc , argv ) ; <nl> + <nl> + cv : : CommandLineParser parser ( argc , ( const char * * ) argv ) ; <nl> + <nl> + std : : string outputLevel = parser . get < std : : string > ( " nvtest_output_level " , " none " ) ; <nl> + <nl> + if ( outputLevel = = " none " ) <nl> + nvidiaTestOutputLevel = OutputLevelNone ; <nl> + else if ( outputLevel = = " compact " ) <nl> + nvidiaTestOutputLevel = OutputLevelCompact ; <nl> + else if ( outputLevel = = " full " ) <nl> + nvidiaTestOutputLevel = OutputLevelFull ; <nl> + <nl> + print_info ( ) ; <nl> return RUN_ALL_TESTS ( ) ; <nl> - # else <nl> - std : : cerr < < " opencv_test_gpu : OpenCV was compiled without GPU support \ n " ; <nl> - return - 1 ; <nl> - # endif <nl> - } <nl> \ No newline at end of file <nl> + } <nl> + <nl> + # else / / HAVE_CUDA <nl> + <nl> + int main ( int argc , char * * argv ) <nl> + { <nl> + printf ( " OpenCV was built without CUDA support \ n " ) ; <nl> + return 0 ; <nl> + } <nl> + <nl> + # endif / / HAVE_CUDA <nl> \ No newline at end of file <nl> deleted file mode 100644 <nl> index b646723051f . . 00000000000 <nl> mmm a / modules / gpu / test / test_match_template . cpp <nl> ppp / dev / null <nl> <nl> - / * M / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / <nl> - / / IMPORTANT : READ BEFORE DOWNLOADING , COPYING , INSTALLING OR USING . <nl> - / / <nl> - / / By downloading , copying , installing or using the software you agree to this license . <nl> - / / If you do not agree to this license , do not download , install , <nl> - / / copy or use the software . <nl> - / / <nl> - / / <nl> - / / License Agreement <nl> - / / For Open Source Computer Vision Library <nl> - / / <nl> - / / Copyright ( C ) 2000 - 2008 , Intel Corporation , all rights reserved . <nl> - / / Copyright ( C ) 2009 , Willow Garage Inc . , all rights reserved . <nl> - / / Third party copyrights are property of their respective owners . <nl> - / / <nl> - / / Redistribution and use in source and binary forms , with or without modification , <nl> - / / are permitted provided that the following conditions are met : <nl> - / / <nl> - / / * Redistribution ' s of source code must retain the above copyright notice , <nl> - / / this list of conditions and the following disclaimer . <nl> - / / <nl> - / / * Redistribution ' s in binary form must reproduce the above copyright notice , <nl> - / / this list of conditions and the following disclaimer in the documentation <nl> - / / and / or other GpuMaterials provided with the distribution . <nl> - / / <nl> - / / * The name of the copyright holders may not be used to endorse or promote products <nl> - / / derived from this software without specific prior written permission . <nl> - / / <nl> - / / This software is provided by the copyright holders and contributors " as is " and <nl> - / / any express or bpied warranties , including , but not limited to , the bpied <nl> - / / warranties of merchantability and fitness for a particular purpose are disclaimed . <nl> - / / In no event shall the Intel Corporation or contributors be liable for any direct , <nl> - / / indirect , incidental , special , exemplary , or consequential damages <nl> - / / ( including , but not limited to , procurement of substitute goods or services ; <nl> - / / loss of use , data , or profits ; or business interruption ) however caused <nl> - / / and on any theory of liability , whether in contract , strict liability , <nl> - / / or tort ( including negligence or otherwise ) arising in any way out of <nl> - / / the use of this software , even if advised of the possibility of such damage . <nl> - / / <nl> - / / M * / <nl> - <nl> - # include " test_precomp . hpp " <nl> - # include < string > <nl> - # include < iostream > <nl> - <nl> - / / # define SHOW_TIME <nl> - <nl> - # ifdef SHOW_TIME <nl> - # include < ctime > <nl> - # define F ( x ) x <nl> - # else <nl> - # define F ( x ) <nl> - # endif <nl> - <nl> - using namespace cv ; <nl> - using namespace std ; <nl> - <nl> - struct CV_GpuMatchTemplateTest : cvtest : : BaseTest <nl> - { <nl> - CV_GpuMatchTemplateTest ( ) { } <nl> - <nl> - void run ( int ) <nl> - { <nl> - bool double_ok = gpu : : TargetArchs : : builtWith ( gpu : : NATIVE_DOUBLE ) & & <nl> - gpu : : DeviceInfo ( ) . supports ( gpu : : NATIVE_DOUBLE ) ; <nl> - if ( ! double_ok ) <nl> - { <nl> - / / For sqrIntegral <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " \ nCode and device double support is required ( CC > = 1 . 3 ) " ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_GENERIC ) ; <nl> - return ; <nl> - } <nl> - <nl> - Mat image , templ ; <nl> - Mat dst_gold ; <nl> - gpu : : GpuMat dst ; <nl> - int n , m , h , w ; <nl> - F ( clock_t t ; ) <nl> - <nl> - RNG & rng = ts - > get_rng ( ) ; <nl> - <nl> - for ( int cn = 1 ; cn < = 4 ; + + cn ) <nl> - { <nl> - F ( ts - > printf ( cvtest : : TS : : CONSOLE , " cn : % d \ n " , cn ) ; ) <nl> - for ( int i = 0 ; i < = 0 ; + + i ) <nl> - { <nl> - n = rng . uniform ( 30 , 100 ) ; <nl> - m = rng . uniform ( 30 , 100 ) ; <nl> - h = rng . uniform ( 5 , n - 1 ) ; <nl> - w = rng . uniform ( 5 , m - 1 ) ; <nl> - <nl> - gen ( image , n , m , CV_8U , cn ) ; <nl> - gen ( templ , h , w , CV_8U , cn ) ; <nl> - F ( t = clock ( ) ; ) <nl> - matchTemplate ( image , templ , dst_gold , CV_TM_SQDIFF ) ; <nl> - F ( cout < < " depth : 8U cn : " < < cn < < " n : " < < n < < " m : " < < m < < " w : " < < w < < " h : " < < h < < endl ; ) <nl> - F ( cout < < " cpu : " < < clock ( ) - t < < endl ; ) <nl> - F ( t = clock ( ) ; ) <nl> - gpu : : matchTemplate ( gpu : : GpuMat ( image ) , gpu : : GpuMat ( templ ) , dst , CV_TM_SQDIFF ) ; <nl> - F ( cout < < " gpu_block : " < < clock ( ) - t < < endl ; ) <nl> - if ( ! check ( dst_gold , Mat ( dst ) , 5 * h * w * 1e - 4f , " SQDIFF 8U " ) ) return ; <nl> - <nl> - gen ( image , n , m , CV_8U , cn ) ; <nl> - gen ( templ , h , w , CV_8U , cn ) ; <nl> - F ( t = clock ( ) ; ) <nl> - matchTemplate ( image , templ , dst_gold , CV_TM_SQDIFF_NORMED ) ; <nl> - F ( cout < < " depth : 8U cn : " < < cn < < " n : " < < n < < " m : " < < m < < " w : " < < w < < " h : " < < h < < endl ; ) <nl> - F ( cout < < " cpu : " < < clock ( ) - t < < endl ; ) <nl> - F ( t = clock ( ) ; ) <nl> - gpu : : matchTemplate ( gpu : : GpuMat ( image ) , gpu : : GpuMat ( templ ) , dst , CV_TM_SQDIFF_NORMED ) ; <nl> - F ( cout < < " gpu_block : " < < clock ( ) - t < < endl ; ) <nl> - if ( ! check ( dst_gold , Mat ( dst ) , h * w * 1e - 5f , " SQDIFF_NOREMD 8U " ) ) return ; <nl> - <nl> - gen ( image , n , m , CV_8U , cn ) ; <nl> - gen ( templ , h , w , CV_8U , cn ) ; <nl> - F ( t = clock ( ) ; ) <nl> - matchTemplate ( image , templ , dst_gold , CV_TM_CCORR ) ; <nl> - F ( cout < < " depth : 8U cn : " < < cn < < " n : " < < n < < " m : " < < m < < " w : " < < w < < " h : " < < h < < endl ; ) <nl> - F ( cout < < " cpu : " < < clock ( ) - t < < endl ; ) <nl> - F ( t = clock ( ) ; ) <nl> - gpu : : matchTemplate ( gpu : : GpuMat ( image ) , gpu : : GpuMat ( templ ) , dst , CV_TM_CCORR ) ; <nl> - F ( cout < < " gpu_block : " < < clock ( ) - t < < endl ; ) <nl> - if ( ! check ( dst_gold , Mat ( dst ) , 5 * h * w * cn * cn * 1e - 5f , " CCORR 8U " ) ) return ; <nl> - <nl> - gen ( image , n , m , CV_8U , cn ) ; <nl> - gen ( templ , h , w , CV_8U , cn ) ; <nl> - F ( t = clock ( ) ; ) <nl> - matchTemplate ( image , templ , dst_gold , CV_TM_CCORR_NORMED ) ; <nl> - F ( cout < < " depth : 8U cn : " < < cn < < " n : " < < n < < " m : " < < m < < " w : " < < w < < " h : " < < h < < endl ; ) <nl> - F ( cout < < " cpu : " < < clock ( ) - t < < endl ; ) <nl> - F ( t = clock ( ) ; ) <nl> - gpu : : matchTemplate ( gpu : : GpuMat ( image ) , gpu : : GpuMat ( templ ) , dst , CV_TM_CCORR_NORMED ) ; <nl> - F ( cout < < " gpu_block : " < < clock ( ) - t < < endl ; ) <nl> - if ( ! check ( dst_gold , Mat ( dst ) , h * w * 1e - 6f , " CCORR_NORMED 8U " ) ) return ; <nl> - <nl> - gen ( image , n , m , CV_8U , cn ) ; <nl> - gen ( templ , h , w , CV_8U , cn ) ; <nl> - F ( t = clock ( ) ; ) <nl> - matchTemplate ( image , templ , dst_gold , CV_TM_CCOEFF ) ; <nl> - F ( cout < < " depth : 8U cn : " < < cn < < " n : " < < n < < " m : " < < m < < " w : " < < w < < " h : " < < h < < endl ; ) <nl> - F ( cout < < " cpu : " < < clock ( ) - t < < endl ; ) <nl> - F ( t = clock ( ) ; ) <nl> - gpu : : matchTemplate ( gpu : : GpuMat ( image ) , gpu : : GpuMat ( templ ) , dst , CV_TM_CCOEFF ) ; <nl> - F ( cout < < " gpu_block : " < < clock ( ) - t < < endl ; ) <nl> - if ( ! check ( dst_gold , Mat ( dst ) , 5 * h * w * cn * cn * 1e - 5f , " CCOEFF 8U " ) ) return ; <nl> - <nl> - gen ( image , n , m , CV_8U , cn ) ; <nl> - gen ( templ , h , w , CV_8U , cn ) ; <nl> - F ( t = clock ( ) ; ) <nl> - matchTemplate ( image , templ , dst_gold , CV_TM_CCOEFF_NORMED ) ; <nl> - F ( cout < < " depth : 8U cn : " < < cn < < " n : " < < n < < " m : " < < m < < " w : " < < w < < " h : " < < h < < endl ; ) <nl> - F ( cout < < " cpu : " < < clock ( ) - t < < endl ; ) <nl> - F ( t = clock ( ) ; ) <nl> - gpu : : matchTemplate ( gpu : : GpuMat ( image ) , gpu : : GpuMat ( templ ) , dst , CV_TM_CCOEFF_NORMED ) ; <nl> - F ( cout < < " gpu_block : " < < clock ( ) - t < < endl ; ) <nl> - if ( ! check ( dst_gold , Mat ( dst ) , h * w * 1e - 6f , " CCOEFF_NORMED 8U " ) ) return ; <nl> - <nl> - gen ( image , n , m , CV_32F , cn ) ; <nl> - gen ( templ , h , w , CV_32F , cn ) ; <nl> - F ( t = clock ( ) ; ) <nl> - matchTemplate ( image , templ , dst_gold , CV_TM_SQDIFF ) ; <nl> - F ( cout < < " depth : 32F cn : " < < cn < < " n : " < < n < < " m : " < < m < < " w : " < < w < < " h : " < < h < < endl ; ) <nl> - F ( cout < < " cpu : " < < clock ( ) - t < < endl ; ) <nl> - F ( t = clock ( ) ; ) <nl> - gpu : : matchTemplate ( gpu : : GpuMat ( image ) , gpu : : GpuMat ( templ ) , dst , CV_TM_SQDIFF ) ; <nl> - F ( cout < < " gpu_block : " < < clock ( ) - t < < endl ; ) <nl> - if ( ! check ( dst_gold , Mat ( dst ) , 0 . 25f * h * w * 1e - 5f , " SQDIFF 32F " ) ) return ; <nl> - <nl> - gen ( image , n , m , CV_32F , cn ) ; <nl> - gen ( templ , h , w , CV_32F , cn ) ; <nl> - F ( t = clock ( ) ; ) <nl> - matchTemplate ( image , templ , dst_gold , CV_TM_CCORR ) ; <nl> - F ( cout < < " depth : 32F cn : " < < cn < < " n : " < < n < < " m : " < < m < < " w : " < < w < < " h : " < < h < < endl ; ) <nl> - F ( cout < < " cpu : " < < clock ( ) - t < < endl ; ) <nl> - F ( t = clock ( ) ; ) <nl> - gpu : : matchTemplate ( gpu : : GpuMat ( image ) , gpu : : GpuMat ( templ ) , dst , CV_TM_CCORR ) ; <nl> - F ( cout < < " gpu_block : " < < clock ( ) - t < < endl ; ) <nl> - if ( ! check ( dst_gold , Mat ( dst ) , 0 . 25f * h * w * 1e - 5f , " CCORR 32F " ) ) return ; <nl> - } <nl> - } <nl> - } <nl> - <nl> - void gen ( Mat & a , int rows , int cols , int depth , int cn ) <nl> - { <nl> - RNG rng ; <nl> - a . create ( rows , cols , CV_MAKETYPE ( depth , cn ) ) ; <nl> - if ( depth = = CV_8U ) <nl> - rng . fill ( a , RNG : : UNIFORM , Scalar : : all ( 1 ) , Scalar : : all ( 10 ) ) ; <nl> - else if ( depth = = CV_32F ) <nl> - rng . fill ( a , RNG : : UNIFORM , Scalar : : all ( 0 . 001f ) , Scalar : : all ( 1 . f ) ) ; <nl> - } <nl> - <nl> - bool check ( const Mat & a , const Mat & b , float max_err , const string & method = " " ) <nl> - { <nl> - if ( a . size ( ) ! = b . size ( ) ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " bad size , method = % s \ n " , method . c_str ( ) ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return false ; <nl> - } <nl> - <nl> - / / for ( int i = 0 ; i < a . rows ; + + i ) <nl> - / / { <nl> - / / for ( int j = 0 ; j < a . cols ; + + j ) <nl> - / / { <nl> - / / float a_ = a . at < float > ( i , j ) ; <nl> - / / float b_ = b . at < float > ( i , j ) ; <nl> - / / if ( fabs ( a_ - b_ ) > max_err ) <nl> - / / { <nl> - / / ts - > printf ( cvtest : : TS : : CONSOLE , " a = % f , b = % f , i = % d , j = % d \ n " , a_ , b_ , i , j ) ; <nl> - / / cin . get ( ) ; <nl> - / / } <nl> - / / } <nl> - / / } <nl> - <nl> - float err = ( float ) norm ( a , b , NORM_INF ) ; <nl> - if ( err > max_err ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " bad accuracy : % f , method = % s \ n " , err , method . c_str ( ) ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return false ; <nl> - } <nl> - <nl> - return true ; <nl> - } <nl> - } ; <nl> - <nl> - TEST ( matchTemplate , accuracy ) { CV_GpuMatchTemplateTest test ; test . safe_run ( ) ; } <nl> - <nl> - struct CV_GpuMatchTemplateFindPatternInBlackTest : cvtest : : BaseTest <nl> - { <nl> - CV_GpuMatchTemplateFindPatternInBlackTest ( ) { } <nl> - <nl> - void run ( int ) <nl> - { <nl> - bool double_ok = gpu : : TargetArchs : : builtWith ( gpu : : NATIVE_DOUBLE ) & & <nl> - gpu : : DeviceInfo ( ) . supports ( gpu : : NATIVE_DOUBLE ) ; <nl> - if ( ! double_ok ) <nl> - { <nl> - / / For sqrIntegral <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " \ nCode and device double support is required ( CC > = 1 . 3 ) " ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_GENERIC ) ; <nl> - return ; <nl> - } <nl> - <nl> - Mat image = imread ( std : : string ( ts - > get_data_path ( ) ) + " matchtemplate / black . png " ) ; <nl> - if ( image . empty ( ) ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " can ' t open file ' % s ' " , ( std : : string ( ts - > get_data_path ( ) ) <nl> - + " matchtemplate / black . png " ) . c_str ( ) ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_MISSING_TEST_DATA ) ; <nl> - return ; <nl> - } <nl> - <nl> - Mat pattern = imread ( std : : string ( ts - > get_data_path ( ) ) + " matchtemplate / cat . png " ) ; <nl> - if ( pattern . empty ( ) ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " can ' t open file ' % s ' " , ( std : : string ( ts - > get_data_path ( ) ) <nl> - + " matchtemplate / cat . png " ) . c_str ( ) ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_MISSING_TEST_DATA ) ; <nl> - return ; <nl> - } <nl> - <nl> - gpu : : GpuMat d_image ( image ) ; <nl> - gpu : : GpuMat d_pattern ( pattern ) ; <nl> - gpu : : GpuMat d_result ; <nl> - <nl> - double maxValue ; <nl> - Point maxLoc ; <nl> - Point maxLocGold ( 284 , 12 ) ; <nl> - <nl> - gpu : : matchTemplate ( d_image , d_pattern , d_result , CV_TM_CCOEFF_NORMED ) ; <nl> - gpu : : minMaxLoc ( d_result , NULL , & maxValue , NULL , & maxLoc ) ; <nl> - if ( maxLoc ! = maxLocGold ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " bad match ( CV_TM_CCOEFF_NORMED ) : % d % d , must be at : % d % d " , <nl> - maxLoc . x , maxLoc . y , maxLocGold . x , maxLocGold . y ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return ; <nl> - } <nl> - <nl> - gpu : : matchTemplate ( d_image , d_pattern , d_result , CV_TM_CCORR_NORMED ) ; <nl> - gpu : : minMaxLoc ( d_result , NULL , & maxValue , NULL , & maxLoc ) ; <nl> - if ( maxLoc ! = maxLocGold ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " bad match ( CV_TM_CCORR_NORMED ) : % d % d , must be at : % d % d " , <nl> - maxLoc . x , maxLoc . y , maxLocGold . x , maxLocGold . y ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return ; <nl> - } <nl> - } <nl> - } ; <nl> - <nl> - TEST ( matchTemplate , find_pattern_in_black ) { CV_GpuMatchTemplateFindPatternInBlackTest test ; test . safe_run ( ) ; } <nl> new file mode 100644 <nl> index 00000000000 . . 470306d5150 <nl> mmm / dev / null <nl> ppp b / modules / gpu / test / test_matop . cpp <nl> <nl> + / * M / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / <nl> + / / IMPORTANT : READ BEFORE DOWNLOADING , COPYING , INSTALLING OR USING . <nl> + / / <nl> + / / By downloading , copying , installing or using the software you agree to this license . <nl> + / / If you do not agree to this license , do not download , install , <nl> + / / copy or use the software . <nl> + / / <nl> + / / <nl> + / / License Agreement <nl> + / / For Open Source Computer Vision Library <nl> + / / <nl> + / / Copyright ( C ) 2000 - 2008 , Intel Corporation , all rights reserved . <nl> + / / Copyright ( C ) 2009 , Willow Garage Inc . , all rights reserved . <nl> + / / Third party copyrights are property of their respective owners . <nl> + / / <nl> + / / Redistribution and use in source and binary forms , with or without modification , <nl> + / / are permitted provided that the following conditions are met : <nl> + / / <nl> + / / * Redistribution ' s of source code must retain the above copyright notice , <nl> + / / this list of conditions and the following disclaimer . <nl> + / / <nl> + / / * Redistribution ' s in binary form must reproduce the above copyright notice , <nl> + / / this list of conditions and the following disclaimer in the documentation <nl> + / / and / or other GpuMaterials provided with the distribution . <nl> + / / <nl> + / / * The name of the copyright holders may not be used to endorse or promote products <nl> + / / derived from this software without specific prior written permission . <nl> + / / <nl> + / / This software is provided by the copyright holders and contributors " as is " and <nl> + / / any express or bpied warranties , including , but not limited to , the bpied <nl> + / / warranties of merchantability and fitness for a particular purpose are disclaimed . <nl> + / / In no event shall the Intel Corporation or contributors be liable for any direct , <nl> + / / indirect , incidental , special , exemplary , or consequential damages <nl> + / / ( including , but not limited to , procurement of substitute goods or services ; <nl> + / / loss of use , data , or profits ; or business interruption ) however caused <nl> + / / and on any theory of liability , whether in contract , strict liability , <nl> + / / or tort ( including negligence or otherwise ) arising in any way out of <nl> + / / the use of this software , even if advised of the possibility of such damage . <nl> + / / <nl> + / / M * / <nl> + <nl> + # include " test_precomp . hpp " <nl> + <nl> + # ifdef HAVE_CUDA <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / merge <nl> + <nl> + struct Merge : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int > > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int type ; <nl> + <nl> + cv : : Size size ; <nl> + std : : vector < cv : : Mat > src ; <nl> + <nl> + cv : : Mat dst_gold ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + type = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + size = cv : : Size ( rng . uniform ( 20 , 150 ) , rng . uniform ( 20 , 150 ) ) ; <nl> + <nl> + int depth = CV_MAT_DEPTH ( type ) ; <nl> + int num_channels = CV_MAT_CN ( type ) ; <nl> + src . reserve ( num_channels ) ; <nl> + for ( int i = 0 ; i < num_channels ; + + i ) <nl> + src . push_back ( cv : : Mat ( size , depth , cv : : Scalar : : all ( i ) ) ) ; <nl> + <nl> + cv : : merge ( src , dst_gold ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( Merge , Accuracy ) <nl> + { <nl> + if ( CV_MAT_DEPTH ( type ) = = CV_64F & & ! supportFeature ( devInfo , cv : : gpu : : NATIVE_DOUBLE ) ) <nl> + return ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + std : : vector < cv : : gpu : : GpuMat > dev_src ; <nl> + cv : : gpu : : GpuMat dev_dst ; <nl> + <nl> + for ( size_t i = 0 ; i < src . size ( ) ; + + i ) <nl> + dev_src . push_back ( cv : : gpu : : GpuMat ( src [ i ] ) ) ; <nl> + <nl> + cv : : gpu : : merge ( dev_src , dev_dst ) ; <nl> + <nl> + dev_dst . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 0 . 0 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( MatOp , Merge , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : ValuesIn ( all_types ( ) ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / split <nl> + <nl> + struct Split : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int > > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int type ; <nl> + <nl> + cv : : Size size ; <nl> + cv : : Mat src ; <nl> + <nl> + std : : vector < cv : : Mat > dst_gold ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + type = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + size = cv : : Size ( rng . uniform ( 20 , 150 ) , rng . uniform ( 20 , 150 ) ) ; <nl> + <nl> + src . create ( size , type ) ; <nl> + src . setTo ( cv : : Scalar ( 1 . 0 , 2 . 0 , 3 . 0 , 4 . 0 ) ) ; <nl> + cv : : split ( src , dst_gold ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( Split , Accuracy ) <nl> + { <nl> + if ( CV_MAT_DEPTH ( type ) = = CV_64F & & ! supportFeature ( devInfo , cv : : gpu : : NATIVE_DOUBLE ) ) <nl> + return ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + <nl> + std : : vector < cv : : Mat > dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + std : : vector < cv : : gpu : : GpuMat > dev_dst ; <nl> + cv : : gpu : : split ( cv : : gpu : : GpuMat ( src ) , dev_dst ) ; <nl> + <nl> + dst . resize ( dev_dst . size ( ) ) ; <nl> + for ( size_t i = 0 ; i < dev_dst . size ( ) ; + + i ) <nl> + dev_dst [ i ] . download ( dst [ i ] ) ; <nl> + ) ; <nl> + <nl> + ASSERT_EQ ( dst_gold . size ( ) , dst . size ( ) ) ; <nl> + <nl> + for ( size_t i = 0 ; i < dst_gold . size ( ) ; + + i ) <nl> + { <nl> + EXPECT_MAT_NEAR ( dst_gold [ i ] , dst [ i ] , 0 . 0 ) ; <nl> + } <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( MatOp , Split , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : ValuesIn ( all_types ( ) ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / split_merge_consistency <nl> + <nl> + struct SplitMerge : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int > > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int type ; <nl> + <nl> + cv : : Size size ; <nl> + cv : : Mat orig ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + type = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + size = cv : : Size ( rng . uniform ( 20 , 150 ) , rng . uniform ( 20 , 150 ) ) ; <nl> + <nl> + orig . create ( size , type ) ; <nl> + orig . setTo ( cv : : Scalar ( 1 . 0 , 2 . 0 , 3 . 0 , 4 . 0 ) ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( SplitMerge , Consistency ) <nl> + { <nl> + if ( CV_MAT_DEPTH ( type ) = = CV_64F & & ! supportFeature ( devInfo , cv : : gpu : : NATIVE_DOUBLE ) ) <nl> + return ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + <nl> + cv : : Mat final ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + std : : vector < cv : : gpu : : GpuMat > dev_vec ; <nl> + cv : : gpu : : GpuMat dev_final ; <nl> + <nl> + cv : : gpu : : split ( cv : : gpu : : GpuMat ( orig ) , dev_vec ) ; <nl> + cv : : gpu : : merge ( dev_vec , dev_final ) ; <nl> + <nl> + dev_final . download ( final ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( orig , final , 0 . 0 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( MatOp , SplitMerge , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : ValuesIn ( all_types ( ) ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / setTo <nl> + <nl> + struct SetTo : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int > > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int type ; <nl> + <nl> + cv : : Size size ; <nl> + cv : : Mat mat_gold ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + type = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + size = cv : : Size ( rng . uniform ( 20 , 150 ) , rng . uniform ( 20 , 150 ) ) ; <nl> + <nl> + mat_gold . create ( size , type ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( SetTo , Zero ) <nl> + { <nl> + if ( CV_MAT_DEPTH ( type ) = = CV_64F & & ! supportFeature ( devInfo , cv : : gpu : : NATIVE_DOUBLE ) ) <nl> + return ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + <nl> + static cv : : Scalar zero = cv : : Scalar : : all ( 0 ) ; <nl> + <nl> + cv : : Mat mat ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat dev_mat ( mat_gold ) ; <nl> + <nl> + mat_gold . setTo ( zero ) ; <nl> + dev_mat . setTo ( zero ) ; <nl> + <nl> + dev_mat . download ( mat ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( mat_gold , mat , 0 . 0 ) ; <nl> + } <nl> + <nl> + TEST_P ( SetTo , SameVal ) <nl> + { <nl> + if ( CV_MAT_DEPTH ( type ) = = CV_64F & & ! supportFeature ( devInfo , cv : : gpu : : NATIVE_DOUBLE ) ) <nl> + return ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + <nl> + static cv : : Scalar s = cv : : Scalar : : all ( 1 ) ; <nl> + <nl> + cv : : Mat mat ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat dev_mat ( mat_gold ) ; <nl> + <nl> + mat_gold . setTo ( s ) ; <nl> + dev_mat . setTo ( s ) ; <nl> + <nl> + dev_mat . download ( mat ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( mat_gold , mat , 0 . 0 ) ; <nl> + } <nl> + <nl> + TEST_P ( SetTo , DifferentVal ) <nl> + { <nl> + if ( CV_MAT_DEPTH ( type ) = = CV_64F & & ! supportFeature ( devInfo , cv : : gpu : : NATIVE_DOUBLE ) ) <nl> + return ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + <nl> + static cv : : Scalar s = cv : : Scalar ( 1 , 2 , 3 , 4 ) ; <nl> + <nl> + cv : : Mat mat ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat dev_mat ( mat_gold ) ; <nl> + <nl> + mat_gold . setTo ( s ) ; <nl> + dev_mat . setTo ( s ) ; <nl> + <nl> + dev_mat . download ( mat ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( mat_gold , mat , 0 . 0 ) ; <nl> + } <nl> + <nl> + TEST_P ( SetTo , Masked ) <nl> + { <nl> + if ( CV_MAT_DEPTH ( type ) = = CV_64F & & ! supportFeature ( devInfo , cv : : gpu : : NATIVE_DOUBLE ) ) <nl> + return ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + <nl> + static cv : : Scalar s = cv : : Scalar ( 1 , 2 , 3 , 4 ) ; <nl> + <nl> + cv : : Mat mat ; <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + cv : : Mat mask = cvtest : : randomMat ( rng , mat . size ( ) , CV_8UC1 , 0 . 0 , 1 . 5 , false ) ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat dev_mat ( mat_gold ) ; <nl> + <nl> + mat_gold . setTo ( s , mask ) ; <nl> + dev_mat . setTo ( s , cv : : gpu : : GpuMat ( mask ) ) ; <nl> + <nl> + dev_mat . download ( mat ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( mat_gold , mat , 0 . 0 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( MatOp , SetTo , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : ValuesIn ( all_types ( ) ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / copyTo <nl> + <nl> + struct CopyTo : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int > > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int type ; <nl> + <nl> + cv : : Size size ; <nl> + cv : : Mat src ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + type = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + size = cv : : Size ( rng . uniform ( 20 , 150 ) , rng . uniform ( 20 , 150 ) ) ; <nl> + <nl> + src = cvtest : : randomMat ( rng , size , type , 0 . 0 , 127 . 0 , false ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( CopyTo , WithoutMask ) <nl> + { <nl> + if ( CV_MAT_DEPTH ( type ) = = CV_64F & & ! supportFeature ( devInfo , cv : : gpu : : NATIVE_DOUBLE ) ) <nl> + return ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + <nl> + cv : : Mat dst_gold ; <nl> + src . copyTo ( dst_gold ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat dev_src ( src ) ; <nl> + <nl> + cv : : gpu : : GpuMat dev_dst ; <nl> + <nl> + dev_src . copyTo ( dev_dst ) ; <nl> + <nl> + dev_dst . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 0 . 0 ) ; <nl> + } <nl> + <nl> + TEST_P ( CopyTo , Masked ) <nl> + { <nl> + if ( CV_MAT_DEPTH ( type ) = = CV_64F & & ! supportFeature ( devInfo , cv : : gpu : : NATIVE_DOUBLE ) ) <nl> + return ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( type ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + cv : : Mat mask = cvtest : : randomMat ( rng , src . size ( ) , CV_8UC1 , 0 . 0 , 1 . 5 , false ) ; <nl> + <nl> + cv : : Mat dst_gold ; <nl> + src . copyTo ( dst_gold , mask ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat dev_src ( src ) ; <nl> + <nl> + cv : : gpu : : GpuMat dev_dst ; <nl> + <nl> + dev_src . copyTo ( dev_dst , cv : : gpu : : GpuMat ( mask ) ) ; <nl> + <nl> + dev_dst . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 0 . 0 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( MatOp , CopyTo , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : ValuesIn ( all_types ( ) ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / convertTo <nl> + <nl> + struct ConvertTo : testing : : TestWithParam < std : : tr1 : : tuple < cv : : gpu : : DeviceInfo , int , int > > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + int depth1 ; <nl> + int depth2 ; <nl> + <nl> + cv : : Size size ; <nl> + cv : : Mat src ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> + depth1 = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> + depth2 = std : : tr1 : : get < 2 > ( GetParam ( ) ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + size = cv : : Size ( rng . uniform ( 20 , 150 ) , rng . uniform ( 20 , 150 ) ) ; <nl> + <nl> + src = cvtest : : randomMat ( rng , size , depth1 , 0 . 0 , 127 . 0 , false ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( ConvertTo , WithoutScaling ) <nl> + { <nl> + if ( ( depth1 = = CV_64F | | depth2 = = CV_64F ) & & ! supportFeature ( devInfo , cv : : gpu : : NATIVE_DOUBLE ) ) <nl> + return ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( depth1 ) ; <nl> + PRINT_TYPE ( depth2 ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + <nl> + cv : : Mat dst_gold ; <nl> + src . convertTo ( dst_gold , depth2 ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat dev_src ( src ) ; <nl> + <nl> + cv : : gpu : : GpuMat dev_dst ; <nl> + <nl> + dev_src . convertTo ( dev_dst , depth2 ) ; <nl> + <nl> + dev_dst . download ( dst ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , 0 . 0 ) ; <nl> + } <nl> + <nl> + TEST_P ( ConvertTo , WithScaling ) <nl> + { <nl> + if ( ( depth1 = = CV_64F | | depth2 = = CV_64F ) & & ! supportFeature ( devInfo , cv : : gpu : : NATIVE_DOUBLE ) ) <nl> + return ; <nl> + <nl> + PRINT_PARAM ( devInfo ) ; <nl> + PRINT_TYPE ( depth1 ) ; <nl> + PRINT_TYPE ( depth2 ) ; <nl> + PRINT_PARAM ( size ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + const double a = rng . uniform ( 0 . 0 , 1 . 0 ) ; <nl> + const double b = rng . uniform ( - 10 . 0 , 10 . 0 ) ; <nl> + <nl> + PRINT_PARAM ( a ) ; <nl> + PRINT_PARAM ( b ) ; <nl> + <nl> + cv : : Mat dst_gold ; <nl> + src . convertTo ( dst_gold , depth2 , a , b ) ; <nl> + <nl> + cv : : Mat dst ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : GpuMat dev_src ( src ) ; <nl> + <nl> + cv : : gpu : : GpuMat dev_dst ; <nl> + <nl> + dev_src . convertTo ( dev_dst , depth2 , a , b ) ; <nl> + <nl> + dev_dst . download ( dst ) ; <nl> + ) ; <nl> + <nl> + const double eps = depth2 < CV_32F ? 1 : 1e - 4 ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold , dst , eps ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( MatOp , ConvertTo , testing : : Combine ( <nl> + testing : : ValuesIn ( devices ( ) ) , <nl> + testing : : ValuesIn ( types ( CV_8U , CV_64F , 1 , 1 ) ) , <nl> + testing : : ValuesIn ( types ( CV_8U , CV_64F , 1 , 1 ) ) ) ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / async <nl> + <nl> + struct Async : testing : : TestWithParam < cv : : gpu : : DeviceInfo > <nl> + { <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + <nl> + cv : : gpu : : CudaMem src ; <nl> + <nl> + cv : : Mat dst_gold0 ; <nl> + cv : : Mat dst_gold1 ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = GetParam ( ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + <nl> + cv : : RNG & rng = cvtest : : TS : : ptr ( ) - > get_rng ( ) ; <nl> + <nl> + int rows = rng . uniform ( 100 , 200 ) ; <nl> + int cols = rng . uniform ( 100 , 200 ) ; <nl> + <nl> + src = cv : : gpu : : CudaMem ( cv : : Mat : : zeros ( rows , cols , CV_8UC1 ) ) ; <nl> + <nl> + dst_gold0 = cv : : Mat ( rows , cols , CV_8UC1 , cv : : Scalar : : all ( 255 ) ) ; <nl> + dst_gold1 = cv : : Mat ( rows , cols , CV_8UC1 , cv : : Scalar : : all ( 128 ) ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( Async , Accuracy ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + <nl> + cv : : Mat dst0 , dst1 ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + cv : : gpu : : CudaMem cpudst0 ; <nl> + cv : : gpu : : CudaMem cpudst1 ; <nl> + <nl> + cv : : gpu : : GpuMat gpusrc ; <nl> + cv : : gpu : : GpuMat gpudst0 ; <nl> + cv : : gpu : : GpuMat gpudst1 ( src . rows , src . cols , CV_8UC1 ) ; <nl> + <nl> + cv : : gpu : : Stream stream0 ; <nl> + cv : : gpu : : Stream stream1 ; <nl> + <nl> + stream0 . enqueueUpload ( src , gpusrc ) ; <nl> + cv : : gpu : : bitwise_not ( gpusrc , gpudst0 , cv : : gpu : : GpuMat ( ) , stream0 ) ; <nl> + stream0 . enqueueDownload ( gpudst0 , cpudst0 ) ; <nl> + <nl> + stream1 . enqueueMemSet ( gpudst1 , cv : : Scalar : : all ( 128 ) ) ; <nl> + stream1 . enqueueDownload ( gpudst1 , cpudst1 ) ; <nl> + <nl> + stream0 . waitForCompletion ( ) ; <nl> + stream1 . waitForCompletion ( ) ; <nl> + <nl> + dst0 = cpudst0 . createMatHeader ( ) ; <nl> + dst1 = cpudst1 . createMatHeader ( ) ; <nl> + ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst_gold0 , dst0 , 0 . 0 ) ; <nl> + EXPECT_MAT_NEAR ( dst_gold1 , dst1 , 0 . 0 ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( MatOp , Async , testing : : ValuesIn ( devices ( ) ) ) ; <nl> + <nl> + # endif / / HAVE_CUDA <nl> deleted file mode 100644 <nl> index b297b982aca . . 00000000000 <nl> mmm a / modules / gpu / test / test_meanshift . cpp <nl> ppp / dev / null <nl> <nl> - / * M / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / <nl> - / / IMPORTANT : READ BEFORE DOWNLOADING , COPYING , INSTALLING OR USING . <nl> - / / <nl> - / / By downloading , copying , installing or using the software you agree to this license . <nl> - / / If you do not agree to this license , do not download , install , <nl> - / / copy or use the software . <nl> - / / <nl> - / / <nl> - / / Intel License Agreement <nl> - / / For Open Source Computer Vision Library <nl> - / / <nl> - / / Copyright ( C ) 2000 , Intel Corporation , all rights reserved . <nl> - / / Third party copyrights are property of their respective owners . <nl> - / / <nl> - / / Redistribution and use in source and binary forms , with or without modification , <nl> - / / are permitted provided that the following conditions are met : <nl> - / / <nl> - / / * Redistribution ' s of source code must retain the above copyright notice , <nl> - / / this list of conditions and the following disclaimer . <nl> - / / <nl> - / / * Redistribution ' s in binary form must reproduce the above copyright notice , <nl> - / / this list of conditions and the following disclaimer in the documentation <nl> - / / and / or other materials provided with the distribution . <nl> - / / <nl> - / / * The name of Intel Corporation may not be used to endorse or promote products <nl> - / / derived from this software without specific prior written permission . <nl> - / / <nl> - / / This software is provided by the copyright holders and contributors " as is " and <nl> - / / any express or implied warranties , including , but not limited to , the implied <nl> - / / warranties of merchantability and fitness for a particular purpose are disclaimed . <nl> - / / In no event shall the Intel Corporation or contributors be liable for any direct , <nl> - / / indirect , incidental , special , exemplary , or consequential damages <nl> - / / ( including , but not limited to , procurement of substitute goods or services ; <nl> - / / loss of use , data , or profits ; or business interruption ) however caused <nl> - / / and on any theory of liability , whether in contract , strict liability , <nl> - / / or tort ( including negligence or otherwise ) arising in any way out of <nl> - / / the use of this software , even if advised of the possibility of such damage . <nl> - / / <nl> - / / M * / <nl> - <nl> - # include " test_precomp . hpp " <nl> - # include < iostream > <nl> - # include < string > <nl> - <nl> - using namespace cv ; <nl> - using namespace cv : : gpu ; <nl> - <nl> - <nl> - struct CV_GpuMeanShiftTest : public cvtest : : BaseTest <nl> - { <nl> - CV_GpuMeanShiftTest ( ) { } <nl> - <nl> - void run ( int ) <nl> - { <nl> - bool cc12_ok = TargetArchs : : builtWith ( FEATURE_SET_COMPUTE_12 ) & & DeviceInfo ( ) . supports ( FEATURE_SET_COMPUTE_12 ) ; <nl> - if ( ! cc12_ok ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " \ nCompute capability 1 . 2 is required " ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_GENERIC ) ; <nl> - return ; <nl> - } <nl> - <nl> - int spatialRad = 30 ; <nl> - int colorRad = 30 ; <nl> - <nl> - cv : : Mat img = cv : : imread ( std : : string ( ts - > get_data_path ( ) ) + " meanshift / cones . png " ) ; <nl> - cv : : Mat img_template ; <nl> - <nl> - if ( cv : : gpu : : TargetArchs : : builtWith ( cv : : gpu : : FEATURE_SET_COMPUTE_20 ) & & <nl> - cv : : gpu : : DeviceInfo ( ) . supports ( cv : : gpu : : FEATURE_SET_COMPUTE_20 ) ) <nl> - img_template = cv : : imread ( std : : string ( ts - > get_data_path ( ) ) + " meanshift / con_result . png " ) ; <nl> - else <nl> - img_template = cv : : imread ( std : : string ( ts - > get_data_path ( ) ) + " meanshift / con_result_CC1X . png " ) ; <nl> - <nl> - if ( img . empty ( ) | | img_template . empty ( ) ) <nl> - { <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_MISSING_TEST_DATA ) ; <nl> - return ; <nl> - } <nl> - <nl> - cv : : Mat rgba ; <nl> - cvtColor ( img , rgba , CV_BGR2BGRA ) ; <nl> - <nl> - <nl> - cv : : gpu : : GpuMat res ; <nl> - cv : : gpu : : meanShiftFiltering ( cv : : gpu : : GpuMat ( rgba ) , res , spatialRad , colorRad ) ; <nl> - <nl> - if ( res . type ( ) ! = CV_8UC4 ) <nl> - { <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return ; <nl> - } <nl> - <nl> - cv : : Mat result ; <nl> - res . download ( result ) ; <nl> - <nl> - uchar maxDiff = 0 ; <nl> - for ( int j = 0 ; j < result . rows ; + + j ) <nl> - { <nl> - const uchar * res_line = result . ptr < uchar > ( j ) ; <nl> - const uchar * ref_line = img_template . ptr < uchar > ( j ) ; <nl> - <nl> - for ( int i = 0 ; i < result . cols ; + + i ) <nl> - { <nl> - for ( int k = 0 ; k < 3 ; + + k ) <nl> - { <nl> - const uchar & ch1 = res_line [ result . channels ( ) * i + k ] ; <nl> - const uchar & ch2 = ref_line [ img_template . channels ( ) * i + k ] ; <nl> - uchar diff = static_cast < uchar > ( abs ( ch1 - ch2 ) ) ; <nl> - if ( maxDiff < diff ) <nl> - maxDiff = diff ; <nl> - } <nl> - } <nl> - } <nl> - if ( maxDiff > 0 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ nMeanShift maxDiff = % d \ n " , maxDiff ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_GENERIC ) ; <nl> - return ; <nl> - } <nl> - <nl> - ts - > set_failed_test_info ( cvtest : : TS : : OK ) ; <nl> - } <nl> - <nl> - } ; <nl> - <nl> - TEST ( meanShift , accuracy ) { CV_GpuMeanShiftTest test ; test . safe_run ( ) ; } <nl> - <nl> - struct CV_GpuMeanShiftProcTest : public cvtest : : BaseTest <nl> - { <nl> - CV_GpuMeanShiftProcTest ( ) { } <nl> - <nl> - void run ( int ) <nl> - { <nl> - bool cc12_ok = TargetArchs : : builtWith ( FEATURE_SET_COMPUTE_12 ) & & DeviceInfo ( ) . supports ( FEATURE_SET_COMPUTE_12 ) ; <nl> - if ( ! cc12_ok ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " \ nCompute capability 1 . 2 is required " ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_GENERIC ) ; <nl> - return ; <nl> - } <nl> - <nl> - int spatialRad = 30 ; <nl> - int colorRad = 30 ; <nl> - <nl> - cv : : Mat img = cv : : imread ( std : : string ( ts - > get_data_path ( ) ) + " meanshift / cones . png " ) ; <nl> - <nl> - if ( img . empty ( ) ) <nl> - { <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_MISSING_TEST_DATA ) ; <nl> - return ; <nl> - } <nl> - <nl> - cv : : Mat rgba ; <nl> - cvtColor ( img , rgba , CV_BGR2BGRA ) ; <nl> - <nl> - cv : : gpu : : GpuMat h_rmap_filtered ; <nl> - cv : : gpu : : meanShiftFiltering ( cv : : gpu : : GpuMat ( rgba ) , h_rmap_filtered , spatialRad , colorRad ) ; <nl> - <nl> - cv : : gpu : : GpuMat d_rmap ; <nl> - cv : : gpu : : GpuMat d_spmap ; <nl> - cv : : gpu : : meanShiftProc ( cv : : gpu : : GpuMat ( rgba ) , d_rmap , d_spmap , spatialRad , colorRad ) ; <nl> - <nl> - if ( d_rmap . type ( ) ! = CV_8UC4 ) <nl> - { <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return ; <nl> - } <nl> - <nl> - cv : : Mat rmap_filtered ; <nl> - h_rmap_filtered . download ( rmap_filtered ) ; <nl> - <nl> - cv : : Mat rmap ; <nl> - d_rmap . download ( rmap ) ; <nl> - <nl> - uchar maxDiff = 0 ; <nl> - for ( int j = 0 ; j < rmap_filtered . rows ; + + j ) <nl> - { <nl> - const uchar * res_line = rmap_filtered . ptr < uchar > ( j ) ; <nl> - const uchar * ref_line = rmap . ptr < uchar > ( j ) ; <nl> - <nl> - for ( int i = 0 ; i < rmap_filtered . cols ; + + i ) <nl> - { <nl> - for ( int k = 0 ; k < 3 ; + + k ) <nl> - { <nl> - const uchar & ch1 = res_line [ rmap_filtered . channels ( ) * i + k ] ; <nl> - const uchar & ch2 = ref_line [ rmap . channels ( ) * i + k ] ; <nl> - uchar diff = static_cast < uchar > ( abs ( ch1 - ch2 ) ) ; <nl> - if ( maxDiff < diff ) <nl> - maxDiff = diff ; <nl> - } <nl> - } <nl> - } <nl> - if ( maxDiff > 0 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ nMeanShiftProc maxDiff = % d \ n " , maxDiff ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_GENERIC ) ; <nl> - return ; <nl> - } <nl> - <nl> - cv : : Mat spmap ; <nl> - d_spmap . download ( spmap ) ; <nl> - <nl> - cv : : Mat spmap_template ; <nl> - cv : : FileStorage fs ; <nl> - <nl> - if ( cv : : gpu : : TargetArchs : : builtWith ( cv : : gpu : : FEATURE_SET_COMPUTE_20 ) & & <nl> - cv : : gpu : : DeviceInfo ( ) . supports ( cv : : gpu : : FEATURE_SET_COMPUTE_20 ) ) <nl> - fs . open ( std : : string ( ts - > get_data_path ( ) ) + " meanshift / spmap . yaml " , cv : : FileStorage : : READ ) ; <nl> - else <nl> - fs . open ( std : : string ( ts - > get_data_path ( ) ) + " meanshift / spmap_CC1X . yaml " , cv : : FileStorage : : READ ) ; <nl> - fs [ " spmap " ] > > spmap_template ; <nl> - <nl> - for ( int y = 0 ; y < spmap . rows ; + + y ) { <nl> - for ( int x = 0 ; x < spmap . cols ; + + x ) { <nl> - cv : : Point_ < short > expected = spmap_template . at < cv : : Point_ < short > > ( y , x ) ; <nl> - cv : : Point_ < short > actual = spmap . at < cv : : Point_ < short > > ( y , x ) ; <nl> - int diff = ( expected - actual ) . dot ( expected - actual ) ; <nl> - if ( actual ! = expected ) { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ nMeanShiftProc SpMap is bad , diff = % d \ n " , diff ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_GENERIC ) ; <nl> - return ; <nl> - } <nl> - } <nl> - } <nl> - <nl> - ts - > set_failed_test_info ( cvtest : : TS : : OK ) ; <nl> - } <nl> - <nl> - } ; <nl> - <nl> - TEST ( meanShiftProc , accuracy ) { CV_GpuMeanShiftProcTest test ; test . safe_run ( ) ; } <nl> deleted file mode 100644 <nl> index b64914704b0 . . 00000000000 <nl> mmm a / modules / gpu / test / test_mssegmentation . cpp <nl> ppp / dev / null <nl> <nl> - / * M / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / <nl> - / / IMPORTANT : READ BEFORE DOWNLOADING , COPYING , INSTALLING OR USING . <nl> - / / <nl> - / / By downloading , copying , installing or using the software you agree to this license . <nl> - / / If you do not agree to this license , do not download , install , <nl> - / / copy or use the software . <nl> - / / <nl> - / / <nl> - / / Intel License Agreement <nl> - / / For Open Source Computer Vision Library <nl> - / / <nl> - / / Copyright ( C ) 2000 , Intel Corporation , all rights reserved . <nl> - / / Third party copyrights are property of their respective owners . <nl> - / / <nl> - / / Redistribution and use in source and binary forms , with or without modification , <nl> - / / are permitted provided that the following conditions are met : <nl> - / / <nl> - / / * Redistribution ' s of source code must retain the above copyright notice , <nl> - / / this list of conditions and the following disclaimer . <nl> - / / <nl> - / / * Redistribution ' s in binary form must reproduce the above copyright notice , <nl> - / / this list of conditions and the following disclaimer in the documentation <nl> - / / and / or other materials provided with the distribution . <nl> - / / <nl> - / / * The name of Intel Corporation may not be used to endorse or promote products <nl> - / / derived from this software without specific prior written permission . <nl> - / / <nl> - / / This software is provided by the copyright holders and contributors " as is " and <nl> - / / any express or implied warranties , including , but not limited to , the implied <nl> - / / warranties of merchantability and fitness for a particular purpose are disclaimed . <nl> - / / In no event shall the Intel Corporation or contributors be liable for any direct , <nl> - / / indirect , incidental , special , exemplary , or consequential damages <nl> - / / ( including , but not limited to , procurement of substitute goods or services ; <nl> - / / loss of use , data , or profits ; or business interruption ) however caused <nl> - / / and on any theory of liability , whether in contract , strict liability , <nl> - / / or tort ( including negligence or otherwise ) arising in any way out of <nl> - / / the use of this software , even if advised of the possibility of such damage . <nl> - / / <nl> - / / M * / <nl> - <nl> - # include < iostream > <nl> - # include < string > <nl> - # include < iosfwd > <nl> - # include " test_precomp . hpp " <nl> - using namespace cv ; <nl> - using namespace cv : : gpu ; <nl> - using namespace std ; <nl> - <nl> - struct CV_GpuMeanShiftSegmentationTest : public cvtest : : BaseTest { <nl> - CV_GpuMeanShiftSegmentationTest ( ) { } <nl> - <nl> - void run ( int ) <nl> - { <nl> - bool cc12_ok = TargetArchs : : builtWith ( FEATURE_SET_COMPUTE_12 ) & & DeviceInfo ( ) . supports ( FEATURE_SET_COMPUTE_12 ) ; <nl> - if ( ! cc12_ok ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " \ nCompute capability 1 . 2 is required " ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_GENERIC ) ; <nl> - return ; <nl> - } <nl> - <nl> - Mat img_rgb = imread ( string ( ts - > get_data_path ( ) ) + " meanshift / cones . png " ) ; <nl> - if ( img_rgb . empty ( ) ) <nl> - { <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_MISSING_TEST_DATA ) ; <nl> - return ; <nl> - } <nl> - <nl> - Mat img ; <nl> - cvtColor ( img_rgb , img , CV_BGR2BGRA ) ; <nl> - <nl> - <nl> - for ( int minsize = 0 ; minsize < 2000 ; minsize = ( minsize + 1 ) * 4 ) <nl> - { <nl> - stringstream path ; <nl> - path < < ts - > get_data_path ( ) < < " meanshift / cones_segmented_sp10_sr10_minsize " < < minsize ; <nl> - if ( TargetArchs : : builtWith ( FEATURE_SET_COMPUTE_20 ) & & DeviceInfo ( ) . supports ( FEATURE_SET_COMPUTE_20 ) ) <nl> - path < < " . png " ; <nl> - else <nl> - path < < " _CC1X . png " ; <nl> - <nl> - Mat dst ; <nl> - meanShiftSegmentation ( ( GpuMat ) img , dst , 10 , 10 , minsize ) ; <nl> - Mat dst_rgb ; <nl> - cvtColor ( dst , dst_rgb , CV_BGRA2BGR ) ; <nl> - <nl> - / / imwrite ( path . str ( ) , dst_rgb ) ; <nl> - Mat dst_ref = imread ( path . str ( ) ) ; <nl> - if ( dst_ref . empty ( ) ) <nl> - { <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_MISSING_TEST_DATA ) ; <nl> - return ; <nl> - } <nl> - if ( CheckSimilarity ( dst_rgb , dst_ref , 1e - 3f ) ! = cvtest : : TS : : OK ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ ndiffers from image * minsize % d . png \ n " , minsize ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_BAD_ACCURACY ) ; <nl> - } <nl> - } <nl> - <nl> - ts - > set_failed_test_info ( cvtest : : TS : : OK ) ; <nl> - } <nl> - <nl> - int CheckSimilarity ( const Mat & m1 , const Mat & m2 , float max_err ) <nl> - { <nl> - Mat diff ; <nl> - cv : : matchTemplate ( m1 , m2 , diff , CV_TM_CCORR_NORMED ) ; <nl> - <nl> - float err = abs ( diff . at < float > ( 0 , 0 ) - 1 . f ) ; <nl> - <nl> - if ( err > max_err ) <nl> - return cvtest : : TS : : FAIL_INVALID_OUTPUT ; <nl> - <nl> - return cvtest : : TS : : OK ; <nl> - } <nl> - <nl> - <nl> - } ; <nl> - <nl> - <nl> - TEST ( meanShiftSegmentation , regression ) { CV_GpuMeanShiftSegmentationTest test ; test . safe_run ( ) ; } <nl> mmm a / modules / gpu / test / test_nvidia . cpp <nl> ppp b / modules / gpu / test / test_nvidia . cpp <nl> <nl> / / M * / <nl> <nl> # include " test_precomp . hpp " <nl> - # include " cvconfig . h " <nl> <nl> - class CV_NVidiaTestsCaller : public cvtest : : BaseTest <nl> + # ifdef HAVE_CUDA <nl> + <nl> + enum OutputLevel <nl> + { <nl> + OutputLevelNone , <nl> + OutputLevelCompact , <nl> + OutputLevelFull <nl> + } ; <nl> + <nl> + bool nvidia_NPPST_Integral_Image ( const std : : string & test_data_path , OutputLevel outputLevel ) ; <nl> + bool nvidia_NPPST_Squared_Integral_Image ( const std : : string & test_data_path , OutputLevel outputLevel ) ; <nl> + bool nvidia_NPPST_RectStdDev ( const std : : string & test_data_path , OutputLevel outputLevel ) ; <nl> + bool nvidia_NPPST_Resize ( const std : : string & test_data_path , OutputLevel outputLevel ) ; <nl> + bool nvidia_NPPST_Vector_Operations ( const std : : string & test_data_path , OutputLevel outputLevel ) ; <nl> + bool nvidia_NPPST_Transpose ( const std : : string & test_data_path , OutputLevel outputLevel ) ; <nl> + bool nvidia_NCV_Vector_Operations ( const std : : string & test_data_path , OutputLevel outputLevel ) ; <nl> + bool nvidia_NCV_Haar_Cascade_Loader ( const std : : string & test_data_path , OutputLevel outputLevel ) ; <nl> + bool nvidia_NCV_Haar_Cascade_Application ( const std : : string & test_data_path , OutputLevel outputLevel ) ; <nl> + bool nvidia_NCV_Hypotheses_Filtration ( const std : : string & test_data_path , OutputLevel outputLevel ) ; <nl> + bool nvidia_NCV_Visualization ( const std : : string & test_data_path , OutputLevel outputLevel ) ; <nl> + <nl> + struct NVidiaTest : testing : : TestWithParam < cv : : gpu : : DeviceInfo > <nl> { <nl> - public : <nl> - CV_NVidiaTestsCaller ( ) { } <nl> - virtual ~ CV_NVidiaTestsCaller ( ) { } <nl> - <nl> - protected : <nl> - <nl> - void run ( int ) <nl> - { <nl> - ; <nl> - <nl> - # if defined ( HAVE_CUDA ) <nl> - bool main_nvidia ( const std : : string & ) ; <nl> - <nl> - / / Invoke all NVIDIA Staging tests and obtain the result <nl> - bool passed = main_nvidia ( std : : string ( ts - > get_data_path ( ) ) + " haarcascade / " ) ; <nl> - <nl> - if ( passed ) <nl> - ts - > set_failed_test_info ( cvtest : : TS : : OK ) ; <nl> - else <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - <nl> - # else <nl> - ts - > set_failed_test_info ( cvtest : : TS : : SKIPPED ) ; <nl> - # endif <nl> - } <nl> + static std : : string path ; <nl> + <nl> + cv : : gpu : : DeviceInfo devInfo ; <nl> + <nl> + static void SetUpTestCase ( ) <nl> + { <nl> + path = std : : string ( cvtest : : TS : : ptr ( ) - > get_data_path ( ) ) + " haarcascade / " ; <nl> + } <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + devInfo = GetParam ( ) ; <nl> + <nl> + cv : : gpu : : setDevice ( devInfo . deviceID ( ) ) ; <nl> + } <nl> } ; <nl> <nl> - TEST ( NVidia , multitest ) { CV_NVidiaTestsCaller test ; test . safe_run ( ) ; } <nl> + std : : string NVidiaTest : : path ; <nl> + <nl> + struct NPPST : NVidiaTest { } ; <nl> + struct NCV : NVidiaTest { } ; <nl> + <nl> + OutputLevel nvidiaTestOutputLevel = OutputLevelNone ; <nl> + <nl> + TEST_P ( NPPST , Integral ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + <nl> + bool res ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + res = nvidia_NPPST_Integral_Image ( path , nvidiaTestOutputLevel ) ; <nl> + ) ; <nl> + <nl> + ASSERT_TRUE ( res ) ; <nl> + } <nl> + <nl> + TEST_P ( NPPST , SquaredIntegral ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + <nl> + bool res ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + res = nvidia_NPPST_Squared_Integral_Image ( path , nvidiaTestOutputLevel ) ; <nl> + ) ; <nl> + <nl> + ASSERT_TRUE ( res ) ; <nl> + } <nl> + <nl> + TEST_P ( NPPST , RectStdDev ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + <nl> + bool res ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + res = nvidia_NPPST_RectStdDev ( path , nvidiaTestOutputLevel ) ; <nl> + ) ; <nl> + <nl> + ASSERT_TRUE ( res ) ; <nl> + } <nl> + <nl> + TEST_P ( NPPST , Resize ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + <nl> + bool res ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + res = nvidia_NPPST_Resize ( path , nvidiaTestOutputLevel ) ; <nl> + ) ; <nl> + <nl> + ASSERT_TRUE ( res ) ; <nl> + } <nl> + <nl> + TEST_P ( NPPST , VectorOperations ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + <nl> + bool res ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + res = nvidia_NPPST_Vector_Operations ( path , nvidiaTestOutputLevel ) ; <nl> + ) ; <nl> + <nl> + ASSERT_TRUE ( res ) ; <nl> + } <nl> + <nl> + TEST_P ( NPPST , Transpose ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + <nl> + bool res ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + res = nvidia_NPPST_Transpose ( path , nvidiaTestOutputLevel ) ; <nl> + ) ; <nl> + <nl> + ASSERT_TRUE ( res ) ; <nl> + } <nl> + <nl> + TEST_P ( NCV , VectorOperations ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + <nl> + bool res ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + res = nvidia_NCV_Vector_Operations ( path , nvidiaTestOutputLevel ) ; <nl> + ) ; <nl> + <nl> + ASSERT_TRUE ( res ) ; <nl> + } <nl> + <nl> + TEST_P ( NCV , HaarCascadeLoader ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + <nl> + bool res ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + res = nvidia_NCV_Haar_Cascade_Loader ( path , nvidiaTestOutputLevel ) ; <nl> + ) ; <nl> + <nl> + ASSERT_TRUE ( res ) ; <nl> + } <nl> + <nl> + TEST_P ( NCV , HaarCascadeApplication ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + <nl> + bool res ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + res = nvidia_NCV_Haar_Cascade_Application ( path , nvidiaTestOutputLevel ) ; <nl> + ) ; <nl> + <nl> + ASSERT_TRUE ( res ) ; <nl> + } <nl> + <nl> + TEST_P ( NCV , HypothesesFiltration ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + <nl> + bool res ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + res = nvidia_NCV_Hypotheses_Filtration ( path , nvidiaTestOutputLevel ) ; <nl> + ) ; <nl> + <nl> + ASSERT_TRUE ( res ) ; <nl> + } <nl> + <nl> + TEST_P ( NCV , Visualization ) <nl> + { <nl> + PRINT_PARAM ( devInfo ) ; <nl> + <nl> + bool res ; <nl> + <nl> + ASSERT_NO_THROW ( <nl> + res = nvidia_NCV_Visualization ( path , nvidiaTestOutputLevel ) ; <nl> + ) ; <nl> + <nl> + ASSERT_TRUE ( res ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( NVidia , NPPST , testing : : ValuesIn ( devices ( ) ) ) ; <nl> + INSTANTIATE_TEST_CASE_P ( NVidia , NCV , testing : : ValuesIn ( devices ( ) ) ) ; <nl> + <nl> + # endif / / HAVE_CUDA <nl> deleted file mode 100644 <nl> index 34843c79dee . . 00000000000 <nl> mmm a / modules / gpu / test / test_operator_async_call . cpp <nl> ppp / dev / null <nl> <nl> - / * M / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / <nl> - / / IMPORTANT : READ BEFORE DOWNLOADING , COPYING , INSTALLING OR USING . <nl> - / / <nl> - / / By downloading , copying , installing or using the software you agree to this license . <nl> - / / If you do not agree to this license , do not download , install , <nl> - / / copy or use the software . <nl> - / / <nl> - / / <nl> - / / Intel License Agreement <nl> - / / For Open Source Computer Vision Library <nl> - / / <nl> - / / Copyright ( C ) 2000 , Intel Corporation , all rights reserved . <nl> - / / Third party copyrights are property of their respective owners . <nl> - / / <nl> - / / Redistribution and use in source and binary forms , with or without modification , <nl> - / / are permitted provided that the following conditions are met : <nl> - / / <nl> - / / * Redistribution ' s of source code must retain the above copyright notice , <nl> - / / this list of conditions and the following disclaimer . <nl> - / / <nl> - / / * Redistribution ' s in binary form must reproduce the above copyright notice , <nl> - / / this list of conditions and the following disclaimer in the documentation <nl> - / / and / or other materials provided with the distribution . <nl> - / / <nl> - / / * The name of Intel Corporation may not be used to endorse or promote products <nl> - / / derived from this software without specific prior written permission . <nl> - / / <nl> - / / This software is provided by the copyright holders and contributors " as is " and <nl> - / / any express or implied warranties , including , but not limited to , the implied <nl> - / / warranties of merchantability and fitness for a particular purpose are disclaimed . <nl> - / / In no event shall the Intel Corporation or contributors be liable for any direct , <nl> - / / indirect , incidental , special , exemplary , or consequential damages <nl> - / / ( including , but not limited to , procurement of substitute goods or services ; <nl> - / / loss of use , data , or profits ; or business interruption ) however caused <nl> - / / and on any theory of liability , whether in contract , strict liability , <nl> - / / or tort ( including negligence or otherwise ) arising in any way out of <nl> - / / the use of this software , even if advised of the possibility of such damage . <nl> - / / <nl> - / / M * / <nl> - <nl> - # include " test_precomp . hpp " <nl> - <nl> - using namespace std ; <nl> - using namespace cv ; <nl> - using namespace cv : : gpu ; <nl> - <nl> - struct CV_AsyncGpuMatTest : public cvtest : : BaseTest <nl> - { <nl> - CV_AsyncGpuMatTest ( ) { } <nl> - <nl> - void run ( int ) <nl> - { <nl> - CudaMem src ( Mat : : zeros ( 100 , 100 , CV_8UC1 ) ) ; <nl> - <nl> - GpuMat gpusrc ; <nl> - GpuMat gpudst0 , gpudst1 ( 100 , 100 , CV_8UC1 ) ; <nl> - <nl> - CudaMem cpudst0 ; <nl> - CudaMem cpudst1 ; <nl> - <nl> - Stream stream0 , stream1 ; <nl> - <nl> - stream0 . enqueueUpload ( src , gpusrc ) ; <nl> - bitwise_not ( gpusrc , gpudst0 , GpuMat ( ) , stream0 ) ; <nl> - stream0 . enqueueDownload ( gpudst0 , cpudst0 ) ; <nl> - <nl> - stream1 . enqueueMemSet ( gpudst1 , Scalar : : all ( 128 ) ) ; <nl> - stream1 . enqueueDownload ( gpudst1 , cpudst1 ) ; <nl> - <nl> - stream0 . waitForCompletion ( ) ; <nl> - stream1 . waitForCompletion ( ) ; <nl> - <nl> - Mat cpu_gold0 ( 100 , 100 , CV_8UC1 , Scalar : : all ( 255 ) ) ; <nl> - Mat cpu_gold1 ( 100 , 100 , CV_8UC1 , Scalar : : all ( 128 ) ) ; <nl> - <nl> - if ( norm ( ( Mat ) cpudst0 , cpu_gold0 , NORM_INF ) > 0 | | norm ( ( Mat ) cpudst1 , cpu_gold1 , NORM_INF ) > 0 ) <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_GENERIC ) ; <nl> - else <nl> - ts - > set_failed_test_info ( cvtest : : TS : : OK ) ; <nl> - } <nl> - } ; <nl> - <nl> - TEST ( GpuMat , async ) { CV_AsyncGpuMatTest test ; test . safe_run ( ) ; } <nl> deleted file mode 100644 <nl> index c5c55b3d959 . . 00000000000 <nl> mmm a / modules / gpu / test / test_operator_convert_to . cpp <nl> ppp / dev / null <nl> <nl> - / * M / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / <nl> - / / IMPORTANT : READ BEFORE DOWNLOADING , COPYING , INSTALLING OR USING . <nl> - / / <nl> - / / By downloading , copying , installing or using the software you agree to this license . <nl> - / / If you do not agree to this license , do not download , install , <nl> - / / copy or use the software . <nl> - / / <nl> - / / <nl> - / / Intel License Agreement <nl> - / / For Open Source Computer Vision Library <nl> - / / <nl> - / / Copyright ( C ) 2000 , Intel Corporation , all rights reserved . <nl> - / / Third party copyrights are property of their respective owners . <nl> - / / <nl> - / / Redistribution and use in source and binary forms , with or without modification , <nl> - / / are permitted provided that the following conditions are met : <nl> - / / <nl> - / / * Redistribution ' s of source code must retain the above copyright notice , <nl> - / / this list of conditions and the following disclaimer . <nl> - / / <nl> - / / * Redistribution ' s in binary form must reproduce the above copyright notice , <nl> - / / this list of conditions and the following disclaimer in the documentation <nl> - / / and / or other materials provided with the distribution . <nl> - / / <nl> - / / * The name of Intel Corporation may not be used to endorse or promote products <nl> - / / derived from this software without specific prior written permission . <nl> - / / <nl> - / / This software is provided by the copyright holders and contributors " as is " and <nl> - / / any express or implied warranties , including , but not limited to , the implied <nl> - / / warranties of merchantability and fitness for a particular purpose are disclaimed . <nl> - / / In no event shall the Intel Corporation or contributors be liable for any direct , <nl> - / / indirect , incidental , special , exemplary , or consequential damages <nl> - / / ( including , but not limited to , procurement of substitute goods or services ; <nl> - / / loss of use , data , or profits ; or business interruption ) however caused <nl> - / / and on any theory of liability , whether in contract , strict liability , <nl> - / / or tort ( including negligence or otherwise ) arising in any way out of <nl> - / / the use of this software , even if advised of the possibility of such damage . <nl> - / / <nl> - / / M * / <nl> - <nl> - # include " test_precomp . hpp " <nl> - <nl> - # include < fstream > <nl> - # include < iterator > <nl> - # include < numeric > <nl> - <nl> - using namespace cv ; <nl> - using namespace std ; <nl> - using namespace gpu ; <nl> - <nl> - class CV_GpuMatOpConvertToTest : public cvtest : : BaseTest <nl> - { <nl> - public : <nl> - CV_GpuMatOpConvertToTest ( ) { } <nl> - ~ CV_GpuMatOpConvertToTest ( ) { } <nl> - <nl> - protected : <nl> - void run ( int ) ; <nl> - } ; <nl> - <nl> - void CV_GpuMatOpConvertToTest : : run ( int / * start_from * / ) <nl> - { <nl> - const Size img_size ( 67 , 35 ) ; <nl> - <nl> - const char * types_str [ ] = { " CV_8U " , " CV_8S " , " CV_16U " , " CV_16S " , " CV_32S " , " CV_32F " , " CV_64F " } ; <nl> - <nl> - bool passed = true ; <nl> - int lastType = CV_32F ; <nl> - <nl> - if ( TargetArchs : : builtWith ( NATIVE_DOUBLE ) & & DeviceInfo ( ) . supports ( NATIVE_DOUBLE ) ) <nl> - lastType = CV_64F ; <nl> - <nl> - for ( int i = 0 ; i < = lastType & & passed ; + + i ) <nl> - { <nl> - for ( int j = 0 ; j < = lastType & & passed ; + + j ) <nl> - { <nl> - for ( int c = 1 ; c < 5 & & passed ; + + c ) <nl> - { <nl> - const int src_type = CV_MAKETYPE ( i , c ) ; <nl> - const int dst_type = j ; <nl> - <nl> - cv : : RNG & rng = ts - > get_rng ( ) ; <nl> - <nl> - Mat cpumatsrc ( img_size , src_type ) ; <nl> - rng . fill ( cpumatsrc , RNG : : UNIFORM , Scalar : : all ( 0 ) , Scalar : : all ( 300 ) ) ; <nl> - <nl> - GpuMat gpumatsrc ( cpumatsrc ) ; <nl> - Mat cpumatdst ; <nl> - GpuMat gpumatdst ; <nl> - <nl> - cpumatsrc . convertTo ( cpumatdst , dst_type , 0 . 5 , 3 . 0 ) ; <nl> - gpumatsrc . convertTo ( gpumatdst , dst_type , 0 . 5 , 3 . 0 ) ; <nl> - <nl> - double r = norm ( cpumatdst , ( Mat ) gpumatdst , NORM_INF ) ; <nl> - if ( r > 1 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , <nl> - " \ nFAILED : SRC_TYPE = % sC % d DST_TYPE = % s NORM = % f \ n " , <nl> - types_str [ i ] , c , types_str [ j ] , r ) ; <nl> - passed = false ; <nl> - } <nl> - } <nl> - } <nl> - } <nl> - <nl> - ts - > set_failed_test_info ( passed ? cvtest : : TS : : OK : cvtest : : TS : : FAIL_GENERIC ) ; <nl> - } <nl> - <nl> - TEST ( GpuMat_convertTo , accuracy ) { CV_GpuMatOpConvertToTest test ; test . safe_run ( ) ; } <nl> deleted file mode 100644 <nl> index dc1e2280bde . . 00000000000 <nl> mmm a / modules / gpu / test / test_operator_copy_to . cpp <nl> ppp / dev / null <nl> <nl> - / * M / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / <nl> - / / IMPORTANT : READ BEFORE DOWNLOADING , COPYING , INSTALLING OR USING . <nl> - / / <nl> - / / By downloading , copying , installing or using the software you agree to this license . <nl> - / / If you do not agree to this license , do not download , install , <nl> - / / copy or use the software . <nl> - / / <nl> - / / <nl> - / / Intel License Agreement <nl> - / / For Open Source Computer Vision Library <nl> - / / <nl> - / / Copyright ( C ) 2000 , Intel Corporation , all rights reserved . <nl> - / / Third party copyrights are property of their respective owners . <nl> - / / <nl> - / / Redistribution and use in source and binary forms , with or without modification , <nl> - / / are permitted provided that the following conditions are met : <nl> - / / <nl> - / / * Redistribution ' s of source code must retain the above copyright notice , <nl> - / / this list of conditions and the following disclaimer . <nl> - / / <nl> - / / * Redistribution ' s in binary form must reproduce the above copyright notice , <nl> - / / this list of conditions and the following disclaimer in the documentation <nl> - / / and / or other materials provided with the distribution . <nl> - / / <nl> - / / * The name of Intel Corporation may not be used to endorse or promote products <nl> - / / derived from this software without specific prior written permission . <nl> - / / <nl> - / / This software is provided by the copyright holders and contributors " as is " and <nl> - / / any express or implied warranties , including , but not limited to , the implied <nl> - / / warranties of merchantability and fitness for a particular purpose are disclaimed . <nl> - / / In no event shall the Intel Corporation or contributors be liable for any direct , <nl> - / / indirect , incidental , special , exemplary , or consequential damages <nl> - / / ( including , but not limited to , procurement of substitute goods or services ; <nl> - / / loss of use , data , or profits ; or business interruption ) however caused <nl> - / / and on any theory of liability , whether in contract , strict liability , <nl> - / / or tort ( including negligence or otherwise ) arising in any way out of <nl> - / / the use of this software , even if advised of the possibility of such damage . <nl> - / / <nl> - / / M * / <nl> - <nl> - # include " test_precomp . hpp " <nl> - # include < fstream > <nl> - # include < iterator > <nl> - # include < numeric > <nl> - # include < iomanip > / / for cout < < setw ( ) <nl> - <nl> - using namespace cv ; <nl> - using namespace std ; <nl> - using namespace gpu ; <nl> - <nl> - class CV_GpuMatOpCopyToTest : public cvtest : : BaseTest <nl> - { <nl> - public : <nl> - CV_GpuMatOpCopyToTest ( ) <nl> - { <nl> - rows = 234 ; <nl> - cols = 123 ; <nl> - } <nl> - ~ CV_GpuMatOpCopyToTest ( ) { } <nl> - <nl> - protected : <nl> - void run ( int ) ; <nl> - template < typename T > <nl> - void print_mat ( const T & mat , const std : : string & name ) const ; <nl> - bool compare_matrix ( cv : : Mat & cpumat , gpu : : GpuMat & gpumat ) ; <nl> - <nl> - private : <nl> - int rows ; <nl> - int cols ; <nl> - } ; <nl> - <nl> - template < typename T > <nl> - void CV_GpuMatOpCopyToTest : : print_mat ( const T & mat , const std : : string & name ) const { cv : : imshow ( name , mat ) ; } <nl> - <nl> - bool CV_GpuMatOpCopyToTest : : compare_matrix ( cv : : Mat & cpumat , gpu : : GpuMat & gpumat ) <nl> - { <nl> - Mat cmat ( cpumat . size ( ) , cpumat . type ( ) , Scalar : : all ( 0 ) ) ; <nl> - GpuMat gmat ( cmat ) ; <nl> - <nl> - Mat cpumask ( cpumat . size ( ) , CV_8U ) ; <nl> - <nl> - cv : : RNG & rng = ts - > get_rng ( ) ; <nl> - <nl> - rng . fill ( cpumask , RNG : : NORMAL , Scalar : : all ( 0 ) , Scalar : : all ( 127 ) ) ; <nl> - <nl> - threshold ( cpumask , cpumask , 0 , 127 , THRESH_BINARY ) ; <nl> - <nl> - GpuMat gpumask ( cpumask ) ; <nl> - <nl> - / / int64 time = getTickCount ( ) ; <nl> - cpumat . copyTo ( cmat , cpumask ) ; <nl> - / / int64 time1 = getTickCount ( ) ; <nl> - gpumat . copyTo ( gmat , gpumask ) ; <nl> - / / int64 time2 = getTickCount ( ) ; <nl> - <nl> - / / std : : cout < < " \ ntime cpu : " < < std : : fixed < < std : : setprecision ( 12 ) < < 1 . 0 / double ( ( time1 - time ) / ( double ) getTickFrequency ( ) ) ; <nl> - / / std : : cout < < " \ ntime gpu : " < < std : : fixed < < std : : setprecision ( 12 ) < < 1 . 0 / double ( ( time2 - time1 ) / ( double ) getTickFrequency ( ) ) ; <nl> - / / std : : cout < < " \ n " ; <nl> - <nl> - # ifdef PRINT_MATRIX <nl> - print_mat ( cmat , " cpu mat " ) ; <nl> - print_mat ( gmat , " gpu mat " ) ; <nl> - print_mat ( cpumask , " cpu mask " ) ; <nl> - print_mat ( gpumask , " gpu mask " ) ; <nl> - cv : : waitKey ( 0 ) ; <nl> - # endif <nl> - <nl> - double ret = norm ( cmat , ( Mat ) gmat ) ; <nl> - <nl> - if ( ret < 1 . 0 ) <nl> - return true ; <nl> - else <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ nNorm : % f \ n " , ret ) ; <nl> - return false ; <nl> - } <nl> - } <nl> - <nl> - void CV_GpuMatOpCopyToTest : : run ( int / * start_from * / ) <nl> - { <nl> - bool is_test_good = true ; <nl> - <nl> - int lastType = CV_32F ; <nl> - <nl> - if ( TargetArchs : : builtWith ( NATIVE_DOUBLE ) & & DeviceInfo ( ) . supports ( NATIVE_DOUBLE ) ) <nl> - lastType = CV_64F ; <nl> - <nl> - for ( int i = 0 ; i < = lastType ; i + + ) <nl> - { <nl> - Mat cpumat ( rows , cols , i ) ; <nl> - cpumat . setTo ( Scalar : : all ( 127 ) ) ; <nl> - <nl> - GpuMat gpumat ( cpumat ) ; <nl> - <nl> - is_test_good & = compare_matrix ( cpumat , gpumat ) ; <nl> - } <nl> - <nl> - if ( is_test_good = = true ) <nl> - ts - > set_failed_test_info ( cvtest : : TS : : OK ) ; <nl> - else <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_GENERIC ) ; <nl> - } <nl> - <nl> - TEST ( GpuMat_copyTo , accuracy ) { CV_GpuMatOpCopyToTest test ; test . safe_run ( ) ; } <nl> deleted file mode 100644 <nl> index f09f4117147 . . 00000000000 <nl> mmm a / modules / gpu / test / test_operator_set_to . cpp <nl> ppp / dev / null <nl> <nl> - / * M / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / <nl> - / / IMPORTANT : READ BEFORE DOWNLOADING , COPYING , INSTALLING OR USING . <nl> - / / <nl> - / / By downloading , copying , installing or using the software you agree to this license . <nl> - / / If you do not agree to this license , do not download , install , <nl> - / / copy or use the software . <nl> - / / <nl> - / / <nl> - / / Intel License Agreement <nl> - / / For Open Source Computer Vision Library <nl> - / / <nl> - / / Copyright ( C ) 2000 , Intel Corporation , all rights reserved . <nl> - / / Third party copyrights are property of their respective owners . <nl> - / / <nl> - / / Redistribution and use in source and binary forms , with or without modification , <nl> - / / are permitted provided that the following conditions are met : <nl> - / / <nl> - / / * Redistribution ' s of source code must retain the above copyright notice , <nl> - / / this list of conditions and the following disclaimer . <nl> - / / <nl> - / / * Redistribution ' s in binary form must reproduce the above copyright notice , <nl> - / / this list of conditions and the following disclaimer in the documentation <nl> - / / and / or other materials provided with the distribution . <nl> - / / <nl> - / / * The name of Intel Corporation may not be used to endorse or promote products <nl> - / / derived from this software without specific prior written permission . <nl> - / / <nl> - / / This software is provided by the copyright holders and contributors " as is " and <nl> - / / any express or implied warranties , including , but not limited to , the implied <nl> - / / warranties of merchantability and fitness for a particular purpose are disclaimed . <nl> - / / In no event shall the Intel Corporation or contributors be liable for any direct , <nl> - / / indirect , incidental , special , exemplary , or consequential damages <nl> - / / ( including , but not limited to , procurement of substitute goods or services ; <nl> - / / loss of use , data , or profits ; or business interruption ) however caused <nl> - / / and on any theory of liability , whether in contract , strict liability , <nl> - / / or tort ( including negligence or otherwise ) arising in any way out of <nl> - / / the use of this software , even if advised of the possibility of such damage . <nl> - / / <nl> - / / M * / <nl> - <nl> - # include " test_precomp . hpp " <nl> - <nl> - using namespace cv ; <nl> - using namespace std ; <nl> - using namespace gpu ; <nl> - <nl> - class CV_GpuMatOpSetToTest : public cvtest : : BaseTest <nl> - { <nl> - public : <nl> - CV_GpuMatOpSetToTest ( ) ; <nl> - ~ CV_GpuMatOpSetToTest ( ) { } <nl> - <nl> - protected : <nl> - void run ( int ) ; <nl> - <nl> - bool testSetTo ( cv : : Mat & cpumat , gpu : : GpuMat & gpumat , const cv : : Mat & cpumask = cv : : Mat ( ) , const cv : : gpu : : GpuMat & gpumask = cv : : gpu : : GpuMat ( ) ) ; <nl> - <nl> - private : <nl> - int rows ; <nl> - int cols ; <nl> - Scalar s ; <nl> - } ; <nl> - <nl> - CV_GpuMatOpSetToTest : : CV_GpuMatOpSetToTest ( ) <nl> - { <nl> - rows = 35 ; <nl> - cols = 67 ; <nl> - <nl> - s . val [ 0 ] = 127 . 0 ; <nl> - s . val [ 1 ] = 127 . 0 ; <nl> - s . val [ 2 ] = 127 . 0 ; <nl> - s . val [ 3 ] = 127 . 0 ; <nl> - } <nl> - <nl> - bool CV_GpuMatOpSetToTest : : testSetTo ( cv : : Mat & cpumat , gpu : : GpuMat & gpumat , const cv : : Mat & cpumask , const cv : : gpu : : GpuMat & gpumask ) <nl> - { <nl> - cpumat . setTo ( s , cpumask ) ; <nl> - gpumat . setTo ( s , gpumask ) ; <nl> - <nl> - double ret = norm ( cpumat , ( Mat ) gpumat , NORM_INF ) ; <nl> - <nl> - if ( ret < std : : numeric_limits < double > : : epsilon ( ) ) <nl> - return true ; <nl> - else <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ nNorm : % f \ n " , ret ) ; <nl> - return false ; <nl> - } <nl> - } <nl> - <nl> - void CV_GpuMatOpSetToTest : : run ( int / * start_from * / ) <nl> - { <nl> - bool is_test_good = true ; <nl> - <nl> - cv : : Mat cpumask ( rows , cols , CV_8UC1 ) ; <nl> - cv : : RNG & rng = ts - > get_rng ( ) ; <nl> - rng . fill ( cpumask , RNG : : UNIFORM , cv : : Scalar : : all ( 0 . 0 ) , cv : : Scalar ( 1 . 5 ) ) ; <nl> - cv : : gpu : : GpuMat gpumask ( cpumask ) ; <nl> - <nl> - int lastType = CV_32F ; <nl> - <nl> - if ( TargetArchs : : builtWith ( NATIVE_DOUBLE ) & & DeviceInfo ( ) . supports ( NATIVE_DOUBLE ) ) <nl> - lastType = CV_64F ; <nl> - <nl> - for ( int i = 0 ; i < = lastType ; i + + ) <nl> - { <nl> - for ( int cn = 1 ; cn < = 4 ; + + cn ) <nl> - { <nl> - int mat_type = CV_MAKETYPE ( i , cn ) ; <nl> - Mat cpumat ( rows , cols , mat_type , Scalar : : all ( 0 ) ) ; <nl> - GpuMat gpumat ( cpumat ) ; <nl> - is_test_good & = testSetTo ( cpumat , gpumat , cpumask , gpumask ) ; <nl> - } <nl> - } <nl> - <nl> - if ( is_test_good = = true ) <nl> - ts - > set_failed_test_info ( cvtest : : TS : : OK ) ; <nl> - else <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_GENERIC ) ; <nl> - } <nl> - <nl> - TEST ( GpuMat_setTo , accuracy ) { CV_GpuMatOpSetToTest test ; test . safe_run ( ) ; } <nl> mmm a / modules / gpu / test / test_precomp . cpp <nl> ppp b / modules / gpu / test / test_precomp . cpp <nl> @ @ - 1 + 1 , 42 @ @ <nl> + / * M / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / <nl> + / / IMPORTANT : READ BEFORE DOWNLOADING , COPYING , INSTALLING OR USING . <nl> + / / <nl> + / / By downloading , copying , installing or using the software you agree to this license . <nl> + / / If you do not agree to this license , do not download , install , <nl> + / / copy or use the software . <nl> + / / <nl> + / / <nl> + / / Intel License Agreement <nl> + / / For Open Source Computer Vision Library <nl> + / / <nl> + / / Copyright ( C ) 2000 , Intel Corporation , all rights reserved . <nl> + / / Third party copyrights are property of their respective owners . <nl> + / / <nl> + / / Redistribution and use in source and binary forms , with or without modification , <nl> + / / are permitted provided that the following conditions are met : <nl> + / / <nl> + / / * Redistribution ' s of source code must retain the above copyright notice , <nl> + / / this list of conditions and the following disclaimer . <nl> + / / <nl> + / / * Redistribution ' s in binary form must reproduce the above copyright notice , <nl> + / / this list of conditions and the following disclaimer in the documentation <nl> + / / and / or other materials provided with the distribution . <nl> + / / <nl> + / / * The name of Intel Corporation may not be used to endorse or promote products <nl> + / / derived from this software without specific prior written permission . <nl> + / / <nl> + / / This software is provided by the copyright holders and contributors " as is " and <nl> + / / any express or implied warranties , including , but not limited to , the implied <nl> + / / warranties of merchantability and fitness for a particular purpose are disclaimed . <nl> + / / In no event shall the Intel Corporation or contributors be liable for any direct , <nl> + / / indirect , incidental , special , exemplary , or consequential damages <nl> + / / ( including , but not limited to , procurement of substitute goods or services ; <nl> + / / loss of use , data , or profits ; or business interruption ) however caused <nl> + / / and on any theory of liability , whether in contract , strict liability , <nl> + / / or tort ( including negligence or otherwise ) arising in any way out of <nl> + / / the use of this software , even if advised of the possibility of such damage . <nl> + / / <nl> + / / M * / <nl> + <nl> # include " test_precomp . hpp " <nl> mmm a / modules / gpu / test / test_precomp . hpp <nl> ppp b / modules / gpu / test / test_precomp . hpp <nl> <nl> + / * M / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / <nl> + / / IMPORTANT : READ BEFORE DOWNLOADING , COPYING , INSTALLING OR USING . <nl> + / / <nl> + / / By downloading , copying , installing or using the software you agree to this license . <nl> + / / If you do not agree to this license , do not download , install , <nl> + / / copy or use the software . <nl> + / / <nl> + / / <nl> + / / Intel License Agreement <nl> + / / For Open Source Computer Vision Library <nl> + / / <nl> + / / Copyright ( C ) 2000 , Intel Corporation , all rights reserved . <nl> + / / Third party copyrights are property of their respective owners . <nl> + / / <nl> + / / Redistribution and use in source and binary forms , with or without modification , <nl> + / / are permitted provided that the following conditions are met : <nl> + / / <nl> + / / * Redistribution ' s of source code must retain the above copyright notice , <nl> + / / this list of conditions and the following disclaimer . <nl> + / / <nl> + / / * Redistribution ' s in binary form must reproduce the above copyright notice , <nl> + / / this list of conditions and the following disclaimer in the documentation <nl> + / / and / or other materials provided with the distribution . <nl> + / / <nl> + / / * The name of Intel Corporation may not be used to endorse or promote products <nl> + / / derived from this software without specific prior written permission . <nl> + / / <nl> + / / This software is provided by the copyright holders and contributors " as is " and <nl> + / / any express or implied warranties , including , but not limited to , the implied <nl> + / / warranties of merchantability and fitness for a particular purpose are disclaimed . <nl> + / / In no event shall the Intel Corporation or contributors be liable for any direct , <nl> + / / indirect , incidental , special , exemplary , or consequential damages <nl> + / / ( including , but not limited to , procurement of substitute goods or services ; <nl> + / / loss of use , data , or profits ; or business interruption ) however caused <nl> + / / and on any theory of liability , whether in contract , strict liability , <nl> + / / or tort ( including negligence or otherwise ) arising in any way out of <nl> + / / the use of this software , even if advised of the possibility of such damage . <nl> + / / <nl> + / / M * / <nl> + <nl> # ifndef __OPENCV_TEST_PRECOMP_HPP__ <nl> # define __OPENCV_TEST_PRECOMP_HPP__ <nl> <nl> - # include < iostream > <nl> + # include < cmath > <nl> + # include < cstdio > <nl> + # include < fstream > <nl> + # include < sstream > <nl> # include < limits > <nl> + # include < string > <nl> + # include < algorithm > <nl> + # include < iterator > <nl> # include " cvconfig . h " <nl> # include " opencv2 / core / core . hpp " <nl> # include " opencv2 / highgui / highgui . hpp " <nl> # include " opencv2 / calib3d / calib3d . hpp " <nl> + # include " opencv2 / imgproc / imgproc . hpp " <nl> # include " opencv2 / ts / ts . hpp " <nl> # include " opencv2 / gpu / gpu . hpp " <nl> + # include " test_gpu_base . hpp " <nl> <nl> # endif <nl> deleted file mode 100644 <nl> index ca5f4a97273 . . 00000000000 <nl> mmm a / modules / gpu / test / test_split_merge . cpp <nl> ppp / dev / null <nl> <nl> - / * M / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / <nl> - / / IMPORTANT : READ BEFORE DOWNLOADING , COPYING , INSTALLING OR USING . <nl> - / / <nl> - / / By downloading , copying , installing or using the software you agree to this license . <nl> - / / If you do not agree to this license , do not download , install , <nl> - / / copy or use the software . <nl> - / / <nl> - / / <nl> - / / License Agreement <nl> - / / For Open Source Computer Vision Library <nl> - / / <nl> - / / Copyright ( C ) 2000 - 2008 , Intel Corporation , all rights reserved . <nl> - / / Copyright ( C ) 2009 , Willow Garage Inc . , all rights reserved . <nl> - / / Third party copyrights are property of their respective owners . <nl> - / / <nl> - / / Redistribution and use in source and binary forms , with or without modification , <nl> - / / are permitted provided that the following conditions are met : <nl> - / / <nl> - / / * Redistribution ' s of source code must retain the above copyright notice , <nl> - / / this list of conditions and the following disclaimer . <nl> - / / <nl> - / / * Redistribution ' s in binary form must reproduce the above copyright notice , <nl> - / / this list of conditions and the following disclaimer in the documentation <nl> - / / and / or other GpuMaterials provided with the distribution . <nl> - / / <nl> - / / * The name of the copyright holders may not be used to endorse or promote products <nl> - / / derived from this software without specific prior written permission . <nl> - / / <nl> - / / This software is provided by the copyright holders and contributors " as is " and <nl> - / / any express or bpied warranties , including , but not limited to , the bpied <nl> - / / warranties of merchantability and fitness for a particular purpose are disclaimed . <nl> - / / In no event shall the Intel Corporation or contributors be liable for any direct , <nl> - / / indirect , incidental , special , exemplary , or consequential damages <nl> - / / ( including , but not limited to , procurement of substitute goods or services ; <nl> - / / loss of use , data , or profits ; or business interruption ) however caused <nl> - / / and on any theory of liability , whether in contract , strict liability , <nl> - / / or tort ( including negligence or otherwise ) arising in any way out of <nl> - / / the use of this software , even if advised of the possibility of such damage . <nl> - / / <nl> - / / M * / <nl> - <nl> - # include " test_precomp . hpp " <nl> - <nl> - using namespace std ; <nl> - using namespace cv ; <nl> - <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / Merge <nl> - <nl> - struct CV_MergeTest : public cvtest : : BaseTest <nl> - { <nl> - void can_merge ( size_t rows , size_t cols ) ; <nl> - void can_merge_submatrixes ( size_t rows , size_t cols ) ; <nl> - void run ( int ) ; <nl> - } ; <nl> - <nl> - <nl> - void CV_MergeTest : : can_merge ( size_t rows , size_t cols ) <nl> - { <nl> - bool double_ok = gpu : : TargetArchs : : builtWith ( gpu : : NATIVE_DOUBLE ) & & <nl> - gpu : : DeviceInfo ( ) . supports ( gpu : : NATIVE_DOUBLE ) ; <nl> - size_t depth_end = double_ok ? CV_64F : CV_32F ; <nl> - <nl> - for ( size_t num_channels = 1 ; num_channels < = 4 ; + + num_channels ) <nl> - for ( size_t depth = CV_8U ; depth < = depth_end ; + + depth ) <nl> - { <nl> - vector < Mat > src ; <nl> - for ( size_t i = 0 ; i < num_channels ; + + i ) <nl> - src . push_back ( Mat ( rows , cols , depth , Scalar : : all ( static_cast < double > ( i ) ) ) ) ; <nl> - <nl> - Mat dst ( rows , cols , CV_MAKETYPE ( depth , num_channels ) ) ; <nl> - <nl> - cv : : merge ( src , dst ) ; <nl> - <nl> - vector < gpu : : GpuMat > dev_src ; <nl> - for ( size_t i = 0 ; i < num_channels ; + + i ) <nl> - dev_src . push_back ( gpu : : GpuMat ( src [ i ] ) ) ; <nl> - <nl> - gpu : : GpuMat dev_dst ( rows , cols , CV_MAKETYPE ( depth , num_channels ) ) ; <nl> - cv : : gpu : : merge ( dev_src , dev_dst ) ; <nl> - <nl> - Mat host_dst = dev_dst ; <nl> - <nl> - double err = norm ( dst , host_dst , NORM_INF ) ; <nl> - <nl> - if ( err > 1e - 3 ) <nl> - { <nl> - / / ts - > printf ( cvtest : : TS : : CONSOLE , " \ nNorm : % f \ n " , err ) ; <nl> - / / ts - > printf ( cvtest : : TS : : CONSOLE , " Depth : % d \ n " , depth ) ; <nl> - / / ts - > printf ( cvtest : : TS : : CONSOLE , " Rows : % d \ n " , rows ) ; <nl> - / / ts - > printf ( cvtest : : TS : : CONSOLE , " Cols : % d \ n " , cols ) ; <nl> - / / ts - > printf ( cvtest : : TS : : CONSOLE , " NumChannels : % d \ n " , num_channels ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return ; <nl> - } <nl> - } <nl> - } <nl> - <nl> - <nl> - void CV_MergeTest : : can_merge_submatrixes ( size_t rows , size_t cols ) <nl> - { <nl> - bool double_ok = gpu : : TargetArchs : : builtWith ( gpu : : NATIVE_DOUBLE ) & & <nl> - gpu : : DeviceInfo ( ) . supports ( gpu : : NATIVE_DOUBLE ) ; <nl> - size_t depth_end = double_ok ? CV_64F : CV_32F ; <nl> - <nl> - for ( size_t num_channels = 1 ; num_channels < = 4 ; + + num_channels ) <nl> - for ( size_t depth = CV_8U ; depth < = depth_end ; + + depth ) <nl> - { <nl> - vector < Mat > src ; <nl> - for ( size_t i = 0 ; i < num_channels ; + + i ) <nl> - { <nl> - Mat m ( rows * 2 , cols * 2 , depth , Scalar : : all ( static_cast < double > ( i ) ) ) ; <nl> - src . push_back ( m ( Range ( rows / 2 , rows / 2 + rows ) , Range ( cols / 2 , cols / 2 + cols ) ) ) ; <nl> - } <nl> - <nl> - Mat dst ( rows , cols , CV_MAKETYPE ( depth , num_channels ) ) ; <nl> - <nl> - cv : : merge ( src , dst ) ; <nl> - <nl> - vector < gpu : : GpuMat > dev_src ; <nl> - for ( size_t i = 0 ; i < num_channels ; + + i ) <nl> - dev_src . push_back ( gpu : : GpuMat ( src [ i ] ) ) ; <nl> - <nl> - gpu : : GpuMat dev_dst ( rows , cols , CV_MAKETYPE ( depth , num_channels ) ) ; <nl> - cv : : gpu : : merge ( dev_src , dev_dst ) ; <nl> - <nl> - Mat host_dst = dev_dst ; <nl> - <nl> - double err = norm ( dst , host_dst , NORM_INF ) ; <nl> - <nl> - if ( err > 1e - 3 ) <nl> - { <nl> - / / ts - > printf ( cvtest : : TS : : CONSOLE , " \ nNorm : % f \ n " , err ) ; <nl> - / / ts - > printf ( cvtest : : TS : : CONSOLE , " Depth : % d \ n " , depth ) ; <nl> - / / ts - > printf ( cvtest : : TS : : CONSOLE , " Rows : % d \ n " , rows ) ; <nl> - / / ts - > printf ( cvtest : : TS : : CONSOLE , " Cols : % d \ n " , cols ) ; <nl> - / / ts - > printf ( cvtest : : TS : : CONSOLE , " NumChannels : % d \ n " , num_channels ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return ; <nl> - } <nl> - } <nl> - } <nl> - <nl> - void CV_MergeTest : : run ( int ) <nl> - { <nl> - can_merge ( 1 , 1 ) ; <nl> - can_merge ( 1 , 7 ) ; <nl> - can_merge ( 53 , 7 ) ; <nl> - can_merge_submatrixes ( 1 , 1 ) ; <nl> - can_merge_submatrixes ( 1 , 7 ) ; <nl> - can_merge_submatrixes ( 53 , 7 ) ; <nl> - } <nl> - <nl> - <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / Split <nl> - <nl> - struct CV_SplitTest : public cvtest : : BaseTest <nl> - { <nl> - void can_split ( size_t rows , size_t cols ) ; <nl> - void can_split_submatrix ( size_t rows , size_t cols ) ; <nl> - void run ( int ) ; <nl> - } ; <nl> - <nl> - void CV_SplitTest : : can_split ( size_t rows , size_t cols ) <nl> - { <nl> - bool double_ok = gpu : : TargetArchs : : builtWith ( gpu : : NATIVE_DOUBLE ) & & <nl> - gpu : : DeviceInfo ( ) . supports ( gpu : : NATIVE_DOUBLE ) ; <nl> - size_t depth_end = double_ok ? CV_64F : CV_32F ; <nl> - <nl> - for ( size_t num_channels = 1 ; num_channels < = 4 ; + + num_channels ) <nl> - for ( size_t depth = CV_8U ; depth < = depth_end ; + + depth ) <nl> - { <nl> - Mat src ( rows , cols , CV_MAKETYPE ( depth , num_channels ) , Scalar ( 1 . 0 , 2 . 0 , 3 . 0 , 4 . 0 ) ) ; <nl> - vector < Mat > dst ; <nl> - cv : : split ( src , dst ) ; <nl> - <nl> - gpu : : GpuMat dev_src ( src ) ; <nl> - vector < gpu : : GpuMat > dev_dst ; <nl> - cv : : gpu : : split ( dev_src , dev_dst ) ; <nl> - <nl> - if ( dev_dst . size ( ) ! = dst . size ( ) ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " Bad output sizes " ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - } <nl> - <nl> - for ( size_t i = 0 ; i < num_channels ; + + i ) <nl> - { <nl> - Mat host_dst = dev_dst [ i ] ; <nl> - double err = norm ( dst [ i ] , host_dst , NORM_INF ) ; <nl> - <nl> - if ( err > 1e - 3 ) <nl> - { <nl> - / / ts - > printf ( cvtest : : TS : : CONSOLE , " \ nNorm : % f \ n " , err ) ; <nl> - / / ts - > printf ( cvtest : : TS : : CONSOLE , " Depth : % d \ n " , depth ) ; <nl> - / / ts - > printf ( cvtest : : TS : : CONSOLE , " Rows : % d \ n " , rows ) ; <nl> - / / ts - > printf ( cvtest : : TS : : CONSOLE , " Cols : % d \ n " , cols ) ; <nl> - / / ts - > printf ( cvtest : : TS : : CONSOLE , " NumChannels : % d \ n " , num_channels ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return ; <nl> - } <nl> - } <nl> - } <nl> - } <nl> - <nl> - void CV_SplitTest : : can_split_submatrix ( size_t rows , size_t cols ) <nl> - { <nl> - bool double_ok = gpu : : TargetArchs : : builtWith ( gpu : : NATIVE_DOUBLE ) & & <nl> - gpu : : DeviceInfo ( ) . supports ( gpu : : NATIVE_DOUBLE ) ; <nl> - size_t depth_end = double_ok ? CV_64F : CV_32F ; <nl> - <nl> - for ( size_t num_channels = 1 ; num_channels < = 4 ; + + num_channels ) <nl> - for ( size_t depth = CV_8U ; depth < = depth_end ; + + depth ) <nl> - { <nl> - Mat src_data ( rows * 2 , cols * 2 , CV_MAKETYPE ( depth , num_channels ) , Scalar ( 1 . 0 , 2 . 0 , 3 . 0 , 4 . 0 ) ) ; <nl> - Mat src ( src_data ( Range ( rows / 2 , rows / 2 + rows ) , Range ( cols / 2 , cols / 2 + cols ) ) ) ; <nl> - vector < Mat > dst ; <nl> - cv : : split ( src , dst ) ; <nl> - <nl> - gpu : : GpuMat dev_src ( src ) ; <nl> - vector < gpu : : GpuMat > dev_dst ; <nl> - cv : : gpu : : split ( dev_src , dev_dst ) ; <nl> - <nl> - if ( dev_dst . size ( ) ! = dst . size ( ) ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : CONSOLE , " Bad output sizes " ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - } <nl> - <nl> - for ( size_t i = 0 ; i < num_channels ; + + i ) <nl> - { <nl> - Mat host_dst = dev_dst [ i ] ; <nl> - double err = norm ( dst [ i ] , host_dst , NORM_INF ) ; <nl> - <nl> - if ( err > 1e - 3 ) <nl> - { <nl> - / / ts - > printf ( cvtest : : TS : : CONSOLE , " \ nNorm : % f \ n " , err ) ; <nl> - / / ts - > printf ( cvtest : : TS : : CONSOLE , " Depth : % d \ n " , depth ) ; <nl> - / / ts - > printf ( cvtest : : TS : : CONSOLE , " Rows : % d \ n " , rows ) ; <nl> - / / ts - > printf ( cvtest : : TS : : CONSOLE , " Cols : % d \ n " , cols ) ; <nl> - / / ts - > printf ( cvtest : : TS : : CONSOLE , " NumChannels : % d \ n " , num_channels ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return ; <nl> - } <nl> - } <nl> - } <nl> - } <nl> - <nl> - void CV_SplitTest : : run ( int ) <nl> - { <nl> - can_split ( 1 , 1 ) ; <nl> - can_split ( 1 , 7 ) ; <nl> - can_split ( 7 , 53 ) ; <nl> - can_split_submatrix ( 1 , 1 ) ; <nl> - can_split_submatrix ( 1 , 7 ) ; <nl> - can_split_submatrix ( 7 , 53 ) ; <nl> - } <nl> - <nl> - <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / Split and merge <nl> - <nl> - struct CV_SplitMergeTest : public cvtest : : BaseTest <nl> - { <nl> - void can_split_merge ( size_t rows , size_t cols ) ; <nl> - void run ( int ) ; <nl> - } ; <nl> - <nl> - void CV_SplitMergeTest : : can_split_merge ( size_t rows , size_t cols ) { <nl> - bool double_ok = gpu : : TargetArchs : : builtWith ( gpu : : NATIVE_DOUBLE ) & & <nl> - gpu : : DeviceInfo ( ) . supports ( gpu : : NATIVE_DOUBLE ) ; <nl> - size_t depth_end = double_ok ? CV_64F : CV_32F ; <nl> - <nl> - for ( size_t num_channels = 1 ; num_channels < = 4 ; + + num_channels ) <nl> - for ( size_t depth = CV_8U ; depth < = depth_end ; + + depth ) <nl> - { <nl> - Mat orig ( rows , cols , CV_MAKETYPE ( depth , num_channels ) , Scalar ( 1 . 0 , 2 . 0 , 3 . 0 , 4 . 0 ) ) ; <nl> - gpu : : GpuMat dev_orig ( orig ) ; <nl> - vector < gpu : : GpuMat > dev_vec ; <nl> - cv : : gpu : : split ( dev_orig , dev_vec ) ; <nl> - <nl> - gpu : : GpuMat dev_final ( rows , cols , CV_MAKETYPE ( depth , num_channels ) ) ; <nl> - cv : : gpu : : merge ( dev_vec , dev_final ) ; <nl> - <nl> - double err = cv : : norm ( ( Mat ) dev_orig , ( Mat ) dev_final , NORM_INF ) ; <nl> - if ( err > 1e - 3 ) <nl> - { <nl> - / / ts - > printf ( cvtest : : TS : : CONSOLE , " \ nNorm : % f \ n " , err ) ; <nl> - / / ts - > printf ( cvtest : : TS : : CONSOLE , " Depth : % d \ n " , depth ) ; <nl> - / / ts - > printf ( cvtest : : TS : : CONSOLE , " Rows : % d \ n " , rows ) ; <nl> - / / ts - > printf ( cvtest : : TS : : CONSOLE , " Cols : % d \ n " , cols ) ; <nl> - / / ts - > printf ( cvtest : : TS : : CONSOLE , " NumChannels : % d \ n " , num_channels ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_INVALID_OUTPUT ) ; <nl> - return ; <nl> - } <nl> - } <nl> - } <nl> - <nl> - <nl> - void CV_SplitMergeTest : : run ( int ) <nl> - { <nl> - can_split_merge ( 1 , 1 ) ; <nl> - can_split_merge ( 1 , 7 ) ; <nl> - can_split_merge ( 7 , 53 ) ; <nl> - } <nl> - <nl> - <nl> - TEST ( merge , accuracy ) { CV_MergeTest test ; test . safe_run ( ) ; } <nl> - TEST ( split , accuracy ) { CV_SplitTest test ; test . safe_run ( ) ; } <nl> - TEST ( split , merge_consistency ) { CV_SplitMergeTest test ; test . safe_run ( ) ; } <nl> deleted file mode 100644 <nl> index 7a4806e6f51 . . 00000000000 <nl> mmm a / modules / gpu / test / test_stereo_bm . cpp <nl> ppp / dev / null <nl> <nl> - / * M / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / <nl> - / / IMPORTANT : READ BEFORE DOWNLOADING , COPYING , INSTALLING OR USING . <nl> - / / <nl> - / / By downloading , copying , installing or using the software you agree to this license . <nl> - / / If you do not agree to this license , do not download , install , <nl> - / / copy or use the software . <nl> - / / <nl> - / / <nl> - / / Intel License Agreement <nl> - / / For Open Source Computer Vision Library <nl> - / / <nl> - / / Copyright ( C ) 2000 , Intel Corporation , all rights reserved . <nl> - / / Third party copyrights are property of their respective owners . <nl> - / / <nl> - / / Redistribution and use in source and binary forms , with or without modification , <nl> - / / are permitted provided that the following conditions are met : <nl> - / / <nl> - / / * Redistribution ' s of source code must retain the above copyright notice , <nl> - / / this list of conditions and the following disclaimer . <nl> - / / <nl> - / / * Redistribution ' s in binary form must reproduce the above copyright notice , <nl> - / / this list of conditions and the following disclaimer in the documentation <nl> - / / and / or other materials provided with the distribution . <nl> - / / <nl> - / / * The name of Intel Corporation may not be used to endorse or promote products <nl> - / / derived from this software without specific prior written permission . <nl> - / / <nl> - / / This software is provided by the copyright holders and contributors " as is " and <nl> - / / any express or implied warranties , including , but not limited to , the implied <nl> - / / warranties of merchantability and fitness for a particular purpose are disclaimed . <nl> - / / In no event shall the Intel Corporation or contributors be liable for any direct , <nl> - / / indirect , incidental , special , exemplary , or consequential damages <nl> - / / ( including , but not limited to , procurement of substitute goods or services ; <nl> - / / loss of use , data , or profits ; or business interruption ) however caused <nl> - / / and on any theory of liability , whether in contract , strict liability , <nl> - / / or tort ( including negligence or otherwise ) arising in any way out of <nl> - / / the use of this software , even if advised of the possibility of such damage . <nl> - / / <nl> - / / M * / <nl> - <nl> - # include " test_precomp . hpp " <nl> - <nl> - using namespace cv ; <nl> - using namespace cv : : gpu ; <nl> - <nl> - struct CV_GpuStereoBMTest : public cvtest : : BaseTest <nl> - { <nl> - void run_stress ( ) <nl> - { <nl> - RNG rng ; <nl> - <nl> - for ( int i = 0 ; i < 10 ; + + i ) <nl> - { <nl> - int winSize = cvRound ( rng . uniform ( 2 , 11 ) ) * 2 + 1 ; <nl> - <nl> - for ( int j = 0 ; j < 10 ; + + j ) <nl> - { <nl> - int ndisp = cvRound ( rng . uniform ( 5 , 32 ) ) * 8 ; <nl> - <nl> - for ( int s = 0 ; s < 10 ; + + s ) <nl> - { <nl> - int w = cvRound ( rng . uniform ( 1024 , 2048 ) ) ; <nl> - int h = cvRound ( rng . uniform ( 768 , 1152 ) ) ; <nl> - <nl> - for ( int p = 0 ; p < 2 ; + + p ) <nl> - { <nl> - / / int winSize = winsz [ i ] ; <nl> - / / int disp = disps [ j ] ; <nl> - Size imgSize ( w , h ) ; / / res [ s ] ; <nl> - int preset = p ; <nl> - <nl> - printf ( " Preset = % d , nidsp = % d , winsz = % d , width = % d , height = % d \ n " , p , ndisp , winSize , imgSize . width , imgSize . height ) ; <nl> - <nl> - GpuMat l ( imgSize , CV_8U ) ; <nl> - GpuMat r ( imgSize , CV_8U ) ; <nl> - <nl> - GpuMat disparity ; <nl> - StereoBM_GPU bm ( preset , ndisp , winSize ) ; <nl> - bm ( l , r , disparity ) ; <nl> - <nl> - <nl> - } <nl> - } <nl> - } <nl> - } <nl> - } <nl> - <nl> - void run ( int ) <nl> - { <nl> - / * run_stress ( ) ; <nl> - return ; * / <nl> - <nl> - cv : : Mat img_l = cv : : imread ( std : : string ( ts - > get_data_path ( ) ) + " stereobm / aloe - L . png " , 0 ) ; <nl> - cv : : Mat img_r = cv : : imread ( std : : string ( ts - > get_data_path ( ) ) + " stereobm / aloe - R . png " , 0 ) ; <nl> - cv : : Mat img_reference = cv : : imread ( std : : string ( ts - > get_data_path ( ) ) + " stereobm / aloe - disp . png " , 0 ) ; <nl> - <nl> - if ( img_l . empty ( ) | | img_r . empty ( ) | | img_reference . empty ( ) ) <nl> - { <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_MISSING_TEST_DATA ) ; <nl> - return ; <nl> - } <nl> - <nl> - cv : : gpu : : GpuMat disp ; <nl> - cv : : gpu : : StereoBM_GPU bm ( 0 , 128 , 19 ) ; <nl> - bm ( cv : : gpu : : GpuMat ( img_l ) , cv : : gpu : : GpuMat ( img_r ) , disp ) ; <nl> - <nl> - disp . convertTo ( disp , img_reference . type ( ) ) ; <nl> - double norm = cv : : norm ( ( Mat ) disp , img_reference , cv : : NORM_INF ) ; <nl> - <nl> - / / cv : : imwrite ( std : : string ( ts - > get_data_path ( ) ) + " stereobm / aloe - disp . png " , disp ) ; <nl> - <nl> - / * cv : : imshow ( " disp " , disp ) ; <nl> - cv : : imshow ( " img_reference " , img_reference ) ; <nl> - <nl> - cv : : Mat diff = ( cv : : Mat ) disp - ( cv : : Mat ) img_reference ; <nl> - cv : : imshow ( " diff " , diff ) ; <nl> - cv : : waitKey ( ) ; * / <nl> - <nl> - if ( norm > = 100 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ nStereoBM norm = % f \ n " , norm ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_GENERIC ) ; <nl> - return ; <nl> - } <nl> - <nl> - ts - > set_failed_test_info ( cvtest : : TS : : OK ) ; <nl> - } <nl> - } ; <nl> - <nl> - TEST ( StereoBM , regression ) { CV_GpuStereoBMTest test ; test . safe_run ( ) ; } <nl> deleted file mode 100644 <nl> index f9632dd283f . . 00000000000 <nl> mmm a / modules / gpu / test / test_stereo_bm_async . cpp <nl> ppp / dev / null <nl> <nl> - / * M / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / <nl> - / / IMPORTANT : READ BEFORE DOWNLOADING , COPYING , INSTALLING OR USING . <nl> - / / <nl> - / / By downloading , copying , installing or using the software you agree to this license . <nl> - / / If you do not agree to this license , do not download , install , <nl> - / / copy or use the software . <nl> - / / <nl> - / / <nl> - / / Intel License Agreement <nl> - / / For Open Source Computer Vision Library <nl> - / / <nl> - / / Copyright ( C ) 2000 , Intel Corporation , all rights reserved . <nl> - / / Third party copyrights are property of their respective owners . <nl> - / / <nl> - / / Redistribution and use in source and binary forms , with or without modification , <nl> - / / are permitted provided that the following conditions are met : <nl> - / / <nl> - / / * Redistribution ' s of source code must retain the above copyright notice , <nl> - / / this list of conditions and the following disclaimer . <nl> - / / <nl> - / / * Redistribution ' s in binary form must reproduce the above copyright notice , <nl> - / / this list of conditions and the following disclaimer in the documentation <nl> - / / and / or other materials provided with the distribution . <nl> - / / <nl> - / / * The name of Intel Corporation may not be used to endorse or promote products <nl> - / / derived from this software without specific prior written permission . <nl> - / / <nl> - / / This software is provided by the copyright holders and contributors " as is " and <nl> - / / any express or implied warranties , including , but not limited to , the implied <nl> - / / warranties of merchantability and fitness for a particular purpose are disclaimed . <nl> - / / In no event shall the Intel Corporation or contributors be liable for any direct , <nl> - / / indirect , incidental , special , exemplary , or consequential damages <nl> - / / ( including , but not limited to , procurement of substitute goods or services ; <nl> - / / loss of use , data , or profits ; or business interruption ) however caused <nl> - / / and on any theory of liability , whether in contract , strict liability , <nl> - / / or tort ( including negligence or otherwise ) arising in any way out of <nl> - / / the use of this software , even if advised of the possibility of such damage . <nl> - / / <nl> - / / M * / <nl> - <nl> - # include " test_precomp . hpp " <nl> - <nl> - using namespace cv ; <nl> - using namespace std ; <nl> - <nl> - struct CV_AsyncStereoBMTest : public cvtest : : BaseTest <nl> - { <nl> - void run ( int / * start_from * / ) <nl> - { <nl> - cv : : Mat img_l = cv : : imread ( std : : string ( ts - > get_data_path ( ) ) + " stereobm / aloe - L . png " , 0 ) ; <nl> - cv : : Mat img_r = cv : : imread ( std : : string ( ts - > get_data_path ( ) ) + " stereobm / aloe - R . png " , 0 ) ; <nl> - cv : : Mat img_reference = cv : : imread ( std : : string ( ts - > get_data_path ( ) ) + " stereobm / aloe - disp . png " , 0 ) ; <nl> - <nl> - if ( img_l . empty ( ) | | img_r . empty ( ) | | img_reference . empty ( ) ) <nl> - { <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_MISSING_TEST_DATA ) ; <nl> - return ; <nl> - } <nl> - <nl> - cv : : gpu : : GpuMat disp ; <nl> - cv : : gpu : : StereoBM_GPU bm ( 0 , 128 , 19 ) ; <nl> - <nl> - cv : : gpu : : Stream stream ; <nl> - <nl> - for ( size_t i = 0 ; i < 50 ; i + + ) <nl> - { <nl> - bm ( cv : : gpu : : GpuMat ( img_l ) , cv : : gpu : : GpuMat ( img_r ) , disp , stream ) ; <nl> - } <nl> - <nl> - stream . waitForCompletion ( ) ; <nl> - disp . convertTo ( disp , img_reference . type ( ) ) ; <nl> - double norm = cv : : norm ( ( Mat ) disp , img_reference , cv : : NORM_INF ) ; <nl> - <nl> - if ( norm > = 100 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ nStereoBM norm = % f \ n " , norm ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_GENERIC ) ; <nl> - return ; <nl> - } <nl> - <nl> - ts - > set_failed_test_info ( cvtest : : TS : : OK ) ; <nl> - } <nl> - } ; <nl> - <nl> - TEST ( StereoBM , async ) { CV_AsyncStereoBMTest test ; test . safe_run ( ) ; } <nl> deleted file mode 100644 <nl> index 77889173751 . . 00000000000 <nl> mmm a / modules / gpu / test / test_stereo_bp . cpp <nl> ppp / dev / null <nl> <nl> - / * M / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / <nl> - / / IMPORTANT : READ BEFORE DOWNLOADING , COPYING , INSTALLING OR USING . <nl> - / / <nl> - / / By downloading , copying , installing or using the software you agree to this license . <nl> - / / If you do not agree to this license , do not download , install , <nl> - / / copy or use the software . <nl> - / / <nl> - / / <nl> - / / Intel License Agreement <nl> - / / For Open Source Computer Vision Library <nl> - / / <nl> - / / Copyright ( C ) 2000 , Intel Corporation , all rights reserved . <nl> - / / Third party copyrights are property of their respective owners . <nl> - / / <nl> - / / Redistribution and use in source and binary forms , with or without modification , <nl> - / / are permitted provided that the following conditions are met : <nl> - / / <nl> - / / * Redistribution ' s of source code must retain the above copyright notice , <nl> - / / this list of conditions and the following disclaimer . <nl> - / / <nl> - / / * Redistribution ' s in binary form must reproduce the above copyright notice , <nl> - / / this list of conditions and the following disclaimer in the documentation <nl> - / / and / or other materials provided with the distribution . <nl> - / / <nl> - / / * The name of Intel Corporation may not be used to endorse or promote products <nl> - / / derived from this software without specific prior written permission . <nl> - / / <nl> - / / This software is provided by the copyright holders and contributors " as is " and <nl> - / / any express or implied warranties , including , but not limited to , the implied <nl> - / / warranties of merchantability and fitness for a particular purpose are disclaimed . <nl> - / / In no event shall the Intel Corporation or contributors be liable for any direct , <nl> - / / indirect , incidental , special , exemplary , or consequential damages <nl> - / / ( including , but not limited to , procurement of substitute goods or services ; <nl> - / / loss of use , data , or profits ; or business interruption ) however caused <nl> - / / and on any theory of liability , whether in contract , strict liability , <nl> - / / or tort ( including negligence or otherwise ) arising in any way out of <nl> - / / the use of this software , even if advised of the possibility of such damage . <nl> - / / <nl> - / / M * / <nl> - <nl> - # include " test_precomp . hpp " <nl> - <nl> - struct CV_GpuStereoBPTest : public cvtest : : BaseTest <nl> - { <nl> - void run ( int ) <nl> - { <nl> - cv : : Mat img_l = cv : : imread ( std : : string ( ts - > get_data_path ( ) ) + " stereobp / aloe - L . png " ) ; <nl> - cv : : Mat img_r = cv : : imread ( std : : string ( ts - > get_data_path ( ) ) + " stereobp / aloe - R . png " ) ; <nl> - cv : : Mat img_template = cv : : imread ( std : : string ( ts - > get_data_path ( ) ) + " stereobp / aloe - disp . png " , 0 ) ; <nl> - <nl> - if ( img_l . empty ( ) | | img_r . empty ( ) | | img_template . empty ( ) ) <nl> - { <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_MISSING_TEST_DATA ) ; <nl> - return ; <nl> - } <nl> - <nl> - { cv : : Mat temp ; cv : : cvtColor ( img_l , temp , CV_BGR2BGRA ) ; cv : : swap ( temp , img_l ) ; } <nl> - { cv : : Mat temp ; cv : : cvtColor ( img_r , temp , CV_BGR2BGRA ) ; cv : : swap ( temp , img_r ) ; } <nl> - <nl> - cv : : gpu : : StereoBeliefPropagation bpm ( 64 , 8 , 2 , 25 , 0 . 1f , 15 , 1 , CV_16S ) ; <nl> - cv : : gpu : : GpuMat disp ; <nl> - <nl> - bpm ( cv : : gpu : : GpuMat ( img_l ) , cv : : gpu : : GpuMat ( img_r ) , disp ) ; <nl> - <nl> - / / cv : : imwrite ( std : : string ( ts - > get_data_path ( ) ) + " stereobp / aloe - disp . png " , disp ) ; <nl> - <nl> - disp . convertTo ( disp , img_template . type ( ) ) ; <nl> - <nl> - double norm = cv : : norm ( ( cv : : Mat ) disp , img_template , cv : : NORM_INF ) ; <nl> - if ( norm > = 0 . 5 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ nStereoBP norm = % f \ n " , norm ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_GENERIC ) ; <nl> - return ; <nl> - } <nl> - <nl> - ts - > set_failed_test_info ( cvtest : : TS : : OK ) ; <nl> - } <nl> - } ; <nl> - <nl> - TEST ( StereoBP , regression ) { CV_GpuStereoBPTest test ; test . safe_run ( ) ; } <nl> deleted file mode 100644 <nl> index a2f794f21b7 . . 00000000000 <nl> mmm a / modules / gpu / test / test_stereo_csbp . cpp <nl> ppp / dev / null <nl> <nl> - / * M / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / <nl> - / / IMPORTANT : READ BEFORE DOWNLOADING , COPYING , INSTALLING OR USING . <nl> - / / <nl> - / / By downloading , copying , installing or using the software you agree to this license . <nl> - / / If you do not agree to this license , do not download , install , <nl> - / / copy or use the software . <nl> - / / <nl> - / / <nl> - / / Intel License Agreement <nl> - / / For Open Source Computer Vision Library <nl> - / / <nl> - / / Copyright ( C ) 2000 , Intel Corporation , all rights reserved . <nl> - / / Third party copyrights are property of their respective owners . <nl> - / / <nl> - / / Redistribution and use in source and binary forms , with or without modification , <nl> - / / are permitted provided that the following conditions are met : <nl> - / / <nl> - / / * Redistribution ' s of source code must retain the above copyright notice , <nl> - / / this list of conditions and the following disclaimer . <nl> - / / <nl> - / / * Redistribution ' s in binary form must reproduce the above copyright notice , <nl> - / / this list of conditions and the following disclaimer in the documentation <nl> - / / and / or other materials provided with the distribution . <nl> - / / <nl> - / / * The name of Intel Corporation may not be used to endorse or promote products <nl> - / / derived from this software without specific prior written permission . <nl> - / / <nl> - / / This software is provided by the copyright holders and contributors " as is " and <nl> - / / any express or implied warranties , including , but not limited to , the implied <nl> - / / warranties of merchantability and fitness for a particular purpose are disclaimed . <nl> - / / In no event shall the Intel Corporation or contributors be liable for any direct , <nl> - / / indirect , incidental , special , exemplary , or consequential damages <nl> - / / ( including , but not limited to , procurement of substitute goods or services ; <nl> - / / loss of use , data , or profits ; or business interruption ) however caused <nl> - / / and on any theory of liability , whether in contract , strict liability , <nl> - / / or tort ( including negligence or otherwise ) arising in any way out of <nl> - / / the use of this software , even if advised of the possibility of such damage . <nl> - / / <nl> - / / M * / <nl> - <nl> - # include " test_precomp . hpp " <nl> - <nl> - struct CV_GpuStereoCSBPTest : public cvtest : : BaseTest <nl> - { <nl> - void run ( int ) <nl> - { <nl> - cv : : Mat img_l = cv : : imread ( std : : string ( ts - > get_data_path ( ) ) + " csstereobp / aloe - L . png " ) ; <nl> - cv : : Mat img_r = cv : : imread ( std : : string ( ts - > get_data_path ( ) ) + " csstereobp / aloe - R . png " ) ; <nl> - <nl> - cv : : Mat img_template ; <nl> - <nl> - if ( cv : : gpu : : TargetArchs : : builtWith ( cv : : gpu : : FEATURE_SET_COMPUTE_20 ) & & <nl> - cv : : gpu : : DeviceInfo ( ) . supports ( cv : : gpu : : FEATURE_SET_COMPUTE_20 ) ) <nl> - img_template = cv : : imread ( std : : string ( ts - > get_data_path ( ) ) + " csstereobp / aloe - disp . png " , CV_LOAD_IMAGE_GRAYSCALE ) ; <nl> - else <nl> - img_template = cv : : imread ( std : : string ( ts - > get_data_path ( ) ) + " csstereobp / aloe - disp_CC1X . png " , CV_LOAD_IMAGE_GRAYSCALE ) ; <nl> - <nl> - if ( img_l . empty ( ) | | img_r . empty ( ) | | img_template . empty ( ) ) <nl> - { <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_MISSING_TEST_DATA ) ; <nl> - return ; <nl> - } <nl> - <nl> - { cv : : Mat temp ; cv : : cvtColor ( img_l , temp , CV_BGR2BGRA ) ; cv : : swap ( temp , img_l ) ; } <nl> - { cv : : Mat temp ; cv : : cvtColor ( img_r , temp , CV_BGR2BGRA ) ; cv : : swap ( temp , img_r ) ; } <nl> - <nl> - cv : : gpu : : GpuMat disp ; <nl> - cv : : gpu : : StereoConstantSpaceBP bpm ( 128 , 16 , 4 , 4 ) ; <nl> - <nl> - bpm ( cv : : gpu : : GpuMat ( img_l ) , cv : : gpu : : GpuMat ( img_r ) , disp ) ; <nl> - <nl> - / / cv : : imwrite ( std : : string ( ts - > get_data_path ( ) ) + " csstereobp / aloe - disp_CC1X . png " , cv : : Mat ( disp ) ) ; <nl> - <nl> - disp . convertTo ( disp , img_template . type ( ) ) ; <nl> - <nl> - double norm = cv : : norm ( ( cv : : Mat ) disp , img_template , cv : : NORM_INF ) ; <nl> - if ( norm > = 1 . 5 ) <nl> - { <nl> - ts - > printf ( cvtest : : TS : : LOG , " \ nConstantSpaceStereoBP norm = % f \ n " , norm ) ; <nl> - ts - > set_failed_test_info ( cvtest : : TS : : FAIL_GENERIC ) ; <nl> - return ; <nl> - } <nl> - <nl> - ts - > set_failed_test_info ( cvtest : : TS : : OK ) ; <nl> - } <nl> - } ; <nl> - <nl> - TEST ( StereoConstantSpaceBP , regression ) { CV_GpuStereoCSBPTest test ; test . safe_run ( ) ; } <nl> | refactored gpu module tests | opencv/opencv | d1b4b5f0de3500e54515b1992cc294721c81b912 | 2011-06-29T10:14:16Z |
mmm a / test / functional / test_runner . py <nl> ppp b / test / functional / test_runner . py <nl> def main ( ) : <nl> run_tests ( test_list , config [ " environment " ] [ " SRCDIR " ] , config [ " environment " ] [ " BUILDDIR " ] , config [ " environment " ] [ " EXEEXT " ] , args . jobs , args . coverage , passon_args ) <nl> <nl> def run_tests ( test_list , src_dir , build_dir , exeext , jobs = 1 , enable_coverage = False , args = [ ] ) : <nl> + # Warn if bitcoind is already running ( unix only ) <nl> + try : <nl> + if subprocess . check_output ( [ " pidof " , " bitcoind " ] ) is not None : <nl> + print ( " % sWARNING ! % s There is already a bitcoind process running on this system . Tests may fail unexpectedly due to resource contention ! " % ( BOLD [ 1 ] , BOLD [ 0 ] ) ) <nl> + except ( OSError , subprocess . SubprocessError ) : <nl> + pass <nl> + <nl> + # Warn if there is a cache directory <nl> + cache_dir = " % s / test / cache " % build_dir <nl> + if os . path . isdir ( cache_dir ) : <nl> + print ( " % sWARNING ! % s There is a cache directory here : % s . If tests fail unexpectedly , try deleting the cache directory . " % ( BOLD [ 1 ] , BOLD [ 0 ] , cache_dir ) ) <nl> <nl> # Set env vars <nl> if " BITCOIND " not in os . environ : <nl> def run_tests ( test_list , src_dir , build_dir , exeext , jobs = 1 , enable_coverage = Fal <nl> tests_dir = src_dir + ' / test / functional / ' <nl> <nl> flags = [ " - - srcdir = { } / src " . format ( build_dir ) ] + args <nl> - flags . append ( " - - cachedir = % s / test / cache " % build_dir ) <nl> + flags . append ( " - - cachedir = % s " % cache_dir ) <nl> <nl> if enable_coverage : <nl> coverage = RPCCoverage ( ) <nl> def check_script_list ( src_dir ) : <nl> python_files = set ( [ t for t in os . listdir ( script_dir ) if t [ - 3 : ] = = " . py " ] ) <nl> missed_tests = list ( python_files - set ( map ( lambda x : x . split ( ) [ 0 ] , ALL_SCRIPTS + NON_SCRIPTS ) ) ) <nl> if len ( missed_tests ) ! = 0 : <nl> - print ( " The following scripts are not being run : " + str ( missed_tests ) ) <nl> - print ( " Check the test lists in test_runner . py " ) <nl> - sys . exit ( 1 ) <nl> + print ( " % sWARNING ! % s The following scripts are not being run : % s . Check the test lists in test_runner . py . " % ( BOLD [ 1 ] , BOLD [ 0 ] , str ( missed_tests ) ) ) <nl> + if os . getenv ( ' TRAVIS ' ) = = ' true ' : <nl> + # On travis this warning is an error to prevent merging incomplete commits into master <nl> + sys . exit ( 1 ) <nl> <nl> class RPCCoverage ( object ) : <nl> " " " <nl> | [ test ] add warnings to test_runner | bitcoin/bitcoin | c85b080cc705f30f99662a7be2a2a04e8e5e58ee | 2017-04-17T14:31:55Z |
mmm a / src / modules . js <nl> ppp b / src / modules . js <nl> var LibraryManager = { <nl> ] ) . concat ( additionalLibraries ) ; <nl> <nl> if ( BOOTSTRAPPING_STRUCT_INFO ) libraries = [ ' library_bootstrap_structInfo . js ' , ' library_formatString . js ' ] ; <nl> + if ( ONLY_MY_CODE ) { <nl> + libraries = [ ] ; <nl> + LibraryManager . library = { } ; <nl> + } <nl> <nl> for ( var i = 0 ; i < libraries . length ; i + + ) { <nl> var filename = libraries [ i ] ; <nl> new file mode 100644 <nl> index 00000000000 . . 2014de7af46 <nl> mmm / dev / null <nl> ppp b / tests / hello_123 . c <nl> <nl> + int main ( ) { <nl> + return 123 ; <nl> + } <nl> + <nl> mmm a / tests / test_other . py <nl> ppp b / tests / test_other . py <nl> def test_canonicalize_nan_warning ( self ) : <nl> self . assertContained ( " emcc : warning : cannot represent a NaN literal " , stderr ) <nl> self . assertContained ( ' / / @ line 12 " src . cpp " ' , stderr ) <nl> <nl> - def test_no_linking ( self ) : <nl> + def test_only_my_code ( self ) : <nl> check_execute ( [ PYTHON , EMCC , ' - O1 ' , path_from_root ( ' tests ' , ' hello_world . c ' ) , ' - - separate - asm ' ] ) <nl> count = open ( ' a . out . asm . js ' ) . read ( ) . count ( ' function ' ) <nl> assert count > 30 , count # libc brings in a bunch of stuff <nl> <nl> - check_execute ( [ PYTHON , EMCC , ' - O1 ' , path_from_root ( ' tests ' , ' hello_world . c ' ) , ' - - separate - asm ' , ' - s ' , ' ONLY_MY_CODE = 1 ' ] ) <nl> - count = open ( ' a . out . asm . js ' ) . read ( ) . count ( ' function ' ) <nl> - assert count = = 2 , count # without libc , we are minimal , just the _main we wrote ourselves ( plus the asm function itself ) <nl> - full = ' var Module = { } ; \ n ' + open ( ' a . out . asm . js ' ) . read ( ) <nl> - open ( ' asm . js ' , ' w ' ) . write ( full ) <nl> - if SPIDERMONKEY_ENGINE in JS_ENGINES : <nl> - out = run_js ( ' asm . js ' , engine = SPIDERMONKEY_ENGINE , stderr = STDOUT ) <nl> - self . validate_asmjs ( out ) <nl> - else : <nl> - print ' ( skipping asm . js validation check ) ' <nl> + def test ( filename , opts , expected ) : <nl> + print filename , opts <nl> + check_execute ( [ PYTHON , EMCC , path_from_root ( ' tests ' , filename ) , ' - - separate - asm ' , ' - s ' , ' ONLY_MY_CODE = 1 ' ] + opts ) <nl> + full = ' var Module = { } ; \ n ' + open ( ' a . out . asm . js ' ) . read ( ) <nl> + open ( ' asm . js ' , ' w ' ) . write ( full ) <nl> + count = open ( ' a . out . asm . js ' ) . read ( ) . count ( ' function ' ) <nl> + assert count = = expected , count # without libc , we are minimal , just the code we wrote ourselves ( plus the asm function itself ) <nl> + if SPIDERMONKEY_ENGINE in JS_ENGINES : <nl> + out = run_js ( ' asm . js ' , engine = SPIDERMONKEY_ENGINE , stderr = STDOUT ) <nl> + self . validate_asmjs ( out ) <nl> + else : <nl> + print ' ( skipping asm . js validation check ) ' <nl> + <nl> + test ( ' hello_123 . c ' , [ ' - O1 ' ] , 2 ) <nl> + test ( ' fasta . cpp ' , [ ' - O3 ' , ' - g2 ' ] , 3 ) <nl> <nl> | don ' t pull in code from js libraries when ONLY_MY_CODE | emscripten-core/emscripten | 7ab7daeac0b1524baa033d6f12e3c6a742a73faf | 2015-12-09T23:10:05Z |
mmm a / src / hydrogen - instructions . h <nl> ppp b / src / hydrogen - instructions . h <nl> class HConstant : public HTemplateInstruction < 0 > { <nl> <nl> Handle < Object > handle ( ) { <nl> if ( handle_ . is_null ( ) ) { <nl> - handle_ = isolate ( ) - > factory ( ) - > NewNumber ( double_value_ , TENURED ) ; <nl> + handle_ = FACTORY - > NewNumber ( double_value_ , TENURED ) ; <nl> } <nl> - ALLOW_HANDLE_DEREF ( isolate ( ) , " smi check " ) ; <nl> + ALLOW_HANDLE_DEREF ( Isolate : : Current ( ) , " smi check " ) ; <nl> ASSERT ( has_int32_value_ | | ! handle_ - > IsSmi ( ) ) ; <nl> return handle_ ; <nl> } <nl> | Get isolate from thread local instead of ( potentially missing ) block in HConstant . | v8/v8 | 1ad3d57d9d9fa905316d5c072d22463abd0fee94 | 2013-04-25T10:57:24Z |
mmm a / src / rdb_protocol / serialize_datum . cc <nl> ppp b / src / rdb_protocol / serialize_datum . cc <nl> struct size_tree_node_t { <nl> <nl> ARCHIVE_PRIM_MAKE_RANGED_SERIALIZABLE ( datum_serialized_type_t , int8_t , <nl> datum_serialized_type_t : : R_ARRAY , <nl> - datum_serialized_type_t : : BUF_R_OBJECT ) ; <nl> + datum_serialized_type_t : : UNINITIALIZED ) ; <nl> <nl> serialization_result_t datum_serialize ( write_message_t * wm , <nl> datum_serialized_type_t type ) { <nl> | Fixed serialization of ` datum_serialized_type_t ` . | rethinkdb/rethinkdb | ebc0ace4c89c745fd1c486ead075f7097b61ec5b | 2015-01-08T22:28:43Z |
mmm a / torch / utils / data / dataloader . py <nl> ppp b / torch / utils / data / dataloader . py <nl> def _worker_loop ( dataset , index_queue , data_queue , collate_fn , seed , init_fn , wo <nl> data_queue . put ( ( idx , ExceptionWrapper ( sys . exc_info ( ) ) ) ) <nl> else : <nl> data_queue . put ( ( idx , samples ) ) <nl> + del samples <nl> <nl> <nl> def _worker_manager_loop ( in_queue , out_queue , done_event , pin_memory , device_id ) : <nl> | Scope variables inside the dataloader ( ) | pytorch/pytorch | f15f3ca1afb55c54e6f984eb120ea68293367ffe | 2018-04-17T21:48:12Z |
mmm a / modules / perception / base / BUILD <nl> ppp b / modules / perception / base / BUILD <nl> cc_library ( <nl> " blob . h " , <nl> ] , <nl> deps = [ <nl> + " / / cybertron " , <nl> " : common " , <nl> " : syncedmem " , <nl> ] , <nl> mmm a / modules / perception / base / blob . h <nl> ppp b / modules / perception / base / blob . h <nl> <nl> # include < string > <nl> # include < vector > <nl> <nl> - # include " glog / logging . h " <nl> + # include " cybertron / common / log . h " <nl> # include " modules / perception / base / syncedmem . h " <nl> <nl> namespace apollo { <nl> mmm a / modules / perception / base / syncedmem . h <nl> ppp b / modules / perception / base / syncedmem . h <nl> <nl> # include < cstdlib > <nl> # include < iostream > <nl> <nl> - # include " glog / logging . h " <nl> + # include " cybertron / common / log . h " <nl> # include " modules / perception / base / common . h " <nl> <nl> namespace apollo { <nl> mmm a / modules / perception / camera / common / util . h <nl> ppp b / modules / perception / camera / common / util . h <nl> <nl> / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * <nl> - * Copyright 2018 The Apollo Authors . All Rights Reserved . <nl> - * <nl> - * Licensed under the Apache License , Version 2 . 0 ( the License ) ; <nl> - * you may not use this file except in compliance with the License . <nl> - * You may obtain a copy of the License at <nl> - * <nl> - * http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> - * <nl> - * Unless required by applicable law or agreed to in writing , software <nl> - * distributed under the License is distributed on an AS IS BASIS , <nl> - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> - * See the License for the specific language governing permissions and <nl> - * limitations under the License . <nl> - * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + * Copyright 2018 The Apollo Authors . All Rights Reserved . <nl> + * <nl> + * Licensed under the Apache License , Version 2 . 0 ( the License ) ; <nl> + * you may not use this file except in compliance with the License . <nl> + * You may obtain a copy of the License at <nl> + * <nl> + * http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + * <nl> + * Unless required by applicable law or agreed to in writing , software <nl> + * distributed under the License is distributed on an AS IS BASIS , <nl> + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + * See the License for the specific language governing permissions and <nl> + * limitations under the License . <nl> + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> # pragma once <nl> - # include < fcntl . h > <nl> <nl> + # include < cblas . h > <nl> # include < google / protobuf / io / coded_stream . h > <nl> - # include < google / protobuf / io / zero_copy_stream_impl . h > <nl> # include < google / protobuf / io / gzip_stream . h > <nl> + # include < google / protobuf / io / zero_copy_stream_impl . h > <nl> # include < google / protobuf / text_format . h > <nl> - # include < cblas . h > <nl> # include < algorithm > <nl> # include < fstream > <nl> # include < iostream > <nl> <nl> # include < numeric > <nl> # include < string > <nl> # include < vector > <nl> - # include " glog / logging . h " <nl> + <nl> + # include " cybertron / common / log . h " <nl> # include " modules / perception / base / blob . h " <nl> # include " modules / perception / base / image . h " <nl> # include " modules / perception / base / object . h " <nl> bool Equal ( float x , float target , float eps = 1e - 6 ) ; <nl> bool Equal ( double x , double target , double eps = 1e - 6 ) ; <nl> <nl> / / @ brief whether rect1 is covered by rect2 <nl> - template < typename T > <nl> - bool IsCovered ( const base : : Rect < T > & rect1 , <nl> - const base : : Rect < T > & rect2 , <nl> + template < typename T > <nl> + bool IsCovered ( const base : : Rect < T > & rect1 , const base : : Rect < T > & rect2 , <nl> float thresh ) { <nl> base : : RectF inter = rect1 & rect2 ; <nl> return inter . Area ( ) / rect1 . Area ( ) > thresh ; <nl> } <nl> - template < typename T > <nl> - bool IsCoveredHorizon ( const base : : Rect < T > & rect1 , <nl> - const base : : Rect < T > & rect2 , <nl> + template < typename T > <nl> + bool IsCoveredHorizon ( const base : : Rect < T > & rect1 , const base : : Rect < T > & rect2 , <nl> float thresh ) { <nl> base : : RectF inter = rect1 & rect2 ; <nl> if ( inter . Area ( ) > 0 ) { <nl> bool IsCoveredHorizon ( const base : : Rect < T > & rect1 , <nl> } <nl> return false ; <nl> } <nl> - template < typename T > <nl> - bool IsCoveredVertical ( const base : : Rect < T > & rect1 , <nl> - const base : : Rect < T > & rect2 , <nl> + template < typename T > <nl> + bool IsCoveredVertical ( const base : : Rect < T > & rect1 , const base : : Rect < T > & rect2 , <nl> float thresh ) { <nl> base : : RectF inter = rect1 & rect2 ; <nl> if ( inter . Area ( ) > 0 ) { <nl> bool IsCoveredVertical ( const base : : Rect < T > & rect1 , <nl> return false ; <nl> } <nl> <nl> - template < typename T > <nl> + template < typename T > <nl> bool Contain ( const std : : vector < T > & array , const T & element ) { <nl> for ( const auto & item : array ) { <nl> if ( item = = element ) { <nl> bool Contain ( const std : : vector < T > & array , const T & element ) { <nl> return false ; <nl> } <nl> <nl> - template < typename T > <nl> - bool OutOfValidRegion ( const base : : BBox2D < T > box , <nl> - const T width , <nl> - const T height , <nl> + template < typename T > <nl> + bool OutOfValidRegion ( const base : : BBox2D < T > box , const T width , const T height , <nl> const T border_size = 0 ) { <nl> if ( box . xmin < border_size | | box . ymin < border_size ) { <nl> return true ; <nl> } <nl> - if ( box . xmax + border_size > width | | <nl> - box . ymax + border_size > height ) { <nl> + if ( box . xmax + border_size > width | | box . ymax + border_size > height ) { <nl> return true ; <nl> } <nl> return false ; <nl> } <nl> - template < typename T > <nl> - bool OutOfValidRegion ( const base : : Rect < T > rect , <nl> - const T width , <nl> - const T height , <nl> + template < typename T > <nl> + bool OutOfValidRegion ( const base : : Rect < T > rect , const T width , const T height , <nl> const T border_size = 0 ) { <nl> base : : BBox2D < T > box ( rect ) ; <nl> return OutOfValidRegion ( box , width , height , border_size ) ; <nl> } <nl> <nl> - template < typename T > <nl> - void RefineBox ( const base : : Rect < T > & box_in , <nl> - const T width , <nl> - const T height , <nl> + template < typename T > <nl> + void RefineBox ( const base : : Rect < T > & box_in , const T width , const T height , <nl> base : : Rect < T > * box_out ) { <nl> if ( ! box_out ) { <nl> return ; <nl> void RefineBox ( const base : : Rect < T > & box_in , <nl> box_out - > y = 0 ; <nl> box_out - > height = 0 ; <nl> } <nl> - box_out - > width = ( box_out - > x + box_out - > width < = width ) ? box_out - > width : <nl> - width - box_out - > x ; <nl> - box_out - > height = ( box_out - > y + box_out - > height < = height ) ? box_out - > height : <nl> - height - box_out - > y ; <nl> + box_out - > width = ( box_out - > x + box_out - > width < = width ) ? box_out - > width <nl> + : width - box_out - > x ; <nl> + box_out - > height = ( box_out - > y + box_out - > height < = height ) <nl> + ? box_out - > height <nl> + : height - box_out - > y ; <nl> if ( box_out - > width < 0 ) { <nl> box_out - > width = 0 ; <nl> } <nl> void RefineBox ( const base : : Rect < T > & box_in , <nl> } <nl> } <nl> <nl> - template < typename T > <nl> - void RefineBox ( const base : : BBox2D < T > & box_in , <nl> - const T width , <nl> - const T height , <nl> + template < typename T > <nl> + void RefineBox ( const base : : BBox2D < T > & box_in , const T width , const T height , <nl> base : : BBox2D < T > * box_out ) { <nl> if ( ! box_out ) { <nl> return ; <nl> void RefineBox ( const base : : BBox2D < T > & box_in , <nl> bool LoadAnchors ( const std : : string & path , std : : vector < float > * anchors ) ; <nl> bool LoadTypes ( const std : : string & path , <nl> std : : vector < base : : ObjectSubType > * types ) ; <nl> - bool LoadExpand ( const std : : string & path , <nl> - std : : vector < float > * expands ) ; <nl> + bool LoadExpand ( const std : : string & path , std : : vector < float > * expands ) ; <nl> <nl> bool ResizeCPU ( const base : : Blob < uint8_t > & src_gpu , <nl> - std : : shared_ptr < base : : Blob < float > > dst , <nl> - int stepwidth , <nl> + std : : shared_ptr < base : : Blob < float > > dst , int stepwidth , <nl> int start_axis ) ; <nl> <nl> - <nl> void GetCybertronWorkRoot ( std : : string * work_root ) ; <nl> void FillObjectPolygonFromBBox3D ( base : : Object * object_ptr ) ; <nl> <nl> - template < typename T > <nl> - void CalculateMeanAndVariance ( const std : : vector < T > & data , <nl> - T * mean , T * variance ) { <nl> + template < typename T > <nl> + void CalculateMeanAndVariance ( const std : : vector < T > & data , T * mean , <nl> + T * variance ) { <nl> if ( ! mean | | ! variance ) { <nl> return ; <nl> } <nl> void CalculateMeanAndVariance ( const std : : vector < T > & data , <nl> * mean = sum / data . size ( ) ; <nl> <nl> std : : vector < T > diff ( data . size ( ) ) ; <nl> - std : : transform ( data . begin ( ) , data . end ( ) , diff . begin ( ) , [ mean ] ( T x ) { <nl> - return x - * mean ; <nl> - } ) ; <nl> + std : : transform ( data . begin ( ) , data . end ( ) , diff . begin ( ) , <nl> + [ mean ] ( T x ) { return x - * mean ; } ) ; <nl> T sum_of_diff_sqrs = std : : inner_product ( diff . begin ( ) , diff . end ( ) , <nl> - diff . begin ( ) , static_cast < T > ( 0 ) ) ; <nl> + diff . begin ( ) , static_cast < T > ( 0 ) ) ; <nl> * variance = sum_of_diff_sqrs / data . size ( ) ; <nl> } <nl> <nl> mmm a / modules / perception / camera / lib / obstacle / tracker / common / BUILD <nl> ppp b / modules / perception / camera / lib / obstacle / tracker / common / BUILD <nl> cuda_library ( <nl> deps = [ <nl> " @ cuda " , <nl> " / / cybertron " , <nl> - " / / modules / perception / camera / common : common " , <nl> - " / / modules / perception / inference / utils : inference_util_lib " , <nl> + " / / modules / perception / camera / common : camera_frame " , <nl> " / / modules / perception / inference / utils : inference_gemm_lib " , <nl> ] , <nl> ) <nl> mmm a / modules / perception / camera / test / BUILD <nl> ppp b / modules / perception / camera / test / BUILD <nl> <nl> # " - lopencv_highgui " , <nl> # ] , <nl> # deps = [ <nl> - # " / / external : gflags " , <nl> + # " / / cybertron " , <nl> # " / / modules / perception / camera / lib / lane / detector / denseline : denseline_lane_detector " , <nl> # " / / modules / perception / base : base " , <nl> # " / / modules / perception / common / io : io_util " , <nl> <nl> # " - lcaffe " , <nl> # ] , <nl> # deps = [ <nl> + # " / / cybertron " , <nl> # " / / modules / perception / base : distortion_model " , <nl> # " / / modules / perception / common / io : io_util " , <nl> # " / / modules / perception / camera / lib / traffic_light / tracker : semantic_decision " , <nl> mmm a / modules / perception / camera / test / camera_common_undistortion . cc <nl> ppp b / modules / perception / camera / test / camera_common_undistortion . cc <nl> <nl> * limitations under the License . <nl> * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> # include " modules / perception / camera / test / camera_common_undistortion . h " <nl> - # include < npp . h > <nl> <nl> - # include < glog / logging . h > <nl> + # include < npp . h > <nl> # include < boost / filesystem . hpp > <nl> # include < yaml - cpp / yaml . h > <nl> - <nl> # include < opencv2 / core / core . hpp > <nl> # include < opencv2 / opencv . hpp > <nl> - <nl> # include < vector > <nl> <nl> - / / # include " cybertron / common / log . h " <nl> - <nl> namespace apollo { <nl> namespace perception { <nl> namespace camera { <nl> int ImageGpuPreprocessHandler : : load_camera_intrinsics ( <nl> < < " File not exists : " < < intrinsics_path ; <nl> YAML : : Node node = YAML : : LoadFile ( intrinsics_path ) ; <nl> if ( node . IsNull ( ) ) { <nl> - / / AINFO < < " Load " < < intrinsics_path < < " failed ! please check ! " ; <nl> return - 1 ; <nl> } <nl> D - > resize ( node [ " D " ] . size ( ) ) ; <nl> mmm a / modules / perception / camera / test / camera_lib_lane_detector_denseline_lane_detector_test . cc <nl> ppp b / modules / perception / camera / test / camera_lib_lane_detector_denseline_lane_detector_test . cc <nl> <nl> * See the License for the specific language governing permissions and <nl> * limitations under the License . <nl> * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + <nl> # include < gtest / gtest . h > <nl> # include < opencv2 / opencv . hpp > <nl> # include < fstream > <nl> # include < iostream > <nl> + <nl> + # include " cybertron / common / log . h " <nl> # include " modules / perception / camera / lib / lane / detector / denseline / denseline_lane_detector . h " <nl> - # include " glog / logging . h " <nl> - # include " gflags / gflags . h " <nl> # include " modules / perception / base / distortion_model . h " <nl> # include " modules / perception / common / io / io_util . h " <nl> <nl> mmm a / modules / perception / camera / test / camera_lib_traffic_light_tracker_test . cc <nl> ppp b / modules / perception / camera / test / camera_lib_traffic_light_tracker_test . cc <nl> <nl> # include < iostream > <nl> <nl> # include " gtest / gtest . h " <nl> - # include " glog / logging . h " <nl> - # include " gflags / gflags . h " <nl> <nl> + # include " cybertron / common / log . h " <nl> # include " modules / perception / base / distortion_model . h " <nl> # include " modules / perception / common / io / io_util . h " <nl> # include " modules / perception / camera / lib / traffic_light / tracker / semantic_decision . h " <nl> | Perception : fixed misusing of logging | ApolloAuto/apollo | 9e33ae6f8de0c7640ec50d29206c74aeb20fa334 | 2018-12-13T23:17:30Z |
mmm a / fmt / posix . cc <nl> ppp b / fmt / posix . cc <nl> fmt : : BufferedFile : : BufferedFile ( <nl> fmt : : CStringRef filename , fmt : : CStringRef mode ) { <nl> FMT_RETRY_VAL ( file_ , FMT_SYSTEM ( fopen ( filename . c_str ( ) , mode . c_str ( ) ) ) , 0 ) ; <nl> if ( ! file_ ) <nl> - throw SystemError ( errno , " cannot open file { } " , filename ) ; <nl> + FMT_THROW ( SystemError ( errno , " cannot open file { } " , filename ) ) ; <nl> } <nl> <nl> void fmt : : BufferedFile : : close ( ) { <nl> void fmt : : BufferedFile : : close ( ) { <nl> int result = FMT_SYSTEM ( fclose ( file_ ) ) ; <nl> file_ = 0 ; <nl> if ( result ! = 0 ) <nl> - throw SystemError ( errno , " cannot close file " ) ; <nl> + FMT_THROW ( SystemError ( errno , " cannot close file " ) ) ; <nl> } <nl> <nl> / / A macro used to prevent expansion of fileno on broken versions of MinGW . <nl> void fmt : : BufferedFile : : close ( ) { <nl> int fmt : : BufferedFile : : fileno ( ) const { <nl> int fd = FMT_POSIX_CALL ( fileno FMT_ARGS ( file_ ) ) ; <nl> if ( fd = = - 1 ) <nl> - throw SystemError ( errno , " cannot get file descriptor " ) ; <nl> + FMT_THROW ( SystemError ( errno , " cannot get file descriptor " ) ) ; <nl> return fd ; <nl> } <nl> <nl> fmt : : File : : File ( fmt : : CStringRef path , int oflag ) { <nl> FMT_RETRY ( fd_ , FMT_POSIX_CALL ( open ( path . c_str ( ) , oflag , mode ) ) ) ; <nl> # endif <nl> if ( fd_ = = - 1 ) <nl> - throw SystemError ( errno , " cannot open file { } " , path ) ; <nl> + FMT_THROW ( SystemError ( errno , " cannot open file { } " , path ) ) ; <nl> } <nl> <nl> fmt : : File : : ~ File ( ) FMT_NOEXCEPT { <nl> void fmt : : File : : close ( ) { <nl> int result = FMT_POSIX_CALL ( close ( fd_ ) ) ; <nl> fd_ = - 1 ; <nl> if ( result ! = 0 ) <nl> - throw SystemError ( errno , " cannot close file " ) ; <nl> + FMT_THROW ( SystemError ( errno , " cannot close file " ) ) ; <nl> } <nl> <nl> fmt : : LongLong fmt : : File : : size ( ) const { <nl> fmt : : LongLong fmt : : File : : size ( ) const { <nl> typedef struct stat Stat ; <nl> Stat file_stat = Stat ( ) ; <nl> if ( FMT_POSIX_CALL ( fstat ( fd_ , & file_stat ) ) = = - 1 ) <nl> - throw SystemError ( errno , " cannot get file attributes " ) ; <nl> + FMT_THROW ( SystemError ( errno , " cannot get file attributes " ) ) ; <nl> FMT_STATIC_ASSERT ( sizeof ( fmt : : LongLong ) > = sizeof ( file_stat . st_size ) , <nl> " return type of File : : size is not large enough " ) ; <nl> return file_stat . st_size ; <nl> std : : size_t fmt : : File : : read ( void * buffer , std : : size_t count ) { <nl> RWResult result = 0 ; <nl> FMT_RETRY ( result , FMT_POSIX_CALL ( read ( fd_ , buffer , convert_rwcount ( count ) ) ) ) ; <nl> if ( result < 0 ) <nl> - throw SystemError ( errno , " cannot read from file " ) ; <nl> + FMT_THROW ( SystemError ( errno , " cannot read from file " ) ) ; <nl> return internal : : to_unsigned ( result ) ; <nl> } <nl> <nl> std : : size_t fmt : : File : : write ( const void * buffer , std : : size_t count ) { <nl> RWResult result = 0 ; <nl> FMT_RETRY ( result , FMT_POSIX_CALL ( write ( fd_ , buffer , convert_rwcount ( count ) ) ) ) ; <nl> if ( result < 0 ) <nl> - throw SystemError ( errno , " cannot write to file " ) ; <nl> + FMT_THROW ( SystemError ( errno , " cannot write to file " ) ) ; <nl> return internal : : to_unsigned ( result ) ; <nl> } <nl> <nl> fmt : : File fmt : : File : : dup ( int fd ) { <nl> / / http : / / pubs . opengroup . org / onlinepubs / 009695399 / functions / dup . html <nl> int new_fd = FMT_POSIX_CALL ( dup ( fd ) ) ; <nl> if ( new_fd = = - 1 ) <nl> - throw SystemError ( errno , " cannot duplicate file descriptor { } " , fd ) ; <nl> + FMT_THROW ( SystemError ( errno , " cannot duplicate file descriptor { } " , fd ) ) ; <nl> return File ( new_fd ) ; <nl> } <nl> <nl> void fmt : : File : : dup2 ( int fd ) { <nl> int result = 0 ; <nl> FMT_RETRY ( result , FMT_POSIX_CALL ( dup2 ( fd_ , fd ) ) ) ; <nl> if ( result = = - 1 ) { <nl> - throw SystemError ( errno , <nl> - " cannot duplicate file descriptor { } to { } " , fd_ , fd ) ; <nl> + FMT_THROW ( SystemError ( errno , <nl> + " cannot duplicate file descriptor { } to { } " , fd_ , fd ) ) ; <nl> } <nl> } <nl> <nl> void fmt : : File : : pipe ( File & read_end , File & write_end ) { <nl> int result = FMT_POSIX_CALL ( pipe ( fds ) ) ; <nl> # endif <nl> if ( result ! = 0 ) <nl> - throw SystemError ( errno , " cannot create pipe " ) ; <nl> + FMT_THROW ( SystemError ( errno , " cannot create pipe " ) ) ; <nl> / / The following assignments don ' t throw because read_fd and write_fd <nl> / / are closed . <nl> read_end = File ( fds [ 0 ] ) ; <nl> fmt : : BufferedFile fmt : : File : : fdopen ( const char * mode ) { <nl> / / Don ' t retry as fdopen doesn ' t return EINTR . <nl> FILE * f = FMT_POSIX_CALL ( fdopen ( fd_ , mode ) ) ; <nl> if ( ! f ) <nl> - throw SystemError ( errno , " cannot associate stream with file descriptor " ) ; <nl> + FMT_THROW ( SystemError ( errno , " cannot associate stream with file descriptor " ) ) ; <nl> BufferedFile file ( f ) ; <nl> fd_ = - 1 ; <nl> return file ; <nl> long fmt : : getpagesize ( ) { <nl> # else <nl> long size = FMT_POSIX_CALL ( sysconf ( _SC_PAGESIZE ) ) ; <nl> if ( size < 0 ) <nl> - throw SystemError ( errno , " cannot get memory page size " ) ; <nl> + FMT_THROW ( SystemError ( errno , " cannot get memory page size " ) ) ; <nl> return size ; <nl> # endif <nl> } <nl> mmm a / fmt / posix . h <nl> ppp b / fmt / posix . h <nl> class Locale { <nl> <nl> Locale ( ) : locale_ ( newlocale ( LC_NUMERIC_MASK , " C " , NULL ) ) { <nl> if ( ! locale_ ) <nl> - throw fmt : : SystemError ( errno , " cannot create locale " ) ; <nl> + FMT_THROW ( fmt : : SystemError ( errno , " cannot create locale " ) ) ; <nl> } <nl> ~ Locale ( ) { freelocale ( locale_ ) ; } <nl> <nl> | Fix Linux compilation with - fno - exceptions ( ) | fmtlib/fmt | 8c63ea432c7985eb056f1457d7edc8574d4fa2f8 | 2016-10-29T23:16:40Z |
mmm a / tools / run_tests / run_xds_tests . py <nl> ppp b / tools / run_tests / run_xds_tests . py <nl> <nl> ' secondary_locality_gets_no_requests_on_partial_primary_failure ' , <nl> ' secondary_locality_gets_requests_on_primary_failure ' , <nl> ' traffic_splitting ' , <nl> + ' circuit_breaking ' , <nl> ] <nl> # Valid test cases , but not in all . So the tests can only run manually , and <nl> # aren ' t enabled automatically for all languages . <nl> def get_client_stats ( num_rpcs , timeout_sec ) : <nl> logger . debug ( ' Invoked GetClientStats RPC to % s : % s ' , host , response ) <nl> return response <nl> <nl> + def get_client_accumulated_stats ( ) : <nl> + if CLIENT_HOSTS : <nl> + hosts = CLIENT_HOSTS <nl> + else : <nl> + hosts = [ ' localhost ' ] <nl> + for host in hosts : <nl> + with grpc . insecure_channel ( ' % s : % d ' % <nl> + ( host , args . stats_port ) ) as channel : <nl> + stub = test_pb2_grpc . LoadBalancerStatsServiceStub ( channel ) <nl> + request = messages_pb2 . LoadBalancerAccumulatedStatsRequest ( ) <nl> + logger . debug ( ' Invoking GetClientAccumulatedStats RPC to % s : % d : ' , <nl> + host , args . stats_port ) <nl> + response = stub . GetClientAccumulatedStats ( request , <nl> + wait_for_ready = True , <nl> + timeout = _CONNECTION_TIMEOUT_SEC ) <nl> + logger . debug ( ' Invoked GetClientAccumulatedStats RPC to % s : % s ' , <nl> + host , <nl> + response ) <nl> + return response <nl> + <nl> + def configure_client ( rpc_types , metadata ) : <nl> + if CLIENT_HOSTS : <nl> + hosts = CLIENT_HOSTS <nl> + else : <nl> + hosts = [ ' localhost ' ] <nl> + for host in hosts : <nl> + with grpc . insecure_channel ( ' % s : % d ' % <nl> + ( host , args . stats_port ) ) as channel : <nl> + stub = test_pb2_grpc . XdsUpdateClientConfigureServiceStub ( channel ) <nl> + request = messages_pb2 . ClientConfigureRequest ( ) <nl> + for rpc_type in rpc_types : <nl> + if rpc_type not in [ ' empty_call ' , ' unary_call ' ] : <nl> + continue <nl> + request . types . append ( <nl> + messages_pb2 . ClientConfigureRequest . RpcType . EMPTY_CALL <nl> + if rpc_type = = ' empty_call ' <nl> + else messages_pb2 . ClientConfigureRequest . RpcType . UNARY_CALL <nl> + ) <nl> + for rpc_type , md_key , md_value in metadata : <nl> + if rpc_type not in [ ' empty_call ' , ' unary_call ' ] : <nl> + continue <nl> + md = request . metadata . add ( ) <nl> + md . type = ( <nl> + messages_pb2 . ClientConfigureRequest . RpcType . EMPTY_CALL <nl> + if rpc_type = = ' empty_call ' <nl> + else messages_pb2 . ClientConfigureRequest . RpcType . UNARY_CALL <nl> + ) <nl> + md . key = md_key <nl> + md . value = md_value <nl> + logger . debug ( ' Invoking XdsUpdateClientConfigureService RPC to % s : % d : % s ' , <nl> + host , <nl> + args . stats_port , <nl> + request ) <nl> + stub . Configure ( request , <nl> + wait_for_ready = True , <nl> + timeout = _CONNECTION_TIMEOUT_SEC ) <nl> + logger . debug ( ' Invoked XdsUpdateClientConfigureService RPC to % s ' , host ) <nl> <nl> class RpcDistributionError ( Exception ) : <nl> pass <nl> def wait_until_all_rpcs_go_to_given_backends ( backends , <nl> num_rpcs , <nl> allow_failures = False ) <nl> <nl> + def wait_until_all_rpcs_fail ( timeout_sec , num_rpcs ) : <nl> + start_time = time . time ( ) <nl> + error_msg = None <nl> + logger . debug ( ' Waiting for % d sec until all of next % d RPCs fail ' % <nl> + ( timeout_sec , num_rpcs ) ) <nl> + while time . time ( ) - start_time < = timeout_sec : <nl> + error_msg = None <nl> + stats = get_client_stats ( num_rpcs , timeout_sec ) <nl> + diff = num_rpcs - stats . num_failures <nl> + if not diff : <nl> + error_msg = ' Unexpected completion for % d RPCs ' % diff <nl> + time . sleep ( 2 ) <nl> + else : <nl> + return <nl> + raise RpcDistributionError ( error_msg ) <nl> + <nl> + def wait_until_rpcs_in_flight ( timeout_sec , num_rpcs ) : <nl> + start_time = time . time ( ) <nl> + error_msg = None <nl> + logger . debug ( ' Waiting for % d sec until % d RPCs in - flight ' % ( timeout_sec , num_rpcs ) ) <nl> + while time . time ( ) - start_time < = timeout_sec : <nl> + error_msg = None <nl> + stats = get_client_accumulated_stats ( ) <nl> + rpcs_in_flight = ( stats . num_rpcs_started <nl> + - stats . num_rpcs_succeeded <nl> + - stats . num_rpcs_failed ) <nl> + if rpcs_in_flight < num_rpcs : <nl> + error_msg = ( ' Expected % d RPCs in - flight , actual : % d ' % <nl> + ( num_rpcs , rpcs_in_flight ) ) <nl> + time . sleep ( 2 ) <nl> + else : <nl> + return <nl> + raise RpcDistributionError ( error_msg ) <nl> <nl> def compare_distributions ( actual_distribution , expected_distribution , <nl> threshold ) : <nl> def test_change_backend_service ( gcp , original_backend_service , instance_group , <nl> original_backend_instances = get_instance_names ( gcp , instance_group ) <nl> alternate_backend_instances = get_instance_names ( gcp , <nl> same_zone_instance_group ) <nl> - patch_backend_instances ( gcp , alternate_backend_service , <nl> + patch_backend_service ( gcp , alternate_backend_service , <nl> [ same_zone_instance_group ] ) <nl> wait_for_healthy_backends ( gcp , original_backend_service , instance_group ) <nl> wait_for_healthy_backends ( gcp , alternate_backend_service , <nl> def test_change_backend_service ( gcp , original_backend_service , instance_group , <nl> _WAIT_FOR_URL_MAP_PATCH_SEC ) <nl> finally : <nl> patch_url_map_backend_service ( gcp , original_backend_service ) <nl> - patch_backend_instances ( gcp , alternate_backend_service , [ ] ) <nl> + patch_backend_service ( gcp , alternate_backend_service , [ ] ) <nl> <nl> <nl> def test_gentle_failover ( gcp , <nl> def test_gentle_failover ( gcp , <nl> if num_primary_instances < min_instances_for_gentle_failover : <nl> resize_instance_group ( gcp , primary_instance_group , <nl> min_instances_for_gentle_failover ) <nl> - patch_backend_instances ( <nl> + patch_backend_service ( <nl> gcp , backend_service , <nl> [ primary_instance_group , secondary_instance_group ] ) <nl> primary_instance_names = get_instance_names ( gcp , primary_instance_group ) <nl> def test_gentle_failover ( gcp , <nl> else : <nl> raise e <nl> finally : <nl> - patch_backend_instances ( gcp , backend_service , [ primary_instance_group ] ) <nl> + patch_backend_service ( gcp , backend_service , [ primary_instance_group ] ) <nl> resize_instance_group ( gcp , primary_instance_group , <nl> num_primary_instances ) <nl> instance_names = get_instance_names ( gcp , primary_instance_group ) <nl> def test_remove_instance_group ( gcp , backend_service , instance_group , <nl> same_zone_instance_group ) : <nl> logger . info ( ' Running test_remove_instance_group ' ) <nl> try : <nl> - patch_backend_instances ( gcp , <nl> + patch_backend_service ( gcp , <nl> backend_service , <nl> [ instance_group , same_zone_instance_group ] , <nl> balancing_mode = ' RATE ' ) <nl> def test_remove_instance_group ( gcp , backend_service , instance_group , <nl> same_zone_instance_names , _WAIT_FOR_STATS_SEC ) <nl> remaining_instance_group = instance_group <nl> remaining_instance_names = instance_names <nl> - patch_backend_instances ( gcp , <nl> + patch_backend_service ( gcp , <nl> backend_service , [ remaining_instance_group ] , <nl> balancing_mode = ' RATE ' ) <nl> wait_until_all_rpcs_go_to_given_backends ( remaining_instance_names , <nl> _WAIT_FOR_BACKEND_SEC ) <nl> finally : <nl> - patch_backend_instances ( gcp , backend_service , [ instance_group ] ) <nl> + patch_backend_service ( gcp , backend_service , [ instance_group ] ) <nl> wait_until_all_rpcs_go_to_given_backends ( instance_names , <nl> _WAIT_FOR_BACKEND_SEC ) <nl> <nl> def test_secondary_locality_gets_no_requests_on_partial_primary_failure ( <nl> ' Running secondary_locality_gets_no_requests_on_partial_primary_failure ' <nl> ) <nl> try : <nl> - patch_backend_instances ( <nl> + patch_backend_service ( <nl> gcp , backend_service , <nl> [ primary_instance_group , secondary_instance_group ] ) <nl> wait_for_healthy_backends ( gcp , backend_service , primary_instance_group ) <nl> def test_secondary_locality_gets_no_requests_on_partial_primary_failure ( <nl> else : <nl> raise e <nl> finally : <nl> - patch_backend_instances ( gcp , backend_service , [ primary_instance_group ] ) <nl> + patch_backend_service ( gcp , backend_service , [ primary_instance_group ] ) <nl> <nl> <nl> def test_secondary_locality_gets_requests_on_primary_failure ( <nl> def test_secondary_locality_gets_requests_on_primary_failure ( <nl> swapped_primary_and_secondary = False ) : <nl> logger . info ( ' Running secondary_locality_gets_requests_on_primary_failure ' ) <nl> try : <nl> - patch_backend_instances ( <nl> + patch_backend_service ( <nl> gcp , backend_service , <nl> [ primary_instance_group , secondary_instance_group ] ) <nl> wait_for_healthy_backends ( gcp , backend_service , primary_instance_group ) <nl> def test_secondary_locality_gets_requests_on_primary_failure ( <nl> else : <nl> raise e <nl> finally : <nl> - patch_backend_instances ( gcp , backend_service , [ primary_instance_group ] ) <nl> + patch_backend_service ( gcp , backend_service , [ primary_instance_group ] ) <nl> <nl> <nl> def prepare_services_for_urlmap_tests ( gcp , original_backend_service , <nl> def prepare_services_for_urlmap_tests ( gcp , original_backend_service , <nl> logger . info ( ' waiting for original backends to become healthy ' ) <nl> wait_for_healthy_backends ( gcp , original_backend_service , instance_group ) <nl> <nl> - patch_backend_instances ( gcp , alternate_backend_service , <nl> + patch_backend_service ( gcp , alternate_backend_service , <nl> [ same_zone_instance_group ] ) <nl> logger . info ( ' waiting for alternate to become healthy ' ) <nl> wait_for_healthy_backends ( gcp , alternate_backend_service , <nl> def test_traffic_splitting ( gcp , original_backend_service , instance_group , <nl> break <nl> finally : <nl> patch_url_map_backend_service ( gcp , original_backend_service ) <nl> - patch_backend_instances ( gcp , alternate_backend_service , [ ] ) <nl> + patch_backend_service ( gcp , alternate_backend_service , [ ] ) <nl> <nl> <nl> def test_path_matching ( gcp , original_backend_service , instance_group , <nl> def test_path_matching ( gcp , original_backend_service , instance_group , <nl> break <nl> finally : <nl> patch_url_map_backend_service ( gcp , original_backend_service ) <nl> - patch_backend_instances ( gcp , alternate_backend_service , [ ] ) <nl> + patch_backend_service ( gcp , alternate_backend_service , [ ] ) <nl> <nl> <nl> def test_header_matching ( gcp , original_backend_service , instance_group , <nl> def test_header_matching ( gcp , original_backend_service , instance_group , <nl> break <nl> finally : <nl> patch_url_map_backend_service ( gcp , original_backend_service ) <nl> - patch_backend_instances ( gcp , alternate_backend_service , [ ] ) <nl> + patch_backend_service ( gcp , alternate_backend_service , [ ] ) <nl> + <nl> + <nl> + def test_circuit_breaking ( gcp , <nl> + original_backend_service , <nl> + instance_group , <nl> + alternate_backend_service , <nl> + same_zone_instance_group ) : <nl> + logger . info ( ' Running test_circuit_breaking ' ) <nl> + max_requests = _NUM_TEST_RPCS <nl> + alternate_backend_instances = get_instance_names ( gcp , <nl> + same_zone_instance_group ) <nl> + try : <nl> + # Switch to a new backend_service configured with circuit breakers . <nl> + patch_backend_service ( gcp , alternate_backend_service , <nl> + [ same_zone_instance_group ] , <nl> + circuit_breakers = { ' maxRequests ' : max_requests } ) <nl> + wait_for_healthy_backends ( gcp , alternate_backend_service , <nl> + same_zone_instance_group ) <nl> + patch_url_map_backend_service ( gcp , alternate_backend_service ) <nl> + wait_until_all_rpcs_go_to_given_backends ( alternate_backend_instances , <nl> + _WAIT_FOR_URL_MAP_PATCH_SEC ) <nl> + <nl> + # Make unary calls open . <nl> + configure_client ( rpc_types = [ ' unary_call ' ] , <nl> + metadata = [ ( ' unary_call ' , ' rpc - behavior ' , ' keep - open ' ) ] ) <nl> + wait_until_all_rpcs_fail ( int ( _WAIT_FOR_STATS_SEC + _NUM_TEST_RPCS / args . qps ) , <nl> + _NUM_TEST_RPCS ) <nl> + _assert_rpcs_in_flight ( max_requests ) <nl> + <nl> + # Increment circuit breakers max_requests threshold . <nl> + max_requests = _NUM_TEST_RPCS * 2 <nl> + patch_backend_service ( gcp , alternate_backend_service , <nl> + [ same_zone_instance_group ] , <nl> + circuit_breakers = { ' maxRequests ' : max_requests } ) <nl> + wait_until_rpcs_in_flight ( int ( _WAIT_FOR_STATS_SEC + max_requests / args . qps ) , <nl> + max_requests ) <nl> + wait_until_all_rpcs_fail ( int ( _WAIT_FOR_STATS_SEC + _NUM_TEST_RPCS / args . qps ) , <nl> + _NUM_TEST_RPCS ) <nl> + _assert_rpcs_in_flight ( max_requests ) <nl> + finally : <nl> + patch_url_map_backend_service ( gcp , original_backend_service ) <nl> + patch_backend_service ( gcp , alternate_backend_service , [ ] ) <nl> <nl> + def _assert_rpcs_in_flight ( num_rpcs ) : <nl> + stats = get_client_accumulated_stats ( ) <nl> + rpcs_in_flight = ( stats . num_rpcs_started <nl> + - stats . num_rpcs_succeeded <nl> + - stats . num_rpcs_failed ) <nl> + compare_distributions ( [ rpcs_in_flight ] , [ num_rpcs ] , threshold = 2 ) <nl> <nl> def get_serving_status ( instance , service_port ) : <nl> with grpc . insecure_channel ( ' % s : % d ' % ( instance , service_port ) ) as channel : <nl> def create_target_proxy ( gcp , name ) : <nl> config = { <nl> ' name ' : name , <nl> ' url_map ' : gcp . url_map . url , <nl> - ' validate_for_proxyless ' : True , <nl> } <nl> logger . debug ( ' Sending GCP request with body = % s ' , config ) <nl> result = gcp . alpha_compute . targetGrpcProxies ( ) . insert ( <nl> def delete_instance_template ( gcp ) : <nl> logger . info ( ' Delete failed : % s ' , http_error ) <nl> <nl> <nl> - def patch_backend_instances ( gcp , <nl> + def patch_backend_service ( gcp , <nl> backend_service , <nl> instance_groups , <nl> - balancing_mode = ' UTILIZATION ' ) : <nl> + balancing_mode = ' UTILIZATION ' , <nl> + circuit_breakers = None ) : <nl> if gcp . alpha_compute : <nl> compute_to_use = gcp . alpha_compute <nl> else : <nl> def patch_backend_instances ( gcp , <nl> ' balancingMode ' : balancing_mode , <nl> ' maxRate ' : 1 if balancing_mode = = ' RATE ' else None <nl> } for instance_group in instance_groups ] , <nl> + ' circuitBreakers ' : circuit_breakers , <nl> } <nl> logger . debug ( ' Sending GCP request with body = % s ' , config ) <nl> result = compute_to_use . backendServices ( ) . patch ( <nl> def __init__ ( self , compute , alpha_compute , project ) : <nl> startup_script ) <nl> instance_group = add_instance_group ( gcp , args . zone , instance_group_name , <nl> _INSTANCE_GROUP_SIZE ) <nl> - patch_backend_instances ( gcp , backend_service , [ instance_group ] ) <nl> + patch_backend_service ( gcp , backend_service , [ instance_group ] ) <nl> same_zone_instance_group = add_instance_group ( <nl> gcp , args . zone , same_zone_instance_group_name , _INSTANCE_GROUP_SIZE ) <nl> secondary_zone_instance_group = add_instance_group ( <nl> def __init__ ( self , compute , alpha_compute , project ) : <nl> test_header_matching ( gcp , backend_service , instance_group , <nl> alternate_backend_service , <nl> same_zone_instance_group ) <nl> + elif test_case = = ' circuit_breaking ' : <nl> + test_circuit_breaking ( gcp , backend_service , <nl> + instance_group , <nl> + alternate_backend_service , <nl> + same_zone_instance_group ) <nl> else : <nl> logger . error ( ' Unknown test case : % s ' , test_case ) <nl> sys . exit ( 1 ) <nl> | Implement the basic test case for limiting max number of concurrent RPCs . | grpc/grpc | 66feb8c2d99f675ff876f67314cd8175c0e71b9e | 2020-11-06T19:57:02Z |
mmm a / core / image . cpp <nl> ppp b / core / image . cpp <nl> void Image : : resize ( int p_width , int p_height , Interpolation p_interpolation ) { <nl> <nl> _copy_internals_from ( dst ) ; <nl> } <nl> - void Image : : crop ( int p_width , int p_height ) { <nl> <nl> + void Image : : crop_from_point ( int p_x , int p_y , int p_width , int p_height ) { <nl> if ( ! _can_modify ( format ) ) { <nl> ERR_EXPLAIN ( " Cannot crop in indexed , compressed or custom image formats . " ) ; <nl> ERR_FAIL ( ) ; <nl> } <nl> + ERR_FAIL_COND ( p_x < 0 ) ; <nl> + ERR_FAIL_COND ( p_y < 0 ) ; <nl> ERR_FAIL_COND ( p_width < = 0 ) ; <nl> ERR_FAIL_COND ( p_height < = 0 ) ; <nl> - ERR_FAIL_COND ( p_width > MAX_WIDTH ) ; <nl> - ERR_FAIL_COND ( p_height > MAX_HEIGHT ) ; <nl> + ERR_FAIL_COND ( p_x + p_width > MAX_WIDTH ) ; <nl> + ERR_FAIL_COND ( p_y + p_height > MAX_HEIGHT ) ; <nl> <nl> / * to save memory , cropping should be done in - place , however , since this function <nl> will most likely either not be used much , or in critical areas , for now it wont , because <nl> it ' s a waste of time . * / <nl> <nl> - if ( p_width = = width & & p_height = = height ) <nl> + if ( p_width = = width & & p_height = = height & & p_x = = 0 & & p_y = = 0 ) <nl> return ; <nl> <nl> uint8_t pdata [ 16 ] ; / / largest is 16 <nl> void Image : : crop ( int p_width , int p_height ) { <nl> PoolVector < uint8_t > : : Read r = data . read ( ) ; <nl> PoolVector < uint8_t > : : Write w = dst . data . write ( ) ; <nl> <nl> - for ( int y = 0 ; y < p_height ; y + + ) { <nl> + int m_h = p_y + p_height ; <nl> + int m_w = p_x + p_width ; <nl> + for ( int y = p_y ; y < m_h ; y + + ) { <nl> <nl> - for ( int x = 0 ; x < p_width ; x + + ) { <nl> + for ( int x = p_x ; x < m_w ; x + + ) { <nl> <nl> if ( ( x > = width | | y > = height ) ) { <nl> for ( uint32_t i = 0 ; i < pixel_size ; i + + ) <nl> void Image : : crop ( int p_width , int p_height ) { <nl> _get_pixelb ( x , y , pixel_size , r . ptr ( ) , pdata ) ; <nl> } <nl> <nl> - dst . _put_pixelb ( x , y , pixel_size , w . ptr ( ) , pdata ) ; <nl> + dst . _put_pixelb ( x - p_x , y - p_y , pixel_size , w . ptr ( ) , pdata ) ; <nl> } <nl> } <nl> } <nl> void Image : : crop ( int p_width , int p_height ) { <nl> _copy_internals_from ( dst ) ; <nl> } <nl> <nl> + void Image : : crop ( int p_width , int p_height ) { <nl> + <nl> + crop_from_point ( 0 , 0 , p_width , p_height ) ; <nl> + } <nl> + <nl> void Image : : flip_y ( ) { <nl> <nl> if ( ! _can_modify ( format ) ) { <nl> mmm a / core / image . h <nl> ppp b / core / image . h <nl> class Image : public Resource { <nl> / * * <nl> * Crop the image to a specific size , if larger , then the image is filled by black <nl> * / <nl> + void crop_from_point ( int p_x , int p_y , int p_width , int p_height ) ; <nl> void crop ( int p_width , int p_height ) ; <nl> <nl> void flip_x ( ) ; <nl> mmm a / editor / editor_node . cpp <nl> ppp b / editor / editor_node . cpp <nl> void EditorNode : : _save_scene_with_preview ( String p_file , int p_idx ) { <nl> <nl> int preview_size = EditorSettings : : get_singleton ( ) - > get ( " filesystem / file_dialog / thumbnail_size " ) ; <nl> preview_size * = EDSCALE ; <nl> - int width , height ; <nl> - if ( img - > get_width ( ) > preview_size & & img - > get_width ( ) > = img - > get_height ( ) ) { <nl> <nl> - width = preview_size ; <nl> - height = img - > get_height ( ) * preview_size / img - > get_width ( ) ; <nl> - } else if ( img - > get_height ( ) > preview_size & & img - > get_height ( ) > = img - > get_width ( ) ) { <nl> + / / consider a square region <nl> + int vp_size = MIN ( img - > get_width ( ) , img - > get_height ( ) ) ; <nl> + int x = ( img - > get_width ( ) - vp_size ) / 2 ; <nl> + int y = ( img - > get_height ( ) - vp_size ) / 2 ; <nl> <nl> - height = preview_size ; <nl> - width = img - > get_width ( ) * preview_size / img - > get_height ( ) ; <nl> + img - > convert ( Image : : FORMAT_RGB8 ) ; <nl> + <nl> + if ( vp_size < preview_size ) { <nl> + / / just square it . <nl> + img - > crop_from_point ( x , y , vp_size , vp_size ) ; <nl> } else { <nl> + int ratio = vp_size / preview_size ; <nl> + int size = preview_size * ( ratio / 2 ) ; <nl> <nl> - width = img - > get_width ( ) ; <nl> - height = img - > get_height ( ) ; <nl> + x = ( img - > get_width ( ) - size ) / 2 ; <nl> + y = ( img - > get_height ( ) - size ) / 2 ; <nl> + <nl> + img - > crop_from_point ( x , y , size , size ) ; <nl> + / / We could get better pictures with better filters <nl> + img - > resize ( preview_size , preview_size , Image : : INTERPOLATE_CUBIC ) ; <nl> } <nl> <nl> - img - > convert ( Image : : FORMAT_RGB8 ) ; <nl> - img - > resize ( width , height ) ; <nl> img - > flip_y ( ) ; <nl> <nl> / / save thumbnail directly , as thumbnailer may not update due to actual scene not changing md5 <nl> mmm a / scene / resources / mesh . cpp <nl> ppp b / scene / resources / mesh . cpp <nl> void ArrayMesh : : _bind_methods ( ) { <nl> } <nl> <nl> void ArrayMesh : : reload_from_file ( ) { <nl> - for ( int i = 0 ; i < get_surface_count ( ) ; i + + ) { <nl> - surface_remove ( i ) ; <nl> - } <nl> + VisualServer : : get_singleton ( ) - > mesh_clear ( mesh ) ; <nl> + surfaces . clear ( ) ; <nl> + clear_blend_shapes ( ) ; <nl> + <nl> Resource : : reload_from_file ( ) ; <nl> - String path = get_path ( ) ; <nl> + <nl> + _change_notify ( ) ; <nl> } <nl> <nl> ArrayMesh : : ArrayMesh ( ) { <nl> | Merge pull request from djrm / pr_import_fixes | godotengine/godot | d2bc9613887d9ad02f5c3f95ebd65714fe5c4aee | 2017-11-19T20:59:11Z |
mmm a / src / base / settingsstorage . cpp <nl> ppp b / src / base / settingsstorage . cpp <nl> QVariantHash TransactionalSettings : : read ( ) <nl> . arg ( Utils : : Fs : : toNativePath ( newPath ) ) <nl> , Log : : WARNING ) ; <nl> <nl> - Utils : : Fs : : forceRemove ( newPath ) ; <nl> - write ( res ) ; <nl> + QString finalPath = newPath ; <nl> + int index = finalPath . lastIndexOf ( " _new " , - 1 , Qt : : CaseInsensitive ) ; <nl> + finalPath . remove ( index , 4 ) ; <nl> + <nl> + Utils : : Fs : : forceRemove ( finalPath ) ; <nl> + QFile : : rename ( newPath , finalPath ) ; <nl> } <nl> else { <nl> deserialize ( m_name , res ) ; <nl> | Make settings file recovery more robust | qbittorrent/qBittorrent | 099314d17fdff0fd245103e6eb75265e04301577 | 2018-04-30T05:01:10Z |
mmm a / include / envoy / stats / scope . h <nl> ppp b / include / envoy / stats / scope . h <nl> class Scope { <nl> * @ return a counter within the scope ' s namespace . <nl> * / <nl> virtual Counter & counterFromStatNameWithTags ( const StatName & name , <nl> - StatNameTagVectorOptRef tags ) PURE ; <nl> + StatNameTagVectorOptConstRef tags ) PURE ; <nl> <nl> / * * <nl> * TODO ( # 6667 ) : this variant is deprecated : use counterFromStatName . <nl> class Scope { <nl> * @ param import_mode Whether hot - restart should accumulate this value . <nl> * @ return a gauge within the scope ' s namespace . <nl> * / <nl> - virtual Gauge & gaugeFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptRef tags , <nl> + virtual Gauge & gaugeFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptConstRef tags , <nl> Gauge : : ImportMode import_mode ) PURE ; <nl> <nl> / * * <nl> class Scope { <nl> * @ return a histogram within the scope ' s namespace with a particular value type . <nl> * / <nl> virtual Histogram & histogramFromStatNameWithTags ( const StatName & name , <nl> - StatNameTagVectorOptRef tags , <nl> + StatNameTagVectorOptConstRef tags , <nl> Histogram : : Unit unit ) PURE ; <nl> <nl> / * * <nl> mmm a / include / envoy / stats / tag . h <nl> ppp b / include / envoy / stats / tag . h <nl> using TagVector = std : : vector < Tag > ; <nl> <nl> using StatNameTag = std : : pair < StatName , StatName > ; <nl> using StatNameTagVector = std : : vector < StatNameTag > ; <nl> - using StatNameTagVectorOptRef = absl : : optional < std : : reference_wrapper < StatNameTagVector > > ; <nl> + using StatNameTagVectorOptConstRef = <nl> + absl : : optional < std : : reference_wrapper < const StatNameTagVector > > ; <nl> <nl> } / / namespace Stats <nl> } / / namespace Envoy <nl> mmm a / source / common / stats / isolated_store_impl . h <nl> ppp b / source / common / stats / isolated_store_impl . h <nl> class IsolatedStoreImpl : public StoreImpl { <nl> <nl> / / Stats : : Scope <nl> Counter & counterFromStatNameWithTags ( const StatName & name , <nl> - StatNameTagVectorOptRef tags ) override { <nl> + StatNameTagVectorOptConstRef tags ) override { <nl> TagUtility : : TagStatNameJoiner joiner ( name , tags , symbolTable ( ) ) ; <nl> Counter & counter = counters_ . get ( joiner . nameWithTags ( ) ) ; <nl> return counter ; <nl> } <nl> ScopePtr createScope ( const std : : string & name ) override ; <nl> void deliverHistogramToSinks ( const Histogram & , uint64_t ) override { } <nl> - Gauge & gaugeFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptRef tags , <nl> + Gauge & gaugeFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptConstRef tags , <nl> Gauge : : ImportMode import_mode ) override { <nl> TagUtility : : TagStatNameJoiner joiner ( name , tags , symbolTable ( ) ) ; <nl> Gauge & gauge = gauges_ . get ( joiner . nameWithTags ( ) , import_mode ) ; <nl> class IsolatedStoreImpl : public StoreImpl { <nl> } <nl> NullCounterImpl & nullCounter ( ) { return * null_counter_ ; } <nl> NullGaugeImpl & nullGauge ( const std : : string & ) override { return * null_gauge_ ; } <nl> - Histogram & histogramFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptRef tags , <nl> + Histogram & histogramFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptConstRef tags , <nl> Histogram : : Unit unit ) override { <nl> TagUtility : : TagStatNameJoiner joiner ( name , tags , symbolTable ( ) ) ; <nl> Histogram & histogram = histograms_ . get ( joiner . nameWithTags ( ) , unit ) ; <nl> mmm a / source / common / stats / scope_prefixer . cc <nl> ppp b / source / common / stats / scope_prefixer . cc <nl> ScopePtr ScopePrefixer : : createScope ( const std : : string & name ) { <nl> } <nl> <nl> Counter & ScopePrefixer : : counterFromStatNameWithTags ( const StatName & name , <nl> - StatNameTagVectorOptRef tags ) { <nl> + StatNameTagVectorOptConstRef tags ) { <nl> Stats : : SymbolTable : : StoragePtr stat_name_storage = <nl> scope_ . symbolTable ( ) . join ( { prefix_ . statName ( ) , name } ) ; <nl> return scope_ . counterFromStatNameWithTags ( StatName ( stat_name_storage . get ( ) ) , tags ) ; <nl> } <nl> <nl> - Gauge & ScopePrefixer : : gaugeFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptRef tags , <nl> + Gauge & ScopePrefixer : : gaugeFromStatNameWithTags ( const StatName & name , <nl> + StatNameTagVectorOptConstRef tags , <nl> Gauge : : ImportMode import_mode ) { <nl> Stats : : SymbolTable : : StoragePtr stat_name_storage = <nl> scope_ . symbolTable ( ) . join ( { prefix_ . statName ( ) , name } ) ; <nl> Gauge & ScopePrefixer : : gaugeFromStatNameWithTags ( const StatName & name , StatNameTa <nl> } <nl> <nl> Histogram & ScopePrefixer : : histogramFromStatNameWithTags ( const StatName & name , <nl> - StatNameTagVectorOptRef tags , <nl> + StatNameTagVectorOptConstRef tags , <nl> Histogram : : Unit unit ) { <nl> Stats : : SymbolTable : : StoragePtr stat_name_storage = <nl> scope_ . symbolTable ( ) . join ( { prefix_ . statName ( ) , name } ) ; <nl> mmm a / source / common / stats / scope_prefixer . h <nl> ppp b / source / common / stats / scope_prefixer . h <nl> class ScopePrefixer : public Scope { <nl> <nl> / / Scope <nl> ScopePtr createScope ( const std : : string & name ) override ; <nl> - Counter & counterFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptRef tags ) override ; <nl> - Gauge & gaugeFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptRef tags , <nl> + Counter & counterFromStatNameWithTags ( const StatName & name , <nl> + StatNameTagVectorOptConstRef tags ) override ; <nl> + Gauge & gaugeFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptConstRef tags , <nl> Gauge : : ImportMode import_mode ) override ; <nl> - Histogram & histogramFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptRef tags , <nl> + Histogram & histogramFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptConstRef tags , <nl> Histogram : : Unit unit ) override ; <nl> void deliverHistogramToSinks ( const Histogram & histograms , uint64_t val ) override ; <nl> <nl> mmm a / source / common / stats / tag_utility . cc <nl> ppp b / source / common / stats / tag_utility . cc <nl> namespace Stats { <nl> namespace TagUtility { <nl> <nl> TagStatNameJoiner : : TagStatNameJoiner ( StatName prefix , StatName stat_name , <nl> - StatNameTagVectorOptRef stat_name_tags , <nl> + StatNameTagVectorOptConstRef stat_name_tags , <nl> SymbolTable & symbol_table ) { <nl> prefix_storage_ = symbol_table . join ( { prefix , stat_name } ) ; <nl> tag_extracted_name_ = StatName ( prefix_storage_ . get ( ) ) ; <nl> TagStatNameJoiner : : TagStatNameJoiner ( StatName prefix , StatName stat_name , <nl> } <nl> } <nl> <nl> - TagStatNameJoiner : : TagStatNameJoiner ( StatName stat_name , StatNameTagVectorOptRef stat_name_tags , <nl> + TagStatNameJoiner : : TagStatNameJoiner ( StatName stat_name , <nl> + StatNameTagVectorOptConstRef stat_name_tags , <nl> SymbolTable & symbol_table ) { <nl> tag_extracted_name_ = stat_name ; <nl> <nl> mmm a / source / common / stats / tag_utility . h <nl> ppp b / source / common / stats / tag_utility . h <nl> class TagStatNameJoiner { <nl> * @ param name StaName the stat name to use . <nl> * @ param stat_name_tags optionally StatNameTagVector the stat name tags to add to the stat name . <nl> * / <nl> - TagStatNameJoiner ( StatName prefix , StatName stat_name , StatNameTagVectorOptRef stat_name_tags , <nl> - SymbolTable & symbol_table ) ; <nl> + TagStatNameJoiner ( StatName prefix , StatName stat_name , <nl> + StatNameTagVectorOptConstRef stat_name_tags , SymbolTable & symbol_table ) ; <nl> <nl> / * * <nl> * Combines a stat name and tags into a single stat name . <nl> * @ param name StaName the stat name to use . <nl> * @ param stat_name_tags StatNameTagVector the stat name tags to optionally add to the stat name . <nl> * / <nl> - TagStatNameJoiner ( StatName stat_name , StatNameTagVectorOptRef stat_name_tags , <nl> + TagStatNameJoiner ( StatName stat_name , StatNameTagVectorOptConstRef stat_name_tags , <nl> SymbolTable & symbol_table ) ; <nl> <nl> / * * <nl> mmm a / source / common / stats / thread_local_store . cc <nl> ppp b / source / common / stats / thread_local_store . cc <nl> ThreadLocalStoreImpl : : ScopeImpl : : findStatLockHeld ( <nl> } <nl> <nl> Counter & ThreadLocalStoreImpl : : ScopeImpl : : counterFromStatNameWithTags ( <nl> - const StatName & name , StatNameTagVectorOptRef stat_name_tags ) { <nl> + const StatName & name , StatNameTagVectorOptConstRef stat_name_tags ) { <nl> if ( parent_ . rejectsAll ( ) ) { <nl> return parent_ . null_counter_ ; <nl> } <nl> void ThreadLocalStoreImpl : : ScopeImpl : : deliverHistogramToSinks ( const Histogram & h <nl> } <nl> <nl> Gauge & ThreadLocalStoreImpl : : ScopeImpl : : gaugeFromStatNameWithTags ( <nl> - const StatName & name , StatNameTagVectorOptRef stat_name_tags , Gauge : : ImportMode import_mode ) { <nl> + const StatName & name , StatNameTagVectorOptConstRef stat_name_tags , <nl> + Gauge : : ImportMode import_mode ) { <nl> if ( parent_ . rejectsAll ( ) ) { <nl> return parent_ . null_gauge_ ; <nl> } <nl> Gauge & ThreadLocalStoreImpl : : ScopeImpl : : gaugeFromStatNameWithTags ( <nl> } <nl> <nl> Histogram & ThreadLocalStoreImpl : : ScopeImpl : : histogramFromStatNameWithTags ( <nl> - const StatName & name , StatNameTagVectorOptRef stat_name_tags , Histogram : : Unit unit ) { <nl> + const StatName & name , StatNameTagVectorOptConstRef stat_name_tags , Histogram : : Unit unit ) { <nl> if ( parent_ . rejectsAll ( ) ) { <nl> return parent_ . null_histogram_ ; <nl> } <nl> mmm a / source / common / stats / thread_local_store . h <nl> ppp b / source / common / stats / thread_local_store . h <nl> class ThreadLocalStoreImpl : Logger : : Loggable < Logger : : Id : : stats > , public StoreRo <nl> <nl> / / Stats : : Scope <nl> Counter & counterFromStatNameWithTags ( const StatName & name , <nl> - StatNameTagVectorOptRef tags ) override { <nl> + StatNameTagVectorOptConstRef tags ) override { <nl> return default_scope_ - > counterFromStatNameWithTags ( name , tags ) ; <nl> } <nl> Counter & counter ( const std : : string & name ) override { return default_scope_ - > counter ( name ) ; } <nl> class ThreadLocalStoreImpl : Logger : : Loggable < Logger : : Id : : stats > , public StoreRo <nl> void deliverHistogramToSinks ( const Histogram & histogram , uint64_t value ) override { <nl> return default_scope_ - > deliverHistogramToSinks ( histogram , value ) ; <nl> } <nl> - Gauge & gaugeFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptRef tags , <nl> + Gauge & gaugeFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptConstRef tags , <nl> Gauge : : ImportMode import_mode ) override { <nl> return default_scope_ - > gaugeFromStatNameWithTags ( name , tags , import_mode ) ; <nl> } <nl> Gauge & gauge ( const std : : string & name , Gauge : : ImportMode import_mode ) override { <nl> return default_scope_ - > gauge ( name , import_mode ) ; <nl> } <nl> - Histogram & histogramFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptRef tags , <nl> + Histogram & histogramFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptConstRef tags , <nl> Histogram : : Unit unit ) override { <nl> return default_scope_ - > histogramFromStatNameWithTags ( name , tags , unit ) ; <nl> } <nl> class ThreadLocalStoreImpl : Logger : : Loggable < Logger : : Id : : stats > , public StoreRo <nl> <nl> / / Stats : : Scope <nl> Counter & counterFromStatNameWithTags ( const StatName & name , <nl> - StatNameTagVectorOptRef tags ) override ; <nl> + StatNameTagVectorOptConstRef tags ) override ; <nl> void deliverHistogramToSinks ( const Histogram & histogram , uint64_t value ) override ; <nl> - Gauge & gaugeFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptRef tags , <nl> + Gauge & gaugeFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptConstRef tags , <nl> Gauge : : ImportMode import_mode ) override ; <nl> - Histogram & histogramFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptRef tags , <nl> + Histogram & histogramFromStatNameWithTags ( const StatName & name , <nl> + StatNameTagVectorOptConstRef tags , <nl> Histogram : : Unit unit ) override ; <nl> Histogram & tlsHistogram ( StatName name , ParentHistogramImpl & parent ) override ; <nl> ScopePtr createScope ( const std : : string & name ) override { <nl> mmm a / test / common / stats / stat_test_utility . cc <nl> ppp b / test / common / stats / stat_test_utility . cc <nl> Counter & TestStore : : counter ( const std : : string & name ) { <nl> } <nl> <nl> Counter & TestStore : : counterFromStatNameWithTags ( const StatName & stat_name , <nl> - StatNameTagVectorOptRef tags ) { <nl> + StatNameTagVectorOptConstRef tags ) { <nl> std : : string name = symbolTable ( ) . toString ( stat_name ) ; <nl> Counter * & counter_ref = counter_map_ [ name ] ; <nl> if ( counter_ref = = nullptr ) { <nl> Gauge & TestStore : : gauge ( const std : : string & name , Gauge : : ImportMode mode ) { <nl> return * gauge_ref ; <nl> } <nl> <nl> - Gauge & TestStore : : gaugeFromStatNameWithTags ( const StatName & stat_name , StatNameTagVectorOptRef tags , <nl> + Gauge & TestStore : : gaugeFromStatNameWithTags ( const StatName & stat_name , <nl> + StatNameTagVectorOptConstRef tags , <nl> Gauge : : ImportMode mode ) { <nl> std : : string name = symbolTable ( ) . toString ( stat_name ) ; <nl> Gauge * & gauge_ref = gauge_map_ [ name ] ; <nl> Histogram & TestStore : : histogram ( const std : : string & name , Histogram : : Unit unit ) { <nl> } <nl> <nl> Histogram & TestStore : : histogramFromStatNameWithTags ( const StatName & stat_name , <nl> - StatNameTagVectorOptRef tags , <nl> + StatNameTagVectorOptConstRef tags , <nl> Histogram : : Unit unit ) { <nl> std : : string name = symbolTable ( ) . toString ( stat_name ) ; <nl> Histogram * & histogram_ref = histogram_map_ [ name ] ; <nl> mmm a / test / common / stats / stat_test_utility . h <nl> ppp b / test / common / stats / stat_test_utility . h <nl> class TestStore : public IsolatedStoreImpl { <nl> Counter & counter ( const std : : string & name ) override ; <nl> Gauge & gauge ( const std : : string & name , Gauge : : ImportMode import_mode ) override ; <nl> Histogram & histogram ( const std : : string & name , Histogram : : Unit unit ) override ; <nl> - Counter & counterFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptRef tags ) override ; <nl> - Gauge & gaugeFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptRef tags , <nl> + Counter & counterFromStatNameWithTags ( const StatName & name , <nl> + StatNameTagVectorOptConstRef tags ) override ; <nl> + Gauge & gaugeFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptConstRef tags , <nl> Gauge : : ImportMode import_mode ) override ; <nl> - Histogram & histogramFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptRef tags , <nl> + Histogram & histogramFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptConstRef tags , <nl> Histogram : : Unit unit ) override ; <nl> <nl> / / New APIs available for tests . <nl> mmm a / test / integration / server . h <nl> ppp b / test / integration / server . h <nl> class TestScopeWrapper : public Scope { <nl> } <nl> <nl> Counter & counterFromStatNameWithTags ( const StatName & name , <nl> - StatNameTagVectorOptRef tags ) override { <nl> + StatNameTagVectorOptConstRef tags ) override { <nl> Thread : : LockGuard lock ( lock_ ) ; <nl> return wrapped_scope_ - > counterFromStatNameWithTags ( name , tags ) ; <nl> } <nl> <nl> - Gauge & gaugeFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptRef tags , <nl> + Gauge & gaugeFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptConstRef tags , <nl> Gauge : : ImportMode import_mode ) override { <nl> Thread : : LockGuard lock ( lock_ ) ; <nl> return wrapped_scope_ - > gaugeFromStatNameWithTags ( name , tags , import_mode ) ; <nl> } <nl> <nl> - Histogram & histogramFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptRef tags , <nl> + Histogram & histogramFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptConstRef tags , <nl> Histogram : : Unit unit ) override { <nl> Thread : : LockGuard lock ( lock_ ) ; <nl> return wrapped_scope_ - > histogramFromStatNameWithTags ( name , tags , unit ) ; <nl> class TestIsolatedStoreImpl : public StoreRoot { <nl> public : <nl> / / Stats : : Scope <nl> Counter & counterFromStatNameWithTags ( const StatName & name , <nl> - StatNameTagVectorOptRef tags ) override { <nl> + StatNameTagVectorOptConstRef tags ) override { <nl> Thread : : LockGuard lock ( lock_ ) ; <nl> return store_ . counterFromStatNameWithTags ( name , tags ) ; <nl> } <nl> class TestIsolatedStoreImpl : public StoreRoot { <nl> return ScopePtr { new TestScopeWrapper ( lock_ , store_ . createScope ( name ) ) } ; <nl> } <nl> void deliverHistogramToSinks ( const Histogram & , uint64_t ) override { } <nl> - Gauge & gaugeFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptRef tags , <nl> + Gauge & gaugeFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptConstRef tags , <nl> Gauge : : ImportMode import_mode ) override { <nl> Thread : : LockGuard lock ( lock_ ) ; <nl> return store_ . gaugeFromStatNameWithTags ( name , tags , import_mode ) ; <nl> class TestIsolatedStoreImpl : public StoreRoot { <nl> Thread : : LockGuard lock ( lock_ ) ; <nl> return store_ . gauge ( name , import_mode ) ; <nl> } <nl> - Histogram & histogramFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptRef tags , <nl> + Histogram & histogramFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptConstRef tags , <nl> Histogram : : Unit unit ) override { <nl> Thread : : LockGuard lock ( lock_ ) ; <nl> return store_ . histogramFromStatNameWithTags ( name , tags , unit ) ; <nl> mmm a / test / mocks / stats / mocks . h <nl> ppp b / test / mocks / stats / mocks . h <nl> class MockStore : public SymbolTableProvider , public StoreImpl { <nl> MOCK_METHOD ( GaugeOptConstRef , findGauge , ( StatName ) , ( const ) ) ; <nl> MOCK_METHOD ( HistogramOptConstRef , findHistogram , ( StatName ) , ( const ) ) ; <nl> <nl> - Counter & counterFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptRef ) override { <nl> + Counter & counterFromStatNameWithTags ( const StatName & name , <nl> + StatNameTagVectorOptConstRef ) override { <nl> / / We always just respond with the mocked counter , so the tags don ' t matter . <nl> return counter ( symbol_table_ - > toString ( name ) ) ; <nl> } <nl> - Gauge & gaugeFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptRef , <nl> + Gauge & gaugeFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptConstRef , <nl> Gauge : : ImportMode import_mode ) override { <nl> / / We always just respond with the mocked gauge , so the tags don ' t matter . <nl> return gauge ( symbol_table_ - > toString ( name ) , import_mode ) ; <nl> } <nl> - Histogram & histogramFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptRef , <nl> + Histogram & histogramFromStatNameWithTags ( const StatName & name , StatNameTagVectorOptConstRef , <nl> Histogram : : Unit unit ) override { <nl> return histogram ( symbol_table_ - > toString ( name ) , unit ) ; <nl> } <nl> | stats : pass tags by const ref ( ) | envoyproxy/envoy | cb7f13c67cb8b9f02afc053f6eef743a3ed3c1af | 2020-03-05T23:51:07Z |
mmm a / tensorflow / compiler / mlir / tensorflow / ir / tf_ops . cc <nl> ppp b / tensorflow / compiler / mlir / tensorflow / ir / tf_ops . cc <nl> void TruncateDivOp : : getCanonicalizationPatterns ( <nl> static LogicalResult Verify ( WhileOp op ) { <nl> auto module = op . getParentOfType < ModuleOp > ( ) ; <nl> auto condFn = module . lookupSymbol < FuncOp > ( op . cond ( ) ) ; <nl> + auto bodyFn = module . lookupSymbol < FuncOp > ( op . body ( ) ) ; <nl> + if ( ! condFn ) { <nl> + return op . emitOpError ( " cond refers to an undefined function : " ) <nl> + < < op . cond ( ) ; <nl> + } <nl> + if ( ! bodyFn ) { <nl> + return op . emitOpError ( " body refers to an undefined function : " ) <nl> + < < op . body ( ) ; <nl> + } <nl> + <nl> auto condFuncType = condFn . getType ( ) ; <nl> + auto bodyFuncType = bodyFn . getType ( ) ; <nl> <nl> / / Verify that the cond function has exactly one result . <nl> if ( condFuncType . getNumResults ( ) ! = 1 ) <nl> return op . emitOpError ( " requires cond function to have exactly one result " ) ; <nl> <nl> - auto bodyFn = module . lookupSymbol < FuncOp > ( op . body ( ) ) ; <nl> - auto bodyFuncType = bodyFn . getType ( ) ; <nl> - <nl> SmallVector < Type , 4 > operands ( op . getOperandTypes ( ) ) ; <nl> SmallVector < Type , 4 > results ( op . getResultTypes ( ) ) ; <nl> <nl> mmm a / tensorflow / compiler / mlir / tensorflow / tests / tf - ops . mlir <nl> ppp b / tensorflow / compiler / mlir / tensorflow / tests / tf - ops . mlir <nl> func @ testWhileResult ( tensor < * xf32 > ) - > ( tensor < * xf32 > ) { <nl> return % 1 : tensor < * xf32 > <nl> } <nl> <nl> + / / mmm - - <nl> + func @ testWhileUndefinedCond ( % arg0 : tensor < i1 > , % arg1 : tensor < f32 > ) - > tensor < f32 > { <nl> + / / expected - error @ + 1 { { cond refers to an undefined function : undefined_func } } <nl> + % 0 = " tf . While " ( % arg0 , % arg1 ) { cond = @ undefined_func , body = @ body , is_stateless = false } : ( tensor < i1 > , tensor < f32 > ) - > ( tensor < f32 > ) <nl> + return % 0 : tensor < f32 > <nl> + } <nl> + <nl> + func @ body ( % arg0 : tensor < i1 > , % arg1 : tensor < f32 > ) - > tensor < f32 > <nl> + <nl> + / / mmm - - <nl> + func @ testWhileUndefinedBody ( % arg0 : tensor < i1 > , % arg1 : tensor < f32 > ) - > tensor < f32 > { <nl> + / / expected - error @ + 1 { { body refers to an undefined function : undefined_func } } <nl> + % 0 = " tf . While " ( % arg0 , % arg1 ) { cond = @ cond , body = @ undefined_func , is_stateless = false } : ( tensor < i1 > , tensor < f32 > ) - > ( tensor < f32 > ) <nl> + return % 0 : tensor < f32 > <nl> + } <nl> + <nl> + func @ cond ( % arg0 : tensor < i1 > , % arg1 : tensor < f32 > ) - > tensor < i1 > <nl> + <nl> / / mmm - - <nl> <nl> func @ testWhileCond ( tensor < * xf32 > ) - > ( ) <nl> func @ testConcatV2 ( % arg : tensor < 8x16xf32 > , % axis : tensor < 1xi32 > ) - > tensor < ? xf32 <nl> % 0 = " tf . ConcatV2 " ( % arg , % axis ) { N = 1 : i64 } : ( tensor < 8x16xf32 > , tensor < 1xi32 > ) - > tensor < ? xf32 > <nl> return % 0 : tensor < ? xf32 > <nl> } <nl> + <nl> | Check " cond " and " body " are defined in tf . While verifier . | tensorflow/tensorflow | 3f5348e84fc74f9e426ee1122ea45fd5cc3ab0e8 | 2019-08-09T18:40:03Z |
mmm a / tools / editor / plugins / canvas_item_editor_plugin . cpp <nl> ppp b / tools / editor / plugins / canvas_item_editor_plugin . cpp <nl> void CanvasItemEditor : : _find_canvas_items_span ( Node * p_node , Rect2 & r_rect , cons <nl> <nl> <nl> <nl> - if ( c ) { <nl> + if ( c & & c - > is_visible_in_tree ( ) ) { <nl> <nl> Rect2 rect = c - > get_item_rect ( ) ; <nl> Transform2D xform = p_xform * c - > get_transform ( ) ; <nl> mmm a / tools / editor / scene_tree_editor . cpp <nl> ppp b / tools / editor / scene_tree_editor . cpp <nl> void SceneTreeEditor : : _node_visibility_changed ( Node * p_node ) { <nl> <nl> bool visible = false ; <nl> <nl> - if ( p_node - > is_class ( " CanvasItem " ) | | p_node - > is_class ( " Spatial " ) ) { <nl> + if ( p_node - > is_class ( " CanvasItem " ) ) { <nl> + visible = p_node - > call ( " is_visible " ) ; <nl> + CanvasItemEditor : : get_singleton ( ) - > get_viewport_control ( ) - > update ( ) ; <nl> + } else if ( p_node - > is_class ( " Spatial " ) ) { <nl> visible = p_node - > call ( " is_visible " ) ; <nl> } <nl> <nl> | 2D Editor : Don ' t show lock icons for hidden nodes . | godotengine/godot | a043ce7304c4a9b56b5d79efa4cca05160339e72 | 2017-01-19T16:11:00Z |
mmm a / arangod / Cluster / AgencyComm . cpp <nl> ppp b / arangod / Cluster / AgencyComm . cpp <nl> bool AgencyComm : : unregisterCallback ( std : : string const & key , std : : string const & e <nl> return result . successful ( ) ; <nl> } <nl> <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / / @ brief blocks on a change of a single value in the backend <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - <nl> - AgencyCommResult AgencyComm : : watchValue ( std : : string const & key , <nl> - uint64_t waitIndex , double timeout , <nl> - bool recursive ) { <nl> - AgencyCommResult result = getValues ( key , recursive ) ; <nl> - <nl> - usleep ( 1000 ) ; <nl> - return result ; <nl> - } <nl> - <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> / / / @ brief acquire a read lock <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> mmm a / arangod / Cluster / AgencyComm . h <nl> ppp b / arangod / Cluster / AgencyComm . h <nl> class AgencyComm { <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> bool unregisterCallback ( std : : string const & key , std : : string const & endpoint ) ; <nl> <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / / @ brief blocks on a change of a single value in the back end <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - <nl> - AgencyCommResult watchValue ( std : : string const & , uint64_t , double , bool ) ; <nl> - <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> / / / @ brief acquire a read lock <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> mmm a / arangod / Cluster / v8 - cluster . cpp <nl> ppp b / arangod / Cluster / v8 - cluster . cpp <nl> static void JS_SetAgency ( v8 : : FunctionCallbackInfo < v8 : : Value > const & args ) { <nl> TRI_V8_TRY_CATCH_END <nl> } <nl> <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / / / @ brief watches a value in the agency <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - <nl> - static void JS_WatchAgency ( v8 : : FunctionCallbackInfo < v8 : : Value > const & args ) { <nl> - TRI_V8_TRY_CATCH_BEGIN ( isolate ) ; <nl> - v8 : : HandleScope scope ( isolate ) ; <nl> - <nl> - if ( args . Length ( ) < 1 ) { <nl> - TRI_V8_THROW_EXCEPTION_USAGE ( <nl> - " watch ( < key > , < waitIndex > , < timeout > , < recursive > ) " ) ; <nl> - } <nl> - <nl> - std : : string const key = TRI_ObjectToString ( args [ 0 ] ) ; <nl> - double timeout = 1 . 0 ; <nl> - uint64_t waitIndex = 0 ; <nl> - bool recursive = false ; <nl> - <nl> - if ( args . Length ( ) > 1 ) { <nl> - waitIndex = TRI_ObjectToUInt64 ( args [ 1 ] , true ) ; <nl> - } <nl> - if ( args . Length ( ) > 2 ) { <nl> - timeout = TRI_ObjectToDouble ( args [ 2 ] ) ; <nl> - } <nl> - if ( args . Length ( ) > 3 ) { <nl> - recursive = TRI_ObjectToBoolean ( args [ 3 ] ) ; <nl> - } <nl> - <nl> - AgencyComm comm ; <nl> - AgencyCommResult result = comm . watchValue ( key , waitIndex , timeout , recursive ) ; <nl> - <nl> - if ( result . _statusCode = = 0 ) { <nl> - / / watch timed out <nl> - TRI_V8_RETURN_FALSE ( ) ; <nl> - } <nl> - <nl> - if ( ! result . successful ( ) ) { <nl> - THROW_AGENCY_EXCEPTION ( result ) ; <nl> - } <nl> - <nl> - result . parse ( " " , false ) ; <nl> - std : : map < std : : string , AgencyCommResultEntry > : : const_iterator it = <nl> - result . _values . begin ( ) ; <nl> - <nl> - v8 : : Handle < v8 : : Object > l = v8 : : Object : : New ( isolate ) ; <nl> - <nl> - while ( it ! = result . _values . end ( ) ) { <nl> - std : : string const key = ( * it ) . first ; <nl> - VPackSlice const slice = it - > second . _vpack - > slice ( ) ; <nl> - <nl> - if ( ! slice . isNone ( ) ) { <nl> - l - > Set ( TRI_V8_STD_STRING ( key ) , TRI_VPackToV8 ( isolate , slice ) ) ; <nl> - } <nl> - <nl> - + + it ; <nl> - } <nl> - <nl> - TRI_V8_RETURN ( l ) ; <nl> - TRI_V8_TRY_CATCH_END <nl> - } <nl> - <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> / / / @ brief returns the agency endpoints <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> void TRI_InitV8Cluster ( v8 : : Isolate * isolate , v8 : : Handle < v8 : : Context > context ) { <nl> TRI_AddMethodVocbase ( isolate , rt , TRI_V8_ASCII_STRING ( " remove " ) , <nl> JS_RemoveAgency ) ; <nl> TRI_AddMethodVocbase ( isolate , rt , TRI_V8_ASCII_STRING ( " set " ) , JS_SetAgency ) ; <nl> - TRI_AddMethodVocbase ( isolate , rt , TRI_V8_ASCII_STRING ( " watch " ) , <nl> - JS_WatchAgency ) ; <nl> TRI_AddMethodVocbase ( isolate , rt , TRI_V8_ASCII_STRING ( " endpoints " ) , <nl> JS_EndpointsAgency ) ; <nl> TRI_AddMethodVocbase ( isolate , rt , TRI_V8_ASCII_STRING ( " prefix " ) , <nl> | Remove watchValue from agency | arangodb/arangodb | b03d4e610a01ce6e8f0127851b322242f9989053 | 2016-04-13T13:42:23Z |
mmm a / caffe2 / python / caffe_translator . py <nl> ppp b / caffe2 / python / caffe_translator . py <nl> def TranslateReshape ( layer , pretrained_blobs , is_test ) : <nl> reshape_param = layer . reshape_param <nl> AddArgument ( caffe_op , ' shape ' , reshape_param . shape . dim ) <nl> return caffe_op , [ ] <nl> + <nl> + <nl> + @ TranslatorRegistry . Register ( " Sigmoid " ) <nl> + def TranslateSigmoid ( layer , pretrained_blobs , is_test ) : <nl> + caffe_op = BaseTranslate ( layer , " Sigmoid " ) <nl> + return caffe_op , [ ] <nl> | Run memonger to optimize net if needed | pytorch/pytorch | a4ba0cceb223d69e2d97bcb88066aa97b384f835 | 2017-01-25T23:14:26Z |
new file mode 100644 <nl> index 00000000000 . . 1742f6ae1b5 <nl> mmm / dev / null <nl> ppp b / test / common / access_log / access_log_formatter_corpus / clusterfuzz - testcase - minimized - access_log_formatter_fuzz_test - 5758486359572480 <nl> <nl> + format : " % DYNAMIC_METADATA ( ) % " stream_info { <nl> + dynamic_metadata { <nl> + filter_metadata { <nl> + key : <nl> + " " value { <nl> + fields { <nl> + key : <nl> + " " value { <nl> + list_value { <nl> + values { <nl> + struct_value { <nl> + fields { <nl> + key : <nl> + " " value { <nl> + list_value { <nl> + values { <nl> + struct_value { <nl> + fields { <nl> + key : <nl> + " " value { <nl> + list_value { <nl> + values { <nl> + struct_value { <nl> + fields { <nl> + key : <nl> + " " value { <nl> + list_value { <nl> + values { <nl> + list_value { <nl> + values { <nl> + struct_value { <nl> + fields { <nl> + key : <nl> + " " value { <nl> + list_value { <nl> + values { <nl> + struct_value { <nl> + fields { <nl> + key : <nl> + " " value { <nl> + list_value { <nl> + values { <nl> + struct_value { <nl> + fields { <nl> + key : <nl> + " " value { <nl> + struct_value { <nl> + fields { <nl> + key : <nl> + " " value { <nl> + list_value { <nl> + values { <nl> + list_value { <nl> + values { <nl> + struct_value { <nl> + fields { <nl> + key : <nl> + " " value { <nl> + list_value { <nl> + values { <nl> + struct_value { <nl> + fields { <nl> + key : <nl> + " " value { <nl> + list_value { <nl> + values { <nl> + struct_value { <nl> + fields { <nl> + key : <nl> + " " value { <nl> + list_value { <nl> + values { <nl> + struct_value { <nl> + fields { <nl> + key : <nl> + " " value { <nl> + list_value { <nl> + values { <nl> + struct_value { <nl> + fields { <nl> + key : <nl> + " " value { <nl> + list_value { <nl> + values { <nl> + struct_value { <nl> + fields { <nl> + key : <nl> + " " value { <nl> + list_value { <nl> + values { <nl> + list_value { <nl> + values { <nl> + struct_value { <nl> + fields { <nl> + key : " " <nl> + value { <nl> + list_value { <nl> + values { <nl> + list_value { <nl> + values { <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> mmm a / test / common / access_log / access_log_formatter_fuzz_test . cc <nl> ppp b / test / common / access_log / access_log_formatter_fuzz_test . cc <nl> DEFINE_PROTO_FUZZER ( const test : : common : : access_log : : TestCase & input ) { <nl> try { <nl> std : : vector < AccessLog : : FormatterProviderPtr > formatters = <nl> AccessLog : : AccessLogFormatParser : : parse ( input . format ( ) ) ; <nl> + const auto & request_headers = Fuzz : : fromHeaders ( input . request_headers ( ) ) ; <nl> + const auto & response_headers = Fuzz : : fromHeaders ( input . response_headers ( ) ) ; <nl> + const auto & response_trailers = Fuzz : : fromHeaders ( input . response_trailers ( ) ) ; <nl> + const auto & stream_info = Fuzz : : fromStreamInfo ( input . stream_info ( ) ) ; <nl> for ( const auto & it : formatters ) { <nl> - it - > format ( <nl> - Fuzz : : fromHeaders ( input . request_headers ( ) ) , Fuzz : : fromHeaders ( input . response_headers ( ) ) , <nl> - Fuzz : : fromHeaders ( input . response_trailers ( ) ) , Fuzz : : fromStreamInfo ( input . stream_info ( ) ) ) ; <nl> + it - > format ( request_headers , response_headers , response_trailers , stream_info ) ; <nl> } <nl> ENVOY_LOG_MISC ( trace , " Success " ) ; <nl> } catch ( const EnvoyException & e ) { <nl> new file mode 100644 <nl> index 00000000000 . . d6dbf299fc6 <nl> mmm / dev / null <nl> ppp b / test / common / http / header_map_impl_corpus / clusterfuzz - testcase - minimized - header_map_impl_fuzz_test - 6363647045533696 <nl> <nl> + actions { <nl> + mutate_and_move { <nl> + key : " # " <nl> + append : " ~ " <nl> + } <nl> + } <nl> mmm a / test / common / http / header_map_impl_fuzz_test . cc <nl> ppp b / test / common / http / header_map_impl_fuzz_test . cc <nl> DEFINE_PROTO_FUZZER ( const test : : common : : http : : HeaderMapImplFuzzTestCase & input ) <nl> Http : : HeaderMapImplPtr header_map = std : : make_unique < Http : : HeaderMapImpl > ( ) ; <nl> std : : vector < std : : unique_ptr < Http : : LowerCaseString > > lower_case_strings ; <nl> std : : vector < std : : unique_ptr < std : : string > > strings ; <nl> + uint64_t set_integer ; <nl> constexpr auto max_actions = 128 ; <nl> for ( int i = 0 ; i < std : : min ( max_actions , input . actions ( ) . size ( ) ) ; + + i ) { <nl> const auto & action = input . actions ( i ) ; <nl> DEFINE_PROTO_FUZZER ( const test : : common : : http : : HeaderMapImplFuzzTestCase & input ) <nl> } <nl> case test : : common : : http : : Action : : kMutateAndMove : { <nl> const auto & mutate_and_move = action . mutate_and_move ( ) ; <nl> - Http : : HeaderString header_field ( <nl> - Http : : LowerCaseString ( replaceInvalidCharacters ( mutate_and_move . key ( ) ) ) ) ; <nl> + lower_case_strings . emplace_back ( <nl> + std : : make_unique < Http : : LowerCaseString > ( replaceInvalidCharacters ( mutate_and_move . key ( ) ) ) ) ; <nl> + Http : : HeaderString header_field ( * lower_case_strings . back ( ) ) ; <nl> Http : : HeaderString header_value ; <nl> / / Do some mutation or parameterized action . <nl> switch ( mutate_and_move . mutate_selector_case ( ) ) { <nl> DEFINE_PROTO_FUZZER ( const test : : common : : http : : HeaderMapImplFuzzTestCase & input ) <nl> header_value . setCopy ( replaceInvalidCharacters ( mutate_and_move . set_copy ( ) ) ) ; <nl> break ; <nl> case test : : common : : http : : MutateAndMove : : kSetInteger : <nl> - header_value . setInteger ( mutate_and_move . set_integer ( ) ) ; <nl> + set_integer = mutate_and_move . set_integer ( ) ; <nl> + header_value . setInteger ( set_integer ) ; <nl> break ; <nl> case test : : common : : http : : MutateAndMove : : kSetReference : <nl> strings . emplace_back ( std : : make_unique < std : : string > ( <nl> mmm a / test / fuzz / utility . h <nl> ppp b / test / fuzz / utility . h <nl> inline TestStreamInfo fromStreamInfo ( const test : : fuzz : : StreamInfo & stream_info ) <nl> testing : : DefaultValue < const std : : string & > : : Set ( EMPTY_STRING ) ; <nl> TestStreamInfo test_stream_info ; <nl> test_stream_info . metadata_ = stream_info . dynamic_metadata ( ) ; <nl> + / / Truncate recursive filter metadata fields . <nl> + / / TODO ( asraa ) : Resolve MessageToJsonString failure on recursive filter metadata . <nl> + for ( auto & pair : * test_stream_info . metadata_ . mutable_filter_metadata ( ) ) { <nl> + std : : string value ; <nl> + pair . second . SerializeToString ( & value ) ; <nl> + pair . second . ParseFromString ( value . substr ( 0 , 128 ) ) ; <nl> + } <nl> / / libc + + clocks don ' t track at nanosecond on macOS . <nl> const auto start_time = <nl> static_cast < uint64_t > ( std : : numeric_limits < std : : chrono : : nanoseconds : : rep > : : max ( ) ) < <nl> | [ fuzz ] fix - up small fuzz bugs in JSON parsing ( ) | envoyproxy/envoy | 484f76798e0c94065d5d953c3c111af40f0e9bc8 | 2019-12-23T21:40:46Z |
mmm a / cocos / base / CCTouch . h <nl> ppp b / cocos / base / CCTouch . h <nl> class CC_DLL Touch : public Ref <nl> { <nl> _startPoint = _point ; <nl> _startPointCaptured = true ; <nl> + _prevPoint = _point ; <nl> } <nl> } <nl> / * * <nl> | bug on began touch - prevpoint | cocos2d/cocos2d-x | a7a2490aee854a9587d7286750f11d00f688990c | 2014-07-01T07:35:04Z |
mmm a / programs / eosc / main . cpp <nl> ppp b / programs / eosc / main . cpp <nl> int main ( int argc , char * * argv ) { <nl> <nl> auto benchmark_transfer = benchmark - > add_subcommand ( " transfer " , localized ( " executes random transfers among accounts " ) ) ; <nl> uint64_t number_of_transfers = 0 ; <nl> + uint64_t expiration = 0 ; <nl> bool loop = false ; <nl> benchmark_transfer - > add_option ( " accounts " , number_of_accounts , localized ( " the number of accounts in transfer among " ) ) - > required ( ) ; <nl> benchmark_transfer - > add_option ( " count " , number_of_transfers , localized ( " the number of transfers to execute " ) ) - > required ( ) ; <nl> + benchmark_transfer - > add_option ( " expiration " , expiration , localized ( " the number of seconds to expire " ) ) - > required ( ) ; <nl> benchmark_transfer - > add_option ( " loop " , loop , localized ( " whether or not to loop for ever " ) ) ; <nl> add_standard_transaction_options ( benchmark_transfer ) ; <nl> benchmark_transfer - > set_callback ( [ & ] { <nl> int main ( int argc , char * * argv ) { <nl> transaction_emplace_message ( trx , config : : eos_contract_name , <nl> vector < types : : account_permission > { { sender , " active " } } , <nl> " transfer " , types : : transfer { sender , recipient , amount , memo } ) ; <nl> - trx . expiration = info . head_block_time + fc : : seconds ( 1800 ) ; <nl> + trx . expiration = info . head_block_time + fc : : seconds ( expiration ) ; <nl> transaction_set_reference_block ( trx , info . head_block_id ) ; <nl> sign_transaction ( trx ) ; <nl> batch . emplace_back ( trx ) ; <nl> | Updated expiration in seconds for benchmark transfer command . | EOSIO/eos | 41a4c367b1dd2968083403aa9742ea4ef4878a6a | 2017-11-23T02:50:50Z |
mmm a / BUILD <nl> ppp b / BUILD <nl> config_setting ( <nl> # This should be updated along with build . yaml <nl> g_stands_for = " gizmo " <nl> <nl> - core_version = " 7 . 0 . 0 - dev " <nl> + core_version = " 7 . 0 . 0 - pre1 " <nl> <nl> version = " 1 . 17 . 0 - pre1 " <nl> <nl> mmm a / build . yaml <nl> ppp b / build . yaml <nl> settings : <nl> ' # 08 ' : Use " - preN " suffixes to identify pre - release versions <nl> ' # 09 ' : Per - language overrides are possible with ( eg ) ruby_version tag here <nl> ' # 10 ' : See the expand_version . py for all the quirks here <nl> - core_version : 7 . 0 . 0 - dev <nl> + core_version : 7 . 0 . 0 - pre1 <nl> g_stands_for : gizmo <nl> version : 1 . 17 . 0 - pre1 <nl> filegroups : <nl> | dev - > pre1 for core version | grpc/grpc | 96ed4b75789d422eb362cb7909428217bab63c7d | 2018-11-20T01:01:28Z |
mmm a / tensorflow / compiler / mlir / lite / tests / optimize . mlir <nl> ppp b / tensorflow / compiler / mlir / lite / tests / optimize . mlir <nl> func @ fuseMulIntoFullyConnected ( % arg0 : tensor < 4x2xf32 > ) - > tensor < 4x2xf32 > { <nl> <nl> return % 1 : tensor < 4x2xf32 > <nl> <nl> - / / CHECK : % [ [ CONSTANT : . * ] ] = constant dense < { { \ [ \ [ } } 1 . 000000e + 00 , 4 . 000000e + 00 ] , [ 3 . 000000e + 00 , 8 . 000000e + 00 ] ] > : tensor < 2x2xf32 > <nl> + / / CHECK : % [ [ CONSTANT : . * ] ] = constant dense < { { \ [ \ [ } } 1 . 000000e + 00 , 2 . 000000e + 00 ] , [ 6 . 000000e + 00 , 8 . 000000e + 00 ] ] > : tensor < 2x2xf32 > <nl> / / CHECK : % [ [ CONSTANT0 : . * ] ] = constant dense < [ 2 . 000000e + 00 , 4 . 000000e + 00 ] > : tensor < 2xf32 > <nl> / / CHECK : % [ [ RES : . * ] ] = " tfl . fully_connected " ( % arg0 , % [ [ CONSTANT ] ] , % [ [ CONSTANT0 ] ] ) { fused_activation_function = " RELU6 " , keep_num_dims = false , weights_format = " DEFAULT " } <nl> / / CHECK : return % [ [ RES ] ] : tensor < 4x2xf32 > <nl> func @ fuseMulIntoFullyConnectedNoBias ( % arg0 : tensor < 4x2xf32 > , % arg1 : none ) - > te <nl> <nl> return % 1 : tensor < 4x2xf32 > <nl> <nl> - / / CHECK : % [ [ CONSTANT : . * ] ] = constant dense < { { \ [ \ [ } } 1 . 000000e + 00 , 4 . 000000e + 00 ] , [ 3 . 000000e + 00 , 8 . 000000e + 00 ] ] > : tensor < 2x2xf32 > <nl> + / / CHECK : % [ [ CONSTANT : . * ] ] = constant dense < { { \ [ \ [ } } 1 . 000000e + 00 , 2 . 000000e + 00 ] , [ 6 . 000000e + 00 , 8 . 000000e + 00 ] ] > : tensor < 2x2xf32 > <nl> / / CHECK : % [ [ RES : . * ] ] = " tfl . fully_connected " ( % arg0 , % [ [ CONSTANT ] ] , % arg1 ) { fused_activation_function = " RELU6 " , keep_num_dims = false , weights_format = " DEFAULT " } : ( tensor < 4x2xf32 > , tensor < 2x2xf32 > , none ) - > tensor < 4x2xf32 > <nl> / / CHECK : return % [ [ RES ] ] : tensor < 4x2xf32 > <nl> } <nl> mmm a / tensorflow / compiler / mlir / lite / transforms / optimize . cc <nl> ppp b / tensorflow / compiler / mlir / lite / transforms / optimize . cc <nl> struct FuseFullyConnectedAndMul : public OpRewritePattern < TFL : : MulOp > { <nl> return failure ( ) ; <nl> if ( fc_op . fused_activation_function ( ) ! = " NONE " ) return failure ( ) ; <nl> <nl> - / / Broadcast the constant operand of Mul if it isn ' t compatible to the <nl> - / / filter input . We only support broadcasting the operand along the depth <nl> - / / dimension , when the operand ' s depth is 1 . <nl> - Value new_const_val = constant_val ; <nl> - if ( ! IsBroadcastableElementsAttrAndType ( cst . getType ( ) , filter . getType ( ) ) ) { <nl> - auto original_shape = cst . getType ( ) . getShape ( ) ; <nl> - llvm : : SmallVector < int64_t , 4 > normalized_shape ( original_shape . begin ( ) , <nl> - original_shape . end ( ) ) ; <nl> - normalized_shape . push_back ( 1 ) ; <nl> - auto new_cst = cst . reshape ( RankedTensorType : : get ( <nl> - normalized_shape , cst . getType ( ) . getElementType ( ) ) ) ; <nl> - Type new_type = new_cst . getType ( ) ; <nl> - if ( ! IsBroadcastableElementsAttrAndType ( new_type , filter . getType ( ) ) ) { <nl> - return failure ( ) ; <nl> - } <nl> - auto new_op = <nl> - rewriter . create < ConstantOp > ( mul_op . getLoc ( ) , new_type , new_cst ) ; <nl> - new_const_val = new_op . getResult ( ) ; <nl> + / / Only fuse multiplier if all dimensions other than the depth dimension <nl> + / / are equal to 1 since otherwise <nl> + / / ` matmul ( x , filter ) * cst ! = matmul ( x , filter * cst ) ` <nl> + / / even if ` filter ` and ` cst ` are be broadcastable . <nl> + auto shape = cst . getType ( ) . getShape ( ) ; <nl> + if ( ! IsDimensionsDegenerateExceptLastOne ( shape ) ) return failure ( ) ; <nl> + <nl> + int64_t element_size = shape . empty ( ) ? 1 : shape [ shape . size ( ) - 1 ] ; <nl> + / / Expand and transpose the multiplier since weights are using the <nl> + / / OHWI data format in TFLite . <nl> + int64_t normalized_shape [ 2 ] = { element_size , 1 } ; <nl> + auto new_cst = cst . reshape ( RankedTensorType : : get ( <nl> + normalized_shape , cst . getType ( ) . getElementType ( ) ) ) ; <nl> + Type new_type = new_cst . getType ( ) ; <nl> + if ( ! IsBroadcastableElementsAttrAndType ( new_type , filter . getType ( ) ) ) { <nl> + return failure ( ) ; <nl> } <nl> <nl> + auto new_op = <nl> + rewriter . create < ConstantOp > ( mul_op . getLoc ( ) , new_type , new_cst ) ; <nl> + Value new_const_val = new_op . getResult ( ) ; <nl> + <nl> / / Rewrite . Since the folder of TFL : : MulOp couldn ' t broadcast the operands , <nl> / / TF : : MulOp is used to fold the constant . <nl> / / TODO ( b / 139192933 ) : switch to the TFL constant folding <nl> mmm a / tensorflow / compiler / mlir / lite / utils / validators . cc <nl> ppp b / tensorflow / compiler / mlir / lite / utils / validators . cc <nl> bool IsBroadcastableElementsAttrs ( mlir : : Attribute a , mlir : : Attribute b ) { <nl> return OpTrait : : util : : getBroadcastedType ( a . getType ( ) , b . getType ( ) ) ! = Type ( ) ; <nl> } <nl> <nl> + bool IsDimensionsDegenerateExceptLastOne ( ArrayRef < int64_t > elements_shape ) { <nl> + if ( elements_shape . empty ( ) ) return true ; <nl> + <nl> + for ( auto dim : elements_shape . drop_back ( 1 ) ) { <nl> + if ( dim ! = 1 ) return false ; <nl> + } <nl> + return true ; <nl> + } <nl> + <nl> + bool IsDimensionsDegenerateExceptLastOne ( Attribute val ) { <nl> + if ( auto ranked_type = val . getType ( ) . dyn_cast < RankedTensorType > ( ) ) { <nl> + return IsDimensionsDegenerateExceptLastOne ( ranked_type . getShape ( ) ) ; <nl> + } <nl> + return false ; <nl> + } <nl> + <nl> } / / namespace TFL <nl> } / / namespace mlir <nl> mmm a / tensorflow / compiler / mlir / lite / utils / validators . h <nl> ppp b / tensorflow / compiler / mlir / lite / utils / validators . h <nl> inline bool TFPaddingIsSameOrValid ( Operation * op , StringAttr * padding ) { <nl> / / / Returns whether the given ` a ` and ` b ` have broadcast - compatible <nl> / / / types . <nl> bool IsBroadcastableElementsAttrs ( mlir : : Attribute a , mlir : : Attribute b ) ; <nl> + / / Returns true if every dimension of the attribute is 1 except the last one . <nl> + bool IsDimensionsDegenerateExceptLastOne ( mlir : : Attribute val ) ; <nl> + / / Returns true if every element is 1 except the last one . <nl> + bool IsDimensionsDegenerateExceptLastOne ( ArrayRef < int64_t > elements_shape ) ; <nl> <nl> } / / end namespace TFL <nl> } / / end namespace mlir <nl> mmm a / tensorflow / compiler / mlir / tensorflow / transforms / optimize . td <nl> ppp b / tensorflow / compiler / mlir / tensorflow / transforms / optimize . td <nl> include " mlir / Dialect / StandardOps / IR / Ops . td " <nl> include " tensorflow / compiler / mlir / tensorflow / ir / tf_ops . td " <nl> <nl> def IsDataFormatNHWC : ConstantAttr < TF_ConvnetDataFormatAttr , " NHWC " > ; <nl> - def BroadcastableElements : <nl> - Constraint < CPred < " TFL : : IsBroadcastableElementsAttrs ( $ 0 , $ 1 ) " > > ; <nl> + <nl> + / / Only fuse multiplier if all dimensions other than the channel dimension <nl> + / / are equal to 1 . <nl> + def CanFuseMulAndConv2D : <nl> + Constraint < CPred < " TFL : : IsBroadcastableElementsAttrs ( $ 0 , $ 1 ) & & TFL : : IsDimensionsDegenerateExceptLastOne ( $ 1 ) " > > ; <nl> + <nl> def F32ElementsAttr : ElementsAttrBase < <nl> CPred < " $ _self . cast < ElementsAttr > ( ) . getType ( ) . getElementType ( ) . isF32 ( ) " > , " float constant tensor " > ; <nl> def DefinedByConv2D : Constraint < CPred < " llvm : : isa_and_nonnull < mlir : : TF : : Conv2DOp > ( $ 0 . getDefiningOp ( ) ) " > > ; <nl> def FuseMulAndConv2D : <nl> ( location $ mul ) ) , <nl> $ strides , $ use_cudnn , $ padding , $ explicit_padding , $ data_format , <nl> $ dilations , ( location $ conv ) ) , <nl> - [ ( BroadcastableElements $ filter_value , $ mul_value ) , ( HasOneUse $ conv ) ] > ; <nl> + [ ( CanFuseMulAndConv2D $ filter_value , $ mul_value ) , ( HasOneUse $ conv ) ] > ; <nl> <nl> / / This rule does the following pattern match and rewrite : <nl> / / <nl> mmm a / tensorflow / lite / python / lite_v2_test . py <nl> ppp b / tensorflow / lite / python / lite_v2_test . py <nl> def model ( in_tensor ) : <nl> str ( error . exception ) ) <nl> <nl> <nl> + class AffineOpThenMulFusionTest ( lite_v2_test_util . ModelTest ) : <nl> + <nl> + @ parameterized . named_parameters ( ( ' should_fuse_1d ' , [ 2 ] , True ) , <nl> + ( ' should_fuse_1x2 ' , [ 1 , 2 ] , True ) , <nl> + ( ' should_not_fuse_2x1 ' , [ 2 , 1 ] , False ) , <nl> + ( ' should_not_fuse_2x2 ' , [ 2 , 2 ] , False ) ) <nl> + @ test_util . run_v2_only <nl> + def testFullyConnectedFusion ( self , multiplier_shape , can_fuse ) : <nl> + " " " Test fusion of ( x ∗ w ) * m into fullyconnected . " " " <nl> + <nl> + @ tf . function <nl> + def func ( x ) : <nl> + w = tf . constant ( [ 3 . , 4 . , 5 . , 6 . ] , shape = [ 2 , 2 ] ) <nl> + m_value = [ 7 . , 8 . ] if sum ( multiplier_shape ) < 4 else [ 7 . , 8 . , 9 . , 10 . ] <nl> + m = tf . constant ( m_value , shape = multiplier_shape ) <nl> + return tf . matmul ( x , w ) * m <nl> + <nl> + input_data = tf . constant ( [ 1 . , 2 . ] , shape = [ 1 , 2 ] ) <nl> + self . _checkAffineFusion ( func , input_data , 1 if can_fuse else 2 ) <nl> + <nl> + @ parameterized . named_parameters ( ( ' should_fuse_1d ' , [ 2 ] , True ) , <nl> + ( ' should_fuse_1x2 ' , [ 1 , 2 ] , True ) , <nl> + ( ' should_not_fuse_2x1 ' , [ 2 , 1 ] , False ) ) <nl> + @ test_util . run_v2_only <nl> + def testConvFusion ( self , multiplier_shape , can_fuse ) : <nl> + " " " Test fusion of ( x ∗ w ) * m into conv2d . " " " <nl> + <nl> + @ tf . function <nl> + def func ( x ) : <nl> + w = tf . constant ( [ 3 . , 4 . , 5 . , 6 . ] , shape = [ 2 , 1 , 1 , 2 ] ) <nl> + m = tf . constant ( [ 7 . , 8 . ] , shape = multiplier_shape ) <nl> + return tf . nn . conv2d ( x , w , strides = [ 1 , 1 , 1 , 1 ] , padding = ' SAME ' ) * m <nl> + <nl> + input_data = tf . constant ( [ 1 . , 2 . ] , shape = [ 1 , 1 , 2 , 1 ] ) <nl> + self . _checkAffineFusion ( func , input_data , 1 if can_fuse else 2 ) <nl> + <nl> + def _checkAffineFusion ( self , func , input_data , expected_number_of_ops ) : <nl> + concrete_func = func . get_concrete_function ( input_data ) <nl> + converter = lite . TFLiteConverterV2 . from_concrete_functions ( [ concrete_func ] ) <nl> + tflite_model = converter . convert ( ) <nl> + <nl> + interpreter = Interpreter ( model_content = tflite_model ) <nl> + assert len ( interpreter . _get_ops_details ( ) ) = = expected_number_of_ops <nl> + <nl> + expected_value = func ( input_data ) <nl> + actual_value = self . _evaluateTFLiteModel ( tflite_model , [ input_data ] ) [ 0 ] <nl> + self . assertAllClose ( expected_value . numpy ( ) , actual_value ) <nl> + <nl> + <nl> if __name__ = = ' __main__ ' : <nl> test . main ( ) <nl> | Merge pull request from lgeiger : fix - matmul - fusion | tensorflow/tensorflow | 1dc3d68cf2f99d7818acc454dfddcfd86d9d994e | 2020-11-06T12:41:00Z |
mmm a / src / qtlibtorrent / qbtsession . cpp <nl> ppp b / src / qtlibtorrent / qbtsession . cpp <nl> void QBtSession : : configureSession ( ) { <nl> sessionSettings . announce_to_all_tiers = announce_to_all ; <nl> sessionSettings . auto_scrape_min_interval = 900 ; / / 15 minutes <nl> int cache_size = pref . diskCacheSize ( ) ; <nl> - sessionSettings . cache_size = cache_size ? pref . diskCacheSize ( ) * 64 : - 1 ; <nl> + sessionSettings . cache_size = cache_size ? cache_size * 64 : - 1 ; <nl> qDebug ( ) < < " Using a disk cache size of " < < pref . diskCacheSize ( ) < < " MiB " ; <nl> / / Disable OS cache to avoid memory problems ( uTorrent behavior ) <nl> # ifdef Q_WS_WIN <nl> | Merge pull request from sledgehammer999 / qbtsession_optimize | qbittorrent/qBittorrent | ef9cb84b01ef5b9d47d60a258366e1ccfeefc145 | 2012-12-01T13:05:13Z |
mmm a / include / rapidjson / document . h <nl> ppp b / include / rapidjson / document . h <nl> class GenericValue { <nl> \ post IsString ( ) = = true & & GetString ( ) ! = s . data ( ) & & strcmp ( GetString ( ) , s . data ( ) = = 0 & & GetStringLength ( ) = = s . size ( ) <nl> \ note Requires the definition of the preprocessor symbol \ ref RAPIDJSON_HAS_STDSTRING . <nl> * / <nl> - GenericValue & SetString ( const std : : basic_string < Ch > & s , Allocator & allocator ) { return SetString ( s . data ( ) , s . size ( ) , allocator ) ; } <nl> + GenericValue & SetString ( const std : : basic_string < Ch > & s , Allocator & allocator ) { return SetString ( s . data ( ) , SizeType ( s . size ( ) ) , allocator ) ; } <nl> # endif <nl> <nl> / / @ } <nl> | Merge remote - tracking branch ' origin / master ' into json - pointer | Tencent/rapidjson | b0c6a9d7f9ace6f05f2126b7b7336c2204a1d053 | 2015-05-04T02:29:25Z |
mmm a / hphp / runtime / base / comparisons . h <nl> ppp b / hphp / runtime / base / comparisons . h <nl> inline bool equal ( const StringData * v1 , CObjRef v2 ) { <nl> return equal ( toBoolean ( v1 ) , v2 . toBoolean ( ) ) ; <nl> } <nl> if ( v2 - > isCollection ( ) ) return false ; <nl> - try { <nl> - return equal ( v1 , v2 . toString ( ) ) ; <nl> - } catch ( BadTypeConversionException & e ) { <nl> - return false ; <nl> - } <nl> - return false ; <nl> + if ( ! v2 - > hasToString ( ) ) return false ; <nl> + return equal ( v1 , v2 . toString ( ) ) ; <nl> } <nl> inline bool equal ( const StringData * v1 , CResRef v2 ) { <nl> if ( v1 = = nullptr | | v2 . get ( ) = = nullptr ) { <nl> inline bool less ( const StringData * v1 , CObjRef v2 ) { <nl> return less ( toBoolean ( v1 ) , v2 . toBoolean ( ) ) ; <nl> } <nl> check_collection_compare ( v2 . get ( ) ) ; <nl> - try { <nl> - return less ( v1 , v2 . toString ( ) ) ; <nl> - } catch ( BadTypeConversionException & e ) { <nl> - return true ; <nl> - } <nl> + if ( ! v2 - > hasToString ( ) ) return true ; <nl> + return less ( v1 , v2 . toString ( ) ) ; <nl> } <nl> inline bool less ( const StringData * v1 , CResRef v2 ) { <nl> if ( v1 = = nullptr | | v2 . get ( ) = = nullptr ) { <nl> inline bool more ( const StringData * v1 , CObjRef v2 ) { <nl> return more ( toBoolean ( v1 ) , v2 . toBoolean ( ) ) ; <nl> } <nl> check_collection_compare ( v2 . get ( ) ) ; <nl> - try { <nl> - return more ( v1 , v2 . toString ( ) ) ; <nl> - } catch ( BadTypeConversionException & e ) { <nl> - return false ; <nl> - } <nl> + if ( ! v2 - > hasToString ( ) ) return false ; <nl> + return more ( v1 , v2 . toString ( ) ) ; <nl> } <nl> inline bool more ( const StringData * v1 , CResRef v2 ) { <nl> if ( v1 = = nullptr | | v2 . get ( ) = = nullptr ) { <nl> mmm a / hphp / runtime / base / exceptions . h <nl> ppp b / hphp / runtime / base / exceptions . h <nl> class BadArrayOperandException : public InvalidOperandException { <nl> EXCEPTION_COMMON_IMPL ( BadArrayOperandException ) ; <nl> } ; <nl> <nl> - class BadTypeConversionException : public ExtendedException { <nl> - public : <nl> - explicit BadTypeConversionException ( const char * msg ) <nl> - : ExtendedException ( " Bad type conversion : % s . " , msg ) { } <nl> - virtual ~ BadTypeConversionException ( ) throw ( ) { } <nl> - EXCEPTION_COMMON_IMPL ( BadTypeConversionException ) ; <nl> - } ; <nl> - <nl> class OffsetOutOfRangeException : public ExtendedException { <nl> public : <nl> OffsetOutOfRangeException ( ) <nl> mmm a / hphp / runtime / base / object_data . cpp <nl> ppp b / hphp / runtime / base / object_data . cpp <nl> Variant * ObjectData : : o_realProp ( CStrRef propName , int flags , <nl> <nl> auto thiz = const_cast < ObjectData * > ( this ) ; <nl> bool visible , accessible , unset ; <nl> - TypedValue * ret = ( flags & RealPropNoDynamic ) <nl> - ? thiz - > getDeclProp ( ctx , propName . get ( ) , visible , <nl> - accessible , unset ) <nl> - : thiz - > getProp ( ctx , propName . get ( ) , visible , <nl> - accessible , unset ) ; <nl> + TypedValue * ret = thiz - > getProp ( ctx , propName . get ( ) , visible , <nl> + accessible , unset ) ; <nl> if ( ! ret ) { <nl> / / Property is not declared , and not dynamically created yet . <nl> if ( ! ( flags & RealPropCreate ) ) { <nl> return nullptr ; <nl> } <nl> - assert ( ! ( flags & RealPropNoDynamic ) ) ; <nl> if ( ! o_properties . get ( ) ) { <nl> thiz - > initDynProps ( ) ; <nl> } <nl> Variant ObjectData : : o_get ( CStrRef propName , bool error / * = true * / , <nl> <nl> template < class T > <nl> inline ALWAYS_INLINE Variant ObjectData : : o_setImpl ( CStrRef propName , T v , <nl> - bool forInit , <nl> CStrRef context ) { <nl> if ( UNLIKELY ( ! * propName . data ( ) ) ) { <nl> throw_invalid_property_name ( propName ) ; <nl> } <nl> <nl> - bool useSet = ! forInit & & getAttribute ( UseSet ) ; <nl> + bool useSet = getAttribute ( UseSet ) ; <nl> auto flags = useSet ? 0 : RealPropCreate ; <nl> - if ( forInit ) flags | = RealPropUnchecked ; <nl> <nl> if ( Variant * t = o_realProp ( propName , flags , context ) ) { <nl> if ( ! useSet | | t - > isInitialized ( ) ) { <nl> inline ALWAYS_INLINE Variant ObjectData : : o_setImpl ( CStrRef propName , T v , <nl> } <nl> <nl> Variant ObjectData : : o_set ( CStrRef propName , CVarRef v ) { <nl> - return o_setImpl < CVarRef > ( propName , v , false , null_string ) ; <nl> + return o_setImpl < CVarRef > ( propName , v , null_string ) ; <nl> } <nl> <nl> Variant ObjectData : : o_set ( CStrRef propName , RefResult v ) { <nl> Variant ObjectData : : o_set ( CStrRef propName , RefResult v ) { <nl> } <nl> <nl> Variant ObjectData : : o_setRef ( CStrRef propName , CVarRef v ) { <nl> - return o_setImpl < RefResult > ( propName , ref ( v ) , false , null_string ) ; <nl> + return o_setImpl < RefResult > ( propName , ref ( v ) , null_string ) ; <nl> } <nl> <nl> Variant ObjectData : : o_set ( CStrRef propName , CVarRef v , CStrRef context ) { <nl> - return o_setImpl < CVarRef > ( propName , v , false , context ) ; <nl> + return o_setImpl < CVarRef > ( propName , v , context ) ; <nl> } <nl> <nl> Variant ObjectData : : o_set ( CStrRef propName , RefResult v , CStrRef context ) { <nl> Variant ObjectData : : o_set ( CStrRef propName , RefResult v , CStrRef context ) { <nl> } <nl> <nl> Variant ObjectData : : o_setRef ( CStrRef propName , CVarRef v , CStrRef context ) { <nl> - return o_setImpl < RefResult > ( propName , ref ( v ) , false , context ) ; <nl> + return o_setImpl < RefResult > ( propName , ref ( v ) , context ) ; <nl> } <nl> <nl> HOT_FUNC <nl> Slot ObjectData : : declPropInd ( TypedValue * prop ) const { <nl> } <nl> } <nl> <nl> - template < bool declOnly > <nl> - TypedValue * ObjectData : : getPropImpl ( Class * ctx , const StringData * key , <nl> - bool & visible , bool & accessible , <nl> - bool & unset ) { <nl> + TypedValue * ObjectData : : getProp ( Class * ctx , const StringData * key , <nl> + bool & visible , bool & accessible , <nl> + bool & unset ) { <nl> TypedValue * prop = nullptr ; <nl> unset = false ; <nl> Slot propInd = m_cls - > getDeclPropIndex ( ctx , key , accessible ) ; <nl> TypedValue * ObjectData : : getPropImpl ( Class * ctx , const StringData * key , <nl> } <nl> } else { <nl> assert ( ! visible & & ! accessible ) ; <nl> - / / We could not find a visible property . We need to check for a <nl> - / / dynamic property with this name if declOnly = false . <nl> - if ( ! declOnly & & o_properties . get ( ) ) { <nl> + / / We could not find a visible declared property . We need to check <nl> + / / for a dynamic property with this name . <nl> + if ( o_properties . get ( ) ) { <nl> prop = static_cast < HphpArray * > ( o_properties . get ( ) ) - > nvGet ( key ) ; <nl> if ( prop ) { <nl> / / o_properties . get ( ) - > nvGet ( ) returned a non - declared property , <nl> TypedValue * ObjectData : : getPropImpl ( Class * ctx , const StringData * key , <nl> return prop ; <nl> } <nl> <nl> - TypedValue * ObjectData : : getProp ( Class * ctx , const StringData * key , <nl> - bool & visible , bool & accessible , bool & unset ) { <nl> - return getPropImpl < false > ( ctx , key , visible , accessible , unset ) ; <nl> - } <nl> - <nl> - TypedValue * ObjectData : : getDeclProp ( Class * ctx , const StringData * key , <nl> - bool & visible , bool & accessible , <nl> - bool & unset ) { <nl> - return getPropImpl < true > ( ctx , key , visible , accessible , unset ) ; <nl> - } <nl> - <nl> void ObjectData : : invokeSet ( TypedValue * retval , const StringData * key , <nl> TypedValue * val ) { <nl> AttributeClearer a ( UseSet , this ) ; <nl> Variant ObjectData : : t___wakeup ( ) { <nl> } <nl> } <nl> <nl> - String ObjectData : : t___tostring ( ) { <nl> + String ObjectData : : invokeToString ( ) { <nl> const Func * method = m_cls - > getToString ( ) ; <nl> if ( method ) { <nl> TypedValue tv ; <nl> String ObjectData : : t___tostring ( ) { <nl> m_cls - > m_preClass - > name ( ) - > data ( ) ) ; <nl> } <nl> return tv . m_data . pstr ; <nl> - } else { <nl> - std : : string msg = m_cls - > m_preClass - > name ( ) - > data ( ) ; <nl> - msg + = " : : __toString ( ) was not defined " ; <nl> - throw BadTypeConversionException ( msg . c_str ( ) ) ; <nl> } <nl> + raise_recoverable_error ( <nl> + " Object of class % s could not be converted to string " , <nl> + m_cls - > m_preClass - > name ( ) - > data ( ) <nl> + ) ; <nl> + / / If the user error handler decides to allow execution to continue , <nl> + / / we return the empty string . <nl> + return empty_string ; <nl> + } <nl> + <nl> + bool ObjectData : : hasToString ( ) { <nl> + return ( m_cls - > getToString ( ) ! = nullptr ) ; <nl> } <nl> <nl> void ObjectData : : cloneSet ( ObjectData * clone ) { <nl> mmm a / hphp / runtime / base / object_data . h <nl> ppp b / hphp / runtime / base / object_data . h <nl> class ObjectData { <nl> <nl> enum { <nl> RealPropCreate = 1 , / / Property should be created if it doesn ' t exist <nl> - RealPropNoDynamic = 4 , / / Don ' t return dynamic properties <nl> RealPropUnchecked = 8 , / / Don ' t check property accessibility <nl> RealPropExist = 16 , / / For property_exists <nl> } ; <nl> class ObjectData { <nl> virtual ObjectData * clone ( ) ; <nl> <nl> Variant offsetGet ( Variant key ) ; <nl> + String invokeToString ( ) ; <nl> + bool hasToString ( ) ; <nl> <nl> virtual Variant t___sleep ( ) ; <nl> virtual Variant t___wakeup ( ) ; <nl> - virtual String t___tostring ( ) ; <nl> <nl> static int GetMaxId ( ) ATTRIBUTE_COLD ; <nl> <nl> class ObjectData { <nl> inline Variant o_getImpl ( CStrRef propName , int flags , <nl> bool error = true , CStrRef context = null_string ) ; <nl> template < typename T > <nl> - inline Variant o_setImpl ( CStrRef propName , T v , <nl> - bool forInit , CStrRef context ) ; <nl> - template < bool declOnly > <nl> - TypedValue * getPropImpl ( Class * ctx , const StringData * key , bool & visible , <nl> - bool & accessible , bool & unset ) ; <nl> + inline Variant o_setImpl ( CStrRef propName , T v , CStrRef context ) ; <nl> public : <nl> TypedValue * getProp ( Class * ctx , const StringData * key , bool & visible , <nl> bool & accessible , bool & unset ) ; <nl> - TypedValue * getDeclProp ( Class * ctx , const StringData * key , bool & visible , <nl> - bool & accessible , bool & unset ) ; <nl> private : <nl> template < bool warn , bool define > <nl> void propImpl ( TypedValue * & retval , TypedValue & tvRef , Class * ctx , <nl> mmm a / hphp / runtime / base / tv_comparisons . cpp <nl> ppp b / hphp / runtime / base / tv_comparisons . cpp <nl> bool cellRelOp ( Op op , Cell cell , const StringData * val ) { <nl> <nl> case KindOfObject : <nl> { <nl> - auto const od = cell . m_data . pobj ; <nl> + auto od = cell . m_data . pobj ; <nl> if ( od - > isCollection ( ) ) return op . collectionVsNonObj ( ) ; <nl> - try { <nl> - String str ( const_cast < ObjectData * > ( od ) - > t___tostring ( ) ) ; <nl> + if ( od - > hasToString ( ) ) { <nl> + String str ( od - > invokeToString ( ) ) ; <nl> return op ( str . get ( ) , val ) ; <nl> - } catch ( BadTypeConversionException & ) { <nl> - return op ( true , false ) ; <nl> } <nl> + return op ( true , false ) ; <nl> } <nl> <nl> case KindOfResource : <nl> bool cellRelOp ( Op op , Cell cell , const ObjectData * od ) { <nl> case KindOfArray : <nl> return od - > isCollection ( ) ? op . collectionVsNonObj ( ) : op ( false , true ) ; <nl> case KindOfString : <nl> - case KindOfStaticString : <nl> - if ( od - > isCollection ( ) ) return op . collectionVsNonObj ( ) ; <nl> - try { <nl> - String str ( const_cast < ObjectData * > ( od ) - > t___tostring ( ) ) ; <nl> + case KindOfStaticString : { <nl> + auto obj = const_cast < ObjectData * > ( od ) ; <nl> + if ( obj - > isCollection ( ) ) return op . collectionVsNonObj ( ) ; <nl> + if ( obj - > hasToString ( ) ) { <nl> + String str ( obj - > invokeToString ( ) ) ; <nl> return op ( cell . m_data . pstr , str . get ( ) ) ; <nl> - } catch ( BadTypeConversionException & ) { <nl> - return op ( false , true ) ; <nl> } <nl> + return op ( false , true ) ; <nl> + } <nl> case KindOfObject : <nl> return op ( cell . m_data . pobj , od ) ; <nl> case KindOfResource : <nl> mmm a / hphp / runtime / base / tv_helpers . cpp <nl> ppp b / hphp / runtime / base / tv_helpers . cpp <nl> void tvCastToStringInPlace ( TypedValue * tv ) { <nl> goto static_string ; <nl> case KindOfObject : <nl> / / For objects , we fall back on the Variant machinery <nl> - tvAsVariant ( tv ) = tv - > m_data . pobj - > t___tostring ( ) ; <nl> + tvAsVariant ( tv ) = tv - > m_data . pobj - > invokeToString ( ) ; <nl> return ; <nl> case KindOfResource : <nl> / / For resources , we fall back on the Variant machinery <nl> StringData * tvCastToString ( TypedValue * tv ) { <nl> case KindOfStaticString : return tv - > m_data . pstr ; <nl> case KindOfString : s = tv - > m_data . pstr ; break ; <nl> case KindOfArray : return s_Array . get ( ) ; <nl> - case KindOfObject : return tv - > m_data . pobj - > t___tostring ( ) . detach ( ) ; <nl> + case KindOfObject : return tv - > m_data . pobj - > invokeToString ( ) . detach ( ) ; <nl> case KindOfResource : return tv - > m_data . pres - > o_toString ( ) . detach ( ) ; <nl> default : not_reached ( ) ; <nl> } <nl> bool tvCoerceParamToStringInPlace ( TypedValue * tv ) { <nl> case KindOfArray : <nl> return false ; <nl> case KindOfObject : <nl> - try { <nl> - tvAsVariant ( tv ) = tv - > m_data . pobj - > t___tostring ( ) ; <nl> + if ( tv - > m_data . pobj - > hasToString ( ) ) { <nl> + tvAsVariant ( tv ) = tv - > m_data . pobj - > invokeToString ( ) ; <nl> return true ; <nl> - } catch ( BadTypeConversionException & e ) { <nl> } <nl> return false ; <nl> case KindOfResource : <nl> mmm a / hphp / runtime / base / type_conversions . h <nl> ppp b / hphp / runtime / base / type_conversions . h <nl> inline String toString ( CStrRef v ) { return toString ( v . get ( ) ) ; } <nl> inline String toString ( const ArrayData * v ) { return v ? " Array " : " " ; } <nl> inline String toString ( CArrRef v ) { return toString ( v . get ( ) ) ; } <nl> inline String toString ( ObjectData * v ) { <nl> - return v ? v - > t___tostring ( ) : String ( " " ) ; <nl> + return v ? v - > invokeToString ( ) : String ( " " ) ; <nl> } <nl> inline String toString ( CObjRef v ) { return toString ( v . get ( ) ) ; } <nl> inline String toString ( CVarRef v ) { return v . toString ( ) ; } <nl> mmm a / hphp / runtime / base / type_object . cpp <nl> ppp b / hphp / runtime / base / type_object . cpp <nl> Array Object : : toArray ( ) const { <nl> return m_px ? m_px - > o_toArray ( ) : Array ( ) ; <nl> } <nl> <nl> - Variant Object : : toKey ( ) const { <nl> - return m_px ? m_px - > t___tostring ( ) : String ( ) ; <nl> - } <nl> - <nl> int64_t Object : : toInt64ForCompare ( ) const { <nl> check_collection_compare ( m_px ) ; <nl> return toInt64 ( ) ; <nl> mmm a / hphp / runtime / base / type_object . h <nl> ppp b / hphp / runtime / base / type_object . h <nl> class Object : protected SmartPtr < ObjectData > { <nl> int toInt32 ( ) const { return m_px ? m_px - > o_toInt64 ( ) : 0 ; } <nl> int64_t toInt64 ( ) const { return m_px ? m_px - > o_toInt64 ( ) : 0 ; } <nl> double toDouble ( ) const { return m_px ? m_px - > o_toDouble ( ) : 0 ; } <nl> - String toString ( ) const { return m_px ? m_px - > t___tostring ( ) : String ( ) ; } <nl> + String toString ( ) const { return m_px ? m_px - > invokeToString ( ) : String ( ) ; } <nl> Array toArray ( ) const ; <nl> - Variant toKey ( ) const ; <nl> <nl> int64_t toInt64ForCompare ( ) const ; <nl> double toDoubleForCompare ( ) const ; <nl> mmm a / hphp / runtime / base / type_variant . cpp <nl> ppp b / hphp / runtime / base / type_variant . cpp <nl> String Variant : : toStringHelper ( ) const { <nl> assert ( false ) ; / / Should be done in caller <nl> return m_data . pstr ; <nl> case KindOfArray : return s_array ; <nl> - case KindOfObject : return m_data . pobj - > t___tostring ( ) ; <nl> + case KindOfObject : return m_data . pobj - > invokeToString ( ) ; <nl> case KindOfResource : return m_data . pres - > o_toString ( ) ; <nl> case KindOfRef : return m_data . pref - > var ( ) - > toString ( ) ; <nl> default : <nl> mmm a / hphp / runtime / debugger / debugger_proxy . cpp <nl> ppp b / hphp / runtime / debugger / debugger_proxy . cpp <nl> Variant DebuggerProxy : : ExecutePHP ( const std : : string & php , String & output , <nl> } catch ( Exception & e ) { <nl> sb . append ( Debugger : : ColorStderr ( String ( e . what ( ) ) ) ) ; <nl> } catch ( Object & e ) { <nl> - try { <nl> + if ( e - > hasToString ( ) ) { <nl> sb . append ( Debugger : : ColorStderr ( e . toString ( ) ) ) ; <nl> - } catch ( BadTypeConversionException & e ) { <nl> + } else { <nl> sb . append ( Debugger : : ColorStderr <nl> ( String ( " ( object without __toString ( ) is thrown ) " ) ) ) ; <nl> } <nl> mmm a / hphp / runtime / ext / filter / ext_filter . cpp <nl> ppp b / hphp / runtime / ext / filter / ext_filter . cpp <nl> static filter_list_entry php_find_filter ( uint64_t id ) { <nl> return filter_list [ 0 ] ; <nl> } <nl> <nl> - static Variant filter_var ( CVarRef variable , int64_t filter , CVarRef options ) { <nl> + # define FAIL_IF ( x ) do { if ( x ) return false ; } while ( 0 ) <nl> + <nl> + static bool filter_var ( Variant & ret , CVarRef variable , int64_t filter , <nl> + CVarRef options ) { <nl> filter_list_entry filter_func = php_find_filter ( filter ) ; <nl> <nl> int64_t flags ; <nl> static Variant filter_var ( CVarRef variable , int64_t filter , CVarRef options ) { <nl> option_array = options [ s_options ] ; <nl> } <nl> <nl> - Variant ret ( filter_func . function ( variable . toString ( ) , flags , option_array ) ) ; <nl> + FAIL_IF ( variable . isObject ( ) & & ! variable . getObjectData ( ) - > hasToString ( ) ) ; <nl> + <nl> + ret = filter_func . function ( variable . toString ( ) , flags , option_array ) ; <nl> if ( option_array . isArray ( ) & & option_array . toArray ( ) . exists ( s_default ) & & <nl> ( ( flags & k_FILTER_NULL_ON_FAILURE & & ret . isNull ( ) ) | | <nl> ( ! ( flags & k_FILTER_NULL_ON_FAILURE ) & & ret . isBoolean ( ) & & <nl> ret . asBooleanVal ( ) = = 0 ) ) ) { <nl> ret = option_array [ s_default ] ; <nl> } <nl> - return ret ; <nl> + return true ; <nl> } <nl> <nl> - static Variant filter_recursive ( CVarRef variable , int64_t filter , <nl> - CVarRef options ) { <nl> - Array ret ; <nl> + static bool filter_recursive ( Variant & ret , CVarRef variable , int64_t filter , <nl> + CVarRef options ) { <nl> + Array arr ; <nl> for ( ArrayIter iter ( variable . toArray ( ) ) ; iter ; + + iter ) { <nl> + Variant v ; <nl> if ( iter . second ( ) . isArray ( ) ) { <nl> - ret . add ( <nl> - iter . first ( ) , <nl> - filter_recursive ( iter . second ( ) . toArray ( ) , filter , options ) <nl> - ) ; <nl> + FAIL_IF ( ! filter_recursive ( v , iter . second ( ) . toArray ( ) , filter , options ) ) ; <nl> } else { <nl> - ret . add ( iter . first ( ) , filter_var ( iter . second ( ) , filter , options ) ) ; <nl> + FAIL_IF ( ! filter_var ( v , iter . second ( ) , filter , options ) ) ; <nl> } <nl> + arr . add ( iter . first ( ) , v ) ; <nl> } <nl> - return ret ; <nl> + ret = arr ; <nl> + return true ; <nl> } <nl> <nl> + # undef FAIL_IF <nl> + <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> Variant f_filter_list ( ) { <nl> Variant f_filter_id ( CStrRef filtername ) { <nl> return false ; <nl> } <nl> <nl> + # define FAIL_IF ( x ) \ <nl> + do { \ <nl> + if ( x ) return fail ( filter_flags & k_FILTER_NULL_ON_FAILURE , options ) ; \ <nl> + } while ( 0 ) <nl> + <nl> Variant f_filter_var ( CVarRef variable , int64_t filter / * = 516 * / , <nl> CVarRef options / * = empty_array * / ) { <nl> int64_t filter_flags ; <nl> Variant f_filter_var ( CVarRef variable , int64_t filter / * = 516 * / , <nl> } <nl> <nl> if ( variable . isArray ( ) ) { <nl> - if ( filter_flags & k_FILTER_REQUIRE_SCALAR ) { <nl> - return fail ( filter_flags & k_FILTER_NULL_ON_FAILURE , options ) ; <nl> - } <nl> - return filter_recursive ( variable , filter , options ) ; <nl> - } <nl> - if ( filter_flags & k_FILTER_REQUIRE_ARRAY ) { <nl> - return fail ( filter_flags & k_FILTER_NULL_ON_FAILURE , options ) ; <nl> + FAIL_IF ( filter_flags & k_FILTER_REQUIRE_SCALAR ) ; <nl> + Variant ret ; <nl> + FAIL_IF ( ! filter_recursive ( ret , variable , filter , options ) ) ; <nl> + return ret ; <nl> } <nl> + FAIL_IF ( filter_flags & k_FILTER_REQUIRE_ARRAY ) ; <nl> <nl> - try { <nl> - Variant ret ( filter_var ( variable , filter , options ) ) ; <nl> - if ( filter_flags & k_FILTER_FORCE_ARRAY & & ! ret . isArray ( ) ) { <nl> - ret = CREATE_VECTOR1 ( ret ) ; <nl> - } <nl> - return ret ; <nl> - } catch ( BadTypeConversionException & e ) { <nl> - return fail ( filter_flags & k_FILTER_NULL_ON_FAILURE , options ) ; <nl> + Variant ret ; <nl> + FAIL_IF ( ! filter_var ( ret , variable , filter , options ) ) ; <nl> + if ( filter_flags & k_FILTER_FORCE_ARRAY & & ! ret . isArray ( ) ) { <nl> + ret = CREATE_VECTOR1 ( ret ) ; <nl> } <nl> + return ret ; <nl> } <nl> <nl> + # undef FAIL_IF <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> } <nl> mmm a / hphp / runtime / vm / bytecode . cpp <nl> ppp b / hphp / runtime / vm / bytecode . cpp <nl> void VMExecutionContext : : evalPHPDebugger ( TypedValue * retval , StringData * code , <nl> } catch ( Object & e ) { <nl> g_vmContext - > write ( s_phpException . data ( ) ) ; <nl> g_vmContext - > write ( " : " ) ; <nl> - g_vmContext - > write ( e - > t___tostring ( ) . data ( ) ) ; <nl> + g_vmContext - > write ( e - > invokeToString ( ) . data ( ) ) ; <nl> } catch ( . . . ) { <nl> g_vmContext - > write ( s_cppException . data ( ) ) ; <nl> } <nl> mmm a / hphp / runtime / vm / jit / translator - runtime . cpp <nl> ppp b / hphp / runtime / vm / jit / translator - runtime . cpp <nl> StringData * convIntToStrHelper ( int64_t i ) { <nl> <nl> StringData * convObjToStrHelper ( ObjectData * o ) { <nl> try { <nl> - auto s = o - > t___tostring ( ) ; <nl> + auto s = o - > invokeToString ( ) ; <nl> auto r = s . get ( ) ; <nl> decRefObj ( o ) ; <nl> if ( ! r - > isStatic ( ) ) r - > incRefCount ( ) ; <nl> mmm a / hphp / test / quick / cnvStr . php . expectf <nl> ppp b / hphp / test / quick / cnvStr . php . expectf <nl> string ( 3 ) " abc " <nl> string ( 3 ) " a C " <nl> string ( 5 ) " Array " <nl> string ( 5 ) " Array " <nl> - HipHop Fatal error : Bad type conversion : D : : __toString ( ) was not defined . in % s on line 4 <nl> + HipHop Fatal error : Object of class D could not be converted to string in % s on line 4 <nl> mmm a / hphp / test / quick / tobadtype . php . expectf <nl> ppp b / hphp / test / quick / tobadtype . php . expectf <nl> HipHop Notice : Object of class X could not be converted to int in % s on line 21 <nl> test dbl <nl> HipHop Notice : Object of class X could not be converted to int in % s on line 25 <nl> test str <nl> - HipHop Fatal error : Bad type conversion : X : : __toString ( ) was not defined . in % s on line 17 <nl> + HipHop Fatal error : Object of class X could not be converted to string in % s on line 17 <nl> new file mode 100644 <nl> index 00000000000 . . 051b12793e3 <nl> mmm / dev / null <nl> ppp b / hphp / test / slow / object / toStringRecoverableError . php <nl> <nl> + < ? php <nl> + function my_handler ( $ errno , $ errmsg ) { return true ; } <nl> + set_error_handler ( ' my_handler ' ) ; <nl> + var_dump ( ( string ) ( new stdclass ) ) ; <nl> new file mode 100644 <nl> index 00000000000 . . c6d098d63b1 <nl> mmm / dev / null <nl> ppp b / hphp / test / slow / object / toStringRecoverableError . php . expect <nl> @ @ - 0 , 0 + 1 @ @ <nl> + string ( 0 ) " " <nl> | Unrevert " Raise a recoverable error when Obj - > Str conversion fails " " | facebook/hhvm | 0e5e16522440da54fa4f2cc95234921b384f8994 | 2013-08-02T21:21:52Z |
mmm a / include / swift / Reflection / ReflectionContext . h <nl> ppp b / include / swift / Reflection / ReflectionContext . h <nl> <nl> # include " swift / Reflection / TypeRef . h " <nl> # include " swift / Reflection / TypeRefBuilder . h " <nl> # include " swift / Runtime / Unreachable . h " <nl> + # include " . . / . . / . . / stdlib / public / runtime / ImageInspectionELF . h " <nl> <nl> # include < iostream > <nl> # include < set > <nl> template < unsigned char ELFClass > struct ELFTraits ; <nl> <nl> template < > struct ELFTraits < llvm : : ELF : : ELFCLASS32 > { <nl> using Header = const struct llvm : : ELF : : Elf32_Ehdr ; <nl> - using Section = const struct llvm : : ELF : : Elf32_Shdr ; <nl> + using ProgramHeader = const struct llvm : : ELF : : Elf32_Phdr ; <nl> using Offset = llvm : : ELF : : Elf32_Off ; <nl> using Size = llvm : : ELF : : Elf32_Word ; <nl> static constexpr unsigned char ELFClass = llvm : : ELF : : ELFCLASS32 ; <nl> template < > struct ELFTraits < llvm : : ELF : : ELFCLASS32 > { <nl> <nl> template < > struct ELFTraits < llvm : : ELF : : ELFCLASS64 > { <nl> using Header = const struct llvm : : ELF : : Elf64_Ehdr ; <nl> - using Section = const struct llvm : : ELF : : Elf64_Shdr ; <nl> + using ProgramHeader = const struct llvm : : ELF : : Elf64_Phdr ; <nl> using Offset = llvm : : ELF : : Elf64_Off ; <nl> using Size = llvm : : ELF : : Elf64_Xword ; <nl> static constexpr unsigned char ELFClass = llvm : : ELF : : ELFCLASS64 ; <nl> class ReflectionContext <nl> <nl> ReflectionContext ( const ReflectionContext & other ) = delete ; <nl> ReflectionContext & operator = ( const ReflectionContext & other ) = delete ; <nl> - <nl> + <nl> MemoryReader & getReader ( ) { <nl> return * this - > Reader ; <nl> } <nl> class ReflectionContext <nl> / / introduce misaligned pointers mapping between local and remote <nl> / / address space . <nl> RangeStart = RangeStart & ~ 7 ; <nl> - RangeEnd = RangeEnd + 7 & ~ 7 ; <nl> + RangeEnd = RangeEnd + 7 & ~ 7 ; <nl> } <nl> - <nl> + <nl> if ( RangeStart = = UINT64_MAX & & RangeEnd = = UINT64_MAX ) <nl> return false ; <nl> <nl> class ReflectionContext <nl> } <nl> <nl> template < typename T > bool readELFSections ( RemoteAddress ImageStart ) { <nl> - auto Buf = <nl> + auto HeaderBuf = <nl> this - > getReader ( ) . readBytes ( ImageStart , sizeof ( typename T : : Header ) ) ; <nl> <nl> - auto Hdr = reinterpret_cast < const typename T : : Header * > ( Buf . get ( ) ) ; <nl> + auto Hdr = reinterpret_cast < const typename T : : Header * > ( HeaderBuf . get ( ) ) ; <nl> assert ( Hdr - > getFileClass ( ) = = T : : ELFClass & & " invalid ELF file class " ) ; <nl> <nl> - / / From the header , grab informations about the section header table . <nl> - auto SectionHdrAddress = ImageStart . getAddressData ( ) + Hdr - > e_shoff ; <nl> - auto SectionHdrNumEntries = Hdr - > e_shnum ; <nl> - auto SectionEntrySize = Hdr - > e_shentsize ; <nl> - <nl> - / / Collect all the section headers , we need them to look up the <nl> - / / reflection sections ( by name ) and the string table . <nl> - std : : vector < const typename T : : Section * > SecHdrVec ; <nl> - for ( unsigned I = 0 ; I < SectionHdrNumEntries ; + + I ) { <nl> - auto SecBuf = this - > getReader ( ) . readBytes ( <nl> - RemoteAddress ( SectionHdrAddress + ( I * SectionEntrySize ) ) , <nl> - SectionEntrySize ) ; <nl> - auto SecHdr = <nl> - reinterpret_cast < const typename T : : Section * > ( SecBuf . get ( ) ) ; <nl> - SecHdrVec . push_back ( SecHdr ) ; <nl> + const auto ProgramHdrAddress = ImageStart . getAddressData ( ) + Hdr - > e_phoff ; <nl> + const auto NumEntries = Hdr - > e_phnum ; <nl> + const auto EntrySize = Hdr - > e_phentsize ; <nl> + <nl> + uintptr_t MetadataSectionsPtrValue = 0 ; <nl> + for ( unsigned I = 0 ; I < NumEntries ; + + I ) { <nl> + const StringRef MagicString = <nl> + SWIFT_REFLECTION_METADATA_ELF_NOTE_MAGIC_STRING ; <nl> + auto ProgramHdrBuf = this - > getReader ( ) . readBytes ( <nl> + RemoteAddress ( ProgramHdrAddress + ( I * EntrySize ) ) , EntrySize ) ; <nl> + auto ProgramHdr = reinterpret_cast < const typename T : : ProgramHeader * > ( <nl> + ProgramHdrBuf . get ( ) ) ; <nl> + if ( ProgramHdr - > p_type ! = llvm : : ELF : : PT_NOTE | | <nl> + ProgramHdr - > p_memsz < = MagicString . size ( ) ) <nl> + continue ; <nl> + const auto SegmentAddr = <nl> + ImageStart . getAddressData ( ) + ProgramHdr - > p_vaddr ; <nl> + const auto SegmentSize = ProgramHdr - > p_memsz ; <nl> + auto SegmentBuf = <nl> + this - > getReader ( ) . readBytes ( RemoteAddress ( SegmentAddr ) , SegmentSize ) ; <nl> + const char * SegmentData = <nl> + reinterpret_cast < const char * > ( SegmentBuf . get ( ) ) ; <nl> + if ( ! StringRef ( SegmentData , SegmentSize ) . startswith ( MagicString ) ) <nl> + continue ; <nl> + MetadataSectionsPtrValue = * reinterpret_cast < const uintptr_t * > ( <nl> + SegmentData + MagicString . size ( ) + 1 ) ; <nl> + break ; <nl> } <nl> + if ( ! MetadataSectionsPtrValue ) <nl> + return false ; <nl> <nl> - / / This provides quick access to the section header string table index . <nl> - / / We also here handle the unlikely even where the section index overflows <nl> - / / and it ' s just a pointer to secondary storage ( SHN_XINDEX ) . <nl> - uint32_t SecIdx = Hdr - > e_shstrndx ; <nl> - if ( SecIdx = = llvm : : ELF : : SHN_XINDEX ) { <nl> - assert ( ! SecHdrVec . empty ( ) & & " malformed ELF object " ) ; <nl> - SecIdx = SecHdrVec [ 0 ] - > sh_link ; <nl> + auto MetadataSectionsStructBuf = this - > getReader ( ) . readBytes ( <nl> + RemoteAddress ( MetadataSectionsPtrValue ) , sizeof ( MetadataSections ) ) ; <nl> + const auto * Sections = reinterpret_cast < const MetadataSections * > ( <nl> + MetadataSectionsStructBuf . get ( ) ) ; <nl> + <nl> + auto BeginAddr = std : : min ( <nl> + { Sections - > swift5_fieldmd . start , Sections - > swift5_assocty . start , <nl> + Sections - > swift5_builtin . start , Sections - > swift5_capture . start , <nl> + Sections - > swift5_typeref . start , Sections - > swift5_reflstr . start } ) ; <nl> + auto EndAddr = std : : max ( { <nl> + Sections - > swift5_fieldmd . start + Sections - > swift5_fieldmd . length , <nl> + Sections - > swift5_assocty . start + Sections - > swift5_assocty . length , <nl> + Sections - > swift5_builtin . start + Sections - > swift5_builtin . length , <nl> + Sections - > swift5_capture . start + Sections - > swift5_capture . length , <nl> + Sections - > swift5_typeref . start + Sections - > swift5_typeref . length , <nl> + Sections - > swift5_reflstr . start + Sections - > swift5_reflstr . length , <nl> + } ) ; <nl> + <nl> + / / Extend the range [ BeginAddr , EndAddr ) to include the data segments . <nl> + for ( unsigned I = 0 ; I < NumEntries ; + + I ) { <nl> + auto ProgramHdrBuf = this - > getReader ( ) . readBytes ( <nl> + RemoteAddress ( ProgramHdrAddress + ( I * EntrySize ) ) , EntrySize ) ; <nl> + auto ProgramHdr = reinterpret_cast < const typename T : : ProgramHeader * > ( <nl> + ProgramHdrBuf . get ( ) ) ; <nl> + if ( ProgramHdr - > p_type = = llvm : : ELF : : PT_LOAD & & <nl> + ProgramHdr - > p_flags & ( llvm : : ELF : : PF_W & llvm : : ELF : : PF_R ) ) { <nl> + const decltype ( BeginAddr ) SegmentBeginAddr = <nl> + ImageStart . getAddressData ( ) + ProgramHdr - > p_vaddr ; <nl> + const decltype ( BeginAddr ) SegmentEndAddr = <nl> + SegmentBeginAddr + ProgramHdr - > p_memsz ; <nl> + BeginAddr = std : : min ( BeginAddr , SegmentBeginAddr ) ; <nl> + EndAddr = std : : max ( EndAddr , SegmentEndAddr ) ; <nl> + } <nl> } <nl> <nl> - assert ( SecIdx < SecHdrVec . size ( ) & & " malformed ELF object " ) ; <nl> - <nl> - const typename T : : Section * SecHdrStrTab = SecHdrVec [ SecIdx ] ; <nl> - typename T : : Offset StrTabOffset = SecHdrStrTab - > sh_offset ; <nl> - typename T : : Size StrTabSize = SecHdrStrTab - > sh_size ; <nl> - <nl> - auto StrTabStart = <nl> - RemoteAddress ( ImageStart . getAddressData ( ) + StrTabOffset ) ; <nl> - auto StrTabBuf = this - > getReader ( ) . readBytes ( StrTabStart , StrTabSize ) ; <nl> - auto StrTab = reinterpret_cast < const char * > ( StrTabBuf . get ( ) ) ; <nl> - <nl> - auto findELFSectionByName = [ & ] ( std : : string Name ) <nl> - - > std : : pair < RemoteRef < void > , uint64_t > { <nl> - / / Now for all the sections , find their name . <nl> - for ( const typename T : : Section * Hdr : SecHdrVec ) { <nl> - uint32_t Offset = Hdr - > sh_name ; <nl> - auto SecName = std : : string ( StrTab + Offset ) ; <nl> - if ( SecName ! = Name ) <nl> - continue ; <nl> - auto SecStart = <nl> - RemoteAddress ( ImageStart . getAddressData ( ) + Hdr - > sh_addr ) ; <nl> - auto SecSize = Hdr - > sh_size ; <nl> - auto SecBuf = this - > getReader ( ) . readBytes ( SecStart , SecSize ) ; <nl> - auto SecContents = RemoteRef < void > ( SecStart . getAddressData ( ) , <nl> - SecBuf . get ( ) ) ; <nl> - savedBuffers . push_back ( std : : move ( SecBuf ) ) ; <nl> - return { SecContents , SecSize } ; <nl> - } <nl> - return { nullptr , 0 } ; <nl> + auto Buf = this - > getReader ( ) . readBytes ( RemoteAddress ( BeginAddr ) , <nl> + EndAddr - BeginAddr ) ; <nl> + auto RemoteAddrToRemoteRef = [ & ] ( uintptr_t Addr ) - > RemoteRef < void > { <nl> + return RemoteRef < void > ( <nl> + Addr , reinterpret_cast < void * > ( <nl> + reinterpret_cast < uintptr_t > ( Buf . get ( ) ) + Addr - BeginAddr ) ) ; <nl> } ; <nl> - <nl> - auto FieldMdSec = findELFSectionByName ( " swift5_fieldmd " ) ; <nl> - auto AssocTySec = findELFSectionByName ( " swift5_assocty " ) ; <nl> - auto BuiltinTySec = findELFSectionByName ( " swift5_builtin " ) ; <nl> - auto CaptureSec = findELFSectionByName ( " swift5_capture " ) ; <nl> - auto TypeRefMdSec = findELFSectionByName ( " swift5_typeref " ) ; <nl> - auto ReflStrMdSec = findELFSectionByName ( " swift5_reflstr " ) ; <nl> - <nl> - / / We succeed if at least one of the sections is present in the <nl> - / / ELF executable . <nl> - if ( FieldMdSec . first = = nullptr & & <nl> - AssocTySec . first = = nullptr & & <nl> - BuiltinTySec . first = = nullptr & & <nl> - CaptureSec . first = = nullptr & & <nl> - TypeRefMdSec . first = = nullptr & & <nl> - ReflStrMdSec . first = = nullptr ) <nl> - return false ; <nl> - <nl> - auto LocalStartAddress = reinterpret_cast < uint64_t > ( Buf . get ( ) ) ; <nl> - auto RemoteStartAddress = <nl> - static_cast < uint64_t > ( ImageStart . getAddressData ( ) ) ; <nl> - <nl> - ReflectionInfo info = { <nl> - { FieldMdSec . first , FieldMdSec . second } , <nl> - { AssocTySec . first , AssocTySec . second } , <nl> - { BuiltinTySec . first , BuiltinTySec . second } , <nl> - { CaptureSec . first , CaptureSec . second } , <nl> - { TypeRefMdSec . first , TypeRefMdSec . second } , <nl> - { ReflStrMdSec . first , ReflStrMdSec . second } , <nl> - LocalStartAddress , <nl> - RemoteStartAddress } ; <nl> - <nl> - this - > addReflectionInfo ( info ) ; <nl> - <nl> + # define SECTION_INFO ( NAME ) \ <nl> + { RemoteAddrToRemoteRef ( Sections - > NAME . start ) , Sections - > NAME . length } <nl> + ReflectionInfo Info = { <nl> + SECTION_INFO ( swift5_fieldmd ) , SECTION_INFO ( swift5_assocty ) , <nl> + SECTION_INFO ( swift5_builtin ) , SECTION_INFO ( swift5_capture ) , <nl> + SECTION_INFO ( swift5_typeref ) , SECTION_INFO ( swift5_reflstr ) , <nl> + reinterpret_cast < uint64_t > ( Buf . get ( ) ) , BeginAddr } ; <nl> + # undef SECTION_INFO <nl> + this - > addReflectionInfo ( Info ) ; <nl> savedBuffers . push_back ( std : : move ( Buf ) ) ; <nl> return true ; <nl> } <nl> - <nl> + <nl> bool readELF ( RemoteAddress ImageStart ) { <nl> auto Buf = <nl> this - > getReader ( ) . readBytes ( ImageStart , sizeof ( llvm : : ELF : : Elf64_Ehdr ) ) ; <nl> - <nl> / / Read the header . <nl> auto Hdr = reinterpret_cast < const llvm : : ELF : : Elf64_Ehdr * > ( Buf . get ( ) ) ; <nl> - <nl> if ( ! Hdr - > checkMagic ( ) ) <nl> return false ; <nl> - <nl> / / Check if we have a ELFCLASS32 or ELFCLASS64 <nl> unsigned char FileClass = Hdr - > getFileClass ( ) ; <nl> if ( FileClass = = llvm : : ELF : : ELFCLASS64 ) { <nl> class ReflectionContext <nl> auto Magic = this - > getReader ( ) . readBytes ( ImageStart , sizeof ( uint32_t ) ) ; <nl> if ( ! Magic ) <nl> return false ; <nl> - <nl> + <nl> uint32_t MagicWord ; <nl> memcpy ( & MagicWord , Magic . get ( ) , sizeof ( MagicWord ) ) ; <nl> - <nl> + <nl> / / 32 - and 64 - bit Mach - O . <nl> if ( MagicWord = = llvm : : MachO : : MH_MAGIC ) { <nl> return readMachOSections < MachOTraits < 4 > > ( ImageStart ) ; <nl> } <nl> - <nl> + <nl> if ( MagicWord = = llvm : : MachO : : MH_MAGIC_64 ) { <nl> return readMachOSections < MachOTraits < 8 > > ( ImageStart ) ; <nl> } <nl> - <nl> + <nl> / / PE . ( This just checks for the DOS header ; ` readPECOFF ` will further <nl> / / validate the existence of the PE header . ) <nl> auto MagicBytes = ( const char * ) Magic . get ( ) ; <nl> if ( MagicBytes [ 0 ] = = ' M ' & & MagicBytes [ 1 ] = = ' Z ' ) { <nl> return readPECOFF ( ImageStart ) ; <nl> } <nl> - <nl> + <nl> / / ELF . <nl> if ( MagicBytes [ 0 ] = = llvm : : ELF : : ElfMagic [ 0 ] <nl> & & MagicBytes [ 1 ] = = llvm : : ELF : : ElfMagic [ 1 ] <nl> class ReflectionContext <nl> & & MagicBytes [ 3 ] = = llvm : : ELF : : ElfMagic [ 3 ] ) { <nl> return readELF ( ImageStart ) ; <nl> } <nl> - <nl> + <nl> / / We don ' t recognize the format . <nl> return false ; <nl> } <nl> class ReflectionContext <nl> return true ; <nl> return ownsAddress ( RemoteAddress ( * MetadataAddress ) ) ; <nl> } <nl> - <nl> + <nl> / / / Returns true if the address falls within a registered image . <nl> bool ownsAddress ( RemoteAddress Address ) { <nl> for ( auto Range : imageRanges ) { <nl> class ReflectionContext <nl> & & Address . getAddressData ( ) < End . getAddressData ( ) ) <nl> return true ; <nl> } <nl> - <nl> + <nl> return false ; <nl> } <nl> - <nl> + <nl> / / / Return a description of the layout of a class instance with the given <nl> / / / metadata as its isa pointer . <nl> const TypeInfo * getMetadataTypeInfo ( StoredPointer MetadataAddress ) { <nl> mmm a / stdlib / public / runtime / ImageInspectionELF . h <nl> ppp b / stdlib / public / runtime / ImageInspectionELF . h <nl> <nl> <nl> # define SWIFT_REFLECTION_METADATA_ELF_NOTE_MAGIC_STRING " swift_reflection_metadata_magic_string " <nl> <nl> - # if defined ( __ELF__ ) <nl> - <nl> # include " . . / SwiftShims / Visibility . h " <nl> # include < cstdint > <nl> # include < cstddef > <nl> struct MetadataSections { <nl> } ; <nl> } / / namespace swift <nl> <nl> + # if defined ( __ELF__ ) <nl> / / Called by injected constructors when a dynamic library is loaded . <nl> SWIFT_RUNTIME_EXPORT <nl> void swift_addNewDSOImage ( const void * addr ) ; <nl> - <nl> # endif / / defined ( __ELF__ ) <nl> <nl> # endif / / SWIFT_RUNTIME_IMAGE_INSPECTION_ELF_H <nl> mmm a / tools / swift - reflection - dump / swift - reflection - dump . cpp <nl> ppp b / tools / swift - reflection - dump / swift - reflection - dump . cpp <nl> <nl> / / binaries . <nl> / / = = = mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - = = = / / <nl> <nl> + # include " . . / . . / stdlib / public / runtime / ImageInspectionELF . h " <nl> # include " swift / ABI / MetadataValues . h " <nl> # include " swift / Basic / LLVMInitialize . h " <nl> # include " swift / Demangling / Demangle . h " <nl> # include " swift / Reflection / ReflectionContext . h " <nl> # include " swift / Reflection / TypeRef . h " <nl> # include " swift / Reflection / TypeRefBuilder . h " <nl> + <nl> # include " llvm / ADT / StringSet . h " <nl> # include " llvm / Object / Archive . h " <nl> # include " llvm / Object / COFF . h " <nl> template < typename T > static T unwrap ( llvm : : Expected < T > value ) { <nl> exit ( EXIT_FAILURE ) ; <nl> } <nl> <nl> + static void reportError ( StringRef Message ) { <nl> + llvm : : errs ( ) < < " swift - reflection - test error : " < < Message < < " . \ n " ; <nl> + exit ( EXIT_FAILURE ) ; <nl> + } <nl> + <nl> static void reportError ( std : : error_code EC ) { <nl> assert ( EC ) ; <nl> - llvm : : errs ( ) < < " swift - reflection - test error : " < < EC . message ( ) < < " . \ n " ; <nl> - exit ( EXIT_FAILURE ) ; <nl> + reportError ( EC . message ( ) ) ; <nl> } <nl> <nl> - using NativeReflectionContext = <nl> - swift : : reflection : : ReflectionContext < External < RuntimeTarget < sizeof ( uintptr_t ) > > > ; <nl> + using NativeReflectionContext = swift : : reflection : : ReflectionContext < <nl> + External < RuntimeTarget < sizeof ( uintptr_t ) > > > ; <nl> <nl> using ReadBytesResult = swift : : remote : : MemoryReader : : ReadBytesResult ; <nl> <nl> static uint64_t getSectionAddress ( SectionRef S ) { <nl> - / / See COFFObjectFile . cpp for the implementation of <nl> + / / See COFFObjectFile . cpp for the implementation of <nl> / / COFFObjectFile : : getSectionAddress . The image base address is added <nl> - / / to all the addresses of the sections , thus the behavior is slightly different from <nl> - / / the other platforms . <nl> + / / to all the addresses of the sections , thus the behavior is slightly <nl> + / / different from the other platforms . <nl> if ( auto C = dyn_cast < COFFObjectFile > ( S . getObject ( ) ) ) <nl> return S . getAddress ( ) - C - > getImageBase ( ) ; <nl> return S . getAddress ( ) ; <nl> static bool needToRelocate ( SectionRef S ) { <nl> <nl> if ( auto EO = dyn_cast < ELFObjectFileBase > ( S . getObject ( ) ) ) { <nl> static const llvm : : StringSet < > ELFSectionsList = { <nl> - " . data " , " . rodata " , " swift5_protocols " , " swift5_protocol_conformances " , <nl> - " swift5_typeref " , " swift5_reflstr " , " swift5_assocty " , " swift5_replace " , <nl> - " swift5_type_metadata " , " swift5_fieldmd " , " swift5_capture " , " swift5_builtin " <nl> + " . data " , <nl> + " . rodata " , <nl> + " . note . swift_reflection_metadata " , <nl> + " swift5_protocols " , <nl> + " swift5_protocol_conformances " , <nl> + " swift5_typeref " , <nl> + " swift5_reflstr " , <nl> + " swift5_assocty " , <nl> + " swift5_replace " , <nl> + " swift5_type_metadata " , <nl> + " swift5_fieldmd " , <nl> + " swift5_capture " , <nl> + " swift5_builtin " , <nl> } ; <nl> StringRef Name ; <nl> if ( auto EC = S . getName ( Name ) ) <nl> static bool needToRelocate ( SectionRef S ) { <nl> return true ; <nl> } <nl> <nl> + static section_iterator findSectionByName ( StringRef Name , const ObjectFile & O ) { <nl> + auto Sections = O . sections ( ) ; <nl> + SmallVector < section_iterator , 1 > FoundSections ; <nl> + std : : copy_if ( Sections . begin ( ) , Sections . end ( ) , <nl> + std : : back_inserter ( FoundSections ) , [ Name ] ( SectionRef S ) { <nl> + StringRef N ; <nl> + if ( auto EC = S . getName ( N ) ) <nl> + reportError ( EC ) ; <nl> + return N = = Name ; <nl> + } ) ; <nl> + if ( FoundSections . size ( ) ! = 1 ) <nl> + return Sections . end ( ) ; <nl> + return FoundSections . front ( ) ; <nl> + } <nl> + <nl> + template < class ELFObj , <nl> + typename std : : enable_if < <nl> + std : : is_base_of < ELFObjectFileBase , ELFObj > : : value , int > : : type = 0 > <nl> + const typename ELFObj : : Elf_Rela * findRelaForOffset ( uint64_t Offset , <nl> + const ELFObj & O ) { <nl> + for ( const SectionRef & S : <nl> + static_cast < const ObjectFile * > ( & O ) - > dynamic_relocation_sections ( ) ) { <nl> + const auto * Sec = O . getSection ( S . getRawDataRefImpl ( ) ) ; <nl> + if ( Sec - > sh_type ! = llvm : : ELF : : SHT_RELA ) <nl> + continue ; <nl> + for ( const RelocationRef & R : S . relocations ( ) ) { <nl> + const auto * Rela = O . getRela ( R . getRawDataRefImpl ( ) ) ; <nl> + if ( Rela - > r_offset = = Offset & & <nl> + Rela - > getType ( false / * isMips64EL * / ) = = llvm : : ELF : : R_X86_64_RELATIVE ) <nl> + return Rela ; <nl> + } <nl> + } <nl> + return nullptr ; <nl> + } <nl> + <nl> + static void updateReflectionMetdataNote ( const ObjectFile & O , char * Memory ) { <nl> + auto EO = dyn_cast < const ELFObjectFileBase > ( & O ) ; <nl> + if ( ! EO ) <nl> + return ; <nl> + auto Note = findSectionByName ( " . note . swift_reflection_metadata " , O ) ; <nl> + if ( Note = = O . sections ( ) . end ( ) ) <nl> + return ; <nl> + const StringRef MagicString = SWIFT_REFLECTION_METADATA_ELF_NOTE_MAGIC_STRING ; <nl> + if ( StringRef ( Memory + Note - > getAddress ( ) , MagicString . size ( ) ) ! = MagicString ) <nl> + reportError ( " . note . swift_reflection_metadata is invalid " ) ; <nl> + <nl> + const uint64_t Offset = Note - > getAddress ( ) + MagicString . size ( ) + 1 ; <nl> + uint64_t Addend = 0 ; <nl> + if ( auto * ELF32LEObj = dyn_cast < ELF32LEObjectFile > ( EO ) ) <nl> + if ( auto * Rela = findRelaForOffset ( Offset , * ELF32LEObj ) ) <nl> + Addend = static_cast < uint64_t > ( Rela - > r_addend ) ; <nl> + if ( auto * ELF64LEObj = dyn_cast < ELF64LEObjectFile > ( EO ) ) <nl> + if ( auto * Rela = findRelaForOffset ( Offset , * ELF64LEObj ) ) <nl> + Addend = static_cast < uint64_t > ( Rela - > r_addend ) ; <nl> + if ( ! Addend ) <nl> + reportError ( " No supported relocations found " ) ; <nl> + uintptr_t PtrValue = reinterpret_cast < uintptr_t > ( Memory ) + Addend ; <nl> + * reinterpret_cast < uintptr_t * > ( Memory + Note - > getAddress ( ) + <nl> + MagicString . size ( ) + 1 ) = PtrValue ; <nl> + auto S = reinterpret_cast < MetadataSections * > ( PtrValue ) ; <nl> + <nl> + # define STRINGIFY ( s ) # s <nl> + # define UPDATE_SECTION_RANGE ( Name ) \ <nl> + [ & ] ( ) { \ <nl> + auto It = findSectionByName ( STRINGIFY ( Name ) , O ) ; \ <nl> + if ( It = = O . sections ( ) . end ( ) ) \ <nl> + return ; \ <nl> + uintptr_t Addr = reinterpret_cast < uintptr_t > ( Memory ) + It - > getAddress ( ) ; \ <nl> + S - > Name = { Addr , It - > getSize ( ) } ; \ <nl> + } ( ) ; <nl> + <nl> + UPDATE_SECTION_RANGE ( swift5_protocols ) <nl> + UPDATE_SECTION_RANGE ( swift5_protocol_conformances ) <nl> + UPDATE_SECTION_RANGE ( swift5_type_metadata ) <nl> + UPDATE_SECTION_RANGE ( swift5_typeref ) <nl> + UPDATE_SECTION_RANGE ( swift5_reflstr ) <nl> + UPDATE_SECTION_RANGE ( swift5_fieldmd ) <nl> + UPDATE_SECTION_RANGE ( swift5_assocty ) <nl> + UPDATE_SECTION_RANGE ( swift5_replace ) <nl> + UPDATE_SECTION_RANGE ( swift5_replac2 ) <nl> + UPDATE_SECTION_RANGE ( swift5_builtin ) <nl> + UPDATE_SECTION_RANGE ( swift5_capture ) <nl> + # undef STRINGIFY <nl> + # undef UPDATE_SECTION_RANGE <nl> + } <nl> <nl> class Image { <nl> std : : vector < char > Memory ; <nl> class Image { <nl> std : : memcpy ( & Memory [ getSectionAddress ( S ) ] , Content . data ( ) , <nl> Content . size ( ) ) ; <nl> } <nl> + updateReflectionMetdataNote ( * O , Memory . data ( ) ) ; <nl> } <nl> <nl> RemoteAddress getStartAddress ( ) const { <nl> | Merge pull request from alexshap / fix_elf_image_parsing | apple/swift | 777d557d392d8c0842098e81046924db071c5bac | 2019-09-27T00:40:29Z |
mmm a / dbms / include / DB / Functions / FunctionsDateTime . h <nl> ppp b / dbms / include / DB / Functions / FunctionsDateTime . h <nl> class FunctionDateOrDateTimeToSomething : public IFunction <nl> { <nl> std : : string error_msg ; <nl> <nl> - if ( typeid_cast < const DataTypeDateTime * > ( & * arguments [ 0 ] ) = = nullptr ) <nl> + if ( typeid_cast < const DataTypeDate * > ( & * arguments [ 0 ] ) ! = nullptr ) <nl> error_msg + = " Illegal type " + arguments [ 0 ] - > getName ( ) + " of argument 1 . " <nl> " Should be a date with time ( timezones are not supported for dates ) " ; <nl> + else if ( typeid_cast < const DataTypeDateTime * > ( & * arguments [ 0 ] ) ! = nullptr ) <nl> + { <nl> + / / / Ничего не делаем . <nl> + } <nl> + else <nl> + error_msg + = " Illegal type " + arguments [ 0 ] - > getName ( ) + " of argument 1 . " <nl> + " Should be a date with time " ; <nl> + <nl> if ( typeid_cast < const DataTypeString * > ( & * arguments [ 1 ] ) = = nullptr ) <nl> { <nl> if ( ! error_msg . empty ( ) ) <nl> | dbms : Server : Added more explanatory error messages for date - time - related functions . [ # METR - 19416 ] | ClickHouse/ClickHouse | 3a9e7a7170ff8f4489dcb49a4b394caa20e60c7f | 2015-12-15T10:13:07Z |
mmm a / xbmc / pvr / channels / PVRChannelGroup . cpp <nl> ppp b / xbmc / pvr / channels / PVRChannelGroup . cpp <nl> bool CPVRChannelGroup : : Persist ( void ) <nl> bool bReturn ( true ) ; <nl> CSingleLock lock ( m_critSection ) ; <nl> <nl> - if ( ! HasChanges ( ) ) <nl> + / * don ' t persist until the group is fully loaded and has changes * / <nl> + if ( ! HasChanges ( ) | | ! m_bLoaded ) <nl> return bReturn ; <nl> <nl> if ( CPVRDatabase * database = GetPVRDatabase ( ) ) <nl> | [ pvr ] don ' t persist channel groups ( includes members ) unless the group | xbmc/xbmc | 36d276f091bf64ec5099717d9730d3e1e68f84da | 2015-01-02T12:15:59Z |
mmm a / addons / xbmc . addon / addon . xml <nl> ppp b / addons / xbmc . addon / addon . xml <nl> <nl> < ? xml version = " 1 . 0 " encoding = " UTF - 8 " ? > <nl> - < addon id = " xbmc . addon " version = " 12 . 9 . 1 " provider - name = " Team XBMC " > <nl> + < addon id = " xbmc . addon " version = " 12 . 9 . 2 " provider - name = " Team XBMC " > <nl> < backwards - compatibility abi = " 12 . 0 " / > <nl> < requires > <nl> < import addon = " xbmc . core " version = " 0 . 1 . 0 " / > <nl> mmm a / configure . in <nl> ppp b / configure . in <nl> <nl> # Process this file with autoconf to produce a configure script . <nl> <nl> AC_PREREQ ( 2 . 59 ) <nl> - AC_INIT ( [ xbmc ] , [ 12 . 9 . 1 ] , [ http : / / trac . xbmc . org ] ) <nl> + AC_INIT ( [ xbmc ] , [ 12 . 9 . 2 ] , [ http : / / trac . xbmc . org ] ) <nl> AC_CONFIG_HEADERS ( [ xbmc / config . h ] ) <nl> AH_TOP ( [ # pragma once ] ) <nl> m4_include ( [ m4 / ax_python_devel . m4 ] ) <nl> mmm a / tools / android / packaging / xbmc / AndroidManifest . xml <nl> ppp b / tools / android / packaging / xbmc / AndroidManifest . xml <nl> <nl> < ! - - BEGIN_INCLUDE ( manifest ) - - > <nl> < manifest xmlns : android = " http : / / schemas . android . com / apk / res / android " <nl> package = " org . xbmc . xbmc " <nl> - android : versionCode = " 7 " <nl> - android : versionName = " 13 . 0 - ALPHA1 " > <nl> + android : versionCode = " 8 " <nl> + android : versionName = " 13 . 0 - ALPHA2 " > <nl> <nl> < ! - - This is the platform API where NativeActivity was introduced . - - > <nl> < uses - sdk android : minSdkVersion = " 9 " / > <nl> mmm a / tools / darwin / packaging / xbmc - atv2 / mkdeb - xbmc - atv2 . sh <nl> ppp b / tools / darwin / packaging / xbmc - atv2 / mkdeb - xbmc - atv2 . sh <nl> fi <nl> PACKAGE = org . xbmc . xbmc - atv2 <nl> <nl> VERSION = 13 . 0 <nl> - REVISION = 0 ~ alpha1 <nl> + REVISION = 0 ~ alpha2 <nl> ARCHIVE = $ { PACKAGE } _ $ { VERSION } - $ { REVISION } _iphoneos - arm . deb <nl> <nl> echo Creating $ PACKAGE package version $ VERSION revision $ REVISION <nl> mmm a / tools / darwin / packaging / xbmc - ios / mkdeb - xbmc - ios . sh <nl> ppp b / tools / darwin / packaging / xbmc - ios / mkdeb - xbmc - ios . sh <nl> fi <nl> PACKAGE = org . xbmc . xbmc - ios <nl> <nl> VERSION = 13 . 0 <nl> - REVISION = 0 ~ alpha1 <nl> + REVISION = 0 ~ alpha2 <nl> ARCHIVE = $ { PACKAGE } _ $ { VERSION } - $ { REVISION } _iphoneos - arm . deb <nl> <nl> echo Creating $ PACKAGE package version $ VERSION revision $ REVISION <nl> mmm a / xbmc / GUIInfoManager . h <nl> ppp b / xbmc / GUIInfoManager . h <nl> namespace INFO <nl> <nl> # define VERSION_MAJOR 13 <nl> # define VERSION_MINOR 0 <nl> - # define VERSION_TAG " - ALPHA1 " <nl> + # define VERSION_TAG " - ALPHA2 " <nl> <nl> # define LISTITEM_START 35000 <nl> # define LISTITEM_THUMB ( LISTITEM_START ) <nl> mmm a / xbmc / osx / Info . plist <nl> ppp b / xbmc / osx / Info . plist <nl> <nl> < key > CFBundleExecutable < / key > <nl> < string > XBMC < / string > <nl> < key > CFBundleGetInfoString < / key > <nl> - < string > 13 . 0 . alpha1 < / string > <nl> + < string > 13 . 0 . alpha2 < / string > <nl> < key > CFBundleIconFile < / key > <nl> < string > xbmc . icns < / string > <nl> < key > CFBundleIdentifier < / key > <nl> <nl> < key > CFBundlePackageType < / key > <nl> < string > APPL < / string > <nl> < key > CFBundleShortVersionString < / key > <nl> - < string > 13 . 0 . alpha1 < / string > <nl> + < string > 13 . 0 . alpha2 < / string > <nl> < key > CFBundleVersion < / key > <nl> < string > r # # # # < / string > <nl> < key > CFBundleSignature < / key > <nl> mmm a / xbmc / win32 / XBMC_PC . rc <nl> ppp b / xbmc / win32 / XBMC_PC . rc <nl> END <nl> / / <nl> <nl> VS_VERSION_INFO VERSIONINFO <nl> - FILEVERSION 11 , 9 , 1 , 0 <nl> - PRODUCTVERSION 11 , 9 , 1 , 0 <nl> + FILEVERSION 12 , 9 , 2 , 0 <nl> + PRODUCTVERSION 12 , 9 , 2 , 0 <nl> FILEFLAGSMASK 0x3fL <nl> # ifdef _DEBUG <nl> FILEFLAGS 0x1L <nl> BEGIN <nl> BEGIN <nl> VALUE " CompanyName " , " Team XBMC " <nl> VALUE " FileDescription " , " XBMC " <nl> - VALUE " FileVersion " , " 13 . 0 - ALPHA1 " <nl> + VALUE " FileVersion " , " 13 . 0 - ALPHA2 " <nl> VALUE " InternalName " , " XBMC . exe " <nl> VALUE " LegalCopyright " , " Copyright ( c ) Team XBMC . All rights reserved . " <nl> VALUE " OriginalFilename " , " XBMC . exe " <nl> VALUE " ProductName " , " XBMC for Windows " <nl> - VALUE " ProductVersion " , " 13 . 0 - ALPHA1 " <nl> + VALUE " ProductVersion " , " 13 . 0 - ALPHA2 " <nl> END <nl> END <nl> BLOCK " VarFileInfo " <nl> | [ release ] version bump to 13 . 0 alpha2 as we start new merge window . | xbmc/xbmc | 3bc058871d1a6995843cc6c6aeb2c2de5af4a818 | 2013-02-15T16:11:06Z |
mmm a / Telegram / Resources / langs / lang . strings <nl> ppp b / Telegram / Resources / langs / lang . strings <nl> https : / / github . com / telegramdesktop / tdesktop / blob / master / LEGAL <nl> " lng_proxy_about " = " Proxy servers may be helpful in accessing Telegram if there is no connection in a specific region . " ; <nl> " lng_proxy_add " = " Add proxy " ; <nl> " lng_proxy_share " = " Share " ; <nl> - " lng_proxy_online " = " online " ; <nl> + " lng_proxy_online " = " connected " ; <nl> " lng_proxy_checking " = " checking " ; <nl> " lng_proxy_connecting " = " connecting " ; <nl> - " lng_proxy_available " = " available ( ping : { ping } ms ) " ; <nl> + " lng_proxy_available " = " available , { ping } ms ping " ; <nl> " lng_proxy_unavailable " = " not available " ; <nl> " lng_proxy_edit " = " Edit proxy " ; <nl> " lng_proxy_menu_edit " = " Edit " ; <nl> | Improve proxy phrases . | telegramdesktop/tdesktop | 7a32ad540909e1bd484a6d46f49dcce633057e82 | 2018-05-25T17:46:15Z |
mmm a / CONTRIBUTING . md <nl> ppp b / CONTRIBUTING . md <nl> <nl> - # Table of contents <nl> + # Table of Contents <nl> <nl> - [ Contributing to PyTorch ] ( # contributing - to - pytorch ) <nl> - [ Developing PyTorch ] ( # developing - pytorch ) <nl> <nl> <nl> # # Contributing to PyTorch <nl> <nl> - If you are interested in contributing to PyTorch , your contributions will fall <nl> - into two categories : <nl> + Thank you for your interest in contributing to PyTorch ! Before you begin writing code , it is important <nl> + that you share your intention to contribute with the team , based on the type of contribution : <nl> <nl> 1 . You want to propose a new feature and implement it . <nl> - - Post about your intended feature , and we shall discuss the design and <nl> - implementation . Once we agree that the plan looks good , go ahead and implement it . <nl> + - Post about your intended feature in an [ issue ] ( https : / / github . com / pytorch / pytorch / issues ) , <nl> + and we shall discuss the design and implementation . Once we agree that the plan looks good , <nl> + go ahead and implement it . <nl> 2 . You want to implement a feature or bug - fix for an outstanding issue . <nl> - - Search for your issue here : https : / / github . com / pytorch / pytorch / issues <nl> - - Pick an issue and comment on the task that you want to work on this feature . <nl> + - Search for your issue in the [ PyTorch issue list ] ( https : / / github . com / pytorch / pytorch / issues ) . <nl> + - Pick an issue and comment that you ' d like to work on the feature or bug - fix . <nl> - If you need more context on a particular issue , please ask and we shall provide . <nl> <nl> - Once you finish implementing a feature or bug - fix , please send a Pull Request to <nl> - https : / / github . com / pytorch / pytorch <nl> + Once you implement and test your feature or bug - fix , please submit a Pull Request to <nl> + https : / / github . com / pytorch / pytorch . <nl> <nl> This document covers some of the more technical aspects of contributing <nl> to PyTorch . For more non - technical guidance about how to contribute to <nl> and ` python setup . py clean ` . Then you can install in ` develop ` mode again . <nl> support for PyTorch . <nl> * [ tools ] ( tools ) - Code generation scripts for the PyTorch library . <nl> See [ README ] ( tools / README . md ) of this directory for more details . <nl> - * [ test ] ( tests ) - Python unit tests for PyTorch Python frontend . <nl> + * [ test ] ( test ) - Python unit tests for PyTorch Python frontend . <nl> * [ test_torch . py ] ( test / test_torch . py ) - Basic tests for PyTorch <nl> functionality . <nl> * [ test_autograd . py ] ( test / test_autograd . py ) - Tests for non - NN <nl> If you are working on the CUDA code , here are some useful CUDA debugging tips : <nl> ` ` ` <nl> <nl> <nl> - Hope this helps , and thanks for considering to contribute . <nl> - <nl> # # Windows development tips <nl> <nl> For building from source on Windows , consult <nl> | Fix Broken Link in CONTRIBUTING . md ( ) | pytorch/pytorch | bacca663ffdd8470c437e665bcc6bd572ed4ecd9 | 2020-07-08T03:02:47Z |
mmm a / Python / cntk / __init__ . py <nl> ppp b / Python / cntk / __init__ . py <nl> <nl> + __version__ = ' 1 . 5 ' <nl> + <nl> from . context import * <nl> + import cntk . graph <nl> from . graph import * <nl> from . objectives import * <nl> from . ops import * <nl> new file mode 100644 <nl> index 00000000000 . . e470a3dbed7 <nl> mmm / dev / null <nl> ppp b / Python / cntk / _fetch_ops . py <nl> <nl> + # This is a tool that semi - automatically creates operator classes from <nl> + # CNTK . Core . bs and puts them into _ops . py . <nl> + # It is just a temporary solution until we have CNTK as a library . <nl> + # <nl> + # Ignores deprecated symbols ( e . g . Parameter ) <nl> + <nl> + import os <nl> + import re <nl> + <nl> + DIRNAME_OF_THIS_FILE = os . path . abspath ( os . path . dirname ( __file__ ) ) <nl> + <nl> + # BrainSCript ' s node definitions <nl> + CNTKCORE_DEFS = os . path . abspath ( os . path . join ( DIRNAME_OF_THIS_FILE , ' CNTK . core . bs ' ) ) <nl> + <nl> + # REGEX = re . compile ( ' ComputationNodePtr \ s + ( . * ) ; ' , re . MULTILINE ) <nl> + REGEX_COMPNODE = re . compile ( r ' ( ? P < operator > \ w + ) \ ( ( ? P < operands > . * ? ) \ ) = new ComputationNode \ [ ' ) <nl> + REGEX_COMMENT = re . compile ( r ' / \ * . * \ * / ' ) <nl> + <nl> + OPERANDS_TO_IGNORE = { " tag = ' ' " } <nl> + <nl> + class Operand ( object ) : <nl> + def __init__ ( self , name , init_value ) : <nl> + self . name = name <nl> + <nl> + if init_value is None : <nl> + self . init_value = None <nl> + else : <nl> + init_value = REGEX_COMMENT . sub ( ' ' , init_value ) <nl> + <nl> + if init_value [ 0 ] = = " ' " and init_value [ - 1 ] = = " ' " : <nl> + self . init_value = init_value [ 1 : - 1 ] <nl> + else : <nl> + if init_value . lower ( ) = = ' false ' : <nl> + self . init_value = False <nl> + elif init_value . lower ( ) = = ' true ' : <nl> + self . init_value = True <nl> + elif ' . ' in init_value : <nl> + self . init_value = float ( init_value ) <nl> + else : <nl> + self . init_value = int ( init_value ) <nl> + <nl> + COMP_NODE_TEMPLATE = " " " \ <nl> + class % ( name ) s ( ComputationNode ) : <nl> + def __init__ ( self , % ( signature ) s ) : <nl> + super ( % ( name ) s , self ) . __init__ ( ' % ( name ) s ' ) <nl> + % ( initialization ) s <nl> + " " " <nl> + <nl> + class CompNodeOperator ( object ) : <nl> + def __init__ ( self , comp_node ) : <nl> + self . name = comp_node . group ( ' operator ' ) <nl> + self . raw_operands = comp_node . group ( ' operands ' ) <nl> + <nl> + self . operands = [ ] <nl> + for op in self . raw_operands . split ( ' , ' ) : <nl> + if op . strip ( ) in OPERANDS_TO_IGNORE : <nl> + continue <nl> + <nl> + parts = op . split ( ' = ' ) <nl> + if len ( parts ) = = 1 : <nl> + self . operands . append ( Operand ( parts [ 0 ] . strip ( ) , None ) ) <nl> + elif len ( parts ) = = 2 : <nl> + self . operands . append ( Operand ( parts [ 0 ] . strip ( ) , parts [ 1 ] . strip ( ) ) ) <nl> + else : <nl> + raise ValueError ( ' Did not expect this format ' ) <nl> + <nl> + self . signature = " , " . join ( self . sig ( op ) for op in self . operands ) <nl> + <nl> + self . initialization = " \ n " . join ( ( " " * 8 + " self . % s = % s " % ( op . name , op . name ) for op in self . operands ) ) <nl> + <nl> + # Ensure that arguments with default values are not followed by <nl> + # arguments without default values . <nl> + default_init_started = False <nl> + for op in self . operands : <nl> + if op . init_value is not None : <nl> + default_init_started = True <nl> + assert op . init_value is None or default_init_started <nl> + <nl> + <nl> + def __str__ ( self ) : <nl> + return COMP_NODE_TEMPLATE % self . __dict__ <nl> + <nl> + def sig ( self , op ) : <nl> + name , init = op . name , op . init_value <nl> + if init is None : <nl> + return name <nl> + <nl> + if type ( init ) = = str : <nl> + return " % s = ' % s ' " % ( op . name , op . init_value ) <nl> + else : <nl> + <nl> + return " % s = % s " % ( op . name , op . init_value ) <nl> + <nl> + def convert_bs_to_python ( bs_fn , py_fn ) : <nl> + with open ( py_fn , ' w ' ) as pyf : <nl> + pyf . write ( ' from graph import ComputationNode \ n ' ) <nl> + <nl> + for line in open ( bs_fn , ' r ' ) : <nl> + comp_node = REGEX_COMPNODE . match ( line ) <nl> + if comp_node : <nl> + po = CompNodeOperator ( comp_node ) <nl> + pyf . write ( str ( po ) + ' \ n ' ) <nl> + <nl> + if __name__ = = ' __main__ ' : <nl> + convert_bs_to_python ( CNTKCORE_DEFS , " _ops . py " ) <nl> + <nl> mmm a / Python / cntk / context . py <nl> ppp b / Python / cntk / context . py <nl> <nl> PYDOT = False <nl> <nl> class Context ( object ) : <nl> - import cntk . graph as graph <nl> - def __init__ ( self , desc ) : <nl> - <nl> - self . directory = os . path . abspath ( ' _cntk_ % s ' % id ( desc ) ) <nl> + def __init__ ( self , model ) : <nl> + self . directory = os . path . abspath ( ' _cntk_ % s ' % id ( model ) ) <nl> if os . path . exists ( self . directory ) : <nl> print ( " Directory ' % s ' already exists - overwriting data . " % self . directory ) <nl> else : <nl> mmm a / Python / cntk / graph . py <nl> ppp b / Python / cntk / graph . py <nl> <nl> + <nl> class ComputationNode ( object ) : <nl> def __init__ ( self , name , params = None , value = None , get_output_shape = None , <nl> var_name = None , check = None ) : <nl> mmm a / Python / cntk / objectives . py <nl> ppp b / Python / cntk / objectives . py <nl> @ @ - 1 + 0 , 0 @ @ <nl> - <nl> mmm a / Python / cntk / ops . py <nl> ppp b / Python / cntk / ops . py <nl> <nl> - from . graph import ComputationNode <nl> + <nl> + from cntk . graph import ComputationNode <nl> <nl> # Because CNTK stores the sample in a transposed form , we need to <nl> # switch parameters for some operators <nl> mmm a / Python / cntk / optimizer . py <nl> ppp b / Python / cntk / optimizer . py <nl> <nl> - <nl> - <nl> mmm a / Python / cntk / reader . py <nl> ppp b / Python / cntk / reader . py <nl> @ @ - 1 , 2 + 1 @ @ <nl> <nl> - <nl> new file mode 100644 <nl> index 00000000000 . . d97f2cd8baf <nl> mmm / dev / null <nl> ppp b / Python / cntk / test / test_fetch_ops . py <nl> <nl> + from . . _fetch_ops import REGEX_COMPNODE , CompNodeOperator <nl> + <nl> + import pytest <nl> + @ pytest . mark . parametrize ( " input_line , expected " , [ <nl> + # Format of expected : [ OperatorName , [ ( OperandName_1 , OperandInitValue_1 ) , . . . ] ] <nl> + ( r " Times ( A , B , outputRank = 1 , tag = ' ' ) = new ComputationNode [ operation = ' Times ' ; inputs = ( A : B ) / * plus the function args * / ] " , <nl> + [ ' Times ' , [ ( ' A ' , None ) , ( ' B ' , None ) , ( ' outputRank ' , 1 ) ] ] ) , <nl> + <nl> + <nl> + ( r " Convolution ( weightNode , inputValueNode , kernelWidth , kernelHeight , outputChannels , horizontalSubsample , verticalSubsample , zeroPadding = false , maxTempMemSizeInSamples = 0 , imageLayout = ' CHW ' , tag = ' ' ) = new ComputationNode [ operation = ' Convolution ' ; inputs = ( weightNode : inputValueNode ) / * plus the function args * / ] " , <nl> + [ ' Convolution ' , [ ( ' weightNode ' , None ) , ( ' inputValueNode ' , None ) , ( ' kernelWidth ' , None ) , ( ' kernelHeight ' , None ) , ( ' outputChannels ' , None ) , ( ' horizontalSubsample ' , None ) , ( ' verticalSubsample ' , None ) , ( ' zeroPadding ' , False ) , ( ' maxTempMemSizeInSamples ' , 0 ) , ( ' imageLayout ' , ' CHW ' ) ] ] ) , <nl> + <nl> + ( r " LearnableParameter ( rows , cols , learningRateMultiplier = 1 . 0 , init = ' uniform ' / * | fixedValue | gaussian | fromFile * / , initValueScale = 1 , value = 0 , initFromFilePath = ' ' , initOnCPUOnly = true , randomSeed = - 1 , tag = ' ' ) = new ComputationNode [ operation = ' LearnableParameter ' ; shape = new TensorShape [ dims = ( rows : cols ) ] / * plus the function args * / ] " , <nl> + [ ' LearnableParameter ' , [ ( ' rows ' , None ) , ( ' cols ' , None ) , ( ' learningRateMultiplier ' , 1 . 0 ) , ( ' init ' , ' uniform ' ) , ( ' initValueScale ' , 1 ) , ( ' value ' , 0 ) , ( ' initFromFilePath ' , ' ' ) , ( ' initOnCPUOnly ' , True ) , ( ' randomSeed ' , - 1 ) ] ] ) , <nl> + ] ) <nl> + def test_parsing_comp_nodes ( input_line , expected ) : <nl> + comp_node = REGEX_COMPNODE . match ( input_line ) <nl> + po = CompNodeOperator ( comp_node ) <nl> + <nl> + assert po . name = = expected [ 0 ] <nl> + assert len ( po . operands ) = = len ( expected [ 1 ] ) <nl> + <nl> + for po_op , ( exp_op , exp_init ) in zip ( po . operands , expected [ 1 ] ) : <nl> + assert po_op . name = = exp_op <nl> + assert po_op . init_value = = exp_init <nl> | clean up | microsoft/CNTK | 3982a783e8a1ff4bdb97ee920c9e115ef7de33c7 | 2016-03-09T12:48:58Z |
mmm a / lib / Migrator / SyntacticMigratorPass . cpp <nl> ppp b / lib / Migrator / SyntacticMigratorPass . cpp <nl> struct SyntacticMigratorPass : : Implementation : public SourceEntityWalker { <nl> } <nl> } <nl> <nl> + / / / Migrates code that compiles fine in Swift 3 but breaks in Swift 4 due to <nl> + / / / changes in how the typechecker handles tuple arguments . <nl> + void handleTupleArgumentMismatches ( const CallExpr * E ) { <nl> + if ( ! SF - > getASTContext ( ) . LangOpts . isSwiftVersion3 ( ) ) <nl> + return ; <nl> + if ( E - > isImplicit ( ) ) <nl> + return ; <nl> + <nl> + / / Handles such kind of cases : <nl> + / / \ code <nl> + / / func test ( _ : ( ) ) { } <nl> + / / test ( ) <nl> + / / \ endcode <nl> + / / This compiles fine in Swift 3 but Swift 4 complains with <nl> + / / error : missing argument for parameter # 1 in call <nl> + / / <nl> + / / It will fix the code to " test ( ( ) ) " . <nl> + / / <nl> + auto handleCallsToEmptyTuple = [ & ] ( const CallExpr * E ) - > bool { <nl> + auto fnTy = E - > getFn ( ) - > getType ( ) - > getAs < FunctionType > ( ) ; <nl> + if ( ! fnTy ) <nl> + return false ; <nl> + auto parenT = dyn_cast < ParenType > ( fnTy - > getInput ( ) . getPointer ( ) ) ; <nl> + if ( ! parenT ) <nl> + return false ; <nl> + auto inp = dyn_cast < TupleType > ( parenT - > getUnderlyingType ( ) . getPointer ( ) ) ; <nl> + if ( ! inp ) <nl> + return false ; <nl> + if ( inp - > getNumElements ( ) ! = 0 ) <nl> + return false ; <nl> + auto argTupleT = dyn_cast < TupleType > ( E - > getArg ( ) - > getType ( ) . getPointer ( ) ) ; <nl> + if ( ! argTupleT ) <nl> + return false ; <nl> + if ( argTupleT - > getNumElements ( ) ! = 0 ) <nl> + return false ; <nl> + Editor . insertWrap ( " ( " , E - > getArg ( ) - > getSourceRange ( ) , " ) " ) ; <nl> + return true ; <nl> + } ; <nl> + <nl> + / / Handles such kind of cases : <nl> + / / \ code <nl> + / / func test ( _ : ( ( Int , Int ) ) - > ( ) ) { } <nl> + / / test ( { ( x , y ) in } ) <nl> + / / \ endcode <nl> + / / This compiles fine in Swift 3 but Swift 4 complains with <nl> + / / error : cannot convert value of type ' ( _ , _ ) - > ( ) ' to expected argument type ' ( ( Int , Int ) ) - > ( ) ' <nl> + / / <nl> + / / It will fix the code to " test ( { let ( x , y ) = $ 0 ; } ) " . <nl> + / / <nl> + auto handleTupleMapToClosureArgs = [ & ] ( const CallExpr * E ) - > bool { <nl> + auto fnTy = E - > getFn ( ) - > getType ( ) - > getAs < FunctionType > ( ) ; <nl> + if ( ! fnTy ) <nl> + return false ; <nl> + auto fnTy2 = fnTy - > getInput ( ) - > getAs < FunctionType > ( ) ; <nl> + if ( ! fnTy2 ) <nl> + return false ; <nl> + auto parenT = dyn_cast < ParenType > ( fnTy2 - > getInput ( ) . getPointer ( ) ) ; <nl> + if ( ! parenT ) <nl> + return false ; <nl> + auto tupleInFn = dyn_cast < TupleType > ( parenT - > getUnderlyingType ( ) . getPointer ( ) ) ; <nl> + if ( ! tupleInFn ) <nl> + return false ; <nl> + if ( ! E - > getArg ( ) ) <nl> + return false ; <nl> + auto argE = E - > getArg ( ) - > getSemanticsProvidingExpr ( ) ; <nl> + while ( auto * ICE = dyn_cast < ImplicitConversionExpr > ( argE ) ) <nl> + argE = ICE - > getSubExpr ( ) ; <nl> + argE = argE - > getSemanticsProvidingExpr ( ) ; <nl> + auto closureE = dyn_cast < ClosureExpr > ( argE ) ; <nl> + if ( ! closureE ) <nl> + return false ; <nl> + if ( closureE - > getInLoc ( ) . isInvalid ( ) ) <nl> + return false ; <nl> + auto paramList = closureE - > getParameters ( ) ; <nl> + if ( ! paramList | | <nl> + paramList - > getLParenLoc ( ) . isInvalid ( ) | | paramList - > getRParenLoc ( ) . isInvalid ( ) ) <nl> + return false ; <nl> + if ( paramList - > size ( ) ! = tupleInFn - > getNumElements ( ) ) <nl> + return false ; <nl> + if ( paramList - > size ( ) = = 0 ) <nl> + return false ; <nl> + <nl> + auto hasParamListWithNoTypes = [ & ] ( ) { <nl> + if ( closureE - > hasExplicitResultType ( ) ) <nl> + return false ; <nl> + for ( auto * param : * paramList ) { <nl> + auto tyLoc = param - > getTypeLoc ( ) ; <nl> + if ( ! tyLoc . isNull ( ) ) <nl> + return false ; <nl> + } <nl> + return true ; <nl> + } ; <nl> + <nl> + if ( hasParamListWithNoTypes ( ) ) { <nl> + / / Simpler form depending on type inference . <nl> + / / Change " ( x , y ) in " to " let ( x , y ) = $ 0 ; " . <nl> + <nl> + Editor . insert ( paramList - > getLParenLoc ( ) , " let " ) ; <nl> + for ( auto * param : * paramList ) { <nl> + / / If the argument list is like " ( _ x , _ y ) " , remove the underscores . <nl> + if ( param - > getArgumentNameLoc ( ) . isValid ( ) ) { <nl> + Editor . remove ( CharSourceRange ( SM , param - > getArgumentNameLoc ( ) , <nl> + param - > getNameLoc ( ) ) ) ; <nl> + } <nl> + / / If the argument list has type annotations , remove them . <nl> + auto tyLoc = param - > getTypeLoc ( ) ; <nl> + if ( ! tyLoc . isNull ( ) & & ! tyLoc . getSourceRange ( ) . isInvalid ( ) ) { <nl> + auto nameRange = CharSourceRange ( param - > getNameLoc ( ) , <nl> + param - > getNameStr ( ) . size ( ) ) ; <nl> + auto tyRange = Lexer : : getCharSourceRangeFromSourceRange ( SM , <nl> + tyLoc . getSourceRange ( ) ) ; <nl> + Editor . remove ( CharSourceRange ( SM , nameRange . getEnd ( ) , <nl> + tyRange . getEnd ( ) ) ) ; <nl> + } <nl> + } <nl> + <nl> + Editor . replaceToken ( closureE - > getInLoc ( ) , " = $ 0 ; " ) ; <nl> + return true ; <nl> + } <nl> + <nl> + / / Includes types in the closure signature . The following will do a <nl> + / / more complicated edit than the above : <nl> + / / ( x : Int , y : Int ) - > Int in <nl> + / / to <nl> + / / ( __val : ( Int , Int ) ) - > Int in let ( x , y ) = __val ; <nl> + <nl> + std : : string paramListText ; <nl> + { <nl> + llvm : : raw_string_ostream OS ( paramListText ) ; <nl> + OS < < " ( __val : ( " ; <nl> + for ( size_t i = 0 , e = paramList - > size ( ) ; i ! = e ; + + i ) { <nl> + if ( i ! = 0 ) <nl> + OS < < " , " ; <nl> + auto param = paramList - > get ( i ) ; <nl> + auto tyLoc = param - > getTypeLoc ( ) ; <nl> + if ( ! tyLoc . isNull ( ) & & ! tyLoc . getSourceRange ( ) . isInvalid ( ) ) { <nl> + OS < < SM . extractText ( <nl> + Lexer : : getCharSourceRangeFromSourceRange ( SM , <nl> + tyLoc . getSourceRange ( ) ) ) ; <nl> + } else { <nl> + param - > getType ( ) . print ( OS ) ; <nl> + } <nl> + } <nl> + OS < < " ) ) " ; <nl> + } <nl> + std : : string varBindText ; <nl> + { <nl> + llvm : : raw_string_ostream OS ( varBindText ) ; <nl> + OS < < " let ( " ; <nl> + for ( size_t i = 0 , e = paramList - > size ( ) ; i ! = e ; + + i ) { <nl> + if ( i ! = 0 ) <nl> + OS < < " , " ; <nl> + auto param = paramList - > get ( i ) ; <nl> + OS < < param - > getNameStr ( ) ; <nl> + } <nl> + OS < < " ) = __val ; " ; <nl> + } <nl> + <nl> + Editor . replace ( paramList - > getSourceRange ( ) , paramListText ) ; <nl> + Editor . insertAfterToken ( closureE - > getInLoc ( ) , varBindText ) ; <nl> + return true ; <nl> + } ; <nl> + <nl> + if ( handleCallsToEmptyTuple ( E ) ) <nl> + return ; <nl> + if ( handleTupleMapToClosureArgs ( E ) ) <nl> + return ; <nl> + } <nl> + <nl> bool walkToExprPre ( Expr * E ) override { <nl> if ( auto * CE = dyn_cast < CallExpr > ( E ) ) { <nl> + handleTupleArgumentMismatches ( CE ) ; <nl> + <nl> auto Fn = CE - > getFn ( ) ; <nl> auto Args = CE - > getArg ( ) ; <nl> switch ( Fn - > getKind ( ) ) { <nl> new file mode 100644 <nl> index 000000000000 . . 45b80208db94 <nl> mmm / dev / null <nl> ppp b / test / Migrator / tuple - arguments . swift <nl> <nl> + / / RUN : % target - swift - frontend - typecheck % s - swift - version 3 <nl> + / / RUN : % target - swift - frontend - typecheck - update - code - primary - file % s - emit - migrated - file - path % t . result - disable - migrator - fixits - swift - version 3 <nl> + / / RUN : diff - u % s . expected % t . result <nl> + / / RUN : % target - swift - frontend - typecheck % s . expected - swift - version 4 <nl> + <nl> + func test1 ( _ : ( ) ) { } <nl> + test1 ( ( ) ) <nl> + test1 ( ) <nl> + func test2 ( ) { } <nl> + test2 ( ) <nl> + <nl> + enum Result < T > { <nl> + case success ( T ) <nl> + } <nl> + func test3 ( _ : Result < ( ) > ) { } <nl> + test3 ( . success ( ) ) <nl> + <nl> + func test4 ( _ : ( Int , Int ) - > ( ) ) { } <nl> + test4 ( { ( x , y ) in } ) <nl> + func test5 ( _ : ( Int , Int , Int ) - > ( ) ) { } <nl> + test5 ( { ( x , y , z ) in } ) <nl> + <nl> + func test6 ( _ : ( ( Int , Int ) ) - > ( ) ) { } <nl> + test6 ( { ( x , y ) in } ) <nl> + func test7 ( _ : ( ( Int , Int , Int ) ) - > ( ) ) { } <nl> + test7 ( { ( x , y , z ) in } ) <nl> + test6 ( { ( _ x , _ y ) in } ) <nl> + test6 ( { ( _ , _ ) in } ) <nl> + test6 ( { ( x : Int , y : Int ) in } ) <nl> + test6 ( { ( _ , _ ) - > ( ) in } ) <nl> + <nl> + func toString ( indexes : Int ? . . . ) - > String { <nl> + let _ = indexes . enumerated ( ) . flatMap ( { ( i : Int , index : Int ? ) - > String ? in <nl> + let _ : Int = i <nl> + if index ! = nil { } <nl> + return " " <nl> + } ) <nl> + } <nl> new file mode 100644 <nl> index 000000000000 . . 388119abb978 <nl> mmm / dev / null <nl> ppp b / test / Migrator / tuple - arguments . swift . expected <nl> <nl> + / / RUN : % target - swift - frontend - typecheck % s - swift - version 3 <nl> + / / RUN : % target - swift - frontend - typecheck - update - code - primary - file % s - emit - migrated - file - path % t . result - disable - migrator - fixits - swift - version 3 <nl> + / / RUN : diff - u % s . expected % t . result <nl> + / / RUN : % target - swift - frontend - typecheck % s . expected - swift - version 4 <nl> + <nl> + func test1 ( _ : ( ) ) { } <nl> + test1 ( ( ) ) <nl> + test1 ( ( ) ) <nl> + func test2 ( ) { } <nl> + test2 ( ) <nl> + <nl> + enum Result < T > { <nl> + case success ( T ) <nl> + } <nl> + func test3 ( _ : Result < ( ) > ) { } <nl> + test3 ( . success ( ( ) ) ) <nl> + <nl> + func test4 ( _ : ( Int , Int ) - > ( ) ) { } <nl> + test4 ( { ( x , y ) in } ) <nl> + func test5 ( _ : ( Int , Int , Int ) - > ( ) ) { } <nl> + test5 ( { ( x , y , z ) in } ) <nl> + <nl> + func test6 ( _ : ( ( Int , Int ) ) - > ( ) ) { } <nl> + test6 ( { let ( x , y ) = $ 0 ; } ) <nl> + func test7 ( _ : ( ( Int , Int , Int ) ) - > ( ) ) { } <nl> + test7 ( { let ( x , y , z ) = $ 0 ; } ) <nl> + test6 ( { let ( x , y ) = $ 0 ; } ) <nl> + test6 ( { let ( _ , _ ) = $ 0 ; } ) <nl> + test6 ( { ( __val : ( Int , Int ) ) in let ( x , y ) = __val ; } ) <nl> + test6 ( { ( __val : ( Int , Int ) ) - > ( ) in let ( _ , _ ) = __val ; } ) <nl> + <nl> + func toString ( indexes : Int ? . . . ) - > String { <nl> + let _ = indexes . enumerated ( ) . flatMap ( { ( __val : ( Int , Int ? ) ) - > String ? in let ( i , index ) = __val ; <nl> + let _ : Int = i <nl> + if index ! = nil { } <nl> + return " " <nl> + } ) <nl> + } <nl> | [ migrator ] Add an AST pass to handle tuple mismatches | apple/swift | 1b6e001a196df95eb08a5abe1d9d92ac935652b4 | 2017-05-04T14:26:00Z |
mmm a / doc / released_features . md <nl> ppp b / doc / released_features . md <nl> <nl> OpenPose Library - Latest Released Features <nl> = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> <nl> - - Mar 2018 : [ * * CPU version * * ] ( doc / installation . md # cpu - version ) ! <nl> - - Mar 2018 : Improved [ * * 3 - D keypoint reconstruction module * * ] ( doc / 3d_reconstruction_demo . md ) ( from multiple camera views ) ! <nl> - - Sep 2017 : [ * * CMake * * ] ( doc / installation . md ) installer and * * IP camera * * support ! <nl> + - Mar 2018 : [ * * CPU version * * ] ( . / installation . md # cpu - version ) ! <nl> + - Mar 2018 : Improved [ * * 3 - D keypoint reconstruction module * * ] ( . / 3d_reconstruction_demo . md ) ( from multiple camera views ) ! <nl> + - Sep 2017 : [ * * CMake * * ] ( . / installation . md ) installer and * * IP camera * * support ! <nl> - Jul 2017 : [ * * Windows portable binaries and demo * * ] ( https : / / github . com / CMU - Perceptual - Computing - Lab / openpose / releases ) ! <nl> - Jul 2017 : * * Hands * * released ! <nl> - Jun 2017 : * * Face * * released ! <nl> | Fixed doc typo ( ) | CMU-Perceptual-Computing-Lab/openpose | bc8cf6ccd738ae6a5f78d5e388c13cd9760d4a59 | 2018-05-28T23:50:03Z |
mmm a / src / api . cc <nl> ppp b / src / api . cc <nl> static void InitializeTemplate ( i : : Handle < i : : TemplateInfo > that , int type ) { <nl> <nl> void Template : : Set ( v8 : : Handle < String > name , v8 : : Handle < Data > value , <nl> v8 : : PropertyAttribute attribute ) { <nl> - if ( IsDeadCheck ( " v8 : : Template : : SetProperty ( ) " ) ) return ; <nl> + if ( IsDeadCheck ( " v8 : : Template : : Set ( ) " ) ) return ; <nl> ENTER_V8 ; <nl> HandleScope scope ; <nl> i : : Handle < i : : Object > list ( Utils : : OpenHandle ( this ) - > property_list ( ) ) ; <nl> mmm a / src / bootstrapper . cc <nl> ppp b / src / bootstrapper . cc <nl> static Handle < JSFunction > InstallFunction ( Handle < JSObject > target , <nl> prototype , <nl> call_code , <nl> is_ecma_native ) ; <nl> - SetProperty ( target , symbol , function , DONT_ENUM ) ; <nl> + SetLocalPropertyNoThrow ( target , symbol , function , DONT_ENUM ) ; <nl> if ( is_ecma_native ) { <nl> function - > shared ( ) - > set_instance_class_name ( * symbol ) ; <nl> } <nl> Handle < JSGlobalProxy > Genesis : : CreateNewGlobals ( <nl> Handle < JSObject > prototype = <nl> Handle < JSObject > ( <nl> JSObject : : cast ( js_global_function - > instance_prototype ( ) ) ) ; <nl> - SetProperty ( prototype , Factory : : constructor_symbol ( ) , <nl> - Top : : object_function ( ) , NONE ) ; <nl> + SetLocalPropertyNoThrow ( <nl> + prototype , Factory : : constructor_symbol ( ) , Top : : object_function ( ) , NONE ) ; <nl> } else { <nl> Handle < FunctionTemplateInfo > js_global_constructor ( <nl> FunctionTemplateInfo : : cast ( js_global_template - > constructor ( ) ) ) ; <nl> void Genesis : : InitializeGlobal ( Handle < GlobalObject > inner_global , <nl> global_context ( ) - > set_security_token ( * inner_global ) ; <nl> <nl> Handle < String > object_name = Handle < String > ( Heap : : Object_symbol ( ) ) ; <nl> - SetProperty ( inner_global , object_name , Top : : object_function ( ) , DONT_ENUM ) ; <nl> + SetLocalPropertyNoThrow ( inner_global , object_name , <nl> + Top : : object_function ( ) , DONT_ENUM ) ; <nl> <nl> Handle < JSObject > global = Handle < JSObject > ( global_context ( ) - > global ( ) ) ; <nl> <nl> void Genesis : : InitializeGlobal ( Handle < GlobalObject > inner_global , <nl> cons - > SetInstanceClassName ( * name ) ; <nl> Handle < JSObject > json_object = Factory : : NewJSObject ( cons , TENURED ) ; <nl> ASSERT ( json_object - > IsJSObject ( ) ) ; <nl> - SetProperty ( global , name , json_object , DONT_ENUM ) ; <nl> + SetLocalPropertyNoThrow ( global , name , json_object , DONT_ENUM ) ; <nl> global_context ( ) - > set_json_object ( * json_object ) ; <nl> } <nl> <nl> void Genesis : : InitializeGlobal ( Handle < GlobalObject > inner_global , <nl> global_context ( ) - > set_arguments_boilerplate ( * result ) ; <nl> / / Note : callee must be added as the first property and <nl> / / length must be added as the second property . <nl> - SetProperty ( result , Factory : : callee_symbol ( ) , <nl> - Factory : : undefined_value ( ) , <nl> - DONT_ENUM ) ; <nl> - SetProperty ( result , Factory : : length_symbol ( ) , <nl> - Factory : : undefined_value ( ) , <nl> - DONT_ENUM ) ; <nl> + SetLocalPropertyNoThrow ( result , Factory : : callee_symbol ( ) , <nl> + Factory : : undefined_value ( ) , <nl> + DONT_ENUM ) ; <nl> + SetLocalPropertyNoThrow ( result , Factory : : length_symbol ( ) , <nl> + Factory : : undefined_value ( ) , <nl> + DONT_ENUM ) ; <nl> <nl> # ifdef DEBUG <nl> LookupResult lookup ; <nl> bool Genesis : : InstallNatives ( ) { <nl> static const PropertyAttributes attributes = <nl> static_cast < PropertyAttributes > ( READ_ONLY | DONT_DELETE ) ; <nl> Handle < String > global_symbol = Factory : : LookupAsciiSymbol ( " global " ) ; <nl> - SetProperty ( builtins , <nl> - global_symbol , <nl> - Handle < Object > ( global_context ( ) - > global ( ) ) , <nl> - attributes ) ; <nl> + Handle < Object > global_obj ( global_context ( ) - > global ( ) ) ; <nl> + SetLocalPropertyNoThrow ( builtins , global_symbol , global_obj , attributes ) ; <nl> <nl> / / Setup the reference from the global object to the builtins object . <nl> JSGlobalObject : : cast ( global_context ( ) - > global ( ) ) - > set_builtins ( * builtins ) ; <nl> void Genesis : : InstallSpecialObjects ( Handle < Context > global_context ) { <nl> if ( FLAG_expose_natives_as ! = NULL & & strlen ( FLAG_expose_natives_as ) ! = 0 ) { <nl> Handle < String > natives_string = <nl> Factory : : LookupAsciiSymbol ( FLAG_expose_natives_as ) ; <nl> - SetProperty ( js_global , natives_string , <nl> - Handle < JSObject > ( js_global - > builtins ( ) ) , DONT_ENUM ) ; <nl> + SetLocalPropertyNoThrow ( js_global , natives_string , <nl> + Handle < JSObject > ( js_global - > builtins ( ) ) , DONT_ENUM ) ; <nl> } <nl> <nl> Handle < Object > Error = GetProperty ( js_global , " Error " ) ; <nl> if ( Error - > IsJSObject ( ) ) { <nl> Handle < String > name = Factory : : LookupAsciiSymbol ( " stackTraceLimit " ) ; <nl> - SetProperty ( Handle < JSObject > : : cast ( Error ) , <nl> - name , <nl> - Handle < Smi > ( Smi : : FromInt ( FLAG_stack_trace_limit ) ) , <nl> - NONE ) ; <nl> + SetLocalPropertyNoThrow ( Handle < JSObject > : : cast ( Error ) , <nl> + name , <nl> + Handle < Smi > ( Smi : : FromInt ( FLAG_stack_trace_limit ) ) , <nl> + NONE ) ; <nl> } <nl> <nl> # ifdef ENABLE_DEBUGGER_SUPPORT <nl> void Genesis : : InstallSpecialObjects ( Handle < Context > global_context ) { <nl> <nl> Handle < String > debug_string = <nl> Factory : : LookupAsciiSymbol ( FLAG_expose_debug_as ) ; <nl> - SetProperty ( js_global , debug_string , <nl> - Handle < Object > ( Debug : : debug_context ( ) - > global_proxy ( ) ) , DONT_ENUM ) ; <nl> + Handle < Object > global_proxy ( Debug : : debug_context ( ) - > global_proxy ( ) ) ; <nl> + SetLocalPropertyNoThrow ( js_global , debug_string , global_proxy , DONT_ENUM ) ; <nl> } <nl> # endif <nl> } <nl> void Genesis : : TransferNamedProperties ( Handle < JSObject > from , <nl> Handle < String > key = Handle < String > ( descs - > GetKey ( i ) ) ; <nl> int index = descs - > GetFieldIndex ( i ) ; <nl> Handle < Object > value = Handle < Object > ( from - > FastPropertyAt ( index ) ) ; <nl> - SetProperty ( to , key , value , details . attributes ( ) ) ; <nl> + SetLocalPropertyNoThrow ( to , key , value , details . attributes ( ) ) ; <nl> break ; <nl> } <nl> case CONSTANT_FUNCTION : { <nl> void Genesis : : TransferNamedProperties ( Handle < JSObject > from , <nl> Handle < String > key = Handle < String > ( descs - > GetKey ( i ) ) ; <nl> Handle < JSFunction > fun = <nl> Handle < JSFunction > ( descs - > GetConstantFunction ( i ) ) ; <nl> - SetProperty ( to , key , fun , details . attributes ( ) ) ; <nl> + SetLocalPropertyNoThrow ( to , key , fun , details . attributes ( ) ) ; <nl> break ; <nl> } <nl> case CALLBACKS : { <nl> void Genesis : : TransferNamedProperties ( Handle < JSObject > from , <nl> value = Handle < Object > ( JSGlobalPropertyCell : : cast ( * value ) - > value ( ) ) ; <nl> } <nl> PropertyDetails details = properties - > DetailsAt ( i ) ; <nl> - SetProperty ( to , key , value , details . attributes ( ) ) ; <nl> + SetLocalPropertyNoThrow ( to , key , value , details . attributes ( ) ) ; <nl> } <nl> } <nl> } <nl> mmm a / src / debug . cc <nl> ppp b / src / debug . cc <nl> bool Debug : : Load ( ) { <nl> / / Expose the builtins object in the debugger context . <nl> Handle < String > key = Factory : : LookupAsciiSymbol ( " builtins " ) ; <nl> Handle < GlobalObject > global = Handle < GlobalObject > ( context - > global ( ) ) ; <nl> - SetProperty ( global , key , Handle < Object > ( global - > builtins ( ) ) , NONE ) ; <nl> + RETURN_IF_EMPTY_HANDLE_VALUE ( <nl> + SetProperty ( global , key , Handle < Object > ( global - > builtins ( ) ) , NONE ) , <nl> + false ) ; <nl> <nl> / / Compile the JavaScript for the debugger in the debugger context . <nl> Debugger : : set_compiling_natives ( true ) ; <nl> mmm a / src / factory . cc <nl> ppp b / src / factory . cc <nl> Handle < JSFunction > Factory : : NewFunctionWithPrototype ( Handle < String > name , <nl> / / Set function . prototype and give the prototype a constructor <nl> / / property that refers to the function . <nl> SetPrototypeProperty ( function , prototype ) ; <nl> - SetProperty ( prototype , Factory : : constructor_symbol ( ) , function , DONT_ENUM ) ; <nl> + / / Currently safe because it is only invoked from Genesis . <nl> + SetLocalPropertyNoThrow ( <nl> + prototype , Factory : : constructor_symbol ( ) , function , DONT_ENUM ) ; <nl> return function ; <nl> } <nl> <nl> mmm a / src / handles . cc <nl> ppp b / src / handles . cc <nl> Handle < Object > SetLocalPropertyIgnoreAttributes ( <nl> } <nl> <nl> <nl> + void SetLocalPropertyNoThrow ( Handle < JSObject > object , <nl> + Handle < String > key , <nl> + Handle < Object > value , <nl> + PropertyAttributes attributes ) { <nl> + ASSERT ( ! Top : : has_pending_exception ( ) ) ; <nl> + CHECK ( ! SetLocalPropertyIgnoreAttributes ( <nl> + object , key , value , attributes ) . is_null ( ) ) ; <nl> + CHECK ( ! Top : : has_pending_exception ( ) ) ; <nl> + } <nl> + <nl> + <nl> Handle < Object > SetPropertyWithInterceptor ( Handle < JSObject > object , <nl> Handle < String > key , <nl> Handle < Object > value , <nl> mmm a / src / handles . h <nl> ppp b / src / handles . h <nl> Handle < Object > SetLocalPropertyIgnoreAttributes ( <nl> Handle < Object > value , <nl> PropertyAttributes attributes ) ; <nl> <nl> + / / Used to set local properties on the object we totally control <nl> + / / and which therefore has no accessors and alikes . <nl> + void SetLocalPropertyNoThrow ( Handle < JSObject > object , <nl> + Handle < String > key , <nl> + Handle < Object > value , <nl> + PropertyAttributes attributes = NONE ) ; <nl> + <nl> Handle < Object > SetPropertyWithInterceptor ( Handle < JSObject > object , <nl> Handle < String > key , <nl> Handle < Object > value , <nl> mmm a / src / runtime . cc <nl> ppp b / src / runtime . cc <nl> static MaybeObject * Runtime_DeclareGlobals ( Arguments args ) { <nl> const char * type = ( lookup . IsReadOnly ( ) ) ? " const " : " var " ; <nl> return ThrowRedeclarationError ( type , name ) ; <nl> } <nl> - Handle < Object > result = SetProperty ( global , name , value , attributes ) ; <nl> - if ( result . is_null ( ) ) { <nl> - ASSERT ( Top : : has_pending_exception ( ) ) ; <nl> - return Failure : : Exception ( ) ; <nl> - } <nl> + RETURN_IF_EMPTY_HANDLE ( SetProperty ( global , name , value , attributes ) ) ; <nl> } else { <nl> / / If a property with this name does not already exist on the <nl> / / global object add the property locally . We take special <nl> static MaybeObject * Runtime_DeclareGlobals ( Arguments args ) { <nl> / / of callbacks in the prototype chain ( this rules out using <nl> / / SetProperty ) . Also , we must use the handle - based version to <nl> / / avoid GC issues . <nl> - Handle < Object > result = <nl> - SetLocalPropertyIgnoreAttributes ( global , name , value , attributes ) ; <nl> - if ( result . is_null ( ) ) { <nl> - ASSERT ( Top : : has_pending_exception ( ) ) ; <nl> - return Failure : : Exception ( ) ; <nl> - } <nl> + RETURN_IF_EMPTY_HANDLE ( <nl> + SetLocalPropertyIgnoreAttributes ( global , name , value , attributes ) ) ; <nl> } <nl> } <nl> <nl> static MaybeObject * Runtime_DeclareContextSlot ( Arguments args ) { <nl> } else { <nl> / / Slow case : The property is not in the FixedArray part of the context . <nl> Handle < JSObject > context_ext = Handle < JSObject > : : cast ( holder ) ; <nl> - Handle < Object > result = <nl> - SetProperty ( context_ext , name , initial_value , mode ) ; <nl> - if ( result . is_null ( ) ) return Failure : : Exception ( ) ; <nl> + RETURN_IF_EMPTY_HANDLE ( <nl> + SetProperty ( context_ext , name , initial_value , mode ) ) ; <nl> } <nl> } <nl> <nl> static MaybeObject * Runtime_DeclareContextSlot ( Arguments args ) { <nl> ASSERT ( ! context_ext - > HasLocalProperty ( * name ) ) ; <nl> Handle < Object > value ( Heap : : undefined_value ( ) ) ; <nl> if ( * initial_value ! = NULL ) value = initial_value ; <nl> - Handle < Object > result = SetProperty ( context_ext , name , value , mode ) ; <nl> - if ( result . is_null ( ) ) return Failure : : Exception ( ) ; <nl> + RETURN_IF_EMPTY_HANDLE ( SetProperty ( context_ext , name , value , mode ) ) ; <nl> } <nl> <nl> return Heap : : undefined_value ( ) ; <nl> static MaybeObject * Runtime_InitializeConstGlobal ( Arguments args ) { <nl> / / with setting the value because the property is either absent or <nl> / / read - only . We also have to do redo the lookup . <nl> HandleScope handle_scope ; <nl> - Handle < GlobalObject > global ( Top : : context ( ) - > global ( ) ) ; <nl> + Handle < GlobalObject > global ( Top : : context ( ) - > global ( ) ) ; <nl> <nl> - / / BUG 1213579 : Handle the case where we have to set a read - only <nl> + / / BUG 1213575 : Handle the case where we have to set a read - only <nl> / / property through an interceptor and only do it if it ' s <nl> / / uninitialized , e . g . the hole . Nirk . . . <nl> - SetProperty ( global , name , value , attributes ) ; <nl> + RETURN_IF_EMPTY_HANDLE ( SetProperty ( global , name , value , attributes ) ) ; <nl> return * value ; <nl> } <nl> <nl> static MaybeObject * Runtime_InitializeConstContextSlot ( Arguments args ) { <nl> / / context . <nl> if ( attributes = = ABSENT ) { <nl> Handle < JSObject > global = Handle < JSObject > ( Top : : context ( ) - > global ( ) ) ; <nl> - SetProperty ( global , name , value , NONE ) ; <nl> + RETURN_IF_EMPTY_HANDLE ( SetProperty ( global , name , value , NONE ) ) ; <nl> return * value ; <nl> } <nl> <nl> static MaybeObject * Runtime_InitializeConstContextSlot ( Arguments args ) { <nl> / / The property was found in a different context extension object . <nl> / / Set it if it is not a read - only property . <nl> if ( ( attributes & READ_ONLY ) = = 0 ) { <nl> - Handle < Object > set = SetProperty ( context_ext , name , value , attributes ) ; <nl> - / / Setting a property might throw an exception . Exceptions <nl> - / / are converted to empty handles in handle operations . We <nl> - / / need to convert back to exceptions here . <nl> - if ( set . is_null ( ) ) { <nl> - ASSERT ( Top : : has_pending_exception ( ) ) ; <nl> - return Failure : : Exception ( ) ; <nl> - } <nl> + RETURN_IF_EMPTY_HANDLE ( <nl> + SetProperty ( context_ext , name , value , attributes ) ) ; <nl> } <nl> } <nl> <nl> static MaybeObject * Runtime_StoreContextSlot ( Arguments args ) { <nl> / / extension object itself . <nl> if ( ( attributes & READ_ONLY ) = = 0 | | <nl> ( context_ext - > GetLocalPropertyAttribute ( * name ) = = ABSENT ) ) { <nl> - Handle < Object > result = SetProperty ( context_ext , name , value , NONE ) ; <nl> - if ( result . is_null ( ) ) { <nl> - / / Failure : : Exception is converted to a null handle in the <nl> - / / handle - based methods such as SetProperty . We therefore need <nl> - / / to convert null handles back to exceptions . <nl> - ASSERT ( Top : : has_pending_exception ( ) ) ; <nl> - return Failure : : Exception ( ) ; <nl> - } <nl> + RETURN_IF_EMPTY_HANDLE ( SetProperty ( context_ext , name , value , NONE ) ) ; <nl> } <nl> return * value ; <nl> } <nl> static MaybeObject * Runtime_GetFrameDetails ( Arguments args ) { <nl> <nl> <nl> / / Copy all the context locals into an object used to materialize a scope . <nl> - static void CopyContextLocalsToScopeObject ( <nl> + static bool CopyContextLocalsToScopeObject ( <nl> Handle < SerializedScopeInfo > serialized_scope_info , <nl> ScopeInfo < > & scope_info , <nl> Handle < Context > context , <nl> static void CopyContextLocalsToScopeObject ( <nl> <nl> / / Don ' t include the arguments shadow ( . arguments ) context variable . <nl> if ( * scope_info . context_slot_name ( i ) ! = Heap : : arguments_shadow_symbol ( ) ) { <nl> - SetProperty ( scope_object , <nl> - scope_info . context_slot_name ( i ) , <nl> - Handle < Object > ( context - > get ( context_index ) ) , NONE ) ; <nl> + RETURN_IF_EMPTY_HANDLE_VALUE ( <nl> + SetProperty ( scope_object , <nl> + scope_info . context_slot_name ( i ) , <nl> + Handle < Object > ( context - > get ( context_index ) ) , NONE ) , <nl> + false ) ; <nl> } <nl> } <nl> + <nl> + return true ; <nl> } <nl> <nl> <nl> static Handle < JSObject > MaterializeLocalScope ( JavaScriptFrame * frame ) { <nl> <nl> / / First fill all parameters . <nl> for ( int i = 0 ; i < scope_info . number_of_parameters ( ) ; + + i ) { <nl> - SetProperty ( local_scope , <nl> - scope_info . parameter_name ( i ) , <nl> - Handle < Object > ( frame - > GetParameter ( i ) ) , NONE ) ; <nl> + RETURN_IF_EMPTY_HANDLE_VALUE ( <nl> + SetProperty ( local_scope , <nl> + scope_info . parameter_name ( i ) , <nl> + Handle < Object > ( frame - > GetParameter ( i ) ) , NONE ) , <nl> + Handle < JSObject > ( ) ) ; <nl> } <nl> <nl> / / Second fill all stack locals . <nl> for ( int i = 0 ; i < scope_info . number_of_stack_slots ( ) ; i + + ) { <nl> - SetProperty ( local_scope , <nl> - scope_info . stack_slot_name ( i ) , <nl> - Handle < Object > ( frame - > GetExpression ( i ) ) , NONE ) ; <nl> + RETURN_IF_EMPTY_HANDLE_VALUE ( <nl> + SetProperty ( local_scope , <nl> + scope_info . stack_slot_name ( i ) , <nl> + Handle < Object > ( frame - > GetExpression ( i ) ) , NONE ) , <nl> + Handle < JSObject > ( ) ) ; <nl> } <nl> <nl> / / Third fill all context locals . <nl> Handle < Context > frame_context ( Context : : cast ( frame - > context ( ) ) ) ; <nl> Handle < Context > function_context ( frame_context - > fcontext ( ) ) ; <nl> - CopyContextLocalsToScopeObject ( serialized_scope_info , scope_info , <nl> - function_context , local_scope ) ; <nl> + if ( ! CopyContextLocalsToScopeObject ( serialized_scope_info , scope_info , <nl> + function_context , local_scope ) ) { <nl> + return Handle < JSObject > ( ) ; <nl> + } <nl> <nl> / / Finally copy any properties from the function context extension . This will <nl> / / be variables introduced by eval . <nl> static Handle < JSObject > MaterializeLocalScope ( JavaScriptFrame * frame ) { <nl> / / Names of variables introduced by eval are strings . <nl> ASSERT ( keys - > get ( i ) - > IsString ( ) ) ; <nl> Handle < String > key ( String : : cast ( keys - > get ( i ) ) ) ; <nl> - SetProperty ( local_scope , key , GetProperty ( ext , key ) , NONE ) ; <nl> + RETURN_IF_EMPTY_HANDLE_VALUE ( <nl> + SetProperty ( local_scope , key , GetProperty ( ext , key ) , NONE ) , <nl> + Handle < JSObject > ( ) ) ; <nl> } <nl> } <nl> } <nl> static Handle < JSObject > MaterializeClosure ( Handle < Context > context ) { <nl> for ( int i = 0 ; i < scope_info . number_of_parameters ( ) ; + + i ) { <nl> / / We don ' t expect exception - throwing getters on the arguments shadow . <nl> Object * element = arguments_shadow - > GetElement ( i ) - > ToObjectUnchecked ( ) ; <nl> - SetProperty ( closure_scope , <nl> - scope_info . parameter_name ( i ) , <nl> - Handle < Object > ( element ) , <nl> - NONE ) ; <nl> + RETURN_IF_EMPTY_HANDLE_VALUE ( <nl> + SetProperty ( closure_scope , <nl> + scope_info . parameter_name ( i ) , <nl> + Handle < Object > ( element ) , <nl> + NONE ) , <nl> + Handle < JSObject > ( ) ) ; <nl> } <nl> } <nl> <nl> / / Fill all context locals to the context extension . <nl> - CopyContextLocalsToScopeObject ( serialized_scope_info , scope_info , <nl> - context , closure_scope ) ; <nl> + if ( ! CopyContextLocalsToScopeObject ( serialized_scope_info , scope_info , <nl> + context , closure_scope ) ) { <nl> + return Handle < JSObject > ( ) ; <nl> + } <nl> <nl> / / Finally copy any properties from the function context extension . This will <nl> / / be variables introduced by eval . <nl> static Handle < JSObject > MaterializeClosure ( Handle < Context > context ) { <nl> / / Names of variables introduced by eval are strings . <nl> ASSERT ( keys - > get ( i ) - > IsString ( ) ) ; <nl> Handle < String > key ( String : : cast ( keys - > get ( i ) ) ) ; <nl> - SetProperty ( closure_scope , key , GetProperty ( ext , key ) , NONE ) ; <nl> + RETURN_IF_EMPTY_HANDLE_VALUE ( <nl> + SetProperty ( closure_scope , key , GetProperty ( ext , key ) , NONE ) , <nl> + Handle < JSObject > ( ) ) ; <nl> } <nl> } <nl> <nl> static MaybeObject * Runtime_GetScopeDetails ( Arguments args ) { <nl> / / Fill in scope details . <nl> details - > set ( kScopeDetailsTypeIndex , Smi : : FromInt ( it . Type ( ) ) ) ; <nl> Handle < JSObject > scope_object = it . ScopeObject ( ) ; <nl> + RETURN_IF_EMPTY_HANDLE ( scope_object ) ; <nl> details - > set ( kScopeDetailsObjectIndex , * scope_object ) ; <nl> <nl> return * Factory : : NewJSArrayWithElements ( details ) ; <nl> static MaybeObject * Runtime_DebugEvaluate ( Arguments args ) { <nl> <nl> / / Materialize the content of the local scope into a JSObject . <nl> Handle < JSObject > local_scope = MaterializeLocalScope ( frame ) ; <nl> + RETURN_IF_EMPTY_HANDLE ( local_scope ) ; <nl> <nl> / / Allocate a new context for the debug evaluation and set the extension <nl> / / object build . <nl> mmm a / src / top . cc <nl> ppp b / src / top . cc <nl> Handle < String > Top : : StackTraceString ( ) { <nl> } <nl> <nl> <nl> - static void SetLocalProperty ( Handle < JSObject > object , <nl> - Handle < String > key , <nl> - Handle < Object > value ) { <nl> - / / We set properties on freshly allocated JS object , nothing <nl> - / / should fail except for OOM which is handled by <nl> - / / SetLocalPropertyIgnoreAttributes . <nl> - ASSERT ( ! Top : : has_pending_exception ( ) ) ; <nl> - CHECK ( ! SetLocalPropertyIgnoreAttributes ( object , key , value , NONE ) . is_null ( ) ) ; <nl> - CHECK ( ! Top : : has_pending_exception ( ) ) ; <nl> - } <nl> - <nl> - <nl> Handle < JSArray > Top : : CaptureCurrentStackTrace ( <nl> int frame_limit , StackTrace : : StackTraceOptions options ) { <nl> / / Ensure no negative values . <nl> Handle < JSArray > Top : : CaptureCurrentStackTrace ( <nl> / / tag . <nl> column_offset + = script - > column_offset ( ) - > value ( ) ; <nl> } <nl> - SetLocalProperty ( stackFrame , column_key , <nl> - Handle < Smi > ( Smi : : FromInt ( column_offset + 1 ) ) ) ; <nl> + SetLocalPropertyNoThrow ( stackFrame , column_key , <nl> + Handle < Smi > ( Smi : : FromInt ( column_offset + 1 ) ) ) ; <nl> } <nl> - SetLocalProperty ( stackFrame , line_key , <nl> - Handle < Smi > ( Smi : : FromInt ( line_number + 1 ) ) ) ; <nl> + SetLocalPropertyNoThrow ( stackFrame , line_key , <nl> + Handle < Smi > ( Smi : : FromInt ( line_number + 1 ) ) ) ; <nl> } <nl> <nl> if ( options & StackTrace : : kScriptName ) { <nl> Handle < Object > script_name ( script - > name ( ) ) ; <nl> - SetLocalProperty ( stackFrame , script_key , script_name ) ; <nl> + SetLocalPropertyNoThrow ( stackFrame , script_key , script_name ) ; <nl> } <nl> <nl> if ( options & StackTrace : : kScriptNameOrSourceURL ) { <nl> Handle < JSArray > Top : : CaptureCurrentStackTrace ( <nl> if ( caught_exception ) { <nl> result = Factory : : undefined_value ( ) ; <nl> } <nl> - SetLocalProperty ( stackFrame , script_name_or_source_url_key , result ) ; <nl> + SetLocalPropertyNoThrow ( stackFrame , script_name_or_source_url_key , <nl> + result ) ; <nl> } <nl> <nl> if ( options & StackTrace : : kFunctionName ) { <nl> Handle < JSArray > Top : : CaptureCurrentStackTrace ( <nl> if ( fun_name - > ToBoolean ( ) - > IsFalse ( ) ) { <nl> fun_name = Handle < Object > ( fun - > shared ( ) - > inferred_name ( ) ) ; <nl> } <nl> - SetLocalProperty ( stackFrame , function_key , fun_name ) ; <nl> + SetLocalPropertyNoThrow ( stackFrame , function_key , fun_name ) ; <nl> } <nl> <nl> if ( options & StackTrace : : kIsEval ) { <nl> int type = Smi : : cast ( script - > compilation_type ( ) ) - > value ( ) ; <nl> Handle < Object > is_eval = ( type = = Script : : COMPILATION_TYPE_EVAL ) ? <nl> Factory : : true_value ( ) : Factory : : false_value ( ) ; <nl> - SetLocalProperty ( stackFrame , eval_key , is_eval ) ; <nl> + SetLocalPropertyNoThrow ( stackFrame , eval_key , is_eval ) ; <nl> } <nl> <nl> if ( options & StackTrace : : kIsConstructor ) { <nl> Handle < Object > is_constructor = ( frames [ i ] . is_constructor ( ) ) ? <nl> Factory : : true_value ( ) : Factory : : false_value ( ) ; <nl> - SetLocalProperty ( stackFrame , constructor_key , is_constructor ) ; <nl> + SetLocalPropertyNoThrow ( stackFrame , constructor_key , is_constructor ) ; <nl> } <nl> <nl> FixedArray : : cast ( stack_trace - > elements ( ) ) - > set ( frames_seen , * stackFrame ) ; <nl> mmm a / src / top . h <nl> ppp b / src / top . h <nl> class Simulator ; <nl> # define RETURN_IF_SCHEDULED_EXCEPTION ( ) \ <nl> if ( Top : : has_scheduled_exception ( ) ) return Top : : PromoteScheduledException ( ) <nl> <nl> + # define RETURN_IF_EMPTY_HANDLE_VALUE ( call , value ) \ <nl> + if ( call . is_null ( ) ) { \ <nl> + ASSERT ( Top : : has_pending_exception ( ) ) ; \ <nl> + return value ; \ <nl> + } <nl> + <nl> + # define RETURN_IF_EMPTY_HANDLE ( call ) \ <nl> + RETURN_IF_EMPTY_HANDLE_VALUE ( call , Failure : : Exception ( ) ) <nl> + <nl> / / Top has static variables used for JavaScript execution . <nl> <nl> class SaveContext ; / / Forward declaration . <nl> | Fix various places which do not check if SetProperty threw an exception . | v8/v8 | 2a25c444d564176093ce0e8fd2abb2fae972f61e | 2011-02-10T14:41:16Z |
mmm a / TMessagesProj / build . gradle <nl> ppp b / TMessagesProj / build . gradle <nl> android { <nl> } <nl> } <nl> <nl> - defaultConfig . versionCode = 2096 <nl> + defaultConfig . versionCode = 2098 <nl> <nl> applicationVariants . all { variant - > <nl> variant . outputs . all { output - > <nl> android { <nl> defaultConfig { <nl> minSdkVersion 16 <nl> targetSdkVersion 28 <nl> - versionName " 7 . 1 . 1 " <nl> + versionName " 7 . 1 . 2 " <nl> <nl> vectorDrawables . generatedDensities = [ ' mdpi ' , ' hdpi ' , ' xhdpi ' , ' xxhdpi ' ] <nl> <nl> mmm a / TMessagesProj / jni / tgnet / Defines . h <nl> ppp b / TMessagesProj / jni / tgnet / Defines . h <nl> <nl> <nl> # define USE_DEBUG_SESSION false <nl> # define READ_BUFFER_SIZE 1024 * 128 <nl> - # define DEBUG_VERSION <nl> + / / # define DEBUG_VERSION <nl> # define USE_OLD_KEYS <nl> # define PFS_ENABLED 1 <nl> # define DEFAULT_DATACENTER_ID INT_MAX <nl> mmm a / TMessagesProj / src / main / java / org / telegram / messenger / AndroidUtilities . java <nl> ppp b / TMessagesProj / src / main / java / org / telegram / messenger / AndroidUtilities . java <nl> public static CharSequence highlightText ( CharSequence str , String query ) { <nl> SpannableStringBuilder spannableStringBuilder = SpannableStringBuilder . valueOf ( str ) ; <nl> int i = s . indexOf ( query ) ; <nl> while ( i > = 0 ) { <nl> - spannableStringBuilder . setSpan ( new ForegroundColorSpanThemable ( Theme . key_windowBackgroundWhiteBlueText4 ) , i , i + query . length ( ) , 0 ) ; <nl> + try { <nl> + spannableStringBuilder . setSpan ( new ForegroundColorSpanThemable ( Theme . key_windowBackgroundWhiteBlueText4 ) , i , i + query . length ( ) , 0 ) ; <nl> + } catch ( Exception e ) { <nl> + FileLog . e ( e ) ; <nl> + } <nl> i = s . indexOf ( query , i + 1 ) ; <nl> } <nl> return spannableStringBuilder ; <nl> mmm a / TMessagesProj / src / main / java / org / telegram / messenger / BuildVars . java <nl> ppp b / TMessagesProj / src / main / java / org / telegram / messenger / BuildVars . java <nl> <nl> public static boolean LOGS_ENABLED = false ; <nl> public static boolean USE_CLOUD_STRINGS = true ; <nl> public static boolean CHECK_UPDATES = true ; <nl> - public static int BUILD_VERSION = 2096 ; <nl> + public static int BUILD_VERSION = 2098 ; <nl> public static String BUILD_VERSION_STRING = " 7 . 1 . 0 " ; <nl> public static int APP_ID = 4 ; <nl> public static String APP_HASH = " 014b35b6184100b085b0d0572f9b5103 " ; <nl> mmm a / TMessagesProj / src / main / java / org / telegram / messenger / MediaController . java <nl> ppp b / TMessagesProj / src / main / java / org / telegram / messenger / MediaController . java <nl> public void generateWaveform ( MessageObject messageObject ) { <nl> if ( messageObject1 = = null ) { <nl> return ; <nl> } <nl> - if ( waveform ! = null ) { <nl> + if ( waveform ! = null & & messageObject1 . getDocument ( ) ! = null ) { <nl> for ( int a = 0 ; a < messageObject1 . getDocument ( ) . attributes . size ( ) ; a + + ) { <nl> TLRPC . DocumentAttribute attribute = messageObject1 . getDocument ( ) . attributes . get ( a ) ; <nl> if ( attribute instanceof TLRPC . TL_documentAttributeAudio ) { <nl> mmm a / TMessagesProj / src / main / java / org / telegram / messenger / MediaDataController . java <nl> ppp b / TMessagesProj / src / main / java / org / telegram / messenger / MediaDataController . java <nl> private void searchMessagesInChat ( String query , final long dialogId , final long <nl> final int currentReqId = + + lastReqId ; <nl> lastSearchQuery = query ; <nl> final long queryWithDialogFinal = queryWithDialog ; <nl> - reqId = getConnectionsManager ( ) . sendRequest ( req , ( response , error ) - > AndroidUtilities . runOnUIThread ( ( ) - > { <nl> - if ( currentReqId = = lastReqId ) { <nl> - reqId = 0 ; <nl> - if ( ! jumpToMessage ) { <nl> - loadingMoreSearchMessages = false ; <nl> + String finalQuery = query ; <nl> + reqId = getConnectionsManager ( ) . sendRequest ( req , ( response , error ) - > { <nl> + ArrayList < MessageObject > messageObjects = new ArrayList < > ( ) ; <nl> + <nl> + if ( error = = null ) { <nl> + TLRPC . messages_Messages res = ( TLRPC . messages_Messages ) response ; <nl> + int N = Math . min ( res . messages . size ( ) , 20 ) ; <nl> + for ( int a = 0 ; a < N ; a + + ) { <nl> + TLRPC . Message message = res . messages . get ( a ) ; <nl> + MessageObject messageObject = new MessageObject ( currentAccount , message , false , false ) ; <nl> + messageObject . setQuery ( finalQuery ) ; <nl> + messageObjects . add ( messageObject ) ; <nl> } <nl> - if ( response ! = null ) { <nl> - TLRPC . messages_Messages res = ( TLRPC . messages_Messages ) response ; <nl> - for ( int a = 0 ; a < res . messages . size ( ) ; a + + ) { <nl> - TLRPC . Message message = res . messages . get ( a ) ; <nl> - if ( message instanceof TLRPC . TL_messageEmpty | | message . action instanceof TLRPC . TL_messageActionHistoryClear ) { <nl> - res . messages . remove ( a ) ; <nl> - a - - ; <nl> - } <nl> + } <nl> + AndroidUtilities . runOnUIThread ( ( ) - > { <nl> + if ( currentReqId = = lastReqId ) { <nl> + reqId = 0 ; <nl> + if ( ! jumpToMessage ) { <nl> + loadingMoreSearchMessages = false ; <nl> } <nl> - getMessagesStorage ( ) . putUsersAndChats ( res . users , res . chats , true , true ) ; <nl> - getMessagesController ( ) . putUsers ( res . users , false ) ; <nl> - getMessagesController ( ) . putChats ( res . chats , false ) ; <nl> - if ( req . offset_id = = 0 & & queryWithDialogFinal = = dialogId ) { <nl> - lastReturnedNum = 0 ; <nl> - searchResultMessages . clear ( ) ; <nl> - searchResultMessagesMap [ 0 ] . clear ( ) ; <nl> - searchResultMessagesMap [ 1 ] . clear ( ) ; <nl> - messagesSearchCount [ 0 ] = 0 ; <nl> - getNotificationCenter ( ) . postNotificationName ( NotificationCenter . chatSearchResultsLoading , guid ) ; <nl> - } <nl> - boolean added = false ; <nl> - int N = Math . min ( res . messages . size ( ) , 20 ) ; <nl> - for ( int a = 0 ; a < N ; a + + ) { <nl> - TLRPC . Message message = res . messages . get ( a ) ; <nl> - added = true ; <nl> - MessageObject messageObject = new MessageObject ( currentAccount , message , false , false ) ; <nl> - searchResultMessages . add ( messageObject ) ; <nl> - searchResultMessagesMap [ queryWithDialogFinal = = dialogId ? 0 : 1 ] . put ( messageObject . getId ( ) , messageObject ) ; <nl> - } <nl> - messagesSearchEndReached [ queryWithDialogFinal = = dialogId ? 0 : 1 ] = res . messages . size ( ) < 21 ; <nl> - messagesSearchCount [ queryWithDialogFinal = = dialogId ? 0 : 1 ] = res instanceof TLRPC . TL_messages_messagesSlice | | res instanceof TLRPC . TL_messages_channelMessages ? res . count : res . messages . size ( ) ; <nl> - if ( searchResultMessages . isEmpty ( ) ) { <nl> - getNotificationCenter ( ) . postNotificationName ( NotificationCenter . chatSearchResultsAvailable , guid , 0 , getMask ( ) , ( long ) 0 , 0 , 0 , jumpToMessage ) ; <nl> - } else { <nl> - if ( added ) { <nl> - if ( lastReturnedNum > = searchResultMessages . size ( ) ) { <nl> - lastReturnedNum = searchResultMessages . size ( ) - 1 ; <nl> + if ( response ! = null ) { <nl> + TLRPC . messages_Messages res = ( TLRPC . messages_Messages ) response ; <nl> + for ( int a = 0 ; a < res . messages . size ( ) ; a + + ) { <nl> + TLRPC . Message message = res . messages . get ( a ) ; <nl> + if ( message instanceof TLRPC . TL_messageEmpty | | message . action instanceof TLRPC . TL_messageActionHistoryClear ) { <nl> + res . messages . remove ( a ) ; <nl> + a - - ; <nl> } <nl> - MessageObject messageObject = searchResultMessages . get ( lastReturnedNum ) ; <nl> - getNotificationCenter ( ) . postNotificationName ( NotificationCenter . chatSearchResultsAvailable , guid , messageObject . getId ( ) , getMask ( ) , messageObject . getDialogId ( ) , lastReturnedNum , messagesSearchCount [ 0 ] + messagesSearchCount [ 1 ] , jumpToMessage ) ; <nl> } <nl> - } <nl> - if ( queryWithDialogFinal = = dialogId & & messagesSearchEndReached [ 0 ] & & mergeDialogId ! = 0 & & ! messagesSearchEndReached [ 1 ] ) { <nl> - searchMessagesInChat ( lastSearchQuery , dialogId , mergeDialogId , guid , 0 , replyMessageId , true , user , jumpToMessage ) ; <nl> + getMessagesStorage ( ) . putUsersAndChats ( res . users , res . chats , true , true ) ; <nl> + getMessagesController ( ) . putUsers ( res . users , false ) ; <nl> + getMessagesController ( ) . putChats ( res . chats , false ) ; <nl> + if ( req . offset_id = = 0 & & queryWithDialogFinal = = dialogId ) { <nl> + lastReturnedNum = 0 ; <nl> + searchResultMessages . clear ( ) ; <nl> + searchResultMessagesMap [ 0 ] . clear ( ) ; <nl> + searchResultMessagesMap [ 1 ] . clear ( ) ; <nl> + messagesSearchCount [ 0 ] = 0 ; <nl> + getNotificationCenter ( ) . postNotificationName ( NotificationCenter . chatSearchResultsLoading , guid ) ; <nl> + } <nl> + boolean added = false ; <nl> + int N = Math . min ( res . messages . size ( ) , 20 ) ; <nl> + for ( int a = 0 ; a < N ; a + + ) { <nl> + TLRPC . Message message = res . messages . get ( a ) ; <nl> + added = true ; <nl> + MessageObject messageObject = messageObjects . get ( a ) ; <nl> + searchResultMessages . add ( messageObject ) ; <nl> + searchResultMessagesMap [ queryWithDialogFinal = = dialogId ? 0 : 1 ] . put ( messageObject . getId ( ) , messageObject ) ; <nl> + } <nl> + messagesSearchEndReached [ queryWithDialogFinal = = dialogId ? 0 : 1 ] = res . messages . size ( ) < 21 ; <nl> + messagesSearchCount [ queryWithDialogFinal = = dialogId ? 0 : 1 ] = res instanceof TLRPC . TL_messages_messagesSlice | | res instanceof TLRPC . TL_messages_channelMessages ? res . count : res . messages . size ( ) ; <nl> + if ( searchResultMessages . isEmpty ( ) ) { <nl> + getNotificationCenter ( ) . postNotificationName ( NotificationCenter . chatSearchResultsAvailable , guid , 0 , getMask ( ) , ( long ) 0 , 0 , 0 , jumpToMessage ) ; <nl> + } else { <nl> + if ( added ) { <nl> + if ( lastReturnedNum > = searchResultMessages . size ( ) ) { <nl> + lastReturnedNum = searchResultMessages . size ( ) - 1 ; <nl> + } <nl> + MessageObject messageObject = searchResultMessages . get ( lastReturnedNum ) ; <nl> + getNotificationCenter ( ) . postNotificationName ( NotificationCenter . chatSearchResultsAvailable , guid , messageObject . getId ( ) , getMask ( ) , messageObject . getDialogId ( ) , lastReturnedNum , messagesSearchCount [ 0 ] + messagesSearchCount [ 1 ] , jumpToMessage ) ; <nl> + } <nl> + } <nl> + if ( queryWithDialogFinal = = dialogId & & messagesSearchEndReached [ 0 ] & & mergeDialogId ! = 0 & & ! messagesSearchEndReached [ 1 ] ) { <nl> + searchMessagesInChat ( lastSearchQuery , dialogId , mergeDialogId , guid , 0 , replyMessageId , true , user , jumpToMessage ) ; <nl> + } <nl> } <nl> } <nl> - } <nl> - } ) , ConnectionsManager . RequestFlagFailOnServerErrors ) ; <nl> + } ) ; <nl> + } , ConnectionsManager . RequestFlagFailOnServerErrors ) ; <nl> } <nl> <nl> public String getLastSearchQuery ( ) { <nl> mmm a / TMessagesProj / src / main / java / org / telegram / messenger / MessagesController . java <nl> ppp b / TMessagesProj / src / main / java / org / telegram / messenger / MessagesController . java <nl> public void processLoadedMessages ( TLRPC . messages_Messages messagesRes , long dial <nl> boolean isMegagroup = false ; <nl> if ( messagesRes instanceof TLRPC . TL_messages_channelMessages ) { <nl> int channelId = - ( int ) dialogId ; <nl> - if ( ! scheduled ) { <nl> + if ( ! scheduled & & threadMessageId = = 0 ) { <nl> int channelPts = channelsPts . get ( channelId ) ; <nl> if ( channelPts = = 0 ) { <nl> channelPts = getMessagesStorage ( ) . getChannelPtsSync ( channelId ) ; <nl> mmm a / TMessagesProj / src / main / java / org / telegram / messenger / MessagesStorage . java <nl> ppp b / TMessagesProj / src / main / java / org / telegram / messenger / MessagesStorage . java <nl> public void putChannelViews ( final SparseArray < SparseIntArray > channelViews , fina <nl> } <nl> replies = currentReplies ; <nl> } <nl> + if ( currentReplies ! = null & & currentReplies . read_max_id > replies . read_max_id ) { <nl> + replies . read_max_id = currentReplies . read_max_id ; <nl> + } <nl> state . requery ( ) ; <nl> NativeByteBuffer data = new NativeByteBuffer ( replies . getObjectSize ( ) ) ; <nl> replies . serializeToStream ( data ) ; <nl> mmm a / TMessagesProj / src / main / java / org / telegram / messenger / NotificationsController . java <nl> ppp b / TMessagesProj / src / main / java / org / telegram / messenger / NotificationsController . java <nl> private int addToPopupMessages ( final ArrayList < MessageObject > popupArrayAdd , Mes <nl> } <nl> <nl> public void processEditedMessages ( final LongSparseArray < ArrayList < MessageObject > > editedMessages ) { <nl> - / * if ( editedMessages . size ( ) = = 0 ) { <nl> + if ( editedMessages . size ( ) = = 0 ) { <nl> return ; <nl> } <nl> final ArrayList < MessageObject > popupArrayAdd = new ArrayList < > ( 0 ) ; <nl> notificationsQueue . postRunnable ( ( ) - > { <nl> - boolean added = false ; <nl> - boolean edited = false ; <nl> - <nl> - LongSparseArray < Boolean > settingsCache = new LongSparseArray < > ( ) ; <nl> - SharedPreferences preferences = getAccountInstance ( ) . getNotificationsSettings ( ) ; <nl> - boolean allowPinned = preferences . getBoolean ( " PinnedMessages " , true ) ; <nl> - int popup = 0 ; <nl> - boolean hasScheduled = false ; <nl> - <nl> - for ( int a = 0 ; a < messageObjects . size ( ) ; a + + ) { <nl> - MessageObject messageObject = messageObjects . get ( a ) ; <nl> - if ( messageObject . messageOwner ! = null & & messageObject . messageOwner . silent & & ( messageObject . messageOwner . action instanceof TLRPC . TL_messageActionContactSignUp | | messageObject . messageOwner . action instanceof TLRPC . TL_messageActionUserJoined ) ) { <nl> - continue ; <nl> - } <nl> - long mid = messageObject . getId ( ) ; <nl> - long random_id = messageObject . isFcmMessage ( ) ? messageObject . messageOwner . random_id : 0 ; <nl> - long dialog_id = messageObject . getDialogId ( ) ; <nl> - int lower_id = ( int ) dialog_id ; <nl> - boolean isChannel ; <nl> - if ( messageObject . isFcmMessage ( ) ) { <nl> - isChannel = messageObject . localChannel ; <nl> - } else if ( lower_id < 0 ) { <nl> - TLRPC . Chat chat = getMessagesController ( ) . getChat ( - lower_id ) ; <nl> - isChannel = ChatObject . isChannel ( chat ) & & ! chat . megagroup ; <nl> - } else { <nl> - isChannel = false ; <nl> - } <nl> - if ( messageObject . messageOwner . to_id . channel_id ! = 0 ) { <nl> - mid | = ( ( long ) messageObject . messageOwner . to_id . channel_id ) < < 32 ; <nl> - } <nl> - <nl> - MessageObject oldMessageObject = pushMessagesDict . get ( mid ) ; <nl> - if ( oldMessageObject = = null & & messageObject . messageOwner . random_id ! = 0 ) { <nl> - oldMessageObject = fcmRandomMessagesDict . get ( messageObject . messageOwner . random_id ) ; <nl> - if ( oldMessageObject ! = null ) { <nl> - fcmRandomMessagesDict . remove ( messageObject . messageOwner . random_id ) ; <nl> - } <nl> - } <nl> - if ( oldMessageObject ! = null ) { <nl> - if ( oldMessageObject . isFcmMessage ( ) ) { <nl> - pushMessagesDict . put ( mid , messageObject ) ; <nl> - int idxOld = pushMessages . indexOf ( oldMessageObject ) ; <nl> - if ( idxOld > = 0 ) { <nl> - pushMessages . set ( idxOld , messageObject ) ; <nl> - popup = addToPopupMessages ( popupArrayAdd , messageObject , lower_id , dialog_id , isChannel , preferences ) ; <nl> - } <nl> - if ( isFcm & & ( edited = messageObject . localEdit ) ) { <nl> - getMessagesStorage ( ) . putPushMessage ( messageObject ) ; <nl> - } <nl> - } <nl> + boolean updated = false ; <nl> + for ( int a = 0 , N = editedMessages . size ( ) ; a < N ; a + + ) { <nl> + long did = editedMessages . keyAt ( a ) ; <nl> + if ( pushDialogs . indexOfKey ( did ) < 0 ) { <nl> continue ; <nl> } <nl> - if ( edited ) { <nl> - continue ; <nl> - } <nl> - if ( isFcm ) { <nl> - getMessagesStorage ( ) . putPushMessage ( messageObject ) ; <nl> - } <nl> - <nl> - long original_dialog_id = dialog_id ; <nl> - if ( dialog_id = = opened_dialog_id & & ApplicationLoader . isScreenOn ) { <nl> - if ( ! isFcm ) { <nl> - playInChatSound ( ) ; <nl> - } <nl> - continue ; <nl> - } <nl> - if ( messageObject . messageOwner . mentioned ) { <nl> - if ( ! allowPinned & & messageObject . messageOwner . action instanceof TLRPC . TL_messageActionPinMessage ) { <nl> - continue ; <nl> - } <nl> - dialog_id = messageObject . messageOwner . from_id ; <nl> - } <nl> - if ( isPersonalMessage ( messageObject ) ) { <nl> - personal_count + + ; <nl> - } <nl> - added = true ; <nl> - <nl> - boolean isChat = lower_id < 0 ; <nl> - int index = settingsCache . indexOfKey ( dialog_id ) ; <nl> - boolean value ; <nl> - if ( index > = 0 ) { <nl> - value = settingsCache . valueAt ( index ) ; <nl> - } else { <nl> - int notifyOverride = getNotifyOverride ( preferences , dialog_id ) ; <nl> - if ( notifyOverride = = - 1 ) { <nl> - value = isGlobalNotificationsEnabled ( dialog_id , isChannel ) ; <nl> - } else { <nl> - value = notifyOverride ! = 2 ; <nl> - } <nl> - <nl> - settingsCache . put ( dialog_id , value ) ; <nl> - } <nl> - <nl> - if ( value ) { <nl> - if ( ! isFcm ) { <nl> - popup = addToPopupMessages ( popupArrayAdd , messageObject , lower_id , dialog_id , isChannel , preferences ) ; <nl> - } <nl> - if ( ! hasScheduled ) { <nl> - hasScheduled = messageObject . messageOwner . from_scheduled ; <nl> + ArrayList < MessageObject > messages = editedMessages . valueAt ( a ) ; <nl> + for ( int b = 0 , N2 = messages . size ( ) ; b < N2 ; b + + ) { <nl> + MessageObject messageObject = messages . get ( b ) ; <nl> + long mid = messageObject . getId ( ) ; <nl> + if ( messageObject . messageOwner . peer_id . channel_id ! = 0 ) { <nl> + mid | = ( ( long ) messageObject . messageOwner . peer_id . channel_id ) < < 32 ; <nl> } <nl> - delayedPushMessages . add ( messageObject ) ; <nl> - pushMessages . add ( 0 , messageObject ) ; <nl> - if ( mid ! = 0 ) { <nl> + MessageObject oldMessage = pushMessagesDict . get ( mid ) ; <nl> + if ( oldMessage ! = null ) { <nl> + updated = true ; <nl> pushMessagesDict . put ( mid , messageObject ) ; <nl> - } else if ( random_id ! = 0 ) { <nl> - fcmRandomMessagesDict . put ( random_id , messageObject ) ; <nl> - } <nl> - if ( original_dialog_id ! = dialog_id ) { <nl> - Integer current = pushDialogsOverrideMention . get ( original_dialog_id ) ; <nl> - pushDialogsOverrideMention . put ( original_dialog_id , current = = null ? 1 : current + 1 ) ; <nl> - } <nl> - } <nl> - } <nl> - <nl> - if ( added ) { <nl> - notifyCheck = isLast ; <nl> - } <nl> - <nl> - if ( ! popupArrayAdd . isEmpty ( ) & & ! AndroidUtilities . needShowPasscode ( ) & & ! SharedConfig . isWaitingForPasscodeEnter ) { <nl> - final int popupFinal = popup ; <nl> - AndroidUtilities . runOnUIThread ( ( ) - > { <nl> - popupMessages . addAll ( 0 , popupArrayAdd ) ; <nl> - if ( ApplicationLoader . mainInterfacePaused | | ! ApplicationLoader . isScreenOn ) { <nl> - if ( popupFinal = = 3 | | popupFinal = = 1 & & ApplicationLoader . isScreenOn | | popupFinal = = 2 & & ! ApplicationLoader . isScreenOn ) { <nl> - Intent popupIntent = new Intent ( ApplicationLoader . applicationContext , PopupNotificationActivity . class ) ; <nl> - popupIntent . setFlags ( Intent . FLAG_ACTIVITY_NEW_TASK | Intent . FLAG_ACTIVITY_NO_ANIMATION | Intent . FLAG_ACTIVITY_NO_USER_ACTION | Intent . FLAG_FROM_BACKGROUND ) ; <nl> - try { <nl> - ApplicationLoader . applicationContext . startActivity ( popupIntent ) ; <nl> - } catch ( Throwable ignore ) { <nl> - <nl> - } <nl> + int idx = pushMessages . indexOf ( oldMessage ) ; <nl> + if ( idx > = 0 ) { <nl> + pushMessages . set ( idx , messageObject ) ; <nl> } <nl> - } <nl> - } ) ; <nl> - } <nl> - if ( isFcm | | hasScheduled ) { <nl> - if ( edited ) { <nl> - delayedPushMessages . clear ( ) ; <nl> - showOrUpdateNotification ( notifyCheck ) ; <nl> - } else if ( added ) { <nl> - MessageObject messageObject = messageObjects . get ( 0 ) ; <nl> - long dialog_id = messageObject . getDialogId ( ) ; <nl> - Boolean isChannel ; <nl> - if ( messageObject . isFcmMessage ( ) ) { <nl> - isChannel = messageObject . localChannel ; <nl> - } else { <nl> - isChannel = null ; <nl> - } <nl> - int old_unread_count = total_unread_count ; <nl> - <nl> - int notifyOverride = getNotifyOverride ( preferences , dialog_id ) ; <nl> - boolean canAddValue ; <nl> - if ( notifyOverride = = - 1 ) { <nl> - canAddValue = isGlobalNotificationsEnabled ( dialog_id , isChannel ) ; <nl> - } else { <nl> - canAddValue = notifyOverride ! = 2 ; <nl> - } <nl> - <nl> - Integer currentCount = pushDialogs . get ( dialog_id ) ; <nl> - int newCount = currentCount ! = null ? currentCount + 1 : 1 ; <nl> - <nl> - if ( notifyCheck & & ! canAddValue ) { <nl> - Integer override = pushDialogsOverrideMention . get ( dialog_id ) ; <nl> - if ( override ! = null & & override ! = 0 ) { <nl> - canAddValue = true ; <nl> - newCount = override ; <nl> + idx = delayedPushMessages . indexOf ( oldMessage ) ; <nl> + if ( idx > = 0 ) { <nl> + delayedPushMessages . set ( idx , messageObject ) ; <nl> } <nl> } <nl> - <nl> - if ( canAddValue ) { <nl> - if ( currentCount ! = null ) { <nl> - total_unread_count - = currentCount ; <nl> - } <nl> - total_unread_count + = newCount ; <nl> - pushDialogs . put ( dialog_id , newCount ) ; <nl> - } <nl> - if ( old_unread_count ! = total_unread_count ) { <nl> - delayedPushMessages . clear ( ) ; <nl> - showOrUpdateNotification ( notifyCheck ) ; <nl> - final int pushDialogsCount = pushDialogs . size ( ) ; <nl> - AndroidUtilities . runOnUIThread ( ( ) - > { <nl> - NotificationCenter . getGlobalInstance ( ) . postNotificationName ( NotificationCenter . notificationsCountUpdated , currentAccount ) ; <nl> - getNotificationCenter ( ) . postNotificationName ( NotificationCenter . dialogsUnreadCounterChanged , pushDialogsCount ) ; <nl> - } ) ; <nl> - } <nl> - notifyCheck = false ; <nl> - if ( showBadgeNumber ) { <nl> - setBadge ( getTotalAllUnreadCount ( ) ) ; <nl> - } <nl> } <nl> } <nl> - if ( countDownLatch ! = null ) { <nl> - countDownLatch . countDown ( ) ; <nl> + if ( updated ) { <nl> + showOrUpdateNotification ( false ) ; <nl> } <nl> - } ) ; * / <nl> + } ) ; <nl> } <nl> <nl> public void processNewMessages ( final ArrayList < MessageObject > messageObjects , final boolean isLast , final boolean isFcm , CountDownLatch countDownLatch ) { <nl> public void processDialogsUpdateRead ( final LongSparseArray < Integer > dialogsToUpd <nl> int old_unread_count = total_unread_count ; <nl> SharedPreferences preferences = getAccountInstance ( ) . getNotificationsSettings ( ) ; <nl> for ( int b = 0 ; b < dialogsToUpdate . size ( ) ; b + + ) { <nl> - long dialog_id = dialogsToUpdate . keyAt ( b ) ; <nl> + long dialogId = dialogsToUpdate . keyAt ( b ) ; <nl> + Integer currentCount = pushDialogs . get ( dialogId ) ; <nl> + Integer newCount = dialogsToUpdate . get ( dialogId ) ; <nl> + <nl> + int lowerId = ( int ) dialogId ; <nl> + if ( lowerId < 0 ) { <nl> + TLRPC . Chat chat = getMessagesController ( ) . getChat ( - lowerId ) ; <nl> + if ( chat = = null | | chat . min | | ChatObject . isNotInChat ( chat ) ) { <nl> + newCount = 0 ; <nl> + } <nl> + } <nl> <nl> - int notifyOverride = getNotifyOverride ( preferences , dialog_id ) ; <nl> + int notifyOverride = getNotifyOverride ( preferences , dialogId ) ; <nl> boolean canAddValue ; <nl> if ( notifyOverride = = - 1 ) { <nl> - canAddValue = isGlobalNotificationsEnabled ( dialog_id ) ; <nl> + canAddValue = isGlobalNotificationsEnabled ( dialogId ) ; <nl> } else { <nl> canAddValue = notifyOverride ! = 2 ; <nl> } <nl> - Integer currentCount = pushDialogs . get ( dialog_id ) ; <nl> - Integer newCount = dialogsToUpdate . get ( dialog_id ) ; <nl> <nl> if ( notifyCheck & & ! canAddValue ) { <nl> - Integer override = pushDialogsOverrideMention . get ( dialog_id ) ; <nl> + Integer override = pushDialogsOverrideMention . get ( dialogId ) ; <nl> if ( override ! = null & & override ! = 0 ) { <nl> canAddValue = true ; <nl> newCount = override ; <nl> public void processDialogsUpdateRead ( final LongSparseArray < Integer > dialogsToUpd <nl> } <nl> <nl> if ( newCount = = 0 ) { <nl> - smartNotificationsDialogs . remove ( dialog_id ) ; <nl> + smartNotificationsDialogs . remove ( dialogId ) ; <nl> } <nl> <nl> if ( newCount < 0 ) { <nl> public void processDialogsUpdateRead ( final LongSparseArray < Integer > dialogsToUpd <nl> } <nl> } <nl> if ( newCount = = 0 ) { <nl> - pushDialogs . remove ( dialog_id ) ; <nl> - pushDialogsOverrideMention . remove ( dialog_id ) ; <nl> + pushDialogs . remove ( dialogId ) ; <nl> + pushDialogsOverrideMention . remove ( dialogId ) ; <nl> for ( int a = 0 ; a < pushMessages . size ( ) ; a + + ) { <nl> MessageObject messageObject = pushMessages . get ( a ) ; <nl> - if ( ! messageObject . messageOwner . from_scheduled & & messageObject . getDialogId ( ) = = dialog_id ) { <nl> + if ( ! messageObject . messageOwner . from_scheduled & & messageObject . getDialogId ( ) = = dialogId ) { <nl> if ( isPersonalMessage ( messageObject ) ) { <nl> personal_count - - ; <nl> } <nl> public void processDialogsUpdateRead ( final LongSparseArray < Integer > dialogsToUpd <nl> } <nl> } else if ( canAddValue ) { <nl> total_unread_count + = newCount ; <nl> - pushDialogs . put ( dialog_id , newCount ) ; <nl> + pushDialogs . put ( dialogId , newCount ) ; <nl> } <nl> } <nl> if ( ! popupArrayToRemove . isEmpty ( ) ) { <nl> private int getTotalAllUnreadCount ( ) { <nl> try { <nl> for ( int i = 0 , N = MessagesController . getInstance ( a ) . allDialogs . size ( ) ; i < N ; i + + ) { <nl> TLRPC . Dialog dialog = MessagesController . getInstance ( a ) . allDialogs . get ( i ) ; <nl> + int lowerId = ( int ) dialog . id ; <nl> + if ( lowerId < 0 ) { <nl> + TLRPC . Chat chat = getMessagesController ( ) . getChat ( - lowerId ) ; <nl> + if ( ChatObject . isNotInChat ( chat ) ) { <nl> + continue ; <nl> + } <nl> + } <nl> if ( dialog . unread_count ! = 0 ) { <nl> count + = dialog . unread_count ; <nl> } <nl> private int getTotalAllUnreadCount ( ) { <nl> try { <nl> for ( int i = 0 , N = MessagesController . getInstance ( a ) . allDialogs . size ( ) ; i < N ; i + + ) { <nl> TLRPC . Dialog dialog = MessagesController . getInstance ( a ) . allDialogs . get ( i ) ; <nl> + int lowerId = ( int ) dialog . id ; <nl> + if ( lowerId < 0 ) { <nl> + TLRPC . Chat chat = getMessagesController ( ) . getChat ( - lowerId ) ; <nl> + if ( ChatObject . isNotInChat ( chat ) ) { <nl> + continue ; <nl> + } <nl> + } <nl> if ( dialog . unread_count ! = 0 ) { <nl> count + + ; <nl> } <nl> mmm a / TMessagesProj / src / main / java / org / telegram / tgnet / TLRPC . java <nl> ppp b / TMessagesProj / src / main / java / org / telegram / tgnet / TLRPC . java <nl> public static EncryptedChat TLdeserialize ( AbstractSerializedData stream , int con <nl> public int views ; <nl> public int forwards ; <nl> public TL_messageReplies replies ; <nl> - public ArrayList < Integer > recent_repliers = new ArrayList < > ( ) ; <nl> public int edit_date ; <nl> public boolean silent ; <nl> public boolean post ; <nl> mmm a / TMessagesProj / src / main / java / org / telegram / ui / ActionBar / ActionBarLayout . java <nl> ppp b / TMessagesProj / src / main / java / org / telegram / ui / ActionBar / ActionBarLayout . java <nl> public void setFragmentPanTranslationOffset ( int fragmentPanTranslationOffset ) { <nl> protected Activity parentActivity ; <nl> <nl> public ArrayList < BaseFragment > fragmentsStack ; <nl> + private Rect rect = new Rect ( ) ; <nl> <nl> public ActionBarLayout ( Context context ) { <nl> super ( context ) ; <nl> public boolean onTouchEvent ( MotionEvent ev ) { <nl> velocityTracker . addMovement ( ev ) ; <nl> if ( ! transitionAnimationInProgress & & ! inPreviewMode & & maybeStartTracking & & ! startedTracking & & dx > = AndroidUtilities . getPixelsInCM ( 0 . 4f , true ) & & Math . abs ( dx ) / 3 > dy ) { <nl> BaseFragment currentFragment = fragmentsStack . get ( fragmentsStack . size ( ) - 1 ) ; <nl> - if ( currentFragment . canBeginSlide ( ) ) { <nl> + if ( currentFragment . canBeginSlide ( ) & & findScrollingChild ( this , ev . getX ( ) , ev . getY ( ) ) = = null ) { <nl> prepareForMoving ( ev ) ; <nl> } else { <nl> maybeStartTracking = false ; <nl> public void setFragmentPanTranslationOffset ( int offset ) { <nl> containerView . setFragmentPanTranslationOffset ( offset ) ; <nl> } <nl> } <nl> + <nl> + private View findScrollingChild ( ViewGroup parent , float x , float y ) { <nl> + int n = parent . getChildCount ( ) ; <nl> + for ( int i = 0 ; i < n ; i + + ) { <nl> + View child = parent . getChildAt ( i ) ; <nl> + if ( child . getVisibility ( ) ! = View . VISIBLE ) { <nl> + continue ; <nl> + } <nl> + child . getHitRect ( rect ) ; <nl> + if ( rect . contains ( ( int ) x , ( int ) y ) ) { <nl> + if ( child . canScrollHorizontally ( - 1 ) ) { <nl> + return child ; <nl> + } else if ( child instanceof ViewGroup ) { <nl> + View v = findScrollingChild ( ( ViewGroup ) child , x - rect . left , y - rect . top ) ; <nl> + if ( v ! = null ) { <nl> + return v ; <nl> + } <nl> + } <nl> + } <nl> + } <nl> + return null ; <nl> + } <nl> } <nl> mmm a / TMessagesProj / src / main / java / org / telegram / ui / ActionBar / ActionBarMenuItem . java <nl> ppp b / TMessagesProj / src / main / java / org / telegram / ui / ActionBar / ActionBarMenuItem . java <nl> public boolean toggleSearch ( boolean openKeyboard ) { <nl> if ( ! currentSearchFilters . isEmpty ( ) ) { <nl> if ( listener ! = null ) { <nl> for ( int i = 0 ; i < currentSearchFilters . size ( ) ; i + + ) { <nl> - listener . onSearchFilterCleared ( currentSearchFilters . get ( i ) ) ; <nl> + if ( currentSearchFilters . get ( i ) . removable ) { <nl> + listener . onSearchFilterCleared ( currentSearchFilters . get ( i ) ) ; <nl> + } <nl> } <nl> } <nl> clearSearchFilters ( ) ; <nl> public boolean toggleSearch ( boolean openKeyboard ) { <nl> } <nl> <nl> public void removeSearchFilter ( FiltersView . MediaFilterData filter ) { <nl> + if ( ! filter . removable ) { <nl> + return ; <nl> + } <nl> currentSearchFilters . remove ( filter ) ; <nl> if ( selectedFilterIndex < 0 | | selectedFilterIndex > currentSearchFilters . size ( ) - 1 ) { <nl> selectedFilterIndex = currentSearchFilters . size ( ) - 1 ; <nl> public void addSearchFilter ( FiltersView . MediaFilterData filter ) { <nl> } <nl> <nl> public void clearSearchFilters ( ) { <nl> - currentSearchFilters . clear ( ) ; <nl> + for ( int i = 0 ; i < currentSearchFilters . size ( ) ; i + + ) { <nl> + if ( currentSearchFilters . get ( i ) . removable ) { <nl> + currentSearchFilters . remove ( i ) ; <nl> + i - - ; <nl> + } <nl> + } <nl> onFiltersChanged ( ) ; <nl> } <nl> <nl> public void onTransitionResume ( Transition transition ) { <nl> if ( selectedFilterIndex ! = index ) { <nl> selectedFilterIndex = index ; <nl> onFiltersChanged ( ) ; <nl> - } else if ( ! searchFilterView . selectedForDelete ) { <nl> - searchFilterView . setSelectedForDelete ( true ) ; <nl> - } else { <nl> - FiltersView . MediaFilterData filterToRemove = searchFilterView . getFilter ( ) ; <nl> - removeSearchFilter ( filterToRemove ) ; <nl> - if ( listener ! = null ) { <nl> - listener . onSearchFilterCleared ( filterToRemove ) ; <nl> - listener . onTextChanged ( searchField ) ; <nl> + return ; <nl> + } <nl> + if ( searchFilterView . getFilter ( ) . removable ) { <nl> + if ( ! searchFilterView . selectedForDelete ) { <nl> + searchFilterView . setSelectedForDelete ( true ) ; <nl> + } else { <nl> + FiltersView . MediaFilterData filterToRemove = searchFilterView . getFilter ( ) ; <nl> + removeSearchFilter ( filterToRemove ) ; <nl> + if ( listener ! = null ) { <nl> + listener . onSearchFilterCleared ( filterToRemove ) ; <nl> + listener . onTextChanged ( searchField ) ; <nl> + } <nl> } <nl> - <nl> } <nl> } ) ; <nl> searchFilterLayout . addView ( searchFilterView , LayoutHelper . createLinear ( LayoutHelper . WRAP_CONTENT , LayoutHelper . MATCH_PARENT , 0 , 0 , 0 , 6 , 0 ) ) ; <nl> protected void onSelectionChanged ( int selStart , int selEnd ) { <nl> <nl> @ Override <nl> public boolean onKeyDown ( int keyCode , KeyEvent event ) { <nl> - if ( keyCode = = KeyEvent . KEYCODE_DEL & & searchField . length ( ) = = 0 & & ( ( searchFieldCaption . getVisibility ( ) = = VISIBLE & & searchFieldCaption . length ( ) > 0 ) | | ! currentSearchFilters . isEmpty ( ) ) ) { <nl> - if ( ! currentSearchFilters . isEmpty ( ) ) { <nl> + if ( keyCode = = KeyEvent . KEYCODE_DEL & & searchField . length ( ) = = 0 & & ( ( searchFieldCaption . getVisibility ( ) = = VISIBLE & & searchFieldCaption . length ( ) > 0 ) | | hasRemovableFilters ( ) ) ) { <nl> + if ( hasRemovableFilters ( ) ) { <nl> FiltersView . MediaFilterData filterToRemove = currentSearchFilters . get ( currentSearchFilters . size ( ) - 1 ) ; <nl> if ( listener ! = null ) { <nl> listener . onSearchFilterCleared ( filterToRemove ) ; <nl> protected void onDetachedFromWindow ( ) { <nl> clearButton . setOnClickListener ( v - > { <nl> if ( searchField . length ( ) ! = 0 ) { <nl> searchField . setText ( " " ) ; <nl> - } else if ( ! currentSearchFilters . isEmpty ( ) ) { <nl> + } else if ( hasRemovableFilters ( ) ) { <nl> searchField . hideActionMode ( ) ; <nl> for ( int i = 0 ; i < currentSearchFilters . size ( ) ; i + + ) { <nl> - if ( listener ! = null ) { <nl> + if ( listener ! = null & & currentSearchFilters . get ( i ) . removable ) { <nl> listener . onSearchFilterCleared ( currentSearchFilters . get ( i ) ) ; <nl> } <nl> } <nl> protected void onDetachedFromWindow ( ) { <nl> <nl> private void checkClearButton ( ) { <nl> if ( clearButton ! = null ) { <nl> - if ( currentSearchFilters . isEmpty ( ) & & TextUtils . isEmpty ( searchField . getText ( ) ) & & <nl> + if ( ! hasRemovableFilters ( ) & & TextUtils . isEmpty ( searchField . getText ( ) ) & & <nl> ( listener = = null | | ! listener . forceShowClear ( ) ) & & <nl> ( searchFieldCaption = = null | | searchFieldCaption . getVisibility ( ) ! = VISIBLE ) ) { <nl> if ( clearButton . getTag ( ) ! = null ) { <nl> private void checkClearButton ( ) { <nl> } <nl> } <nl> <nl> + private boolean hasRemovableFilters ( ) { <nl> + if ( currentSearchFilters . isEmpty ( ) ) { <nl> + return false ; <nl> + } <nl> + for ( int i = 0 ; i < currentSearchFilters . size ( ) ; i + + ) { <nl> + if ( currentSearchFilters . get ( i ) . removable ) { <nl> + return true ; <nl> + } <nl> + } <nl> + return false ; <nl> + } <nl> + <nl> public void setShowSearchProgress ( boolean show ) { <nl> if ( progressDrawable = = null ) { <nl> return ; <nl> public void updateColor ( ) { <nl> } <nl> } <nl> <nl> + public void collapseSearchFilters ( ) { <nl> + selectedFilterIndex = - 1 ; <nl> + onFiltersChanged ( ) ; <nl> + } <nl> + <nl> private static class SearchFilterView extends FrameLayout { <nl> <nl> Drawable thumbDrawable ; <nl> private void updateColors ( ) { <nl> Theme . setCombinedDrawableColor ( thumbDrawable , Theme . getColor ( Theme . key_avatar_actionBarIconBlue ) , true ) ; <nl> } <nl> avatarImageView . setAlpha ( 1f - selectedProgress ) ; <nl> + <nl> + if ( data ! = null & & ( data . filterType = = FiltersView . FILTER_TYPE_ARCHIVE ) ) { <nl> + setData ( data ) ; <nl> + } <nl> invalidate ( ) ; <nl> } <nl> <nl> public void setData ( FiltersView . MediaFilterData data ) { <nl> avatarImageView . getImageReceiver ( ) . setRoundRadius ( AndroidUtilities . dp ( 16 ) ) ; <nl> avatarImageView . getImageReceiver ( ) . setImage ( ImageLocation . getForChat ( chat , false ) , " 50_50 " , thumbDrawable , null , chat , 0 ) ; <nl> } <nl> + } else if ( data . filterType = = FiltersView . FILTER_TYPE_ARCHIVE ) { <nl> + CombinedDrawable combinedDrawable = Theme . createCircleDrawableWithIcon ( AndroidUtilities . dp ( 32 ) , R . drawable . chats_archive ) ; <nl> + combinedDrawable . setIconSize ( AndroidUtilities . dp ( 16 ) , AndroidUtilities . dp ( 16 ) ) ; <nl> + Theme . setCombinedDrawableColor ( combinedDrawable , Theme . getColor ( Theme . key_avatar_backgroundArchived ) , false ) ; <nl> + Theme . setCombinedDrawableColor ( combinedDrawable , Theme . getColor ( Theme . key_avatar_actionBarIconBlue ) , true ) ; <nl> + avatarImageView . setImageDrawable ( combinedDrawable ) ; <nl> } else { <nl> avatarImageView . setImageDrawable ( thumbDrawable ) ; <nl> } <nl> mmm a / TMessagesProj / src / main / java / org / telegram / ui / ActionBar / AdjustPanLayoutHelper . java <nl> ppp b / TMessagesProj / src / main / java / org / telegram / ui / ActionBar / AdjustPanLayoutHelper . java <nl> <nl> <nl> import com . google . android . exoplayer2 . util . Log ; <nl> <nl> + import org . telegram . messenger . AndroidUtilities ; <nl> import org . telegram . messenger . NotificationCenter ; <nl> import org . telegram . messenger . SharedConfig ; <nl> import org . telegram . messenger . UserConfig ; <nl> public boolean onPreDraw ( ) { <nl> return true ; <nl> } <nl> <nl> - if ( ! heightAnimationEnabled ( ) ) { <nl> + if ( ! heightAnimationEnabled ( ) | | Math . abs ( previousHeight - contentHeight ) < AndroidUtilities . dp ( 20 ) ) { <nl> previousHeight = contentHeight ; <nl> previousContentHeight = contentView . getHeight ( ) ; <nl> previousStartOffset = startOffset ( ) ; <nl> mmm a / TMessagesProj / src / main / java / org / telegram / ui / Adapters / FiltersView . java <nl> ppp b / TMessagesProj / src / main / java / org / telegram / ui / Adapters / FiltersView . java <nl> <nl> public final static int FILTER_TYPE_CHAT = 4 ; <nl> public final static int FILTER_TYPE_VOICE = 5 ; <nl> public final static int FILTER_TYPE_DATE = 6 ; <nl> + public final static int FILTER_TYPE_ARCHIVE = 7 ; <nl> <nl> public final static MediaFilterData [ ] filters = new MediaFilterData [ ] { <nl> new MediaFilterData ( R . drawable . search_media , R . drawable . search_media_filled , LocaleController . getString ( " SharedMediaTab2 " , R . string . SharedMediaTab2 ) , new TLRPC . TL_inputMessagesFilterPhotoVideo ( ) , FILTER_TYPE_MEDIA ) , <nl> public void setUsersAndDates ( ArrayList < TLObject > localUsers , ArrayList < DateData > <nl> private final static Pattern monthYearOrDayPatter = Pattern . compile ( " ( \ \ w { 3 , } ) ( [ 0 - 9 ] { 0 , 4 } ) " ) ; <nl> private final static Pattern yearOrDayAndMonthPatter = Pattern . compile ( " ( [ 0 - 9 ] { 0 , 4 } ) ( \ \ w { 2 , } ) " ) ; <nl> <nl> - <nl> - private final static Pattern shortDate = Pattern . compile ( " ^ ( [ 0 - 9 ] { 1 , 4 } ) ( \ \ . | | \ \ \ \ ) ( [ 0 - 9 ] { 1 , 4 } ) $ " ) ; <nl> - private final static Pattern longDate = Pattern . compile ( " ^ ( [ 0 - 9 ] { 1 , 2 } ) ( \ \ . | | \ \ \ \ ) ( [ 0 - 9 ] { 1 , 2 } ) ( \ \ . | | \ \ \ \ ) ( [ 0 - 9 ] { 1 , 4 } ) $ " ) ; <nl> + private final static Pattern shortDate = Pattern . compile ( " ^ ( [ 0 - 9 ] { 1 , 4 } ) ( \ \ . | | / | \ \ - ) ( [ 0 - 9 ] { 1 , 4 } ) $ " ) ; <nl> + private final static Pattern longDate = Pattern . compile ( " ^ ( [ 0 - 9 ] { 1 , 2 } ) ( \ \ . | | / | \ \ - ) ( [ 0 - 9 ] { 1 , 2 } ) ( \ \ . | | / | \ \ - ) ( [ 0 - 9 ] { 1 , 4 } ) $ " ) ; <nl> <nl> <nl> private final static int [ ] numberOfDaysEachMonth = new int [ ] { 31 , 29 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31 } ; <nl> public static void fillTipDates ( String query , ArrayList < DateData > dates ) { <nl> int day = Integer . parseInt ( g1 ) ; <nl> int month = Integer . parseInt ( g2 ) - 1 ; <nl> int year = Integer . parseInt ( g3 ) ; <nl> + if ( year > = 10 & & year < = 99 ) { <nl> + year + = 2000 ; <nl> + } <nl> int currentYear = Calendar . getInstance ( ) . get ( Calendar . YEAR ) ; <nl> if ( validDateForMont ( day - 1 , month ) & & year > = minYear & & year < = currentYear ) { <nl> Calendar calendar = Calendar . getInstance ( ) ; <nl> public ViewHolder ( @ NonNull FilterView itemView ) { <nl> public final TLRPC . MessagesFilter filter ; <nl> public TLObject chat ; <nl> public DateData dateData ; <nl> + public boolean removable = true ; <nl> <nl> public MediaFilterData ( int iconRes , int iconResFilled , String title , TLRPC . MessagesFilter filter , int filterType ) { <nl> this . iconRes = iconRes ; <nl> mmm a / TMessagesProj / src / main / java / org / telegram / ui / ArticleViewer . java <nl> ppp b / TMessagesProj / src / main / java / org / telegram / ui / ArticleViewer . java <nl> public WindowInsets dispatchApplyWindowInsets ( WindowInsets insets ) { <nl> WindowInsets oldInsets = ( WindowInsets ) lastInsets ; <nl> lastInsets = insets ; <nl> if ( oldInsets = = null | | ! oldInsets . toString ( ) . equals ( insets . toString ( ) ) ) { <nl> - windowView . requestLayout ( ) ; <nl> + if ( windowView ! = null ) { <nl> + windowView . requestLayout ( ) ; <nl> + } <nl> } <nl> - if ( Build . VERSION . SDK_INT > = 28 ) { <nl> + if ( Build . VERSION . SDK_INT > = 28 & & parentActivity ! = null ) { <nl> DisplayCutout cutout = parentActivity . getWindow ( ) . getDecorView ( ) . getRootWindowInsets ( ) . getDisplayCutout ( ) ; <nl> if ( cutout ! = null ) { <nl> List < Rect > rects = cutout . getBoundingRects ( ) ; <nl> mmm a / TMessagesProj / src / main / java / org / telegram / ui / Cells / ChatMessageCell . java <nl> ppp b / TMessagesProj / src / main / java / org / telegram / ui / Cells / ChatMessageCell . java <nl> private boolean isPhotoDataChanged ( MessageObject object ) { <nl> return false ; <nl> } <nl> <nl> + private int getRepliesCount ( ) { <nl> + if ( currentMessagesGroup ! = null & & ! currentMessagesGroup . messages . isEmpty ( ) ) { <nl> + MessageObject messageObject = currentMessagesGroup . messages . get ( 0 ) ; <nl> + return messageObject . getRepliesCount ( ) ; <nl> + } <nl> + return currentMessageObject . getRepliesCount ( ) ; <nl> + } <nl> + <nl> + private ArrayList < TLRPC . Peer > getRecentRepliers ( ) { <nl> + if ( currentMessagesGroup ! = null & & ! currentMessagesGroup . messages . isEmpty ( ) ) { <nl> + MessageObject messageObject = currentMessagesGroup . messages . get ( 0 ) ; <nl> + if ( messageObject . messageOwner . replies ! = null ) { <nl> + return messageObject . messageOwner . replies . recent_repliers ; <nl> + } <nl> + } <nl> + if ( currentMessageObject . messageOwner . replies ! = null ) { <nl> + return currentMessageObject . messageOwner . replies . recent_repliers ; <nl> + } <nl> + return null ; <nl> + } <nl> + <nl> private boolean isUserDataChanged ( ) { <nl> if ( currentMessageObject ! = null & & ( ! hasLinkPreview & & currentMessageObject . messageOwner . media ! = null & & currentMessageObject . messageOwner . media . webpage instanceof TLRPC . TL_webPage ) ) { <nl> return true ; <nl> private boolean isUserDataChanged ( ) { <nl> if ( lastViewsCount ! = currentMessageObject . messageOwner . views ) { <nl> return true ; <nl> } <nl> - if ( lastRepliesCount ! = currentMessageObject . getRepliesCount ( ) ) { <nl> + if ( lastRepliesCount ! = getRepliesCount ( ) ) { <nl> return true ; <nl> } <nl> if ( lastReactions ! = currentMessageObject . messageOwner . reactions ) { <nl> private void setMessageContent ( MessageObject messageObject , MessageObject . Groupe <nl> lastSendState = messageObject . messageOwner . send_state ; <nl> lastDeleteDate = messageObject . messageOwner . destroyTime ; <nl> lastViewsCount = messageObject . messageOwner . views ; <nl> - lastRepliesCount = messageObject . getRepliesCount ( ) ; <nl> + lastRepliesCount = getRepliesCount ( ) ; <nl> isPressed = false ; <nl> gamePreviewPressed = false ; <nl> sideButtonPressed = false ; <nl> private void setMessageContent ( MessageObject messageObject , MessageObject . Groupe <nl> linked = messageObject . isLinkedToChat ( linkedChatId ) ; <nl> } <nl> if ( ( hasDiscussion & & linked | | isRepliesChat & & ! messageObject . isOutOwner ( ) ) & & ( currentPosition = = null | | ( currentPosition . flags & MessageObject . POSITION_FLAG_BOTTOM ) ! = 0 ) ) { <nl> - int commentCount = messageObject . getRepliesCount ( ) ; <nl> + int commentCount = getRepliesCount ( ) ; <nl> if ( ! messageObject . shouldDrawWithoutBackground ( ) & & ! messageObject . isAnimatedEmoji ( ) ) { <nl> drawCommentButton = true ; <nl> int avatarsOffset = 0 ; <nl> private void setMessageContent ( MessageObject messageObject , MessageObject . Groupe <nl> comment = LocaleController . getString ( " ViewInChat " , R . string . ViewInChat ) ; <nl> } else { <nl> comment = commentCount = = 0 ? LocaleController . getString ( " LeaveAComment " , R . string . LeaveAComment ) : LocaleController . formatPluralString ( " CommentsCount " , commentCount ) ; <nl> - if ( commentCount ! = 0 & & ! messageObject . messageOwner . replies . recent_repliers . isEmpty ( ) ) { <nl> + ArrayList < TLRPC . Peer > recentRepliers = getRecentRepliers ( ) ; <nl> + if ( commentCount ! = 0 & & recentRepliers ! = null & & ! recentRepliers . isEmpty ( ) ) { <nl> createCommentUI ( ) ; <nl> - int size = messageObject . messageOwner . replies . recent_repliers . size ( ) ; <nl> + int size = recentRepliers . size ( ) ; <nl> for ( int a = 0 ; a < commentAvatarImages . length ; a + + ) { <nl> if ( a < size ) { <nl> commentAvatarImages [ a ] . setImageCoords ( 0 , 0 , AndroidUtilities . dp ( 24 ) , AndroidUtilities . dp ( 24 ) ) ; <nl> - int id = MessageObject . getPeerId ( messageObject . messageOwner . replies . recent_repliers . get ( a ) ) ; <nl> + int id = MessageObject . getPeerId ( recentRepliers . get ( a ) ) ; <nl> TLRPC . User user = null ; <nl> TLRPC . Chat chat = null ; <nl> if ( id > 0 ) { <nl> private void measureTime ( MessageObject messageObject ) { <nl> timeWidth + = viewsTextWidth + Theme . chat_msgInViewsDrawable . getIntrinsicWidth ( ) + AndroidUtilities . dp ( 10 ) ; <nl> } <nl> if ( hasLinkedChat & & isChat & & isMegagroup & & ! isThreadChat & & messageObject . hasReplies ( ) ) { <nl> - currentRepliesString = String . format ( " % s " , LocaleController . formatShortNumber ( messageObject . getRepliesCount ( ) , null ) ) ; <nl> + currentRepliesString = String . format ( " % s " , LocaleController . formatShortNumber ( getRepliesCount ( ) , null ) ) ; <nl> repliesTextWidth = ( int ) Math . ceil ( Theme . chat_timePaint . measureText ( currentRepliesString ) ) ; <nl> timeWidth + = repliesTextWidth + Theme . chat_msgInRepliesDrawable . getIntrinsicWidth ( ) + AndroidUtilities . dp ( 10 ) ; <nl> } else { <nl> public void drawCaptionLayout ( Canvas canvas , boolean selectionOnly , float alpha ) <nl> } <nl> <nl> private void drawCaptionLayout ( Canvas canvas , StaticLayout captionLayout , boolean selectionOnly , float alpha ) { <nl> - if ( currentBackgroundDrawable ! = null & & drawCommentButton ) { <nl> + if ( currentBackgroundDrawable ! = null & & drawCommentButton & & timeLayout ! = null ) { <nl> int x ; <nl> float y = layoutHeight - AndroidUtilities . dp ( 18 ) - timeLayout . getHeight ( ) ; <nl> if ( mediaBackground ) { <nl> public void recordDrawingState ( ) { <nl> } <nl> <nl> if ( commentLayout ! = null ) { <nl> - lastCommentsCount = currentMessageObject . getRepliesCount ( ) ; <nl> + lastCommentsCount = getRepliesCount ( ) ; <nl> lastTotalCommentWidth = totalCommentWidth ; <nl> lastCommentLayout = commentLayout ; <nl> lastCommentArrowX = commentArrowX ; <nl> public void recordDrawingState ( ) { <nl> lastCommentDrawUnread = commentDrawUnread ; <nl> } <nl> if ( repliesLayout ! = null ) { <nl> - lastRepliesCount = currentMessageObject . getRepliesCount ( ) ; <nl> + lastRepliesCount = getRepliesCount ( ) ; <nl> lastRepliesLayout = repliesLayout ; <nl> } <nl> <nl> public boolean animateChange ( ) { <nl> } <nl> } <nl> <nl> - if ( repliesLayout ! = null & & lastRepliesCount ! = currentMessageObject . getRepliesCount ( ) ) { <nl> + if ( repliesLayout ! = null & & lastRepliesCount ! = getRepliesCount ( ) ) { <nl> animateRepliesLayout = lastRepliesLayout ; <nl> animateReplies = true ; <nl> changed = true ; <nl> } <nl> <nl> - if ( commentLayout ! = null & & lastCommentsCount ! = currentMessageObject . getRepliesCount ( ) ) { <nl> + if ( commentLayout ! = null & & lastCommentsCount ! = getRepliesCount ( ) ) { <nl> animateCommentsLayout = lastCommentLayout ; <nl> animateTotalCommentWidth = lastTotalCommentWidth ; <nl> animateCommentArrowX = lastCommentArrowX ; <nl> mmm a / TMessagesProj / src / main / java / org / telegram / ui / Cells / DialogCell . java <nl> ppp b / TMessagesProj / src / main / java / org / telegram / ui / Cells / DialogCell . java <nl> public void buildLayout ( ) { <nl> } else if ( message . messageOwner . message ! = null ) { <nl> String mess = message . messageOwner . message ; <nl> if ( message . hasHighlightedWords ( ) ) { <nl> - mess = mess . replace ( ' \ n ' , ' ' ) . trim ( ) ; <nl> + mess = mess . replace ( ' \ n ' , ' ' ) . replaceAll ( " + " , " " ) . trim ( ) ; <nl> int w = getMeasuredWidth ( ) - AndroidUtilities . dp ( 72 + 23 + 10 ) ; <nl> if ( hasNameInMessage ) { <nl> if ( ! TextUtils . isEmpty ( messageNameString ) ) { <nl> public void buildLayout ( ) { <nl> } else { <nl> emoji = " \ uD83D \ uDCCE " ; <nl> } <nl> - if ( message . hasHighlightedWords ( ) ) { <nl> - String str = message . messageOwner . message . replace ( ' \ n ' , ' ' ) . trim ( ) ; <nl> + if ( message . hasHighlightedWords ( ) & & ! TextUtils . isEmpty ( message . messageOwner . message ) ) { <nl> + String str = message . messageOwner . message . replace ( ' \ n ' , ' ' ) . replaceAll ( " + " , " " ) . trim ( ) ; <nl> int w = getMeasuredWidth ( ) - AndroidUtilities . dp ( 72 + 23 + 24 ) ; <nl> if ( hasNameInMessage ) { <nl> if ( ! TextUtils . isEmpty ( messageNameString ) ) { <nl> public void buildLayout ( ) { <nl> } else if ( message . type = = 14 ) { <nl> messageString = String . format ( " \ uD83C \ uDFA7 % s - % s " , message . getMusicAuthor ( ) , message . getMusicTitle ( ) ) ; <nl> } else { <nl> - if ( message . hasHighlightedWords ( ) ) { <nl> + if ( message . hasHighlightedWords ( ) & & ! TextUtils . isEmpty ( message . messageOwner . message ) ) { <nl> messageString = message . messageOwner . message . replace ( ' \ n ' , ' ' ) . trim ( ) ; <nl> int w = getMeasuredWidth ( ) - AndroidUtilities . dp ( 72 + 23 ) ; <nl> messageString = AndroidUtilities . ellipsizeCenterEnd ( messageString , message . highlightedWords . get ( 0 ) , w , currentMessagePaint ) . toString ( ) ; <nl> - AndroidUtilities . highlightText ( messageString , message . highlightedWords ) ; <nl> } else { <nl> messageString = message . messageText ; <nl> } <nl> + AndroidUtilities . highlightText ( messageString , message . highlightedWords ) ; <nl> } <nl> if ( message . messageOwner . media ! = null & & ! message . isMediaEmpty ( ) ) { <nl> currentMessagePaint = Theme . dialogs_messagePrintingPaint [ paintIndex ] ; <nl> } <nl> } <nl> if ( hasMessageThumb ) { <nl> - if ( message . hasHighlightedWords ( ) ) { <nl> - messageString = message . messageOwner . message . replace ( ' \ n ' , ' ' ) . trim ( ) ; <nl> + if ( message . hasHighlightedWords ( ) & & ! TextUtils . isEmpty ( message . messageOwner . message ) ) { <nl> + messageString = message . messageOwner . message . replace ( ' \ n ' , ' ' ) . replaceAll ( " + " , " " ) . trim ( ) ; <nl> int w = getMeasuredWidth ( ) - AndroidUtilities . dp ( 72 + 23 + thumbSize + 6 ) ; <nl> messageString = AndroidUtilities . ellipsizeCenterEnd ( messageString , message . highlightedWords . get ( 0 ) , w , currentMessagePaint ) . toString ( ) ; <nl> } else { <nl> mmm a / TMessagesProj / src / main / java / org / telegram / ui / Cells / SharedAudioCell . java <nl> ppp b / TMessagesProj / src / main / java / org / telegram / ui / Cells / SharedAudioCell . java <nl> protected void onMeasure ( int widthMeasureSpec , int heightMeasureSpec ) { <nl> } <nl> <nl> if ( currentMessageObject . hasHighlightedWords ( ) ) { <nl> - CharSequence caption = Emoji . replaceEmoji ( currentMessageObject . messageOwner . message . replace ( " \ n " , " " ) . trim ( ) , Theme . chat_msgTextPaint . getFontMetricsInt ( ) , AndroidUtilities . dp ( 20 ) , false ) ; <nl> + CharSequence caption = Emoji . replaceEmoji ( currentMessageObject . messageOwner . message . replace ( " \ n " , " " ) . replaceAll ( " + " , " " ) . trim ( ) , Theme . chat_msgTextPaint . getFontMetricsInt ( ) , AndroidUtilities . dp ( 20 ) , false ) ; <nl> CharSequence sequence = AndroidUtilities . highlightText ( caption , currentMessageObject . highlightedWords ) ; <nl> if ( sequence ! = null ) { <nl> sequence = TextUtils . ellipsize ( AndroidUtilities . ellipsizeCenterEnd ( sequence , currentMessageObject . highlightedWords . get ( 0 ) , maxWidth , captionTextPaint ) , captionTextPaint , maxWidth , TextUtils . TruncateAt . END ) ; <nl> mmm a / TMessagesProj / src / main / java / org / telegram / ui / Cells / SharedDocumentCell . java <nl> ppp b / TMessagesProj / src / main / java / org / telegram / ui / Cells / SharedDocumentCell . java <nl> public void setDocument ( MessageObject messageObject , boolean divider ) { <nl> } <nl> <nl> if ( messageObject . hasHighlightedWords ( ) & & ! TextUtils . isEmpty ( message . messageOwner . message ) ) { <nl> - String str = message . messageOwner . message . replace ( " \ n " , " " ) . trim ( ) ; <nl> + String str = message . messageOwner . message . replace ( " \ n " , " " ) . replaceAll ( " + " , " " ) . trim ( ) ; <nl> caption = AndroidUtilities . highlightText ( str , message . highlightedWords ) ; <nl> if ( captionTextView ! = null ) { <nl> captionTextView . setVisibility ( caption = = null ? View . GONE : View . VISIBLE ) ; <nl> mmm a / TMessagesProj / src / main / java / org / telegram / ui / Cells / SharedLinkCell . java <nl> ppp b / TMessagesProj / src / main / java / org / telegram / ui / Cells / SharedLinkCell . java <nl> protected void onMeasure ( int widthMeasureSpec , int heightMeasureSpec ) { <nl> } <nl> <nl> if ( message ! = null & & ! TextUtils . isEmpty ( message . messageOwner . message ) ) { <nl> - CharSequence caption = Emoji . replaceEmoji ( message . messageOwner . message . replace ( " \ n " , " " ) . trim ( ) , Theme . chat_msgTextPaint . getFontMetricsInt ( ) , AndroidUtilities . dp ( 20 ) , false ) ; <nl> + CharSequence caption = Emoji . replaceEmoji ( message . messageOwner . message . replace ( " \ n " , " " ) . replaceAll ( " + " , " " ) . trim ( ) , Theme . chat_msgTextPaint . getFontMetricsInt ( ) , AndroidUtilities . dp ( 20 ) , false ) ; <nl> CharSequence sequence = AndroidUtilities . highlightText ( caption , message . highlightedWords ) ; <nl> if ( sequence ! = null ) { <nl> sequence = TextUtils . ellipsize ( AndroidUtilities . ellipsizeCenterEnd ( sequence , message . highlightedWords . get ( 0 ) , maxWidth , captionTextPaint ) , captionTextPaint , maxWidth , TextUtils . TruncateAt . END ) ; <nl> mmm a / TMessagesProj / src / main / java / org / telegram / ui / ChatActivity . java <nl> ppp b / TMessagesProj / src / main / java / org / telegram / ui / ChatActivity . java <nl> <nl> private int threadMaxInboxReadId ; <nl> private int threadMaxOutboxReadId ; <nl> private int replyMaxReadId = 0 ; <nl> + private Runnable delayedReadRunnable ; <nl> <nl> private ArrayList < MessageObject > animatingMessageObjects = new ArrayList < > ( ) ; <nl> private HashMap < TLRPC . Document , Integer > animatingDocuments = new HashMap < > ( ) ; <nl> public boolean onFragmentCreate ( ) { <nl> getNotificationCenter ( ) . addObserver ( this , NotificationCenter . pinnedMessageDidLoad ) ; <nl> getNotificationCenter ( ) . addObserver ( this , NotificationCenter . commentsRead ) ; <nl> getNotificationCenter ( ) . addObserver ( this , NotificationCenter . changeRepliesCounter ) ; <nl> + getNotificationCenter ( ) . addObserver ( this , NotificationCenter . messagesRead ) ; <nl> } else { <nl> getNotificationCenter ( ) . addObserver ( this , NotificationCenter . threadMessagesRead ) ; <nl> } <nl> - getNotificationCenter ( ) . addObserver ( this , NotificationCenter . messagesRead ) ; <nl> getNotificationCenter ( ) . addObserver ( this , NotificationCenter . removeAllMessagesFromDialog ) ; <nl> getNotificationCenter ( ) . addObserver ( this , NotificationCenter . messagesReadContent ) ; <nl> getNotificationCenter ( ) . addObserver ( this , NotificationCenter . chatSearchResultsAvailable ) ; <nl> protected boolean hasSiblingChild ( int position ) { <nl> <nl> @ Override <nl> public void onLayoutChildren ( RecyclerView . Recycler recycler , RecyclerView . State state ) { <nl> - try { <nl> + if ( BuildVars . DEBUG_PRIVATE_VERSION ) { <nl> super . onLayoutChildren ( recycler , state ) ; <nl> - } catch ( Exception e ) { <nl> - FileLog . e ( e ) ; <nl> - AndroidUtilities . runOnUIThread ( ( ) - > chatAdapter . notifyDataSetChanged ( false ) ) ; <nl> + } else { <nl> + try { <nl> + super . onLayoutChildren ( recycler , state ) ; <nl> + } catch ( Exception e ) { <nl> + FileLog . e ( e ) ; <nl> + AndroidUtilities . runOnUIThread ( ( ) - > chatAdapter . notifyDataSetChanged ( false ) ) ; <nl> + } <nl> } <nl> } <nl> } ; <nl> public void didReceivedNotification ( int id , int account , final Object . . . args ) { <nl> if ( obj ! = null & & obj . hasReplies ( ) ) { <nl> int maxReadId = ( Integer ) args [ 2 ] ; <nl> if ( paused ) { <nl> + if ( delayedReadRunnable ! = null ) { <nl> + AndroidUtilities . cancelRunOnUIThread ( delayedReadRunnable ) ; <nl> + delayedReadRunnable = null ; <nl> + } <nl> obj . messageOwner . replies . read_max_id = maxReadId ; <nl> } else { <nl> - AndroidUtilities . runOnUIThread ( ( ) - > obj . messageOwner . replies . read_max_id = maxReadId , 1000 ) ; <nl> + AndroidUtilities . runOnUIThread ( delayedReadRunnable = ( ) - > { <nl> + delayedReadRunnable = null ; <nl> + obj . messageOwner . replies . read_max_id = maxReadId ; <nl> + } , 500 ) ; <nl> } <nl> } <nl> } <nl> public void didReceivedNotification ( int id , int account , final Object . . . args ) { <nl> } <nl> } <nl> } else { <nl> + if ( messageObject . messageOwner . replies ! = null & & messageObject . messageOwner . replies . read_max_id > newValue . read_max_id ) { <nl> + newValue . read_max_id = messageObject . messageOwner . replies . read_max_id ; <nl> + } <nl> messageObject . messageOwner . replies = newValue ; <nl> } <nl> if ( messageObject . hasValidGroupId ( ) ) { <nl> protected void onBecomeFullyHidden ( ) { <nl> public void onTransitionAnimationStart ( boolean isOpen , boolean backward ) { <nl> int [ ] alowedNotifications = null ; <nl> if ( isOpen ) { <nl> - alowedNotifications = new int [ ] { <nl> - NotificationCenter . dialogsNeedReload , NotificationCenter . closeChats , <nl> - NotificationCenter . botKeyboardDidLoad , NotificationCenter . needDeleteDialog <nl> - } ; <nl> + if ( threadMessageId ! = 0 ) { <nl> + alowedNotifications = new int [ ] { <nl> + NotificationCenter . dialogsNeedReload , NotificationCenter . closeChats , <nl> + NotificationCenter . botKeyboardDidLoad , NotificationCenter . needDeleteDialog , <nl> + NotificationCenter . messagesDidLoad <nl> + } ; <nl> + } else { <nl> + alowedNotifications = new int [ ] { <nl> + NotificationCenter . dialogsNeedReload , NotificationCenter . closeChats , <nl> + NotificationCenter . botKeyboardDidLoad , NotificationCenter . needDeleteDialog <nl> + } ; <nl> + } <nl> openAnimationEnded = false ; <nl> if ( ! backward ) { <nl> openAnimationStartTime = SystemClock . elapsedRealtime ( ) ; <nl> private void processLoadedDiscussionMessage ( boolean noDiscussion , TLRPC . TL_messa <nl> if ( ! noDiscussion & & discussionMessage = = null | | noDiscussion | | ! noHistory & & history = = null ) { <nl> return ; <nl> } <nl> + <nl> if ( history ! = null & & maxReadId ! = 1 & & maxReadId ! = 0 & & maxReadId ! = discussionMessage . read_inbox_max_id ) { <nl> history = null ; <nl> } <nl> private void processLoadedDiscussionMessage ( boolean noDiscussion , TLRPC . TL_messa <nl> } <nl> } <nl> } <nl> - getMessagesController ( ) . processLoadedMessages ( history , dialogId , 0 , 30 , maxReadId , 0 , false , chatActivity . getClassGuid ( ) , fnid , 0 , 0 , 0 , 2 , true , false , false , arrayList . get ( arrayList . size ( ) - 1 ) . getId ( ) , 1 , false , 0 ) ; <nl> + TLRPC . messages_Messages historyFinal = history ; <nl> + int fnidFinal = fnid ; <nl> + Utilities . stageQueue . postRunnable ( ( ) - > getMessagesController ( ) . processLoadedMessages ( historyFinal , dialogId , 0 , 30 , maxReadId , 0 , false , chatActivity . getClassGuid ( ) , fnidFinal , 0 , 0 , 0 , 2 , true , false , false , arrayList . get ( arrayList . size ( ) - 1 ) . getId ( ) , 1 , false , 0 ) ) ; <nl> } <nl> } <nl> <nl> mmm a / TMessagesProj / src / main / java / org / telegram / ui / Components / ChatActivityEnterView . java <nl> ppp b / TMessagesProj / src / main / java / org / telegram / ui / Components / ChatActivityEnterView . java <nl> protected void onDraw ( Canvas canvas ) { <nl> } else { <nl> if ( searchingType ! = 0 ) { <nl> searchingType = 0 ; <nl> - emojiView . closeSearch ( false ) ; <nl> + if ( emojiView ! = null ) { <nl> + emojiView . closeSearch ( false ) ; <nl> + } <nl> messageEditText . requestFocus ( ) ; <nl> } <nl> if ( stickersExpanded ) { <nl> public void setTranslationY ( float translationY ) { <nl> if ( replyingMessageObject ! = null ) { <nl> openKeyboardInternal ( ) ; <nl> setButtons ( botMessageObject , false ) ; <nl> - } else if ( botButtonsMessageObject . messageOwner . reply_markup . single_use ) { <nl> + } else if ( botButtonsMessageObject ! = null & & botButtonsMessageObject . messageOwner . reply_markup . single_use ) { <nl> if ( open ) { <nl> openKeyboardInternal ( ) ; <nl> } else { <nl> mmm a / TMessagesProj / src / main / java / org / telegram / ui / Components / SearchViewPager . java <nl> ppp b / TMessagesProj / src / main / java / org / telegram / ui / Components / SearchViewPager . java <nl> <nl> <nl> import android . animation . Animator ; <nl> import android . animation . AnimatorListenerAdapter ; <nl> - import android . animation . AnimatorSet ; <nl> - import android . animation . ObjectAnimator ; <nl> import android . animation . ValueAnimator ; <nl> import android . content . Context ; <nl> import android . graphics . Canvas ; <nl> import android . os . Bundle ; <nl> - import android . util . SparseArray ; <nl> - import android . util . SparseIntArray ; <nl> import android . view . View ; <nl> import android . view . ViewTreeObserver ; <nl> import android . widget . FrameLayout ; <nl> <nl> <nl> private NumberTextView selectedMessagesCountTextView ; <nl> private boolean isActionModeShowed ; <nl> - private HashMap < FilteredSearchView . MessageHashId , MessageObject > selectedFiles = new HashMap ( ) ; <nl> + private HashMap < FilteredSearchView . MessageHashId , MessageObject > selectedFiles = new HashMap < > ( ) ; <nl> <nl> private ArrayList < FiltersView . MediaFilterData > currentSearchFilters = new ArrayList < > ( ) ; <nl> <nl> private void search ( View view , int position , String query , boolean reset ) { <nl> dialogsSearchAdapter . setFiltersDelegate ( filteredSearchViewDelegate , false ) ; <nl> noMediaFiltersSearchView . animate ( ) . setListener ( null ) . cancel ( ) ; <nl> noMediaFiltersSearchView . setDelegate ( null , false ) ; <nl> - emptyView . showProgress ( ! dialogsSearchAdapter . isSearching ( ) , false ) ; <nl> - emptyView . showProgress ( dialogsSearchAdapter . isSearching ( ) , false ) ; <nl> + if ( reset ) { <nl> + emptyView . showProgress ( ! dialogsSearchAdapter . isSearching ( ) , false ) ; <nl> + emptyView . showProgress ( dialogsSearchAdapter . isSearching ( ) , false ) ; <nl> + } <nl> if ( reset ) { <nl> noMediaFiltersSearchView . setVisibility ( View . GONE ) ; <nl> } else { <nl> public void onActionBarItemClick ( int id ) { <nl> DialogsActivity fragment = new DialogsActivity ( args ) ; <nl> fragment . setDelegate ( ( fragment1 , dids , message , param ) - > { <nl> ArrayList < MessageObject > fmessages = new ArrayList < > ( ) ; <nl> - ArrayList < Integer > ids = new ArrayList < > ( ) ; <nl> Iterator < FilteredSearchView . MessageHashId > idIterator = selectedFiles . keySet ( ) . iterator ( ) ; <nl> while ( idIterator . hasNext ( ) ) { <nl> FilteredSearchView . MessageHashId hashId = idIterator . next ( ) ; <nl> - ids . add ( hashId . messageId ) ; <nl> fmessages . add ( selectedFiles . get ( hashId ) ) ; <nl> } <nl> selectedFiles . clear ( ) ; <nl> public void toggleItemSelection ( MessageObject message , View view , int a ) { <nl> } else if ( view instanceof DialogCell ) { <nl> ( ( DialogCell ) view ) . setChecked ( selectedFiles . containsKey ( hashId ) , true ) ; <nl> } <nl> - return ; <nl> } <nl> <nl> @ Override <nl> public void messagesDeleted ( int channelId , ArrayList < Integer > markAsDeletedMessa <nl> } <nl> noMediaFiltersSearchView . messagesDeleted ( channelId , markAsDeletedMessages ) ; <nl> if ( ! selectedFiles . isEmpty ( ) ) { <nl> + ArrayList < FilteredSearchView . MessageHashId > toRemove = null ; <nl> Iterator < FilteredSearchView . MessageHashId > iterator = selectedFiles . keySet ( ) . iterator ( ) ; <nl> while ( iterator . hasNext ( ) ) { <nl> FilteredSearchView . MessageHashId hashId = iterator . next ( ) ; <nl> public void messagesDeleted ( int channelId , ArrayList < Integer > markAsDeletedMessa <nl> if ( currentChannelId = = channelId ) { <nl> for ( int i = 0 ; i < markAsDeletedMessages . size ( ) ; i + + ) { <nl> if ( messageObject . getId ( ) = = markAsDeletedMessages . get ( i ) ) { <nl> - selectedFiles . remove ( hashId ) ; <nl> - selectedMessagesCountTextView . setNumber ( selectedFiles . size ( ) , true ) ; <nl> - if ( gotoItem ! = null ) { <nl> - gotoItem . setVisibility ( selectedFiles . size ( ) = = 1 ? View . VISIBLE : View . GONE ) ; <nl> - } <nl> + toRemove = new ArrayList < > ( ) ; <nl> + toRemove . add ( hashId ) ; <nl> } <nl> } <nl> } <nl> + if ( toRemove ! = null ) { <nl> + for ( int a = 0 , N = toRemove . size ( ) ; a < N ; a + + ) { <nl> + selectedFiles . remove ( toRemove . get ( a ) ) ; <nl> + } <nl> + selectedMessagesCountTextView . setNumber ( selectedFiles . size ( ) , true ) ; <nl> + if ( gotoItem ! = null ) { <nl> + gotoItem . setVisibility ( selectedFiles . size ( ) = = 1 ? View . VISIBLE : View . GONE ) ; <nl> + } <nl> + } <nl> } <nl> } <nl> } <nl> mmm a / TMessagesProj / src / main / java / org / telegram / ui / Components / SharedMediaLayout . java <nl> ppp b / TMessagesProj / src / main / java / org / telegram / ui / Components / SharedMediaLayout . java <nl> <nl> import org . telegram . ui . ActionBar . BottomSheet ; <nl> import org . telegram . ui . ActionBar . Theme ; <nl> import org . telegram . ui . ActionBar . ThemeDescription ; <nl> + import org . telegram . ui . Adapters . FiltersView ; <nl> import org . telegram . ui . Adapters . SearchAdapterHelper ; <nl> import org . telegram . ui . ArticleViewer ; <nl> import org . telegram . ui . Cells . ChatActionCell ; <nl> <nl> import org . telegram . ui . Cells . UserCell ; <nl> import org . telegram . ui . ChatActivity ; <nl> import org . telegram . ui . DialogsActivity ; <nl> + import org . telegram . ui . FilteredSearchView ; <nl> import org . telegram . ui . PhotoViewer ; <nl> import org . telegram . ui . ProfileActivity ; <nl> <nl> <nl> <nl> private static class MediaPage extends FrameLayout { <nl> private RecyclerListView listView ; <nl> - private LinearLayout progressView ; <nl> + private FilteredSearchView . LoadingView progressView ; <nl> private TextView emptyTextView ; <nl> private ExtendedGridLayoutManager layoutManager ; <nl> private ImageView emptyImageView ; <nl> private LinearLayout emptyView ; <nl> - private RadialProgressView progressBar ; <nl> private ClippingImageView animatingImageView ; <nl> private RecyclerAnimationScrollHelper scrollHelper ; <nl> private int selectedType ; <nl> public void invalidate ( ) { <nl> mediaPages [ a ] . emptyTextView . setPadding ( AndroidUtilities . dp ( 40 ) , 0 , AndroidUtilities . dp ( 40 ) , AndroidUtilities . dp ( 128 ) ) ; <nl> mediaPages [ a ] . emptyView . addView ( mediaPages [ a ] . emptyTextView , LayoutHelper . createLinear ( LayoutHelper . WRAP_CONTENT , LayoutHelper . WRAP_CONTENT , Gravity . CENTER , 0 , 24 , 0 , 0 ) ) ; <nl> <nl> - mediaPages [ a ] . progressView = new LinearLayout ( context ) { <nl> + mediaPages [ a ] . progressView = new FilteredSearchView . LoadingView ( context ) { <nl> + <nl> + @ Override <nl> + public int getColumnsCount ( ) { <nl> + return columnsCount ; <nl> + } <nl> + <nl> + @ Override <nl> + public int getType ( ) { <nl> + if ( mediaPage . selectedType = = 0 | | mediaPage . selectedType = = 5 ) { <nl> + return 2 ; <nl> + } else if ( mediaPage . selectedType = = 1 ) { <nl> + return 3 ; <nl> + } else if ( mediaPage . selectedType = = 2 | | mediaPage . selectedType = = 4 ) { <nl> + return 4 ; <nl> + } else if ( mediaPage . selectedType = = 3 ) { <nl> + return 5 ; <nl> + } <nl> + return super . getType ( ) ; <nl> + } <nl> + <nl> @ Override <nl> protected void onDraw ( Canvas canvas ) { <nl> backgroundPaint . setColor ( Theme . getColor ( Theme . key_windowBackgroundWhite ) ) ; <nl> canvas . drawRect ( 0 , 0 , getMeasuredWidth ( ) , getMeasuredHeight ( ) , backgroundPaint ) ; <nl> + super . onDraw ( canvas ) ; <nl> } <nl> } ; <nl> - mediaPages [ a ] . progressView . setWillNotDraw ( false ) ; <nl> - mediaPages [ a ] . progressView . setGravity ( Gravity . CENTER ) ; <nl> - mediaPages [ a ] . progressView . setOrientation ( LinearLayout . VERTICAL ) ; <nl> mediaPages [ a ] . progressView . setVisibility ( View . GONE ) ; <nl> mediaPages [ a ] . addView ( mediaPages [ a ] . progressView , LayoutHelper . createFrame ( LayoutHelper . MATCH_PARENT , LayoutHelper . MATCH_PARENT ) ) ; <nl> - <nl> - mediaPages [ a ] . progressBar = new RadialProgressView ( context ) ; <nl> - mediaPages [ a ] . progressView . addView ( mediaPages [ a ] . progressBar , LayoutHelper . createLinear ( LayoutHelper . WRAP_CONTENT , LayoutHelper . WRAP_CONTENT ) ) ; <nl> if ( a ! = 0 ) { <nl> mediaPages [ a ] . setVisibility ( View . GONE ) ; <nl> } <nl> public void setVisibleHeight ( int height ) { <nl> height = Math . max ( height , AndroidUtilities . dp ( 120 ) ) ; <nl> for ( int a = 0 ; a < mediaPages . length ; a + + ) { <nl> mediaPages [ a ] . emptyView . setTranslationY ( - ( getMeasuredHeight ( ) - height ) / 2 ) ; <nl> - mediaPages [ a ] . progressView . setTranslationY ( - ( getMeasuredHeight ( ) - height ) / 2 ) ; <nl> } <nl> } <nl> <nl> public void didReceivedNotification ( int id , int account , Object . . . args ) { <nl> profileActivity . getMediaDataController ( ) . loadMedia ( mergeDialogId , 50 , sharedMediaData [ type ] . max_id [ 1 ] , type , 1 , profileActivity . getClassGuid ( ) ) ; <nl> } <nl> if ( adapter ! = null ) { <nl> + RecyclerListView listView = null ; <nl> for ( int a = 0 ; a < mediaPages . length ; a + + ) { <nl> if ( mediaPages [ a ] . listView . getAdapter ( ) = = adapter ) { <nl> + listView = mediaPages [ a ] . listView ; <nl> mediaPages [ a ] . listView . stopScroll ( ) ; <nl> } <nl> } <nl> public void didReceivedNotification ( int id , int account , Object . . . args ) { <nl> } else if ( newItemCount < oldItemCount ) { <nl> adapter . notifyItemRangeRemoved ( newItemCount , ( oldItemCount - newItemCount ) ) ; <nl> } <nl> + if ( listView ! = null & & oldItemCount = = 0 & & newItemCount > 0 ) { <nl> + RecyclerListView finalListView = listView ; <nl> + getViewTreeObserver ( ) . addOnPreDrawListener ( new ViewTreeObserver . OnPreDrawListener ( ) { <nl> + @ Override <nl> + public boolean onPreDraw ( ) { <nl> + getViewTreeObserver ( ) . removeOnPreDrawListener ( this ) ; <nl> + int n = finalListView . getChildCount ( ) ; <nl> + AnimatorSet animatorSet = new AnimatorSet ( ) ; <nl> + for ( int i = 0 ; i < n ; i + + ) { <nl> + View child = finalListView . getChildAt ( i ) ; <nl> + child . setAlpha ( 0 ) ; <nl> + int s = Math . min ( finalListView . getMeasuredHeight ( ) , Math . max ( 0 , child . getTop ( ) ) ) ; <nl> + int delay = ( int ) ( ( s / ( float ) finalListView . getMeasuredHeight ( ) ) * 100 ) ; <nl> + ObjectAnimator a = ObjectAnimator . ofFloat ( child , View . ALPHA , 0 , 1f ) ; <nl> + a . setStartDelay ( delay ) ; <nl> + a . setDuration ( 200 ) ; <nl> + animatorSet . playTogether ( a ) ; <nl> + } <nl> + animatorSet . start ( ) ; <nl> + return true ; <nl> + } <nl> + } ) ; <nl> + } <nl> } <nl> scrolling = true ; <nl> for ( int a = 0 ; a < mediaPages . length ; a + + ) { <nl> if ( mediaPages [ a ] . selectedType = = type ) { <nl> if ( ! sharedMediaData [ type ] . loading ) { <nl> if ( mediaPages [ a ] . progressView ! = null ) { <nl> - mediaPages [ a ] . progressView . setVisibility ( View . GONE ) ; <nl> + View v = mediaPages [ a ] . progressView ; <nl> + v . animate ( ) . alpha ( 0 ) . setListener ( new AnimatorListenerAdapter ( ) { <nl> + @ Override <nl> + public void onAnimationEnd ( Animator animation ) { <nl> + v . setAlpha ( 1f ) ; <nl> + v . setVisibility ( View . GONE ) ; <nl> + } <nl> + } ) ; <nl> } <nl> if ( mediaPages [ a ] . listView ! = null ) { <nl> if ( mediaPages [ a ] . listView . getEmptyView ( ) = = null ) { <nl> private void getChats ( int max_id , final int count ) { <nl> } else { <nl> endReached = true ; <nl> } <nl> - loading = false ; <nl> - firstLoaded = true ; <nl> + <nl> for ( int a = 0 ; a < mediaPages . length ; a + + ) { <nl> if ( mediaPages [ a ] . selectedType = = 6 ) { <nl> if ( mediaPages [ a ] . progressView ! = null ) { <nl> - mediaPages [ a ] . progressView . setVisibility ( View . GONE ) ; <nl> + View v = mediaPages [ a ] . progressView ; <nl> + v . animate ( ) . alpha ( 0 ) . setListener ( new AnimatorListenerAdapter ( ) { <nl> + @ Override <nl> + public void onAnimationEnd ( Animator animation ) { <nl> + v . setAlpha ( 1f ) ; <nl> + v . setVisibility ( View . GONE ) ; <nl> + } <nl> + } ) ; <nl> } <nl> if ( mediaPages [ a ] . listView ! = null ) { <nl> if ( mediaPages [ a ] . listView . getEmptyView ( ) = = null ) { <nl> mediaPages [ a ] . listView . setEmptyView ( mediaPages [ a ] . emptyView ) ; <nl> } <nl> + final RecyclerListView listView = mediaPages [ a ] . listView ; <nl> + if ( firstLoaded ) { <nl> + if ( listView ! = null ) { <nl> + getViewTreeObserver ( ) . addOnPreDrawListener ( new ViewTreeObserver . OnPreDrawListener ( ) { <nl> + @ Override <nl> + public boolean onPreDraw ( ) { <nl> + getViewTreeObserver ( ) . removeOnPreDrawListener ( this ) ; <nl> + int n = listView . getChildCount ( ) ; <nl> + AnimatorSet animatorSet = new AnimatorSet ( ) ; <nl> + for ( int i = 0 ; i < n ; i + + ) { <nl> + View child = listView . getChildAt ( i ) ; <nl> + child . setAlpha ( 0 ) ; <nl> + int s = Math . min ( listView . getMeasuredHeight ( ) , Math . max ( 0 , child . getTop ( ) ) ) ; <nl> + int delay = ( int ) ( ( s / ( float ) listView . getMeasuredHeight ( ) ) * 100 ) ; <nl> + ObjectAnimator a = ObjectAnimator . ofFloat ( child , View . ALPHA , 0 , 1f ) ; <nl> + a . setStartDelay ( delay ) ; <nl> + a . setDuration ( 200 ) ; <nl> + animatorSet . playTogether ( a ) ; <nl> + } <nl> + animatorSet . start ( ) ; <nl> + return true ; <nl> + } <nl> + } ) ; <nl> + } <nl> + } <nl> } <nl> } <nl> } <nl> + loading = false ; <nl> + firstLoaded = true ; <nl> notifyDataSetChanged ( ) ; <nl> } ) ) ; <nl> profileActivity . getConnectionsManager ( ) . bindRequestToGuid ( reqId , profileActivity . getClassGuid ( ) ) ; <nl> public int getItemViewType ( int i ) { <nl> arrayList . add ( new ThemeDescription ( mediaPages [ a ] . listView , ThemeDescription . FLAG_LISTGLOWCOLOR , null , null , null , null , Theme . key_actionBarDefault ) ) ; <nl> arrayList . add ( new ThemeDescription ( mediaPages [ a ] . listView , ThemeDescription . FLAG_SELECTOR , null , null , null , null , Theme . key_listSelector ) ) ; <nl> arrayList . add ( new ThemeDescription ( mediaPages [ a ] . emptyView , ThemeDescription . FLAG_TEXTCOLOR , null , null , null , null , Theme . key_emptyListPlaceholder ) ) ; <nl> - <nl> - arrayList . add ( new ThemeDescription ( mediaPages [ a ] . progressBar , ThemeDescription . FLAG_PROGRESSBAR , null , null , null , null , Theme . key_progressCircle ) ) ; <nl> - <nl> arrayList . add ( new ThemeDescription ( mediaPages [ a ] . emptyTextView , ThemeDescription . FLAG_TEXTCOLOR , null , null , null , null , Theme . key_windowBackgroundWhiteGrayText2 ) ) ; <nl> <nl> arrayList . add ( new ThemeDescription ( mediaPages [ a ] . listView , ThemeDescription . FLAG_SECTIONS , new Class [ ] { GraySectionCell . class } , new String [ ] { " textView " } , null , null , null , Theme . key_graySectionText ) ) ; <nl> mmm a / TMessagesProj / src / main / java / org / telegram / ui / ContactsActivity . java <nl> ppp b / TMessagesProj / src / main / java / org / telegram / ui / ContactsActivity . java <nl> public void setPadding ( int left , int top , int right , int bottom ) { <nl> String str = ( String ) object ; <nl> if ( ! str . equals ( " section " ) ) { <nl> NewContactActivity activity = new NewContactActivity ( ) ; <nl> - activity . setInitialPhoneNumber ( str ) ; <nl> + activity . setInitialPhoneNumber ( str , true ) ; <nl> presentFragment ( activity ) ; <nl> } <nl> } <nl> mmm a / TMessagesProj / src / main / java / org / telegram / ui / DialogsActivity . java <nl> ppp b / TMessagesProj / src / main / java / org / telegram / ui / DialogsActivity . java <nl> protected boolean canUndo ( ) { <nl> <nl> updateFilterTabs ( false ) ; <nl> <nl> + if ( folderId ! = 0 ) { <nl> + FiltersView . MediaFilterData filterData = new FiltersView . MediaFilterData ( R . drawable . chats_archive , R . drawable . chats_archive , LocaleController . getString ( " Archive " , R . string . Archive ) , null , FiltersView . FILTER_TYPE_ARCHIVE ) ; <nl> + filterData . removable = false ; <nl> + actionBar . setSearchFilter ( filterData ) ; <nl> + searchItem . collapseSearchFilters ( ) ; <nl> + } <nl> + <nl> return fragmentView ; <nl> } <nl> <nl> private void updateContextViewPosition ( ) { <nl> searchTabsHeight = searchTabsView . getMeasuredHeight ( ) ; <nl> } <nl> if ( fragmentContextView ! = null ) { <nl> - fragmentContextView . setTranslationY ( topPadding + actionBar . getTranslationY ( ) + filtersTabsHeight * ( 1f - searchAnimationProgress ) + searchTabsHeight * searchAnimationProgress ) ; <nl> + float from = 0 ; <nl> + if ( fragmentLocationContextView ! = null & & fragmentLocationContextView . getVisibility ( ) = = View . VISIBLE ) { <nl> + from + = AndroidUtilities . dp ( 36 ) ; <nl> + } <nl> + fragmentContextView . setTranslationY ( from + fragmentContextView . getTopPadding ( ) + actionBar . getTranslationY ( ) + filtersTabsHeight * ( 1f - searchAnimationProgress ) + searchTabsHeight * searchAnimationProgress ) ; <nl> } <nl> if ( fragmentLocationContextView ! = null ) { <nl> - fragmentLocationContextView . setTranslationY ( topPadding + actionBar . getTranslationY ( ) + filtersTabsHeight * ( 1f - searchAnimationProgress ) + searchTabsHeight * searchAnimationProgress ) ; <nl> + float from = 0 ; <nl> + if ( fragmentContextView ! = null ) { <nl> + from + = fragmentContextView . getTopPadding ( ) ; <nl> + } <nl> + fragmentLocationContextView . setTranslationY ( from + fragmentLocationContextView . getTopPadding ( ) + actionBar . getTranslationY ( ) + filtersTabsHeight * ( 1f - searchAnimationProgress ) + searchTabsHeight * searchAnimationProgress ) ; <nl> } <nl> } <nl> <nl> private void showSearch ( boolean show , boolean animated ) { <nl> searchTabsView . hide ( false , false ) ; <nl> searchTabsView . setVisibility ( View . VISIBLE ) ; <nl> } <nl> + searchItem . getSearchContainer ( ) . setAlpha ( 0f ) ; <nl> } else { <nl> viewPages [ 0 ] . listView . setVisibility ( View . VISIBLE ) ; <nl> viewPages [ 0 ] . setVisibility ( View . VISIBLE ) ; <nl> public void onAnimationEnd ( Animator animation ) { <nl> AndroidUtilities . requestAdjustResize ( getParentActivity ( ) , classGuid ) ; <nl> searchItem . setVisibility ( View . GONE ) ; <nl> } else { <nl> + searchItem . collapseSearchFilters ( ) ; <nl> whiteActionBar = false ; <nl> searchViewPager . setVisibility ( View . GONE ) ; <nl> if ( searchTabsView ! = null ) { <nl> private void onItemClick ( View view , int position , RecyclerListView . Adapter adapt <nl> actionBar . openSearchField ( str , false ) ; <nl> } else if ( ! str . equals ( " section " ) ) { <nl> NewContactActivity activity = new NewContactActivity ( ) ; <nl> - activity . setInitialPhoneNumber ( str ) ; <nl> + activity . setInitialPhoneNumber ( str , true ) ; <nl> presentFragment ( activity ) ; <nl> } <nl> } <nl> mmm a / TMessagesProj / src / main / java / org / telegram / ui / FilteredSearchView . java <nl> ppp b / TMessagesProj / src / main / java / org / telegram / ui / FilteredSearchView . java <nl> public void onLongClickRelease ( ) { <nl> recyclerListView . setLayoutManager ( layoutManager ) ; <nl> addView ( loadingView = new LoadingView ( context ) { <nl> @ Override <nl> - int getType ( ) { <nl> + public int getType ( ) { <nl> if ( currentSearchFilter = = null ) { <nl> return 1 ; <nl> } else if ( currentSearchFilter . filterType = = FiltersView . FILTER_TYPE_MEDIA ) { <nl> int getType ( ) { <nl> } <nl> <nl> @ Override <nl> - int getColumnsCount ( ) { <nl> + public int getColumnsCount ( ) { <nl> return columnsCount ; <nl> } <nl> } ) ; <nl> public void search ( int dialogId , long minDate , long maxDate , FiltersView . MediaFi <nl> } <nl> <nl> if ( ! filterAndQueryIsSame ) { <nl> - / / if ( ! filterAndQueryIsSame | | TextUtils . isEmpty ( query ) ) { <nl> clearCurrentResultsRunnable . run ( ) ; <nl> - / / } else { <nl> - / / AndroidUtilities . runOnUIThread ( clearCurrentResultsRunnable , 1000 ) ; <nl> - / / } <nl> emptyView . showProgress ( true , ! clearOldResults ) ; <nl> } <nl> <nl> public void search ( int dialogId , long minDate , long maxDate , FiltersView . MediaFi <nl> boolean found = false ; <nl> for ( int i = 0 ; i < localTipChats . size ( ) ; i + + ) { <nl> if ( localTipChats . get ( i ) instanceof TLRPC . User ) <nl> - if ( UserConfig . getInstance ( UserConfig . selectedAccount ) . getCurrentUser ( ) . id = = ( ( TLRPC . User ) localTipChats . get ( i ) ) . id ) { <nl> - found = true ; <nl> - break ; <nl> - } <nl> + if ( UserConfig . getInstance ( UserConfig . selectedAccount ) . getCurrentUser ( ) . id = = ( ( TLRPC . User ) localTipChats . get ( i ) ) . id ) { <nl> + found = true ; <nl> + break ; <nl> + } <nl> } <nl> if ( ! found ) { <nl> localTipChats . add ( 0 , UserConfig . getInstance ( UserConfig . selectedAccount ) . getCurrentUser ( ) ) ; <nl> public boolean isEnabled ( RecyclerView . ViewHolder holder ) { <nl> View view ; <nl> switch ( viewType ) { <nl> case 0 : <nl> - view = new SharedPhotoVideoCell ( mContext , SharedPhotoVideoCell . VIEW_TYPE_GLOBAL_SEARCH ) ; <nl> + view = new SharedPhotoVideoCell ( mContext , SharedPhotoVideoCell . VIEW_TYPE_GLOBAL_SEARCH ) ; <nl> SharedPhotoVideoCell cell = ( SharedPhotoVideoCell ) view ; <nl> cell . setDelegate ( new SharedPhotoVideoCell . SharedPhotoVideoCellDelegate ( ) { <nl> @ Override <nl> public void setUiCallback ( UiCallback callback ) { <nl> <nl> public interface UiCallback { <nl> void goToMessage ( MessageObject messageObject ) ; <nl> + <nl> boolean actionModeShowing ( ) ; <nl> + <nl> void toggleItemSelection ( MessageObject item , View view , int a ) ; <nl> + <nl> boolean isSelected ( MessageHashId messageHashId ) ; <nl> + <nl> void showActionMode ( ) ; <nl> + <nl> int getFolderId ( ) ; <nl> } <nl> <nl> public void setUiCallback ( UiCallback callback ) { <nl> int color0 ; <nl> int color1 ; <nl> <nl> - int getType ( ) { <nl> + public int getType ( ) { <nl> return 1 ; <nl> } <nl> <nl> - int getColumnsCount ( ) { <nl> + public int getColumnsCount ( ) { <nl> return 2 ; <nl> } <nl> <nl> protected void onDraw ( Canvas canvas ) { <nl> int h = 0 ; <nl> while ( h < getMeasuredHeight ( ) ) { <nl> int r = AndroidUtilities . dp ( 25 ) ; <nl> - canvas . drawCircle ( AndroidUtilities . dp ( 9 ) + r , h + ( AndroidUtilities . dp ( 78 ) > > 1 ) , r , paint ) ; <nl> + canvas . drawCircle ( checkRtl ( AndroidUtilities . dp ( 9 ) + r ) , h + ( AndroidUtilities . dp ( 78 ) > > 1 ) , r , paint ) ; <nl> <nl> rectF . set ( AndroidUtilities . dp ( 68 ) , h + AndroidUtilities . dp ( 20 ) , AndroidUtilities . dp ( 140 ) , h + AndroidUtilities . dp ( 28 ) ) ; <nl> + checkRtl ( rectF ) ; <nl> canvas . drawRoundRect ( rectF , AndroidUtilities . dp ( 4 ) , AndroidUtilities . dp ( 4 ) , paint ) ; <nl> <nl> rectF . set ( AndroidUtilities . dp ( 68 ) , h + AndroidUtilities . dp ( 42 ) , AndroidUtilities . dp ( 260 ) , h + AndroidUtilities . dp ( 50 ) ) ; <nl> + checkRtl ( rectF ) ; <nl> canvas . drawRoundRect ( rectF , AndroidUtilities . dp ( 4 ) , AndroidUtilities . dp ( 4 ) , paint ) ; <nl> <nl> rectF . set ( getMeasuredWidth ( ) - AndroidUtilities . dp ( 50 ) , h + AndroidUtilities . dp ( 20 ) , getMeasuredWidth ( ) - AndroidUtilities . dp ( 12 ) , h + AndroidUtilities . dp ( 28 ) ) ; <nl> + checkRtl ( rectF ) ; <nl> canvas . drawRoundRect ( rectF , AndroidUtilities . dp ( 4 ) , AndroidUtilities . dp ( 4 ) , paint ) ; <nl> <nl> h + = AndroidUtilities . dp ( 78 ) + 1 ; <nl> protected void onDraw ( Canvas canvas ) { <nl> int h = 0 ; <nl> while ( h < getMeasuredHeight ( ) ) { <nl> rectF . set ( AndroidUtilities . dp ( 12 ) , h + AndroidUtilities . dp ( 8 ) , AndroidUtilities . dp ( 52 ) , h + AndroidUtilities . dp ( 48 ) ) ; <nl> + checkRtl ( rectF ) ; <nl> canvas . drawRoundRect ( rectF , AndroidUtilities . dp ( 4 ) , AndroidUtilities . dp ( 4 ) , paint ) ; <nl> <nl> rectF . set ( AndroidUtilities . dp ( 68 ) , h + AndroidUtilities . dp ( 12 ) , AndroidUtilities . dp ( 140 ) , h + AndroidUtilities . dp ( 20 ) ) ; <nl> + checkRtl ( rectF ) ; <nl> canvas . drawRoundRect ( rectF , AndroidUtilities . dp ( 4 ) , AndroidUtilities . dp ( 4 ) , paint ) ; <nl> <nl> rectF . set ( AndroidUtilities . dp ( 68 ) , h + AndroidUtilities . dp ( 34 ) , AndroidUtilities . dp ( 260 ) , h + AndroidUtilities . dp ( 42 ) ) ; <nl> + checkRtl ( rectF ) ; <nl> canvas . drawRoundRect ( rectF , AndroidUtilities . dp ( 4 ) , AndroidUtilities . dp ( 4 ) , paint ) ; <nl> <nl> rectF . set ( getMeasuredWidth ( ) - AndroidUtilities . dp ( 50 ) , h + AndroidUtilities . dp ( 12 ) , getMeasuredWidth ( ) - AndroidUtilities . dp ( 12 ) , h + AndroidUtilities . dp ( 20 ) ) ; <nl> + checkRtl ( rectF ) ; <nl> canvas . drawRoundRect ( rectF , AndroidUtilities . dp ( 4 ) , AndroidUtilities . dp ( 4 ) , paint ) ; <nl> <nl> h + = AndroidUtilities . dp ( 56 ) + 1 ; <nl> protected void onDraw ( Canvas canvas ) { <nl> int h = 0 ; <nl> while ( h < getMeasuredHeight ( ) ) { <nl> int radius = AndroidUtilities . dp ( 44 ) > > 1 ; <nl> - canvas . drawCircle ( AndroidUtilities . dp ( 12 ) + radius , h + AndroidUtilities . dp ( 6 ) + radius , radius , paint ) ; <nl> + canvas . drawCircle ( checkRtl ( AndroidUtilities . dp ( 12 ) + radius ) , h + AndroidUtilities . dp ( 6 ) + radius , radius , paint ) ; <nl> <nl> rectF . set ( AndroidUtilities . dp ( 68 ) , h + AndroidUtilities . dp ( 12 ) , AndroidUtilities . dp ( 140 ) , h + AndroidUtilities . dp ( 20 ) ) ; <nl> + checkRtl ( rectF ) ; <nl> canvas . drawRoundRect ( rectF , AndroidUtilities . dp ( 4 ) , AndroidUtilities . dp ( 4 ) , paint ) ; <nl> <nl> rectF . set ( AndroidUtilities . dp ( 68 ) , h + AndroidUtilities . dp ( 34 ) , AndroidUtilities . dp ( 260 ) , h + AndroidUtilities . dp ( 42 ) ) ; <nl> + checkRtl ( rectF ) ; <nl> canvas . drawRoundRect ( rectF , AndroidUtilities . dp ( 4 ) , AndroidUtilities . dp ( 4 ) , paint ) ; <nl> <nl> rectF . set ( getMeasuredWidth ( ) - AndroidUtilities . dp ( 50 ) , h + AndroidUtilities . dp ( 12 ) , getMeasuredWidth ( ) - AndroidUtilities . dp ( 12 ) , h + AndroidUtilities . dp ( 20 ) ) ; <nl> + checkRtl ( rectF ) ; <nl> canvas . drawRoundRect ( rectF , AndroidUtilities . dp ( 4 ) , AndroidUtilities . dp ( 4 ) , paint ) ; <nl> <nl> h + = AndroidUtilities . dp ( 56 ) + 1 ; <nl> protected void onDraw ( Canvas canvas ) { <nl> int h = 0 ; <nl> while ( h < getMeasuredHeight ( ) ) { <nl> rectF . set ( AndroidUtilities . dp ( 10 ) , h + AndroidUtilities . dp ( 11 ) , AndroidUtilities . dp ( 62 ) , h + AndroidUtilities . dp ( 11 + 52 ) ) ; <nl> + checkRtl ( rectF ) ; <nl> canvas . drawRoundRect ( rectF , AndroidUtilities . dp ( 4 ) , AndroidUtilities . dp ( 4 ) , paint ) ; <nl> <nl> rectF . set ( AndroidUtilities . dp ( 68 ) , h + AndroidUtilities . dp ( 12 ) , AndroidUtilities . dp ( 140 ) , h + AndroidUtilities . dp ( 20 ) ) ; <nl> + checkRtl ( rectF ) ; <nl> canvas . drawRoundRect ( rectF , AndroidUtilities . dp ( 4 ) , AndroidUtilities . dp ( 4 ) , paint ) ; <nl> <nl> rectF . set ( AndroidUtilities . dp ( 68 ) , h + AndroidUtilities . dp ( 34 ) , AndroidUtilities . dp ( 268 ) , h + AndroidUtilities . dp ( 42 ) ) ; <nl> + checkRtl ( rectF ) ; <nl> canvas . drawRoundRect ( rectF , AndroidUtilities . dp ( 4 ) , AndroidUtilities . dp ( 4 ) , paint ) ; <nl> <nl> rectF . set ( AndroidUtilities . dp ( 68 ) , h + AndroidUtilities . dp ( 34 + 20 ) , AndroidUtilities . dp ( 120 + 68 ) , h + AndroidUtilities . dp ( 42 + 20 ) ) ; <nl> + checkRtl ( rectF ) ; <nl> canvas . drawRoundRect ( rectF , AndroidUtilities . dp ( 4 ) , AndroidUtilities . dp ( 4 ) , paint ) ; <nl> <nl> rectF . set ( getMeasuredWidth ( ) - AndroidUtilities . dp ( 50 ) , h + AndroidUtilities . dp ( 12 ) , getMeasuredWidth ( ) - AndroidUtilities . dp ( 12 ) , h + AndroidUtilities . dp ( 20 ) ) ; <nl> + checkRtl ( rectF ) ; <nl> canvas . drawRoundRect ( rectF , AndroidUtilities . dp ( 4 ) , AndroidUtilities . dp ( 4 ) , paint ) ; <nl> <nl> h + = AndroidUtilities . dp ( 80 ) ; <nl> protected void onDraw ( Canvas canvas ) { <nl> gradient . setLocalMatrix ( matrix ) ; <nl> invalidate ( ) ; <nl> } <nl> + <nl> + private float checkRtl ( float x ) { <nl> + if ( LocaleController . isRTL ) { <nl> + return getMeasuredWidth ( ) - x ; <nl> + } <nl> + return x ; <nl> + } <nl> + <nl> + private void checkRtl ( RectF rectF ) { <nl> + if ( LocaleController . isRTL ) { <nl> + rectF . left = getMeasuredWidth ( ) - rectF . left ; <nl> + rectF . right = getMeasuredWidth ( ) - rectF . right ; <nl> + } <nl> + } <nl> } <nl> <nl> private void showFloatingDateView ( ) { <nl> mmm a / TMessagesProj / src / main / java / org / telegram / ui / LaunchActivity . java <nl> ppp b / TMessagesProj / src / main / java / org / telegram / ui / LaunchActivity . java <nl> private boolean handleIntent ( Intent intent , boolean isNew , boolean restore , bool <nl> fragment . setInitialName ( names [ 0 ] , names . length > 1 ? names [ 1 ] : null ) ; <nl> } <nl> if ( newContactPhone ! = null ) { <nl> - fragment . setInitialPhoneNumber ( PhoneFormat . stripExceptNumbers ( newContactPhone ) ) ; <nl> + fragment . setInitialPhoneNumber ( PhoneFormat . stripExceptNumbers ( newContactPhone , true ) , false ) ; <nl> } <nl> actionBarLayout . presentFragment ( fragment , false , true , true , false ) ; <nl> if ( AndroidUtilities . isTablet ( ) ) { <nl> mmm a / TMessagesProj / src / main / java / org / telegram / ui / NewContactActivity . java <nl> ppp b / TMessagesProj / src / main / java / org / telegram / ui / NewContactActivity . java <nl> <nl> private boolean ignoreSelection ; <nl> private boolean donePressed ; <nl> private String initialPhoneNumber ; <nl> + private boolean initialPhoneNumberWithCountryCode ; <nl> private String initialFirstName ; <nl> private String initialLastName ; <nl> <nl> public void afterTextChanged ( Editable s ) { <nl> Collections . sort ( countriesArray , String : : compareTo ) ; <nl> <nl> if ( ! TextUtils . isEmpty ( initialPhoneNumber ) ) { <nl> - codeField . setText ( initialPhoneNumber ) ; <nl> + TLRPC . User user = getUserConfig ( ) . getCurrentUser ( ) ; <nl> + if ( initialPhoneNumber . startsWith ( " + " ) ) { <nl> + codeField . setText ( initialPhoneNumber . substring ( 1 ) ) ; <nl> + } else if ( initialPhoneNumberWithCountryCode | | user = = null | | TextUtils . isEmpty ( user . phone ) ) { <nl> + codeField . setText ( initialPhoneNumber ) ; <nl> + } else { <nl> + String phone = user . phone ; <nl> + for ( int a = 4 ; a > = 1 ; a - - ) { <nl> + String sub = phone . substring ( 0 , a ) ; <nl> + String country = codesMap . get ( sub ) ; <nl> + if ( country ! = null ) { <nl> + codeField . setText ( sub ) ; <nl> + break ; <nl> + } <nl> + } <nl> + phoneField . setText ( initialPhoneNumber ) ; <nl> + } <nl> initialPhoneNumber = null ; <nl> } else { <nl> String country = null ; <nl> public void onTransitionAnimationEnd ( boolean isOpen , boolean backward ) { <nl> } <nl> } <nl> <nl> - public void setInitialPhoneNumber ( String value ) { <nl> + public void setInitialPhoneNumber ( String value , boolean withCoutryCode ) { <nl> initialPhoneNumber = value ; <nl> + initialPhoneNumberWithCountryCode = withCoutryCode ; <nl> } <nl> <nl> public void setInitialName ( String firstName , String lastName ) { <nl> mmm a / TMessagesProj / src / main / java / org / telegram / ui / PhotoViewer . java <nl> ppp b / TMessagesProj / src / main / java / org / telegram / ui / PhotoViewer . java <nl> private boolean supportsSendingNewEntities ( ) { <nl> } <nl> <nl> private void closeCaptionEnter ( boolean apply ) { <nl> - if ( currentIndex < 0 | | currentIndex > = imagesArrLocals . size ( ) ) { <nl> + if ( currentIndex < 0 | | currentIndex > = imagesArrLocals . size ( ) | | captionEditText . getTag ( ) = = null ) { <nl> return ; <nl> } <nl> Object object = imagesArrLocals . get ( currentIndex ) ; <nl> private void setIsAboutToSwitchToIndex ( int index , boolean init , boolean animateC <nl> setItemVisible ( masksItem , shouldMasksItemBeVisible , ! pipItemVisible ) ; <nl> } <nl> final boolean shouldAutoPlayed = shouldMessageObjectAutoPlayed ( newMessageObject ) ; <nl> - if ( ! shouldAutoPlayed ) { <nl> + if ( ! shouldAutoPlayed & & TextUtils . isEmpty ( placeProvider . getTitleFor ( switchingToIndex ) ) ) { <nl> final boolean animated = ! playerWasPlaying ; <nl> if ( nameOverride ! = null ) { <nl> nameTextView . setText ( nameOverride ) ; <nl> private void setIsAboutToSwitchToIndex ( int index , boolean init , boolean animateC <nl> loadingMoreImages = true ; <nl> } <nl> } <nl> - CharSequence title = placeProvider . getTitleFor ( switchingToIndex ) ; <nl> + CharSequence title = placeProvider . getTitleFor ( switchingToIndex ) ; <nl> if ( title ! = null ) { <nl> actionBar . setTitle ( title ) ; <nl> CharSequence subtitle = placeProvider . getSubtitleFor ( switchingToIndex ) ; <nl> mmm a / TMessagesProj / src / main / java / org / telegram / ui / ProfileActivity . java <nl> ppp b / TMessagesProj / src / main / java / org / telegram / ui / ProfileActivity . java <nl> public void getOutline ( View view , Outline outline ) { <nl> } <nl> frameLayout . addView ( writeButton , LayoutHelper . createFrame ( Build . VERSION . SDK_INT > = 21 ? 56 : 60 , Build . VERSION . SDK_INT > = 21 ? 56 : 60 , Gravity . RIGHT | Gravity . TOP , 0 , 0 , 16 , 0 ) ) ; <nl> writeButton . setOnClickListener ( v - > { <nl> + if ( writeButton . getTag ( ) ! = null ) { <nl> + return ; <nl> + } <nl> if ( user_id ! = 0 ) { <nl> if ( imageUpdater ! = null ) { <nl> TLRPC . User user = MessagesController . getInstance ( currentAccount ) . getUser ( UserConfig . getInstance ( currentAccount ) . getClientUserId ( ) ) ; <nl> private void updateRowsIds ( ) { <nl> } <nl> } else if ( chat_id ! = 0 ) { <nl> if ( chatInfo ! = null & & ( ! TextUtils . isEmpty ( chatInfo . about ) | | chatInfo . location instanceof TLRPC . TL_channelLocation ) | | ! TextUtils . isEmpty ( currentChat . username ) ) { <nl> - if ( LocaleController . isRTL & & ChatObject . isChannel ( currentChat ) & & ! currentChat . megagroup & & chatInfo . linked_chat_id ! = 0 ) { <nl> + if ( LocaleController . isRTL & & ChatObject . isChannel ( currentChat ) & & chatInfo ! = null & & ! currentChat . megagroup & & chatInfo . linked_chat_id ! = 0 ) { <nl> emptyRow = rowCount + + ; <nl> } <nl> infoHeaderRow = rowCount + + ; <nl> mmm a / TMessagesProj / src / main / java / org / telegram / ui / ViewPagerFixed . java <nl> ppp b / TMessagesProj / src / main / java / org / telegram / ui / ViewPagerFixed . java <nl> <nl> import android . graphics . Bitmap ; <nl> import android . graphics . Canvas ; <nl> import android . graphics . Paint ; <nl> + import android . graphics . Rect ; <nl> import android . graphics . RectF ; <nl> import android . graphics . drawable . Drawable ; <nl> import android . graphics . drawable . GradientDrawable ; <nl> public void onAnimationUpdate ( ValueAnimator valueAnimator ) { <nl> } <nl> } <nl> } ; <nl> + private Rect rect = new Rect ( ) ; <nl> <nl> public ViewPagerFixed ( @ NonNull Context context ) { <nl> super ( context ) ; <nl> public boolean onTouchEvent ( MotionEvent ev ) { <nl> velocityTracker . addMovement ( ev ) ; <nl> } <nl> if ( ev ! = null & & ev . getAction ( ) = = MotionEvent . ACTION_DOWN & & checkTabsAnimationInProgress ( ) ) { <nl> + View child = findScrollingChild ( this , ev . getX ( ) , ev . getY ( ) ) ; <nl> + if ( child ! = null & & ( child . canScrollHorizontally ( 1 ) | | child . canScrollHorizontally ( - 1 ) ) ) { <nl> + return false ; <nl> + } <nl> startedTracking = true ; <nl> startedTrackingPointerId = ev . getPointerId ( 0 ) ; <nl> startedTrackingX = ( int ) ev . getX ( ) ; <nl> public boolean canScrollHorizontally ( int direction ) { <nl> if ( direction = = 0 ) { <nl> return false ; <nl> } <nl> - if ( tabsAnimationInProgress ) { <nl> + if ( tabsAnimationInProgress | | startedTracking ) { <nl> return true ; <nl> } <nl> boolean forward = direction > 0 ; <nl> public void hide ( boolean hide , boolean animated ) { <nl> } <nl> } <nl> <nl> + private View findScrollingChild ( ViewGroup parent , float x , float y ) { <nl> + int n = parent . getChildCount ( ) ; <nl> + for ( int i = 0 ; i < n ; i + + ) { <nl> + View child = parent . getChildAt ( i ) ; <nl> + if ( child . getVisibility ( ) ! = View . VISIBLE ) { <nl> + continue ; <nl> + } <nl> + child . getHitRect ( rect ) ; <nl> + if ( rect . contains ( ( int ) x , ( int ) y ) ) { <nl> + if ( child . canScrollHorizontally ( - 1 ) ) { <nl> + return child ; <nl> + } else if ( child instanceof ViewGroup ) { <nl> + View v = findScrollingChild ( ( ViewGroup ) child , x - rect . left , y - rect . top ) ; <nl> + if ( v ! = null ) { <nl> + return v ; <nl> + } <nl> + } <nl> + } <nl> + } <nl> + return null ; <nl> + } <nl> + <nl> <nl> } <nl> | Update to 7 . 1 . 2 ( 2098 ) | DrKLO/Telegram | 75d0903666098ce22ae7f0eaf3bc7e935486b656 | 2020-10-02T21:48:16Z |
mmm a / ports / glfw3 / portfile . cmake <nl> ppp b / ports / glfw3 / portfile . cmake <nl> if ( NOT EXISTS $ { CURRENT_BUILDTREES_DIR } / patch . stamp ) <nl> string ( REPLACE " \ " @ GLFW_LIB_NAME @ \ " " " NAMES @ GLFW_LIB_NAME @ @ GLFW_LIB_NAME @ dll " <nl> CONFIG $ { CONFIG } <nl> ) <nl> - string ( REPLACE " @ PACKAGE_CMAKE_INSTALL_PREFIX @ " " @ PACKAGE_CMAKE_INSTALL_PREFIX @ / . . / . . " <nl> - CONFIG $ { CONFIG } <nl> - ) <nl> + # string ( REPLACE " @ PACKAGE_CMAKE_INSTALL_PREFIX @ " " @ PACKAGE_CMAKE_INSTALL_PREFIX @ / . . / . . " <nl> + # CONFIG $ { CONFIG } <nl> + # ) <nl> file ( WRITE $ { SOURCE_PATH } / src / glfw3Config . cmake . in $ { CONFIG } ) <nl> file ( APPEND $ { SOURCE_PATH } / src / glfw3Config . cmake . in " set ( GLFW3_LIBRARIES \ $ { GLFW3_LIBRARY } ) \ n " ) <nl> file ( WRITE $ { CURRENT_BUILDTREES_DIR } / patch . stamp ) <nl> file ( MAKE_DIRECTORY $ { CURRENT_PACKAGES_DIR } / share ) <nl> file ( RENAME $ { CURRENT_PACKAGES_DIR } / lib / cmake / glfw3 $ { CURRENT_PACKAGES_DIR } / share / glfw3 ) <nl> file ( REMOVE_RECURSE $ { CURRENT_PACKAGES_DIR } / lib / cmake ) <nl> file ( READ $ { CURRENT_PACKAGES_DIR } / share / glfw3 / glfw3Targets . cmake _contents ) <nl> - string ( REPLACE " get_filename_component ( _IMPORT_PREFIX \ " \ $ { _IMPORT_PREFIX } \ " PATH ) \ n \ n " " \ n " _contents " $ { _contents } " ) <nl> + set ( pattern " get_filename_component ( _IMPORT_PREFIX \ " \ $ { _IMPORT_PREFIX } \ " PATH ) \ n " ) <nl> + string ( REPLACE " $ { pattern } $ { pattern } $ { pattern } " " $ { pattern } $ { pattern } " _contents " $ { _contents } " ) <nl> file ( WRITE $ { CURRENT_PACKAGES_DIR } / share / glfw3 / glfw3Targets . cmake $ { _contents } ) <nl> <nl> file ( READ $ { CURRENT_PACKAGES_DIR } / debug / lib / cmake / glfw3 / glfw3Targets - debug . cmake _contents ) <nl> | more glfw3 path fixes | microsoft/vcpkg | 21c4404d393ec7fdb6513eaba01e63073e5f8e33 | 2016-11-17T00:08:47Z |
mmm a / build / deps / github_hashes / facebook / fbthrift - rev . txt <nl> ppp b / build / deps / github_hashes / facebook / fbthrift - rev . txt <nl> @ @ - 1 + 1 @ @ <nl> - Subproject commit 3515c4dc537bb20f413cb0b87e74b742d6e3a618 <nl> + Subproject commit 661419ea85075502860d2779114009299ff8d62d <nl> mmm a / build / deps / github_hashes / facebook / folly - rev . txt <nl> ppp b / build / deps / github_hashes / facebook / folly - rev . txt <nl> @ @ - 1 + 1 @ @ <nl> - Subproject commit e305694f96abe27de30e6a126cfc7cef3f5fd0d8 <nl> + Subproject commit f29868766b689ff9c50c35c4789a621af624a28d <nl> mmm a / build / deps / github_hashes / facebook / wangle - rev . txt <nl> ppp b / build / deps / github_hashes / facebook / wangle - rev . txt <nl> @ @ - 1 + 1 @ @ <nl> - Subproject commit 1051ecc5c616f2cb2214784169e3a364de616bd3 <nl> + Subproject commit aa8fb1a1943071c62295329c2f67e8ecbbd6a0bf <nl> | Updating submodules | facebook/watchman | cc565a1eb9f1923cdd971d8a664aa3b3c8a19847 | 2019-09-29T18:22:45Z |
mmm a / src / core / support / slice . c <nl> ppp b / src / core / support / slice . c <nl> <nl> * <nl> * / <nl> <nl> - # include < sys / types . h > <nl> - <nl> # include < grpc / support / alloc . h > <nl> # include < grpc / support / log . h > <nl> # include < grpc / support / slice . h > <nl> gpr_slice gpr_slice_split_head ( gpr_slice * source , size_t split ) { <nl> } <nl> <nl> int gpr_slice_cmp ( gpr_slice a , gpr_slice b ) { <nl> - ssize_t d = ( ssize_t ) ( GPR_SLICE_LENGTH ( a ) - GPR_SLICE_LENGTH ( b ) ) ; <nl> + int d = ( int ) ( GPR_SLICE_LENGTH ( a ) - GPR_SLICE_LENGTH ( b ) ) ; <nl> if ( d ! = 0 ) return d ; <nl> return memcmp ( GPR_SLICE_START_PTR ( a ) , GPR_SLICE_START_PTR ( b ) , <nl> GPR_SLICE_LENGTH ( a ) ) ; <nl> int gpr_slice_cmp ( gpr_slice a , gpr_slice b ) { <nl> <nl> int gpr_slice_str_cmp ( gpr_slice a , const char * b ) { <nl> size_t b_length = strlen ( b ) ; <nl> - ssize_t d = ( ssize_t ) ( GPR_SLICE_LENGTH ( a ) - b_length ) ; <nl> + int d = ( int ) ( GPR_SLICE_LENGTH ( a ) - b_length ) ; <nl> if ( d ! = 0 ) return d ; <nl> return memcmp ( GPR_SLICE_START_PTR ( a ) , b , b_length ) ; <nl> } <nl> | Reverted slice . c changes | grpc/grpc | 84976a70ce07f13c959e8630b5c10d4fbbace4d8 | 2015-06-22T22:07:23Z |
mmm a / stdlib / core / Arrays . swift . gyb <nl> ppp b / stdlib / core / Arrays . swift . gyb <nl> extension $ { Self } : _ArrayType { <nl> <nl> / / / Return $ { a_Self } containing the results of calling <nl> / / / ` transform ( x ) ` on each element ` x ` of ` self ` <nl> - public func map < U > ( transform : ( T ) - > U ) - > $ { Self } < U > { <nl> - / / ' transform ' should be @ noescape , but there ' s a compiler bug : <nl> + public func map < U > ( @ noescape transform : ( T ) - > U ) - > $ { Self } < U > { <nl> / / Should call Swift . map here , but there ' s a compiler bug : <nl> / / < rdar : / / problem / 19763792 > Calling Swift . map from Array . map causes <nl> / / Assertion failed : UnresolvedDot in wrong phase <nl> | stdlib : really mark the closure in map ( ) as @ noescape | apple/swift | c2bf39704f66c4ab7eb37f39c6e62dde0638fd80 | 2015-02-11T00:28:04Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.