1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
20 #include <sal/config.h>
22 #include <o3tl/safeint.hxx>
23 #include <o3tl/string_view.hxx>
24 #include <svx/fmtools.hxx>
25 #include <svx/fmsrccfg.hxx>
26 #include <tools/debug.hxx>
27 #include <comphelper/diagnose_ex.hxx>
28 #include <tools/wldcrd.hxx>
29 #include <vcl/svapp.hxx>
30 #include <unotools/textsearch.hxx>
31 #include <com/sun/star/awt/XTextComponent.hpp>
32 #include <com/sun/star/awt/XListBox.hpp>
33 #include <com/sun/star/awt/XCheckBox.hpp>
34 #include <com/sun/star/beans/XPropertySet.hpp>
35 #include <com/sun/star/container/XIndexAccess.hpp>
36 #include <com/sun/star/util/SearchAlgorithms2.hpp>
37 #include <com/sun/star/util/SearchFlags.hpp>
38 #include <com/sun/star/lang/Locale.hpp>
39 #include <com/sun/star/i18n/CollatorOptions.hpp>
41 #include <com/sun/star/sdb/XColumn.hpp>
42 #include <com/sun/star/sdbc/XConnection.hpp>
43 #include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
44 #include <com/sun/star/sdbcx/XColumnsSupplier.hpp>
47 #include <svx/fmsrcimp.hxx>
49 #include <comphelper/types.hxx>
50 #include <unotools/syslocale.hxx>
51 #include <i18nutil/searchopt.hxx>
53 #define EQUAL_BOOKMARKS(a, b) a == b
55 #define IFACECAST(c) static_cast<const Reference< XInterface >&>(c)
57 using namespace ::com::sun::star::uno
;
58 using namespace ::com::sun::star::util
;
59 using namespace ::com::sun::star::lang
;
60 using namespace ::com::sun::star::sdbc
;
61 using namespace ::com::sun::star::i18n
;
62 using namespace ::com::sun::star::beans
;
63 using namespace ::svxform
;
66 // = FmRecordCountListener
68 // SMART_UNO_IMPLEMENTATION(FmRecordCountListener, UsrObject);
71 FmRecordCountListener::FmRecordCountListener(const Reference
< css::sdbc::XResultSet
> & dbcCursor
)
74 m_xListening
.set(dbcCursor
, UNO_QUERY
);
75 if (!m_xListening
.is())
78 if (::comphelper::getBOOL(m_xListening
->getPropertyValue(FM_PROP_ROWCOUNTFINAL
)))
80 m_xListening
= nullptr;
81 // there's nothing to do as the record count is already known
85 m_xListening
->addPropertyChangeListener(FM_PROP_ROWCOUNT
, static_cast<css::beans::XPropertyChangeListener
*>(this));
89 void FmRecordCountListener::SetPropChangeHandler(const Link
<sal_Int32
,void>& lnk
)
91 m_lnkWhoWantsToKnow
= lnk
;
93 if (m_xListening
.is())
98 FmRecordCountListener::~FmRecordCountListener()
104 void FmRecordCountListener::DisConnect()
106 if(m_xListening
.is())
107 m_xListening
->removePropertyChangeListener(FM_PROP_ROWCOUNT
, static_cast<css::beans::XPropertyChangeListener
*>(this));
108 m_xListening
= nullptr;
112 void SAL_CALL
FmRecordCountListener::disposing(const css::lang::EventObject
& /*Source*/)
114 DBG_ASSERT(m_xListening
.is(), "FmRecordCountListener::disposing should never have been called without a propset !");
119 void FmRecordCountListener::NotifyCurrentCount()
121 if (m_lnkWhoWantsToKnow
.IsSet())
123 DBG_ASSERT(m_xListening
.is(), "FmRecordCountListener::NotifyCurrentCount : I have no propset ... !?");
124 sal_Int32 theCount
= ::comphelper::getINT32(m_xListening
->getPropertyValue(FM_PROP_ROWCOUNT
));
125 m_lnkWhoWantsToKnow
.Call(theCount
);
130 void FmRecordCountListener::propertyChange(const css::beans::PropertyChangeEvent
& /*evt*/)
132 NotifyCurrentCount();
136 // FmSearchEngine - local classes
138 SimpleTextWrapper::SimpleTextWrapper(const Reference
< css::awt::XTextComponent
> & _xText
)
139 :ControlTextWrapper(_xText
)
142 DBG_ASSERT(m_xText
.is(), "FmSearchEngine::SimpleTextWrapper::SimpleTextWrapper : invalid argument !");
146 OUString
SimpleTextWrapper::getCurrentText() const
148 return m_xText
->getText();
152 ListBoxWrapper::ListBoxWrapper(const Reference
< css::awt::XListBox
> & _xBox
)
153 :ControlTextWrapper(_xBox
)
156 DBG_ASSERT(m_xBox
.is(), "FmSearchEngine::ListBoxWrapper::ListBoxWrapper : invalid argument !");
160 OUString
ListBoxWrapper::getCurrentText() const
162 return m_xBox
->getSelectedItem();
166 CheckBoxWrapper::CheckBoxWrapper(const Reference
< css::awt::XCheckBox
> & _xBox
)
167 :ControlTextWrapper(_xBox
)
170 DBG_ASSERT(m_xBox
.is(), "FmSearchEngine::CheckBoxWrapper::CheckBoxWrapper : invalid argument !");
174 OUString
CheckBoxWrapper::getCurrentText() const
176 switch (static_cast<TriState
>(m_xBox
->getState()))
178 case TRISTATE_FALSE
: return u
"0"_ustr
;
179 case TRISTATE_TRUE
: return u
"1"_ustr
;
188 bool FmSearchEngine::MoveCursor()
190 bool bSuccess
= true;
194 if (m_xSearchCursor
.isLast())
195 m_xSearchCursor
.first();
197 m_xSearchCursor
.next();
199 if (m_xSearchCursor
.isFirst())
201 rtl::Reference
<FmRecordCountListener
> prclListener
= new FmRecordCountListener(m_xSearchCursor
);
202 prclListener
->SetPropChangeHandler(LINK(this, FmSearchEngine
, OnNewRecordCount
));
204 m_xSearchCursor
.last();
206 prclListener
->DisConnect();
209 m_xSearchCursor
.previous();
211 catch(Exception
const&)
213 TOOLS_WARN_EXCEPTION( "svx", "FmSearchEngine::MoveCursor");
218 TOOLS_WARN_EXCEPTION( "svx", "FmSearchEngine::MoveCursor : caught an unknown Exception !");
226 bool FmSearchEngine::MoveField(sal_Int32
& nPos
, FieldCollection::iterator
& iter
, const FieldCollection::iterator
& iterBegin
, const FieldCollection::iterator
& iterEnd
)
235 bSuccess
= MoveCursor();
241 if (iter
== iterBegin
)
243 bSuccess
= MoveCursor();
245 nPos
= iter
-iterBegin
;
254 void FmSearchEngine::BuildAndInsertFieldInfo(const Reference
< css::container::XIndexAccess
> & xAllFields
, sal_Int32 nField
)
256 DBG_ASSERT( xAllFields
.is() && ( nField
>= 0 ) && ( nField
< xAllFields
->getCount() ),
257 "FmSearchEngine::BuildAndInsertFieldInfo: invalid field descriptor!" );
260 Reference
< XInterface
> xCurrentField
;
261 xAllFields
->getByIndex(nField
) >>= xCurrentField
;
263 // From this I now know that it supports the DatabaseRecord service (I hope).
264 // For the FormatKey and the type I need the PropertySet.
265 Reference
< css::beans::XPropertySet
> xProperties(xCurrentField
, UNO_QUERY_THROW
);
267 // build the FieldInfo for that
269 fiCurrent
.xContents
.set(xCurrentField
, UNO_QUERY
);
272 m_arrUsedFields
.insert(m_arrUsedFields
.end(), fiCurrent
);
276 OUString
FmSearchEngine::FormatField(sal_Int32 nWhich
)
278 DBG_ASSERT(o3tl::make_unsigned(nWhich
) < m_aControlTexts
.size(), "FmSearchEngine::FormatField(sal_Int32) : invalid position !");
279 DBG_ASSERT(m_aControlTexts
[nWhich
], "FmSearchEngine::FormatField(sal_Int32) : invalid object in array !");
280 DBG_ASSERT(m_aControlTexts
[nWhich
]->getControl().is(), "FmSearchEngine::FormatField : invalid control !");
282 if (m_nCurrentFieldIndex
!= -1)
284 DBG_ASSERT((nWhich
== 0) || (nWhich
== m_nCurrentFieldIndex
), "FmSearchEngine::FormatField : parameter nWhich is invalid");
285 // analogous situation as below
286 nWhich
= m_nCurrentFieldIndex
;
289 DBG_ASSERT((nWhich
>= 0) && (o3tl::make_unsigned(nWhich
) < m_aControlTexts
.size()),
290 "FmSearchEngine::FormatField : invalid argument nWhich !");
291 return m_aControlTexts
[m_nCurrentFieldIndex
== -1 ? nWhich
: m_nCurrentFieldIndex
]->getCurrentText();
295 FmSearchEngine::SearchResult
FmSearchEngine::SearchSpecial(bool _bSearchForNull
, sal_Int32
& nFieldPos
,
296 FieldCollection::iterator
& iterFieldLoop
, const FieldCollection::iterator
& iterBegin
, const FieldCollection::iterator
& iterEnd
)
298 // memorize the start position
300 try { aStartMark
= m_xSearchCursor
.getBookmark(); }
301 catch ( const Exception
& ) { DBG_UNHANDLED_EXCEPTION("svx"); return SearchResult::Error
; }
302 FieldCollection::const_iterator iterInitialField
= iterFieldLoop
;
306 bool bMovedAround(false);
309 Application::Reschedule( true );
311 // the content to be compared currently
312 iterFieldLoop
->xContents
->getString(); // needed for wasNull
313 bFound
= _bSearchForNull
== bool(iterFieldLoop
->xContents
->wasNull());
317 // next field (implicitly next record, if necessary)
318 if (!MoveField(nFieldPos
, iterFieldLoop
, iterBegin
, iterEnd
))
319 { // When moving to the next field, something went wrong...
320 // Continuing is not possible, since the next time exactly the same
321 // will definitely go wrong again, thus abort.
322 // Before, however, so that the search continues at the current position:
323 try { m_aPreviousLocBookmark
= m_xSearchCursor
.getBookmark(); }
324 catch ( const Exception
& ) { DBG_UNHANDLED_EXCEPTION("svx"); }
325 m_iterPreviousLocField
= iterFieldLoop
;
327 return SearchResult::Error
;
330 Any aCurrentBookmark
;
331 try { aCurrentBookmark
= m_xSearchCursor
.getBookmark(); }
332 catch ( const Exception
& ) { DBG_UNHANDLED_EXCEPTION("svx"); return SearchResult::Error
; }
334 bMovedAround
= EQUAL_BOOKMARKS(aStartMark
, aCurrentBookmark
) && (iterFieldLoop
== iterInitialField
);
337 // that is, I've moved to a new record
338 PropagateProgress(bMovedAround
);
339 // if we moved to the starting position we don't have to propagate an 'overflow' message
340 // FS - 07.12.99 - 68530
343 if (CancelRequested())
344 return SearchResult::Cancelled
;
346 } while (!bMovedAround
);
348 return bFound
? SearchResult::Found
: SearchResult::NotFound
;
352 FmSearchEngine::SearchResult
FmSearchEngine::SearchWildcard(std::u16string_view strExpression
, sal_Int32
& nFieldPos
,
353 FieldCollection::iterator
& iterFieldLoop
, const FieldCollection::iterator
& iterBegin
, const FieldCollection::iterator
& iterEnd
)
355 // memorize the start position
357 try { aStartMark
= m_xSearchCursor
.getBookmark(); }
358 catch ( const Exception
& ) { DBG_UNHANDLED_EXCEPTION("svx"); return SearchResult::Error
; }
359 FieldCollection::const_iterator iterInitialField
= iterFieldLoop
;
361 WildCard
aSearchExpression(strExpression
);
365 bool bMovedAround(false);
368 Application::Reschedule( true );
370 // the content to be compared currently
371 OUString sCurrentCheck
;
373 sCurrentCheck
= FormatField(nFieldPos
);
375 sCurrentCheck
= iterFieldLoop
->xContents
->getString();
377 if (!GetCaseSensitive())
379 sCurrentCheck
= m_aCharacterClassficator
.lowercase(sCurrentCheck
);
381 // now the test is easy...
382 bFound
= aSearchExpression
.Matches(sCurrentCheck
);
387 // next field (implicitly next record, if necessary)
388 if (!MoveField(nFieldPos
, iterFieldLoop
, iterBegin
, iterEnd
))
389 { // When moving to the next field, something went wrong...
390 // Continuing is not possible, since the next time exactly the same
391 // will definitely go wrong again, thus abort.
392 // Before, however, so that the search continues at the current position:
393 try { m_aPreviousLocBookmark
= m_xSearchCursor
.getBookmark(); }
394 catch ( const Exception
& ) { DBG_UNHANDLED_EXCEPTION("svx"); }
395 m_iterPreviousLocField
= iterFieldLoop
;
397 return SearchResult::Error
;
400 Any aCurrentBookmark
;
401 try { aCurrentBookmark
= m_xSearchCursor
.getBookmark(); }
402 catch ( const Exception
& ) { DBG_UNHANDLED_EXCEPTION("svx"); return SearchResult::Error
; }
404 bMovedAround
= EQUAL_BOOKMARKS(aStartMark
, aCurrentBookmark
) && (iterFieldLoop
== iterInitialField
);
407 // that is, I've moved to a new record
408 PropagateProgress(bMovedAround
);
409 // if we moved to the starting position we don't have to propagate an 'overflow' message
410 // FS - 07.12.99 - 68530
413 if (CancelRequested())
414 return SearchResult::Cancelled
;
416 } while (!bMovedAround
);
418 return bFound
? SearchResult::Found
: SearchResult::NotFound
;
422 FmSearchEngine::SearchResult
FmSearchEngine::SearchRegularApprox(const OUString
& strExpression
, sal_Int32
& nFieldPos
,
423 FieldCollection::iterator
& iterFieldLoop
, const FieldCollection::iterator
& iterBegin
, const FieldCollection::iterator
& iterEnd
)
425 DBG_ASSERT(m_bLevenshtein
|| m_bRegular
,
426 "FmSearchEngine::SearchRegularApprox : invalid search mode!");
427 DBG_ASSERT(!m_bLevenshtein
|| !m_bRegular
,
428 "FmSearchEngine::SearchRegularApprox : cannot search for regular expressions and similarities at the same time!");
430 // memorize start position
432 try { aStartMark
= m_xSearchCursor
.getBookmark(); }
433 catch ( const Exception
& ) { DBG_UNHANDLED_EXCEPTION("svx"); return SearchResult::Error
; }
434 FieldCollection::const_iterator iterInitialField
= iterFieldLoop
;
436 // collect parameters
437 i18nutil::SearchOptions2 aParam
;
438 aParam
.AlgorithmType2
= m_bRegular
? SearchAlgorithms2::REGEXP
: SearchAlgorithms2::APPROXIMATE
;
439 aParam
.searchFlag
= 0;
440 aParam
.transliterateFlags
= GetTransliterationFlags();
441 if ( !GetTransliteration() )
442 { // if transliteration is not enabled, the only flags which matter are IGNORE_CASE and IGNORE_WIDTH
443 aParam
.transliterateFlags
&= TransliterationFlags::IGNORE_CASE
| TransliterationFlags::IGNORE_WIDTH
;
448 aParam
.searchFlag
|= SearchFlags::LEV_RELAXED
;
449 aParam
.changedChars
= m_nLevOther
;
450 aParam
.deletedChars
= m_nLevShorter
;
451 aParam
.insertedChars
= m_nLevLonger
;
453 aParam
.searchString
= strExpression
;
454 aParam
.Locale
= SvtSysLocale().GetLanguageTag().getLocale();
455 ::utl::TextSearch
aLocalEngine( aParam
);
459 bool bMovedAround(false);
462 Application::Reschedule( true );
464 // the content to be compared currently
465 OUString sCurrentCheck
;
467 sCurrentCheck
= FormatField(nFieldPos
);
469 sCurrentCheck
= iterFieldLoop
->xContents
->getString();
471 // (don't care about case here, this is done by the TextSearch object, 'cause we passed our case parameter to it)
473 sal_Int32 nStart
= 0, nEnd
= sCurrentCheck
.getLength();
474 bFound
= aLocalEngine
.SearchForward(sCurrentCheck
, &nStart
, &nEnd
);
475 // it says 'forward' here, but that only refers to the search within
476 // sCurrentCheck, so it has nothing to do with the direction of my
477 // record migration (MoveField takes care of that)
479 // check if the position is correct
484 case MATCHING_WHOLETEXT
:
485 if (nEnd
!= sCurrentCheck
.getLength())
491 case MATCHING_BEGINNING
:
496 if (nEnd
!= sCurrentCheck
.getLength())
502 if (bFound
) // still?
505 // next field (implicitly next record, if necessary)
506 if (!MoveField(nFieldPos
, iterFieldLoop
, iterBegin
, iterEnd
))
507 { // When moving to the next field, something went wrong...
508 // Continuing is not possible, since the next time exactly the same
509 // will definitely go wrong again, thus abort (without error
510 // notification, I expect it to be displayed in the Move).
511 // Before, however, so that the search continues at the current position:
512 try { m_aPreviousLocBookmark
= m_xSearchCursor
.getBookmark(); }
513 catch ( const Exception
& ) { DBG_UNHANDLED_EXCEPTION("svx"); }
514 m_iterPreviousLocField
= iterFieldLoop
;
516 return SearchResult::Error
;
519 Any aCurrentBookmark
;
520 try { aCurrentBookmark
= m_xSearchCursor
.getBookmark(); }
521 catch ( const Exception
& ) { DBG_UNHANDLED_EXCEPTION("svx"); return SearchResult::Error
; }
522 bMovedAround
= EQUAL_BOOKMARKS(aStartMark
, aCurrentBookmark
) && (iterFieldLoop
== iterInitialField
);
525 // that is, I've moved to a new record
526 PropagateProgress(bMovedAround
);
527 // if we moved to the starting position we don't have to propagate an 'overflow' message
528 // FS - 07.12.99 - 68530
531 if (CancelRequested())
532 return SearchResult::Cancelled
;
534 } while (!bMovedAround
);
536 return bFound
? SearchResult::Found
: SearchResult::NotFound
;
540 FmSearchEngine::FmSearchEngine(const Reference
< XComponentContext
>& _rxContext
,
541 const Reference
< XResultSet
> & xCursor
, std::u16string_view sVisibleFields
,
542 const InterfaceArray
& arrFields
)
543 :m_xSearchCursor(xCursor
)
544 ,m_aCharacterClassficator( _rxContext
, SvtSysLocale().GetLanguageTag() )
545 ,m_aStringCompare( _rxContext
)
546 ,m_nCurrentFieldIndex(-2) // -1 already has a meaning, so I take -2 for 'invalid'
547 ,m_xOriginalIterator(xCursor
)
548 ,m_xClonedIterator(m_xOriginalIterator
, true)
549 ,m_eSearchForType(SearchFor::String
)
550 ,m_srResult(SearchResult::Found
)
551 ,m_bCancelAsynchRequest(false)
552 ,m_bSearchingCurrently(false)
553 ,m_bFormatter(true) // this must be consistent with m_xSearchCursor, which is generally == m_xOriginalIterator
557 ,m_bLevenshtein(false)
558 ,m_bTransliteration(false)
559 ,m_bLevRelaxed(false)
563 ,m_nPosition(MATCHING_ANYWHERE
)
564 ,m_nTransliterationFlags(TransliterationFlags::NONE
)
567 fillControlTexts(arrFields
);
568 Init(sVisibleFields
);
572 void FmSearchEngine::SetIgnoreWidthCJK(bool bSet
)
575 m_nTransliterationFlags
|= TransliterationFlags::IGNORE_WIDTH
;
577 m_nTransliterationFlags
&= ~TransliterationFlags::IGNORE_WIDTH
;
581 bool FmSearchEngine::GetIgnoreWidthCJK() const
583 return bool(m_nTransliterationFlags
& TransliterationFlags::IGNORE_WIDTH
);
587 void FmSearchEngine::SetCaseSensitive(bool bSet
)
590 m_nTransliterationFlags
&= ~TransliterationFlags::IGNORE_CASE
;
592 m_nTransliterationFlags
|= TransliterationFlags::IGNORE_CASE
;
596 bool FmSearchEngine::GetCaseSensitive() const
598 return !(m_nTransliterationFlags
& TransliterationFlags::IGNORE_CASE
);
602 void FmSearchEngine::fillControlTexts(const InterfaceArray
& arrFields
)
604 m_aControlTexts
.clear();
605 Reference
< XInterface
> xCurrent
;
606 for (const auto & rField
: arrFields
)
609 DBG_ASSERT(xCurrent
.is(), "FmSearchEngine::fillControlTexts : invalid field interface !");
610 // check which type of control this is
611 Reference
< css::awt::XTextComponent
> xAsText(xCurrent
, UNO_QUERY
);
614 m_aControlTexts
.emplace_back(new SimpleTextWrapper(xAsText
));
618 Reference
< css::awt::XListBox
> xAsListBox(xCurrent
, UNO_QUERY
);
621 m_aControlTexts
.emplace_back(new ListBoxWrapper(xAsListBox
));
625 Reference
< css::awt::XCheckBox
> xAsCheckBox(xCurrent
, UNO_QUERY
);
626 DBG_ASSERT(xAsCheckBox
.is(), "FmSearchEngine::fillControlTexts : invalid field interface (no supported type) !");
627 // we don't have any more options ...
628 m_aControlTexts
.emplace_back(new CheckBoxWrapper(xAsCheckBox
));
633 void FmSearchEngine::Init(std::u16string_view sVisibleFields
)
635 // analyze the fields
636 // additionally, create the mapping: because the list of used columns can be shorter than the list
637 // of columns of the cursor, we need a mapping: "used column number n" -> "cursor column m"
638 m_arrFieldMapping
.clear();
640 // important: The case of the columns does not need to be exact - for instance:
641 // - a user created a form which works on a table, for which the driver returns a column name "COLUMN"
642 // - the driver itself works case-insensitive with column names
643 // - a control in the form is bound to "column" - not the different case
644 // In such a scenario, the form and the field would work okay, but we here need to case for the different case
648 // so first of all, check if the database handles identifiers case sensitive
649 Reference
< XConnection
> xConn
;
650 Reference
< XDatabaseMetaData
> xMeta
;
651 Reference
< XPropertySet
> xCursorProps( IFACECAST( m_xSearchCursor
), UNO_QUERY
);
652 if ( xCursorProps
.is() )
656 xCursorProps
->getPropertyValue( FM_PROP_ACTIVE_CONNECTION
) >>= xConn
;
658 catch( const Exception
& ) { /* silent this - will be asserted below */ }
661 xMeta
= xConn
->getMetaData();
662 OSL_ENSURE( xMeta
.is(), "FmSearchEngine::Init: very strange cursor (could not derive connection meta data from it)!" );
664 bool bCaseSensitiveIdentifiers
= true; // assume case sensitivity
666 bCaseSensitiveIdentifiers
= xMeta
->supportsMixedCaseQuotedIdentifiers();
668 // now that we have this information, we need a collator which is able to case (in)sensitivity compare strings
669 m_aStringCompare
.loadDefaultCollator( SvtSysLocale().GetLanguageTag().getLocale(),
670 bCaseSensitiveIdentifiers
? 0 : css::i18n::CollatorOptions::CollatorOptions_IGNORE_CASE
);
674 // the cursor can give me a record (as PropertySet), which supports the DatabaseRecord service
675 Reference
< css::sdbcx::XColumnsSupplier
> xSupplyCols(IFACECAST(m_xSearchCursor
), UNO_QUERY
);
676 DBG_ASSERT(xSupplyCols
.is(), "FmSearchEngine::Init : invalid cursor (no columns supplier) !");
677 Reference
< css::container::XNameAccess
> xAllFieldNames
= xSupplyCols
->getColumns();
678 const Sequence
< OUString
> seqFieldNames
= xAllFieldNames
->getElementNames();
680 OUString sCurrentField
;
681 sal_Int32 nIndex
= 0;
684 sCurrentField
= o3tl::getToken(sVisibleFields
, 0, ';' , nIndex
);
686 // search in the field collection
687 sal_Int32 nFoundIndex
= -1;
688 auto pFieldName
= std::find_if(seqFieldNames
.begin(), seqFieldNames
.end(),
689 [this, &sCurrentField
](const OUString
& rFieldName
) {
690 return 0 == m_aStringCompare
.compareString( rFieldName
, sCurrentField
); });
691 if (pFieldName
!= seqFieldNames
.end())
692 nFoundIndex
= static_cast<sal_Int32
>(std::distance(seqFieldNames
.begin(), pFieldName
));
693 DBG_ASSERT(nFoundIndex
!= -1, "FmSearchEngine::Init : Invalid field name were given !");
694 m_arrFieldMapping
.push_back(nFoundIndex
);
696 while ( nIndex
>= 0 );
698 catch (const Exception
&)
700 TOOLS_WARN_EXCEPTION("svx.form", "");
706 void FmSearchEngine::SetFormatterUsing(bool bSet
)
708 if (m_bFormatter
== bSet
)
712 // I did not use a formatter, but TextComponents -> the SearchIterator needs to be adjusted
717 DBG_ASSERT(m_xSearchCursor
== m_xClonedIterator
, "FmSearchEngine::SetFormatterUsing : inconsistent state !");
718 m_xSearchCursor
= m_xOriginalIterator
;
719 m_xSearchCursor
.moveToBookmark(m_xClonedIterator
.getBookmark());
720 // so that I continue with the new iterator at the actual place where I previously stopped
724 DBG_ASSERT(m_xSearchCursor
== m_xOriginalIterator
, "FmSearchEngine::SetFormatterUsing : inconsistent state !");
725 m_xSearchCursor
= m_xClonedIterator
;
726 m_xSearchCursor
.moveToBookmark(m_xOriginalIterator
.getBookmark());
729 catch( const Exception
& )
731 DBG_UNHANDLED_EXCEPTION("svx");
734 // I have to re-bind the fields, because the text exchange might take
735 // place over these fields and the underlying cursor has changed
736 RebuildUsedFields(m_nCurrentFieldIndex
, true);
740 void FmSearchEngine::PropagateProgress(bool _bDontPropagateOverflow
)
742 if (!m_aProgressHandler
.IsSet())
745 FmSearchProgress aProgress
;
748 aProgress
.aSearchState
= FmSearchProgress::State::Progress
;
749 aProgress
.nCurrentRecord
= m_xSearchCursor
.getRow() - 1;
751 aProgress
.bOverflow
= !_bDontPropagateOverflow
&& m_xSearchCursor
.isFirst();
753 aProgress
.bOverflow
= !_bDontPropagateOverflow
&& m_xSearchCursor
.isLast();
755 catch( const Exception
& )
757 DBG_UNHANDLED_EXCEPTION("svx");
760 m_aProgressHandler
.Call(&aProgress
);
764 void FmSearchEngine::SearchNextImpl()
766 DBG_ASSERT(!(m_bWildcard
&& m_bRegular
) && !(m_bRegular
&& m_bLevenshtein
) && !(m_bLevenshtein
&& m_bWildcard
),
767 "FmSearchEngine::SearchNextImpl : search parameters are mutually exclusive!");
769 DBG_ASSERT(m_xSearchCursor
.is(), "FmSearchEngine::SearchNextImpl : have invalid iterator!");
771 // the parameters of the search
772 OUString
strSearchExpression(m_strSearchExpression
); // I need non-const
773 if (!GetCaseSensitive())
775 strSearchExpression
= m_aCharacterClassficator
.lowercase(strSearchExpression
);
777 if (!m_bRegular
&& !m_bLevenshtein
)
778 { // 'normal' search I run through WildCards in any case, but must before adjust the OUString depending on the mode
781 { // since in all other cases * and ? in the search string are of course
782 // also allowed, but should not count as WildCards, I need to normalize
783 OUString
aTmp(strSearchExpression
);
784 aTmp
= aTmp
.replaceAll("*", "\\*");
785 aTmp
= aTmp
.replaceAll("?", "\\?");
786 strSearchExpression
= aTmp
;
790 case MATCHING_ANYWHERE
:
791 strSearchExpression
= "*" + strSearchExpression
+ "*";
793 case MATCHING_BEGINNING
:
794 strSearchExpression
+= "*";
797 strSearchExpression
= "*" + strSearchExpression
;
799 case MATCHING_WHOLETEXT
:
802 OSL_FAIL("FmSearchEngine::SearchNextImpl() : the methods listbox may contain only 4 entries ...");
807 // for work on field list
808 FieldCollection::iterator iterBegin
= m_arrUsedFields
.begin();
809 FieldCollection::iterator iterEnd
= m_arrUsedFields
.end();
810 FieldCollection::iterator iterFieldCheck
;
814 if (m_aPreviousLocBookmark
.hasValue())
816 DBG_ASSERT(EQUAL_BOOKMARKS(m_aPreviousLocBookmark
, m_xSearchCursor
.getBookmark()),
817 "FmSearchEngine::SearchNextImpl : invalid position!");
818 iterFieldCheck
= m_iterPreviousLocField
;
819 // continue in the field after (or before) the last discovery
820 nFieldPos
= iterFieldCheck
- iterBegin
;
821 MoveField(nFieldPos
, iterFieldCheck
, iterBegin
, iterEnd
);
826 iterFieldCheck
= iterBegin
;
829 iterFieldCheck
= iterEnd
;
832 nFieldPos
= iterFieldCheck
- iterBegin
;
835 PropagateProgress(true);
836 SearchResult srResult
;
837 if (m_eSearchForType
!= SearchFor::String
)
838 srResult
= SearchSpecial(m_eSearchForType
== SearchFor::Null
, nFieldPos
, iterFieldCheck
, iterBegin
, iterEnd
);
839 else if (!m_bRegular
&& !m_bLevenshtein
)
840 srResult
= SearchWildcard(strSearchExpression
, nFieldPos
, iterFieldCheck
, iterBegin
, iterEnd
);
842 srResult
= SearchRegularApprox(strSearchExpression
, nFieldPos
, iterFieldCheck
, iterBegin
, iterEnd
);
844 m_srResult
= srResult
;
846 if (SearchResult::Error
== m_srResult
)
850 if (SearchResult::Found
== m_srResult
)
852 // memorize the position
853 try { m_aPreviousLocBookmark
= m_xSearchCursor
.getBookmark(); }
854 catch ( const Exception
& ) { DBG_UNHANDLED_EXCEPTION("svx"); }
855 m_iterPreviousLocField
= iterFieldCheck
;
858 // invalidate the "last discovery"
859 InvalidatePreviousLoc();
863 void FmSearchEngine::OnSearchTerminated()
865 if (!m_aProgressHandler
.IsSet())
868 FmSearchProgress aProgress
;
873 case SearchResult::Error
:
874 aProgress
.aSearchState
= FmSearchProgress::State::Error
;
876 case SearchResult::Found
:
877 aProgress
.aSearchState
= FmSearchProgress::State::Successful
;
878 aProgress
.aBookmark
= m_aPreviousLocBookmark
;
879 aProgress
.nFieldIndex
= m_iterPreviousLocField
- m_arrUsedFields
.begin();
881 case SearchResult::NotFound
:
882 aProgress
.aSearchState
= FmSearchProgress::State::NothingFound
;
883 aProgress
.aBookmark
= m_xSearchCursor
.getBookmark();
885 case SearchResult::Cancelled
:
886 aProgress
.aSearchState
= FmSearchProgress::State::Canceled
;
887 aProgress
.aBookmark
= m_xSearchCursor
.getBookmark();
890 aProgress
.nCurrentRecord
= m_xSearchCursor
.getRow() - 1;
892 catch( const Exception
& )
894 DBG_UNHANDLED_EXCEPTION("svx");
897 // by definition, the link must be thread-safe (I just require that),
898 // so that I do not have to worry about such things here
899 m_aProgressHandler
.Call(&aProgress
);
901 m_bSearchingCurrently
= false;
905 IMPL_LINK(FmSearchEngine
, OnNewRecordCount
, sal_Int32
, theCounter
, void)
907 if (!m_aProgressHandler
.IsSet())
910 FmSearchProgress aProgress
;
911 aProgress
.nCurrentRecord
= theCounter
;
912 aProgress
.aSearchState
= FmSearchProgress::State::ProgressCounting
;
913 m_aProgressHandler
.Call(&aProgress
);
917 bool FmSearchEngine::CancelRequested()
919 bool bReturn
= m_bCancelAsynchRequest
;
924 void FmSearchEngine::CancelSearch()
926 m_bCancelAsynchRequest
= true;
930 void FmSearchEngine::SwitchToContext(const Reference
< css::sdbc::XResultSet
> & xCursor
, std::u16string_view sVisibleFields
, const InterfaceArray
& arrFields
,
931 sal_Int32 nFieldIndex
)
933 DBG_ASSERT(!m_bSearchingCurrently
, "FmSearchEngine::SwitchToContext : please do not call while I'm searching !");
934 if (m_bSearchingCurrently
)
937 m_xSearchCursor
= xCursor
;
938 m_xOriginalIterator
= xCursor
;
939 m_xClonedIterator
= CursorWrapper(m_xOriginalIterator
, true);
941 fillControlTexts(arrFields
);
943 Init(sVisibleFields
);
944 RebuildUsedFields(nFieldIndex
, true);
948 void FmSearchEngine::ImplStartNextSearch()
950 m_bCancelAsynchRequest
= false;
951 m_bSearchingCurrently
= true;
954 OnSearchTerminated();
958 void FmSearchEngine::SearchNext(const OUString
& strExpression
)
960 m_strSearchExpression
= strExpression
;
961 m_eSearchForType
= SearchFor::String
;
962 ImplStartNextSearch();
966 void FmSearchEngine::SearchNextSpecial(bool _bSearchForNull
)
968 m_eSearchForType
= _bSearchForNull
? SearchFor::Null
: SearchFor::NotNull
;
969 ImplStartNextSearch();
973 void FmSearchEngine::StartOver(const OUString
& strExpression
)
978 m_xSearchCursor
.first();
980 m_xSearchCursor
.last();
982 catch( const Exception
& )
984 DBG_UNHANDLED_EXCEPTION("svx");
988 InvalidatePreviousLoc();
989 SearchNext(strExpression
);
993 void FmSearchEngine::StartOverSpecial(bool _bSearchForNull
)
998 m_xSearchCursor
.first();
1000 m_xSearchCursor
.last();
1002 catch( const Exception
& )
1004 DBG_UNHANDLED_EXCEPTION("svx");
1008 InvalidatePreviousLoc();
1009 SearchNextSpecial(_bSearchForNull
);
1013 void FmSearchEngine::InvalidatePreviousLoc()
1015 m_aPreviousLocBookmark
.clear();
1016 m_iterPreviousLocField
= m_arrUsedFields
.end();
1020 void FmSearchEngine::RebuildUsedFields(sal_Int32 nFieldIndex
, bool bForce
)
1022 if (!bForce
&& (nFieldIndex
== m_nCurrentFieldIndex
))
1024 // (since I allow no change of the iterator from the outside, the same css::sdbcx::Index
1025 // also always means the same column, so I have nothing to do)
1027 DBG_ASSERT((nFieldIndex
== -1) ||
1028 ((nFieldIndex
>= 0) &&
1029 (o3tl::make_unsigned(nFieldIndex
) < m_arrFieldMapping
.size())),
1030 "FmSearchEngine::RebuildUsedFields : nFieldIndex is invalid!");
1031 // collect all fields I need to search through
1032 m_arrUsedFields
.clear();
1033 if (nFieldIndex
== -1)
1035 Reference
< css::container::XIndexAccess
> xFields
;
1036 for (sal_Int32 i
: m_arrFieldMapping
)
1038 Reference
< css::sdbcx::XColumnsSupplier
> xSupplyCols(IFACECAST(m_xSearchCursor
), UNO_QUERY
);
1039 DBG_ASSERT(xSupplyCols
.is(), "FmSearchEngine::RebuildUsedFields : invalid cursor (no columns supplier) !");
1040 xFields
.set(xSupplyCols
->getColumns(), UNO_QUERY
);
1041 BuildAndInsertFieldInfo(xFields
, i
);
1046 Reference
< css::container::XIndexAccess
> xFields
;
1047 Reference
< css::sdbcx::XColumnsSupplier
> xSupplyCols(IFACECAST(m_xSearchCursor
), UNO_QUERY
);
1048 DBG_ASSERT(xSupplyCols
.is(), "FmSearchEngine::RebuildUsedFields : invalid cursor (no columns supplier) !");
1049 xFields
.set (xSupplyCols
->getColumns(), UNO_QUERY
);
1050 BuildAndInsertFieldInfo(xFields
, m_arrFieldMapping
[static_cast< size_t >(nFieldIndex
)]);
1053 m_nCurrentFieldIndex
= nFieldIndex
;
1054 // and of course I start the next search in a virgin state again
1055 InvalidatePreviousLoc();
1058 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */