1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <SwRewriter.hxx>
#include <cmdid.h>
#include <strings.hrc>
#include <doc.hxx>
#include <edtwin.hxx>
#include <helpids.h>
#include <langhelper.hxx>
#include <bitmaps.hlst>
#include <olmenu.hxx>
#include <swmodule.hxx>
#include <swtypes.hxx>
#include <swundo.hxx>
#include <view.hxx>
#include <wrtsh.hxx>

#include <comphelper/lok.hxx>
#include <comphelper/anytostring.hxx>
#include <comphelper/processfactory.hxx>
#include <cppuhelper/exc_hlp.hxx>
#include <editeng/acorrcfg.hxx>
#include <editeng/svxacorr.hxx>
#include <editeng/splwrap.hxx>
#include <editeng/unolingu.hxx>
#include <editeng/editview.hxx>
#include <i18nlangtag/languagetag.hxx>
#include <linguistic/misc.hxx>
#include <rtl/string.hxx>
#include <vcl/commandinfoprovider.hxx>
#include <vcl/svapp.hxx>
#include <vcl/weld.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/request.hxx>
#include <sfx2/viewfrm.hxx>
#include <svl/itemset.hxx>
#include <svl/languageoptions.hxx>
#include <svl/stritem.hxx>
#include <svtools/langtab.hxx>
#include <unotools/lingucfg.hxx>
#include <unotools/linguprops.hxx>
#include <vcl/settings.hxx>

#include <map>

#include <com/sun/star/document/XDocumentLanguages.hpp>
#include <com/sun/star/frame/XFrame.hpp>
#include <com/sun/star/frame/XStorable.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/linguistic2/XLanguageGuessing.hpp>
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/system/SystemShellExecuteFlags.hpp>
#include <com/sun/star/system/SystemShellExecute.hpp>
#include <com/sun/star/linguistic2/XSearchableDictionaryList.hpp>

using namespace ::com::sun::star;

/// @returns : the language for the selected text that is set for the
///     specified attribute (script type).
///     If there are more than one languages used LANGUAGE_DONTKNOW will be returned.
/// @param nLangWhichId : one of
///     RES_CHRATR_LANGUAGE, RES_CHRATR_CJK_LANGUAGE, RES_CHRATR_CTL_LANGUAGE,
/// @returns: the language in use for the selected text.
///     'In use' means the language(s) matching the script type(s) of the
///     selected text. Or in other words, the language a spell checker would use.
///     If there is more than one language LANGUAGE_DONTKNOW will be returned.
// check if nScriptType includes the script type associated to nLang
static bool lcl_checkScriptType( SvtScriptType nScriptType, LanguageType nLang )
{
    return bool(nScriptType & SvtLanguageOptions::GetScriptTypeOfLanguage( nLang ));
}

void SwSpellPopup::fillLangPopupMenu(
    PopupMenu *pPopupMenu,
    sal_uInt16 nLangItemIdStart,
    const uno::Sequence< OUString >& aSeq,
    SwWrtShell* pWrtSh,
    std::map< sal_Int16, OUString > &rLangTable )
{
    if (!pPopupMenu)
        return;

    // set of languages to be displayed in the sub menus
    std::set< OUString > aLangItems;

    OUString    aCurLang( aSeq[0] );
    SvtScriptType  nScriptType = static_cast<SvtScriptType>(aSeq[1].toInt32());
    OUString    aKeyboardLang( aSeq[2] );
    OUString    aGuessedTextLang( aSeq[3] );

    if (!aCurLang.isEmpty() &&
        LANGUAGE_DONTKNOW != SvtLanguageTable::GetLanguageType( aCurLang ))
        aLangItems.insert( aCurLang );

    //2--System
    const AllSettings& rAllSettings = Application::GetSettings();
    LanguageType rSystemLanguage = rAllSettings.GetLanguageTag().getLanguageType();
    if (rSystemLanguage != LANGUAGE_DONTKNOW)
    {
        if (lcl_checkScriptType( nScriptType, rSystemLanguage ))
            aLangItems.insert( SvtLanguageTable::GetLanguageString(rSystemLanguage) );
    }

    //3--UI
    LanguageType rUILanguage = rAllSettings.GetUILanguageTag().getLanguageType();
    if (rUILanguage != LANGUAGE_DONTKNOW)
    {
        if (lcl_checkScriptType(nScriptType, rUILanguage ))
            aLangItems.insert( SvtLanguageTable::GetLanguageString(rUILanguage) );
    }

    //4--guessed language
    if (!aGuessedTextLang.isEmpty())
    {
        if (lcl_checkScriptType(nScriptType, SvtLanguageTable::GetLanguageType(aGuessedTextLang)))
            aLangItems.insert( aGuessedTextLang );
    }

    //5--keyboard language
    if (!aKeyboardLang.isEmpty())
    {
        if (lcl_checkScriptType(nScriptType, SvtLanguageTable::GetLanguageType(aKeyboardLang)))
            aLangItems.insert( aKeyboardLang );
    }

    //6--all languages used in current document
    uno::Reference< css::frame::XModel > xModel;
    uno::Reference< css::frame::XController > xController = pWrtSh->GetView().GetViewFrame()->GetFrame().GetFrameInterface()->getController();
    if ( xController.is() )
        xModel = xController->getModel();
    uno::Reference< document::XDocumentLanguages > xDocumentLanguages( xModel, uno::UNO_QUERY );
    /*the description of nScriptType flags
      LATIN :   0x0001
      ASIAN :   0x0002
      COMPLEX:  0x0004
    */
    const sal_Int16 nMaxCount = 7;
    if (xDocumentLanguages.is())
    {
        const uno::Sequence< lang::Locale > rLocales( xDocumentLanguages->getDocumentLanguages( static_cast<sal_Int16>(nScriptType), nMaxCount ) );
        for (const lang::Locale& rLocale : rLocales)
        {
            if (aLangItems.size() == size_t(nMaxCount))
                break;
            if (lcl_checkScriptType( nScriptType, SvtLanguageTable::GetLanguageType( rLocale.Language )))
                aLangItems.insert( rLocale.Language );
        }
    }

    sal_uInt16 nItemId = nLangItemIdStart;
    for (const OUString& aEntryText : aLangItems)
    {
        if (aEntryText != SvtLanguageTable::GetLanguageString( LANGUAGE_NONE ) &&
            aEntryText != "*" && // multiple languages in current selection
            !aEntryText.isEmpty()) // 'no language found' from language guessing
        {
            OSL_ENSURE( nLangItemIdStart <= nItemId && nItemId <= nLangItemIdStart + MN_MAX_NUM_LANG,
                    "nItemId outside of expected range!" );
            pPopupMenu->InsertItem( nItemId, aEntryText, MenuItemBits::RADIOCHECK );
            if (aEntryText == aCurLang)
            {
                //make a check mark for the current language
                pPopupMenu->CheckItem( nItemId );
            }
            rLangTable[ nItemId ] = aEntryText;
            ++nItemId;
        }
    }

    pPopupMenu->InsertItem( nLangItemIdStart + MN_NONE_OFFSET,  SwResId( STR_LANGSTATUS_NONE ), MenuItemBits::RADIOCHECK );
    if ( SvtLanguageTable::GetLanguageString( LANGUAGE_NONE ) == aCurLang )
        pPopupMenu->CheckItem( nLangItemIdStart + MN_NONE_OFFSET );

    pPopupMenu->InsertItem( nLangItemIdStart + MN_RESET_OFFSET, SwResId( STR_RESET_TO_DEFAULT_LANGUAGE ) );
    pPopupMenu->InsertItem( nLangItemIdStart + MN_MORE_OFFSET,  SwResId( STR_LANGSTATUS_MORE ) );
}

SwSpellPopup::SwSpellPopup(
        SwWrtShell* pWrtSh,
        const uno::Reference< linguistic2::XSpellAlternatives >  &xAlt,
        const OUString &rParaText)
    : m_aBuilder(nullptr, VclBuilderContainer::getUIRootDir(), "modules/swriter/ui/spellmenu.ui", "")
    , m_xPopupMenu(m_aBuilder.get_menu("menu"))
    , m_nIgnoreWordId(m_xPopupMenu->GetItemId("ignoreall"))
    , m_nAddMenuId(m_xPopupMenu->GetItemId("addmenu"))
    , m_nAddId(m_xPopupMenu->GetItemId("add"))
    , m_nSpellDialogId(m_xPopupMenu->GetItemId("spelldialog"))
    , m_nCorrectMenuId(m_xPopupMenu->GetItemId("correctmenu"))
    , m_nCorrectDialogId(m_xPopupMenu->GetItemId("correctdialog"))
    , m_nLangSelectionMenuId(m_xPopupMenu->GetItemId("langselection"))
    , m_nLangParaMenuId(m_xPopupMenu->GetItemId("langpara"))
    , m_nRedlineAcceptId(m_xPopupMenu->GetItemId("accept"))
    , m_nRedlineRejectId(m_xPopupMenu->GetItemId("reject"))
    , m_nRedlineNextId(m_xPopupMenu->GetItemId("next"))
    , m_nRedlinePrevId(m_xPopupMenu->GetItemId("prev"))
    , m_pSh( pWrtSh )
    , m_xSpellAlt(xAlt)
    , m_bGrammarResults(false)
{
    OSL_ENSURE(m_xSpellAlt.is(), "no spelling alternatives available");

    m_xPopupMenu->SetMenuFlags(MenuFlags::NoAutoMnemonics);
    bool bUseImagesInMenus = Application::GetSettings().GetStyleSettings().GetUseImagesInMenus();

    m_nCheckedLanguage = LANGUAGE_NONE;
    css::uno::Sequence< OUString > aSuggestions;
    if (m_xSpellAlt.is())
    {
        m_nCheckedLanguage = LanguageTag( m_xSpellAlt->getLocale() ).getLanguageType();
        aSuggestions = m_xSpellAlt->getAlternatives();
    }
    sal_Int16 nStringCount = static_cast< sal_Int16 >( aSuggestions.getLength() );

    SvtLinguConfig aCfg;

    PopupMenu *pMenu = m_xPopupMenu->GetPopupMenu(m_nCorrectMenuId);
    pMenu->SetMenuFlags(MenuFlags::NoAutoMnemonics);
    bool bEnable = false;
    if( nStringCount )
    {
        Image aImage;
        OUString aSuggestionImageUrl;

        if (bUseImagesInMenus)
        {
            uno::Reference< container::XNamed > xNamed( m_xSpellAlt, uno::UNO_QUERY );
            if (xNamed.is())
            {
                aSuggestionImageUrl = aCfg.GetSpellAndGrammarContextSuggestionImage( xNamed->getName() );
                aImage = Image( aSuggestionImageUrl );
            }
        }

        m_xPopupMenu->InsertSeparator(OString(), 0);
        bEnable = true;
        sal_uInt16 nAutoCorrItemId  = MN_AUTOCORR_START;
        sal_uInt16 nItemId          = MN_SUGGESTION_START;
        for (sal_uInt16 i = 0; i < nStringCount; ++i)
        {
            const OUString aEntry = aSuggestions[ i ];
            m_xPopupMenu->InsertItem(nItemId, aEntry, MenuItemBits::NONE, OString(), i);
            m_xPopupMenu->SetHelpId(nItemId, HID_LINGU_REPLACE);
            if (!aSuggestionImageUrl.isEmpty())
                m_xPopupMenu->SetItemImage(nItemId, aImage);

            pMenu->InsertItem( nAutoCorrItemId, aEntry );
            pMenu->SetHelpId( nAutoCorrItemId, HID_LINGU_AUTOCORR);

            ++nAutoCorrItemId;
            ++nItemId;
        }
    }

    uno::Reference< frame::XFrame > xFrame = pWrtSh->GetView().GetViewFrame()->GetFrame().GetFrameInterface();
    OUString aModuleName(vcl::CommandInfoProvider::GetModuleIdentifier(xFrame));

    {
        auto aProperties = vcl::CommandInfoProvider::GetCommandProperties(".uno:SpellingAndGrammarDialog", aModuleName);
        m_xPopupMenu->SetItemText(m_nSpellDialogId,
            vcl::CommandInfoProvider::GetPopupLabelForCommand(aProperties));
    }
    {
        auto aProperties = vcl::CommandInfoProvider::GetCommandProperties(".uno:AutoCorrectDlg", aModuleName);
        m_xPopupMenu->SetItemText(m_nCorrectDialogId,
            vcl::CommandInfoProvider::GetPopupLabelForCommand(aProperties));
    }

    sal_uInt16 nItemPos = m_xPopupMenu->GetItemPos(m_nIgnoreWordId);
    OUString aIgnoreSelection( SwResId( STR_IGNORE_SELECTION ) );
    m_xPopupMenu->InsertItem(MN_IGNORE_SELECTION, aIgnoreSelection, MenuItemBits::NONE, OString(), nItemPos);
    m_xPopupMenu->SetHelpId(MN_IGNORE_SELECTION, HID_LINGU_IGNORE_SELECTION);

    m_xPopupMenu->EnableItem(m_nCorrectMenuId, bEnable);

    uno::Reference< linguistic2::XLanguageGuessing > xLG = SW_MOD()->GetLanguageGuesser();
    LanguageType nGuessLangWord = LANGUAGE_NONE;
    LanguageType nGuessLangPara = LANGUAGE_NONE;
    if (m_xSpellAlt.is() && xLG.is())
    {
        nGuessLangWord = EditView::CheckLanguage( m_xSpellAlt->getWord(), ::GetSpellChecker(), xLG, false );
        nGuessLangPara = EditView::CheckLanguage( rParaText, ::GetSpellChecker(), xLG, true );
    }
    if (nGuessLangWord != LANGUAGE_NONE || nGuessLangPara != LANGUAGE_NONE)
    {
        // make sure LANGUAGE_NONE gets not used as menu entry
        if (nGuessLangWord == LANGUAGE_NONE)
            nGuessLangWord = nGuessLangPara;
        if (nGuessLangPara == LANGUAGE_NONE)
            nGuessLangPara = nGuessLangWord;
    }

    pMenu = m_xPopupMenu->GetPopupMenu(m_nAddMenuId);
    pMenu->SetMenuFlags(MenuFlags::NoAutoMnemonics);     //! necessary to retrieve the correct dictionary name in 'Execute' below
    uno::Reference< linguistic2::XSearchableDictionaryList >    xDicList( LinguMgr::GetDictionaryList() );
    sal_uInt16 nItemId = MN_DICTIONARIES_START;
    if (xDicList.is())
    {
        // add the default positive dictionary to dic-list (if not already done).
        // This is to ensure that there is at least one dictionary to which
        // words could be added.
        uno::Reference< linguistic2::XDictionary >  xDic( LinguMgr::GetStandardDic() );
        if (xDic.is())
            xDic->setActive( true );

        m_aDics = xDicList->getDictionaries();

        for( const uno::Reference< linguistic2::XDictionary >& rDic : std::as_const(m_aDics) )
        {
            uno::Reference< linguistic2::XDictionary >  xDicTmp = rDic;
            if (!xDicTmp.is() || LinguMgr::GetIgnoreAllList() == xDicTmp)
                continue;

            uno::Reference< frame::XStorable > xStor( xDicTmp, uno::UNO_QUERY );
            LanguageType nActLanguage = LanguageTag( xDicTmp->getLocale() ).getLanguageType();
            if( xDicTmp->isActive()
                &&  xDicTmp->getDictionaryType() != linguistic2::DictionaryType_NEGATIVE
                && (m_nCheckedLanguage == nActLanguage || LANGUAGE_NONE == nActLanguage )
                && (!xStor.is() || !xStor->isReadonly()) )
            {
                // the extra 1 is because of the (possible) external
                // linguistic entry above
                pMenu->InsertItem( nItemId, xDicTmp->getName() );
                m_aDicNameSingle = xDicTmp->getName();

                if (bUseImagesInMenus)
                {
                    uno::Reference< lang::XServiceInfo > xSvcInfo( xDicTmp, uno::UNO_QUERY );
                    if (xSvcInfo.is())
                    {
                        OUString aDictionaryImageUrl( aCfg.GetSpellAndGrammarContextDictionaryImage(
                                xSvcInfo->getImplementationName() ) );
                        if (!aDictionaryImageUrl.isEmpty())
                        {
                            Image aImage( aDictionaryImageUrl );
                            pMenu->SetItemImage( nItemId, aImage );
                        }
                    }
                }

                ++nItemId;
            }
        }
    }
    m_xPopupMenu->EnableItem(m_nAddMenuId, (nItemId - MN_DICTIONARIES_START) > 1);
    m_xPopupMenu->EnableItem(m_nAddId, (nItemId - MN_DICTIONARIES_START) == 1);

    //ADD NEW LANGUAGE MENU ITEM

    OUString aScriptTypesInUse( OUString::number( static_cast<int>(pWrtSh->GetScriptType()) ) );

    // get keyboard language
    OUString aKeyboardLang;
    SwEditWin& rEditWin = pWrtSh->GetView().GetEditWin();
    LanguageType nLang = rEditWin.GetInputLanguage();
    if (nLang != LANGUAGE_DONTKNOW && nLang != LANGUAGE_SYSTEM)
        aKeyboardLang = SvtLanguageTable::GetLanguageString( nLang );

    // get the language that is in use
    OUString aCurrentLang("*");
    nLang = SwLangHelper::GetCurrentLanguage( *pWrtSh );
    if (nLang != LANGUAGE_DONTKNOW)
        aCurrentLang = SvtLanguageTable::GetLanguageString( nLang );

    // build sequence for status value
    uno::Sequence< OUString > aSeq( 4 );
    aSeq[0] = aCurrentLang;
    aSeq[1] = aScriptTypesInUse;
    aSeq[2] = aKeyboardLang;
    aSeq[3] = SvtLanguageTable::GetLanguageString(nGuessLangWord);

    pMenu = m_xPopupMenu->GetPopupMenu(m_nLangSelectionMenuId);
    fillLangPopupMenu( pMenu, MN_SET_LANGUAGE_SELECTION_START, aSeq, pWrtSh, m_aLangTable_Text );
    m_xPopupMenu->EnableItem(m_nLangSelectionMenuId);

    pMenu = m_xPopupMenu->GetPopupMenu(m_nLangParaMenuId);
    fillLangPopupMenu( pMenu, MN_SET_LANGUAGE_PARAGRAPH_START, aSeq, pWrtSh, m_aLangTable_Paragraph );
    m_xPopupMenu->EnableItem(m_nLangParaMenuId);

    if (bUseImagesInMenus)
        m_xPopupMenu->SetItemImage(m_nSpellDialogId,
            vcl::CommandInfoProvider::GetImageForCommand(".uno:SpellingAndGrammarDialog", xFrame));

    checkRedline();
    m_xPopupMenu->RemoveDisabledEntries( true, true );

    InitItemCommands(aSuggestions);
}

SwSpellPopup::SwSpellPopup(
    SwWrtShell *pWrtSh,
    const linguistic2::ProofreadingResult &rResult,
    sal_Int32 nErrorInResult,
    const uno::Sequence< OUString > &rSuggestions,
    const OUString &rParaText )
    : m_aBuilder(nullptr, VclBuilderContainer::getUIRootDir(), "modules/swriter/ui/spellmenu.ui", "")
    , m_xPopupMenu(m_aBuilder.get_menu("menu"))
    , m_nIgnoreWordId(m_xPopupMenu->GetItemId("ignoreall"))
    , m_nAddMenuId(m_xPopupMenu->GetItemId("addmenu"))
    , m_nAddId(m_xPopupMenu->GetItemId("add"))
    , m_nSpellDialogId(m_xPopupMenu->GetItemId("spelldialog"))
    , m_nCorrectMenuId(m_xPopupMenu->GetItemId("correctmenu"))
    , m_nCorrectDialogId(m_xPopupMenu->GetItemId("correctdialog"))
    , m_nLangSelectionMenuId(m_xPopupMenu->GetItemId("langselection"))
    , m_nLangParaMenuId(m_xPopupMenu->GetItemId("langpara"))
    , m_nRedlineAcceptId(m_xPopupMenu->GetItemId("accept"))
    , m_nRedlineRejectId(m_xPopupMenu->GetItemId("reject"))
    , m_nRedlineNextId(m_xPopupMenu->GetItemId("next"))
    , m_nRedlinePrevId(m_xPopupMenu->GetItemId("prev"))
    , m_pSh(pWrtSh)
    , m_sExplanationLink()
    , m_bGrammarResults(true)
{
    m_nCheckedLanguage = LanguageTag::convertToLanguageType( rResult.aLocale );
    bool bUseImagesInMenus = Application::GetSettings().GetStyleSettings().GetUseImagesInMenus();

    sal_uInt16 nPos = 0;
    OUString aMessageText( rResult.aErrors[ nErrorInResult ].aShortComment );
    m_xPopupMenu->InsertSeparator(OString(), nPos++);
    m_xPopupMenu->InsertItem(MN_SHORT_COMMENT, aMessageText, MenuItemBits::NOSELECT, OString(), nPos++);
    if (bUseImagesInMenus)
        m_xPopupMenu->SetItemImage(MN_SHORT_COMMENT, Image(StockImage::Yes, BMP_INFO_16));

    // Add an item to show detailed infos if the FullCommentURL property is defined
    const beans::PropertyValues  aProperties = rResult.aErrors[ nErrorInResult ].aProperties;
    for ( const auto& rProp : aProperties )
    {
        if ( rProp.Name == "FullCommentURL" )
        {
            uno::Any aValue = rProp.Value;
            aValue >>= m_sExplanationLink;

            if ( !m_sExplanationLink.isEmpty( ) )
                break;
        }
    }

    if ( !m_sExplanationLink.isEmpty( ) )
    {
        m_xPopupMenu->InsertItem(MN_EXPLANATION_LINK, SwResId(STR_EXPLANATION_LINK), MenuItemBits::TEXT | MenuItemBits::HELP, OString(), nPos++);
    }

    m_xPopupMenu->SetMenuFlags(MenuFlags::NoAutoMnemonics);

    m_xPopupMenu->InsertSeparator(OString(), nPos++);
    if ( rSuggestions.hasElements() )     // suggestions available...
    {
        Image aImage;
        OUString aSuggestionImageUrl;

        if (bUseImagesInMenus)
        {
            uno::Reference< lang::XServiceInfo > xInfo( rResult.xProofreader, uno::UNO_QUERY );
            if (xInfo.is())
            {
                aSuggestionImageUrl = SvtLinguConfig().GetSpellAndGrammarContextSuggestionImage( xInfo->getImplementationName() );
                aImage = Image( aSuggestionImageUrl );
            }
        }

        sal_uInt16 nItemId = MN_SUGGESTION_START;
        for (const OUString& aEntry : std::as_const(rSuggestions))
        {
            m_xPopupMenu->InsertItem(nItemId, aEntry, MenuItemBits::NONE, OString(), nPos++);
            m_xPopupMenu->SetHelpId(nItemId, HID_LINGU_REPLACE);
            if (!aSuggestionImageUrl.isEmpty())
                m_xPopupMenu->SetItemImage(nItemId, aImage);

            ++nItemId;
        }
        m_xPopupMenu->InsertSeparator(OString(), nPos++);
    }

    uno::Reference< frame::XFrame > xFrame = pWrtSh->GetView().GetViewFrame()->GetFrame().GetFrameInterface();
    OUString aModuleName(vcl::CommandInfoProvider::GetModuleIdentifier(xFrame));

    OUString aIgnoreSelection( SwResId( STR_IGNORE_SELECTION ) );
    auto aCommandProperties = vcl::CommandInfoProvider::GetCommandProperties(".uno:SpellingAndGrammarDialog", aModuleName);
    m_xPopupMenu->SetItemText(m_nSpellDialogId,
        vcl::CommandInfoProvider::GetPopupLabelForCommand(aCommandProperties));
    sal_uInt16 nItemPos = m_xPopupMenu->GetItemPos(m_nIgnoreWordId);
    m_xPopupMenu->InsertItem(MN_IGNORE_SELECTION, aIgnoreSelection, MenuItemBits::NONE, OString(), nItemPos);
    m_xPopupMenu->SetHelpId(MN_IGNORE_SELECTION, HID_LINGU_IGNORE_SELECTION);

    m_xPopupMenu->EnableItem(m_nCorrectMenuId, false);
    m_xPopupMenu->EnableItem(m_nCorrectDialogId, false);

    uno::Reference< linguistic2::XLanguageGuessing > xLG = SW_MOD()->GetLanguageGuesser();
    LanguageType nGuessLangWord = LANGUAGE_NONE;
    LanguageType nGuessLangPara = LANGUAGE_NONE;
    if (xLG.is())
    {
        nGuessLangPara = EditView::CheckLanguage( rParaText, ::GetSpellChecker(), xLG, true );
    }
    if (nGuessLangWord != LANGUAGE_NONE || nGuessLangPara != LANGUAGE_NONE)
    {
        // make sure LANGUAGE_NONE gets not used as menu entry
        if (nGuessLangWord == LANGUAGE_NONE)
            nGuessLangWord = nGuessLangPara;
        if (nGuessLangPara == LANGUAGE_NONE)
            nGuessLangPara = nGuessLangWord;<--- Variable 'nGuessLangPara' is assigned a value that is never used.
    }

    m_xPopupMenu->EnableItem(m_nAddMenuId, false);
    m_xPopupMenu->EnableItem(m_nAddId, false);

    //ADD NEW LANGUAGE MENU ITEM

    OUString aScriptTypesInUse( OUString::number( static_cast<int>(pWrtSh->GetScriptType()) ) );

    // get keyboard language
    OUString aKeyboardLang;
    SwEditWin& rEditWin = pWrtSh->GetView().GetEditWin();
    LanguageType nLang = rEditWin.GetInputLanguage();
    if (nLang != LANGUAGE_DONTKNOW && nLang != LANGUAGE_SYSTEM)
        aKeyboardLang = SvtLanguageTable::GetLanguageString( nLang );

    // get the language that is in use
    OUString aCurrentLang("*");
    nLang = SwLangHelper::GetCurrentLanguage( *pWrtSh );
    if (nLang != LANGUAGE_DONTKNOW)
        aCurrentLang = SvtLanguageTable::GetLanguageString( nLang );

    // build sequence for status value
    uno::Sequence< OUString > aSeq( 4 );
    aSeq[0] = aCurrentLang;
    aSeq[1] = aScriptTypesInUse;
    aSeq[2] = aKeyboardLang;
    aSeq[3] = SvtLanguageTable::GetLanguageString(nGuessLangWord);

    PopupMenu *pMenu = m_xPopupMenu->GetPopupMenu(m_nLangSelectionMenuId);
    fillLangPopupMenu( pMenu, MN_SET_LANGUAGE_SELECTION_START, aSeq, pWrtSh, m_aLangTable_Text );
    m_xPopupMenu->EnableItem(m_nLangSelectionMenuId);

    pMenu = m_xPopupMenu->GetPopupMenu(m_nLangParaMenuId);
    fillLangPopupMenu( pMenu, MN_SET_LANGUAGE_PARAGRAPH_START, aSeq, pWrtSh, m_aLangTable_Paragraph );
    m_xPopupMenu->EnableItem(m_nLangParaMenuId);

    if (bUseImagesInMenus)
        m_xPopupMenu->SetItemImage(m_nSpellDialogId,
            vcl::CommandInfoProvider::GetImageForCommand(".uno:SpellingAndGrammarDialog", xFrame));

    checkRedline();
    m_xPopupMenu->RemoveDisabledEntries(true, true);

    SvtLinguConfig().SetProperty( UPN_IS_GRAMMAR_INTERACTIVE, uno::makeAny( true ));

    InitItemCommands(rSuggestions);
}

SwSpellPopup::~SwSpellPopup() {}

void SwSpellPopup::InitItemCommands(const css::uno::Sequence< OUString >& aSuggestions)
{
    if (comphelper::LibreOfficeKit::isActive())
    {
        // None is added only for LOK, it means there is no need to execute anything
        m_xPopupMenu->SetItemCommand(MN_SHORT_COMMENT, ".uno:None");
        m_xPopupMenu->SetItemCommand(m_nSpellDialogId, ".uno:SpellingAndGrammarDialog");
        if(m_bGrammarResults)
            m_xPopupMenu->SetItemCommand(m_nIgnoreWordId, ".uno:SpellCheckIgnoreAll?Type:string=Grammar");
        else
            m_xPopupMenu->SetItemCommand(m_nIgnoreWordId, ".uno:SpellCheckIgnoreAll?Type:string=Spelling");
        if(m_bGrammarResults)
            m_xPopupMenu->SetItemCommand(MN_IGNORE_SELECTION, ".uno:SpellCheckIgnore?Type:string=Grammar");
        else
            m_xPopupMenu->SetItemCommand(MN_IGNORE_SELECTION, ".uno:SpellCheckIgnore?Type:string=Spelling");

        for(int i = 0; i < aSuggestions.getLength(); ++i)
        {
            sal_uInt16 nItemId = MN_SUGGESTION_START + i;
            OUString sCommandString = ".uno:SpellCheckApplySuggestion?ApplyRule:string=";
            if(m_bGrammarResults)
                sCommandString += "Grammar_";
            else if (m_xSpellAlt.is())
                sCommandString += "Spelling_";
            sCommandString += m_xPopupMenu->GetItemText(nItemId);
            m_xPopupMenu->SetItemCommand(nItemId, sCommandString);
        }

        PopupMenu *pMenu = m_xPopupMenu->GetPopupMenu(m_nLangSelectionMenuId);
        m_xPopupMenu->SetItemCommand(m_nLangSelectionMenuId, ".uno:SetSelectionLanguageMenu");
        if(pMenu)
        {
            for (const auto& item : m_aLangTable_Text)
            {
                OUString sCommandString = ".uno:LanguageStatus?Language:string=Current_" + item.second;
                pMenu->SetItemCommand(item.first, sCommandString);
            }

            pMenu->SetItemCommand(MN_SET_SELECTION_NONE, ".uno:LanguageStatus?Language:string=Current_LANGUAGE_NONE");
            pMenu->SetItemCommand(MN_SET_SELECTION_RESET, ".uno:LanguageStatus?Language:string=Current_RESET_LANGUAGES");
            pMenu->SetItemCommand(MN_SET_SELECTION_MORE, ".uno:FontDialog?Page:string=font");
        }

        pMenu = m_xPopupMenu->GetPopupMenu(m_nLangParaMenuId);
        m_xPopupMenu->SetItemCommand(m_nLangParaMenuId, ".uno:SetParagraphLanguageMenu");
        if(pMenu)
        {
            for (const auto& item : m_aLangTable_Paragraph)
            {
                OUString sCommandString = ".uno:LanguageStatus?Language:string=Paragraph_" + item.second;
                pMenu->SetItemCommand(item.first, sCommandString);
            }

            pMenu->SetItemCommand(MN_SET_PARA_NONE, ".uno:LanguageStatus?Language:string=Paragraph_LANGUAGE_NONE");
            pMenu->SetItemCommand(MN_SET_PARA_RESET, ".uno:LanguageStatus?Language:string=Paragraph_RESET_LANGUAGES");
            pMenu->SetItemCommand(MN_SET_PARA_MORE, ".uno:FontDialogForParagraph");
        }
    }
}

void SwSpellPopup::checkRedline()
{
    // Let SwView::GetState() already has the logic on when to disable the
    // accept/reject and the next/prev change items, let it do the decision.

    // Build an item set that contains a void item for each menu entry. The
    // WhichId of each item is set, so SwView may clear it.
    static const sal_uInt16 pRedlineIds[] = {
        FN_REDLINE_ACCEPT_DIRECT,
        FN_REDLINE_REJECT_DIRECT,
        FN_REDLINE_NEXT_CHANGE,
        FN_REDLINE_PREV_CHANGE
    };
    SwDoc *pDoc = m_pSh->GetDoc();
    SfxItemSet aSet(pDoc->GetAttrPool(), svl::Items<FN_REDLINE_ACCEPT_DIRECT, FN_REDLINE_PREV_CHANGE>{});
    for (sal_uInt16 nWhich : pRedlineIds)
    {
        aSet.Put(SfxVoidItem(nWhich));
    }
    m_pSh->GetView().GetState(aSet);

    // Enable/disable items based on if the which id of the void items are
    // cleared or not.
    for (sal_uInt16 nWhich : pRedlineIds)
    {
        sal_uInt16 nId(0);
        if (nWhich == FN_REDLINE_ACCEPT_DIRECT)
            nId = m_nRedlineAcceptId;
        else if (nWhich == FN_REDLINE_REJECT_DIRECT)
            nId = m_nRedlineRejectId;
        else if (nWhich == FN_REDLINE_NEXT_CHANGE)
            nId = m_nRedlineNextId;
        else if (nWhich == FN_REDLINE_PREV_CHANGE)
            nId = m_nRedlinePrevId;
        m_xPopupMenu->EnableItem(nId, aSet.Get(nWhich).Which() != 0);
    }
}

void SwSpellPopup::Execute( const tools::Rectangle& rWordPos, vcl::Window* pWin )
{
    sal_uInt16 nRet = m_xPopupMenu->Execute(pWin, pWin->LogicToPixel(rWordPos));
    Execute( nRet );
}

void SwSpellPopup::Execute( sal_uInt16 nId )
{
    if (nId == USHRT_MAX)
        return;

    if (/*m_bGrammarResults && */nId == MN_SHORT_COMMENT)
        return;     // nothing to do since it is the error message (short comment)

    if (MN_SUGGESTION_START <= nId && nId <= MN_SUGGESTION_END)
    {
        OUString sApplyRule("");
        if(m_bGrammarResults)
            sApplyRule += "Grammar_";
        else if (m_xSpellAlt.is())
            sApplyRule += "Spelling_";
        sApplyRule += m_xPopupMenu->GetItemText(nId);

        SfxStringItem aApplyItem(FN_PARAM_1, sApplyRule);
        m_pSh->GetView().GetViewFrame()->GetDispatcher()->ExecuteList(SID_SPELLCHECK_APPLY_SUGGESTION, SfxCallMode::SYNCHRON, { &aApplyItem });
    }
    else if(MN_AUTOCORR_START <= nId && nId <= MN_AUTOCORR_END)
    {
        if (m_xSpellAlt.is())
        {
            bool bOldIns = m_pSh->IsInsMode();
            m_pSh->SetInsMode();

            PopupMenu* pMenu = m_xPopupMenu->GetPopupMenu(m_nCorrectMenuId);
            assert(pMenu);
            OUString aTmp( pMenu->GetItemText(nId) );
            OUString aOrig( m_xSpellAlt->getWord() );

            // if original word has a trailing . (likely the end of a sentence)
            // and the replacement text hasn't, then add it to the replacement
            if (!aTmp.isEmpty() && !aOrig.isEmpty() &&
                aOrig.endsWith(".") && /* !IsAlphaNumeric ??*/
                !aTmp.endsWith("."))
            {
                aTmp += ".";
            }

            SwRewriter aRewriter;

            aRewriter.AddRule(UndoArg1, m_pSh->GetCursorDescr());
            aRewriter.AddRule(UndoArg2, SwResId(STR_YIELDS));

            OUString aTmpStr = SwResId(STR_START_QUOTE) +
                aTmp + SwResId(STR_END_QUOTE);
            aRewriter.AddRule(UndoArg3, aTmpStr);

            m_pSh->StartUndo(SwUndoId::UI_REPLACE, &aRewriter);
            m_pSh->StartAction();
            m_pSh->DelLeft();

            m_pSh->Insert( aTmp );

            /* #102505# EndAction/EndUndo moved down since insertion
               of temporary auto correction is now undoable two and
               must reside in the same undo group.*/

            // record only if it's NOT already present in autocorrection
            SvxAutoCorrect* pACorr = SvxAutoCorrCfg::Get().GetAutoCorrect();

            OUString aOrigWord( m_xSpellAlt->getWord() ) ;
            OUString aNewWord( pMenu->GetItemText(nId) );
            SvxPrepareAutoCorrect( aOrigWord, aNewWord );

            pACorr->PutText( aOrigWord, aNewWord, m_nCheckedLanguage );

            /* #102505# EndAction/EndUndo moved down since insertion
               of temporary auto correction is now undoable two and
               must reside in the same undo group.*/
            m_pSh->EndAction();
            m_pSh->EndUndo();

            m_pSh->SetInsMode( bOldIns );
        }
    }
    else if (nId == m_nSpellDialogId)
    {
        m_pSh->Left(CRSR_SKIP_CHARS, false, 1, false );
        {
            m_pSh->GetView().GetViewFrame()->GetDispatcher()->
                Execute( FN_SPELL_GRAMMAR_DIALOG, SfxCallMode::ASYNCHRON );
        }
    }
    else if (nId == m_nCorrectDialogId)
    {
        m_pSh->GetView().GetViewFrame()->GetDispatcher()->Execute( SID_AUTO_CORRECT_DLG, SfxCallMode::ASYNCHRON );
    }
    else if (nId == MN_IGNORE_SELECTION)
    {
        SfxStringItem aIgnoreString(FN_PARAM_1, m_bGrammarResults ? OUString("Grammar") : OUString("Spelling"));
        m_pSh->GetView().GetViewFrame()->GetDispatcher()->ExecuteList(SID_SPELLCHECK_IGNORE, SfxCallMode::SYNCHRON, { &aIgnoreString });
    }
    else if (nId == m_nIgnoreWordId)
    {
        SfxStringItem aIgnoreString(FN_PARAM_1, m_bGrammarResults ? OUString("Grammar") : OUString("Spelling"));
        m_pSh->GetView().GetViewFrame()->GetDispatcher()->ExecuteList(SID_SPELLCHECK_IGNORE_ALL, SfxCallMode::SYNCHRON, { &aIgnoreString });
    }
    else if ((MN_DICTIONARIES_START <= nId && nId <= MN_DICTIONARIES_END) || nId == m_nAddId)
    {
        OUString sWord( m_xSpellAlt->getWord() );
        OUString aDicName;

        if (MN_DICTIONARIES_START <= nId && nId <= MN_DICTIONARIES_END)
        {
            PopupMenu *pMenu = m_xPopupMenu->GetPopupMenu(m_nAddMenuId);
            aDicName = pMenu->GetItemText(nId);
        }
        else
            aDicName = m_aDicNameSingle;

        uno::Reference< linguistic2::XDictionary >      xDic;
        uno::Reference< linguistic2::XSearchableDictionaryList >  xDicList( LinguMgr::GetDictionaryList() );
        if (xDicList.is())
            xDic = xDicList->getDictionaryByName( aDicName );

        if (xDic.is())
        {
            linguistic::DictionaryError nAddRes = linguistic::AddEntryToDic(xDic, sWord, false, OUString());
            // save modified user-dictionary if it is persistent
            uno::Reference< frame::XStorable >  xSavDic( xDic, uno::UNO_QUERY );
            if (xSavDic.is())
                xSavDic->store();

            if (linguistic::DictionaryError::NONE != nAddRes && !xDic->getEntry(sWord).is())
            {
                SvxDicError(m_pSh->GetView().GetFrameWeld(), nAddRes);
            }
        }
    }
    else if ( nId == MN_EXPLANATION_LINK && !m_sExplanationLink.isEmpty() )
    {
        try
        {
            uno::Reference< css::system::XSystemShellExecute > xSystemShellExecute(
                css::system::SystemShellExecute::create( ::comphelper::getProcessComponentContext() ) );
            xSystemShellExecute->execute( m_sExplanationLink, OUString(),
                    css::system::SystemShellExecuteFlags::URIS_ONLY );
        }
        catch (const uno::Exception&)
        {
            uno::Any exc( ::cppu::getCaughtException() );
            OUString msg( ::comphelper::anyToString( exc ) );
            const SolarMutexGuard guard;
            std::unique_ptr<weld::MessageDialog> xBox(Application::CreateMessageDialog(m_pSh->GetView().GetFrameWeld(),
                                                      VclMessageType::Warning, VclButtonsType::Ok, msg));
            xBox->set_title("Explanations");
            xBox->run();
        }
    }
    else if (nId == m_nRedlineAcceptId || nId == m_nRedlineRejectId
            || nId == m_nRedlineNextId || nId == m_nRedlinePrevId)
    {
        if (nId == m_nRedlineAcceptId)
            nId = FN_REDLINE_ACCEPT_DIRECT;
        else if (nId == m_nRedlineRejectId)
            nId = FN_REDLINE_REJECT_DIRECT;
        else if (nId == m_nRedlineNextId)
            nId = FN_REDLINE_NEXT_CHANGE;
        else if (nId == m_nRedlinePrevId)
            nId = FN_REDLINE_PREV_CHANGE;
        // Let SwView::Execute() handle the redline actions.
        SfxRequest aReq(m_pSh->GetView().GetViewFrame(), nId);
        m_pSh->GetView().Execute(aReq);
    }
    else
    {
        if (MN_SET_LANGUAGE_SELECTION_START <= nId && nId <= MN_SET_LANGUAGE_SELECTION_END)
        {
            SfxStringItem aLangString(SID_LANGUAGE_STATUS, "Current_" + m_aLangTable_Text[nId]);
            m_pSh->GetView().GetViewFrame()->GetDispatcher()->ExecuteList(SID_LANGUAGE_STATUS, SfxCallMode::SYNCHRON, { &aLangString });
        }
        else if (nId == MN_SET_SELECTION_NONE)
        {
            SfxStringItem aLangString(SID_LANGUAGE_STATUS, "Current_LANGUAGE_NONE");
            m_pSh->GetView().GetViewFrame()->GetDispatcher()->ExecuteList(SID_LANGUAGE_STATUS, SfxCallMode::SYNCHRON, { &aLangString });
        }
        else if (nId == MN_SET_SELECTION_RESET)
        {
            SfxStringItem aLangString(SID_LANGUAGE_STATUS, "Current_RESET_LANGUAGES");
            m_pSh->GetView().GetViewFrame()->GetDispatcher()->ExecuteList(SID_LANGUAGE_STATUS, SfxCallMode::SYNCHRON, { &aLangString });
        }
        else if (nId == MN_SET_SELECTION_MORE)
        {
            SfxStringItem aDlgString(FN_PARAM_1, "font");
            m_pSh->GetView().GetViewFrame()->GetDispatcher()->ExecuteList(SID_CHAR_DLG, SfxCallMode::SYNCHRON, { &aDlgString });
        }
        else if (MN_SET_LANGUAGE_PARAGRAPH_START <= nId && nId <= MN_SET_LANGUAGE_PARAGRAPH_END)
        {
            SfxStringItem aLangString(SID_LANGUAGE_STATUS, "Paragraph_" + m_aLangTable_Paragraph[nId]);
            m_pSh->GetView().GetViewFrame()->GetDispatcher()->ExecuteList(SID_LANGUAGE_STATUS, SfxCallMode::SYNCHRON, { &aLangString });
        }
        else if (nId == MN_SET_PARA_NONE)
        {
            SfxStringItem aLangString(SID_LANGUAGE_STATUS, "Paragraph_LANGUAGE_NONE");
            m_pSh->GetView().GetViewFrame()->GetDispatcher()->ExecuteList(SID_LANGUAGE_STATUS, SfxCallMode::SYNCHRON, { &aLangString });
        }
        else if (nId == MN_SET_PARA_RESET)
        {
            SfxStringItem aLangString(SID_LANGUAGE_STATUS, "Paragraph_RESET_LANGUAGES");
            m_pSh->GetView().GetViewFrame()->GetDispatcher()->ExecuteList(SID_LANGUAGE_STATUS, SfxCallMode::SYNCHRON, { &aLangString });
        }
        else if (nId == MN_SET_PARA_MORE)
        {
            m_pSh->GetView().GetViewFrame()->GetDispatcher()->Execute( SID_CHAR_DLG_FOR_PARAGRAPH );
        }
    }

    m_pSh->EnterStdMode();
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */