summaryrefslogtreecommitdiffstats
path: root/shell/source/win32/jumplist/JumpList.cxx
blob: cbc72299b41a8227c60095566c91f364c9802b6a (plain)
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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */
/*
 * 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/.
 */

#include <sal/config.h>

#include <algorithm>
#include <cassert>

#include <cppuhelper/basemutex.hxx>
#include <cppuhelper/compbase.hxx>
#include <comphelper/sequence.hxx>
#include <cppuhelper/supportsservice.hxx>
#include <o3tl/char16_t2wchar_t.hxx>
#include <o3tl/runtimetooustring.hxx>
#include <o3tl/safeCoInitUninit.hxx>
#include <osl/file.hxx>
#include <osl/mutex.hxx>
#include <osl/process.h>
#include <sal/log.hxx>
#include <systools/win32/comtools.hxx>

#include <com/sun/star/lang/IllegalArgumentException.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/system/windows/JumpListItem.hpp>
#include <com/sun/star/system/windows/XJumpList.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>

#include <prewin.h>
#include <Shlobj.h>
#include <propkey.h>
#include <propvarutil.h>
#include <postwin.h>

using namespace comphelper;
using namespace cppu;
using namespace css;
using namespace css::uno;
using namespace css::lang;
using namespace css::system::windows;
using namespace osl;
using sal::systools::COMReference;
using sal::systools::COM_QUERY_THROW;
using sal::systools::ComError;
using sal::systools::ThrowIfFailed;

class JumpListImpl : public BaseMutex, public WeakComponentImplHelper<XJumpList, XServiceInfo>
{
    Reference<XComponentContext> m_xContext;

public:
    explicit JumpListImpl(const Reference<XComponentContext>& xContext);
    ~JumpListImpl();

    // XJumpList
    virtual void SAL_CALL appendCategory(const OUString& sCategory,
                                         const Sequence<JumpListItem>& aJumpListItems,
                                         const OUString& sApplication) override;
    virtual void SAL_CALL deleteCategory(const OUString& sApplication) override;
    virtual Sequence<JumpListItem> SAL_CALL getRemovedItems(const OUString& sApplication) override;

    // XServiceInfo
    virtual OUString SAL_CALL getImplementationName() override;
    virtual sal_Bool SAL_CALL supportsService(const OUString& ServiceName) override;
    virtual Sequence<OUString> SAL_CALL getSupportedServiceNames() override;
};

JumpListImpl::JumpListImpl(const Reference<XComponentContext>& xContext)
    : WeakComponentImplHelper(m_aMutex)
    , m_xContext(xContext)
{
}

JumpListImpl::~JumpListImpl() {}

namespace
{
// Determines if the provided IShellLinkItem is listed in the array of items that the user has removed
bool lcl_isItemInArray(COMReference<IShellLinkW> pShellLinkItem,
                       COMReference<IObjectArray> poaRemoved)
{
    UINT nItems;
    ThrowIfFailed(poaRemoved->GetCount(&nItems), "GetCount failed.");

    COMReference<IShellLinkW> pShellLinkItemCompare;
    for (UINT i = 0; i < nItems; i++)
    {
        if (!SUCCEEDED(poaRemoved->GetAt(i, IID_PPV_ARGS(&pShellLinkItemCompare))))
            continue;

        PROPVARIANT propvar;
        COMReference<IPropertyStore> pps(pShellLinkItem, COM_QUERY_THROW);
        ThrowIfFailed(pps->GetValue(PKEY_Title, &propvar), "GetValue failed.");
        OUString title(o3tl::toU(PropVariantToStringWithDefault(propvar, L"")));

        COMReference<IPropertyStore> ppsCompare(pShellLinkItemCompare, COM_QUERY_THROW);
        ThrowIfFailed(ppsCompare->GetValue(PKEY_Title, &propvar), "GetValue failed.");
        OUString titleCompare(o3tl::toU(PropVariantToStringWithDefault(propvar, L"")));
        PropVariantClear(&propvar);

        if (title == titleCompare)
            return true;
    }

    return false;
}
}

void SAL_CALL JumpListImpl::appendCategory(const OUString& sCategory,
                                           const Sequence<JumpListItem>& aJumpListItems,
                                           const OUString& sApplication)
{
    if (sCategory.isEmpty())
    {
        throw IllegalArgumentException("Parameter 'category' must not be empty",
                                       static_cast<OWeakObject*>(this), 1);
    }
    if (sApplication != "Writer" && sApplication != "Calc" && sApplication != "Impress"
        && sApplication != "Draw" && sApplication != "Math" && sApplication != "Base"
        && sApplication != "Startcenter")
    {
        throw IllegalArgumentException(
            "Parameter 'application' must be one of 'Writer', 'Calc', 'Impress', 'Draw', "
            "'Math', 'Base', 'Startcenter'.",
            static_cast<OWeakObject*>(this), 1);
    }
    OUString sApplicationID("TheDocumentFoundation.LibreOffice." + sApplication);

    try
    {
        COMReference<ICustomDestinationList> aDestinationList;
        CoCreateInstance(CLSID_DestinationList, nullptr, CLSCTX_INPROC_SERVER,
                         IID_PPV_ARGS(&aDestinationList));

        aDestinationList->SetAppID(o3tl::toW(sApplicationID.getStr()));

        UINT min_slots;
        COMReference<IObjectArray> removed;
        ThrowIfFailed(aDestinationList->BeginList(&min_slots, IID_PPV_ARGS(&removed)),
                      "BeginList failed");

        OUString sofficeURL;
        OUString sofficePath;
        oslProcessError err = osl_getExecutableFile(&sofficeURL.pData);
        FileBase::getSystemPathFromFileURL(sofficeURL, sofficePath);
        if (err != osl_Process_E_None)
        {
            SAL_WARN("shell.jumplist", "osl_getExecutableFile failed");
            return;
        }
        // We need to run soffice.exe, not soffice.bin
        sofficePath = sofficePath.replaceFirst("soffice.bin", "soffice.exe");

        COMReference<IObjectCollection> aCollection;
        CoCreateInstance(CLSID_EnumerableObjectCollection, nullptr, CLSCTX_INPROC_SERVER,
                         IID_PPV_ARGS(&aCollection));

        for (auto item : aJumpListItems)
        {
            if (item.name.isEmpty())
                continue;
            try
            {
                COMReference<IShellLinkW> pShellLinkItem;
                CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
                                 IID_PPV_ARGS(&pShellLinkItem));

                {
                    COMReference<IPropertyStore> pps(pShellLinkItem, COM_QUERY_THROW);

                    PROPVARIANT propvar;
                    ThrowIfFailed(
                        InitPropVariantFromString(o3tl::toW(item.name.getStr()), &propvar),
                        "InitPropVariantFromString failed.");

                    ThrowIfFailed(pps->SetValue(PKEY_Title, propvar), "SetValue failed.");

                    ThrowIfFailed(pps->Commit(), "Commit failed.");

                    PropVariantClear(&propvar);
                }
                ThrowIfFailed(
                    pShellLinkItem->SetDescription(o3tl::toW(item.description.getStr())),
                    OString("Setting description '" + item.description.toUtf8() + "' failed."));

                ThrowIfFailed(pShellLinkItem->SetPath(o3tl::toW(sofficePath.getStr())),
                              OString("Setting path '" + sofficePath.toUtf8() + "' failed."));

                ThrowIfFailed(
                    pShellLinkItem->SetArguments(o3tl::toW(item.arguments.getStr())),
                    OString("Setting arguments '" + item.arguments.toUtf8() + "' failed."));

                ThrowIfFailed(
                    pShellLinkItem->SetIconLocation(o3tl::toW(item.iconPath.getStr()), 0),
                    OString("Setting icon path '" + item.iconPath.toUtf8() + "' failed."));

                if (lcl_isItemInArray(pShellLinkItem, removed))
                {
                    SAL_INFO("shell.jumplist", "Ignoring item '"
                                                   << item.name
                                                   << "' (was removed by user). See output of "
                                                      "XJumpList::getRemovedItems().");
                    continue;
                }
                aCollection->AddObject(pShellLinkItem.get());
            }
            catch (const ComError& e)
            {
                SAL_WARN("shell.jumplist", e.what());
                continue;
            }
        }

        COMReference<IObjectArray> pObjectArray(aCollection, COM_QUERY_THROW);
        UINT nItems;
        ThrowIfFailed(pObjectArray->GetCount(&nItems), "GetCount failed.");
        if (nItems == 0)
        {
            throw IllegalArgumentException(
                "No valid items given. `jumpListItems` is either empty, or contains only items "
                "which were removed by the user. See `XJumpList::getRemovedItems()`.",
                static_cast<OWeakObject*>(this), 1);
        }

        ThrowIfFailed(
            aDestinationList->AppendCategory(o3tl::toW(sCategory.getStr()), pObjectArray.get()),
            "AppendCategory failed.");

        ThrowIfFailed(aDestinationList->CommitList(), "CommitList failed.");
    }
    catch (const ComError& e)
    {
        SAL_WARN("shell.jumplist", e.what());
    }
}

void SAL_CALL JumpListImpl::deleteCategory(const OUString& sApplication)
{
    if (sApplication != "Writer" && sApplication != "Calc" && sApplication != "Impress"
        && sApplication != "Draw" && sApplication != "Math" && sApplication != "Base"
        && sApplication != "Startcenter")
    {
        throw IllegalArgumentException(
            "Parameter 'application' must be one of 'Writer', 'Calc', 'Impress', 'Draw', "
            "'Math', 'Base', 'Startcenter'.",
            static_cast<OWeakObject*>(this), 1);
    }
    OUString sApplicationID("TheDocumentFoundation.LibreOffice." + sApplication);

    try
    {
        COMReference<ICustomDestinationList> aDestinationList;
        CoCreateInstance(CLSID_DestinationList, nullptr, CLSCTX_INPROC_SERVER,
                         IID_PPV_ARGS(&aDestinationList));
        aDestinationList->DeleteList(o3tl::toW(sApplicationID.getStr()));
    }
    catch (const ComError& e)
    {
        SAL_WARN("shell.jumplist", e.what());
    }
}

Sequence<JumpListItem> SAL_CALL JumpListImpl::getRemovedItems(const OUString& sApplication)
{
    if (sApplication != "Writer" && sApplication != "Calc" && sApplication != "Impress"
        && sApplication != "Draw" && sApplication != "Math" && sApplication != "Base"
        && sApplication != "Startcenter")
    {
        throw IllegalArgumentException(
            "Parameter 'application' must be one of 'Writer', 'Calc', 'Impress', 'Draw', "
            "'Math', 'Base', 'Startcenter'.",
            static_cast<OWeakObject*>(this), 1);
    }
    OUString sApplicationID("TheDocumentFoundation.LibreOffice." + sApplication);

    std::vector<JumpListItem> removedItems;
    try
    {
        sal::systools::COMReference<ICustomDestinationList> aDestinationList;
        CoCreateInstance(CLSID_DestinationList, nullptr, CLSCTX_INPROC_SERVER,
                         IID_PPV_ARGS(&aDestinationList));

        aDestinationList->SetAppID(o3tl::toW(sApplicationID.getStr()));

        sal::systools::COMReference<IObjectArray> removed;
        ThrowIfFailed(aDestinationList->GetRemovedDestinations(IID_PPV_ARGS(&removed)),
                      "BeginList failed");

        UINT removed_count;
        if (SUCCEEDED(removed->GetCount(&removed_count) && (removed_count > 0)))
        {
            JumpListItem item;
            sal::systools::COMReference<IShellLinkW> pShellLinkItem;
            for (UINT i = 0; i < removed_count; ++i)
            {
                if (SUCCEEDED(removed->GetAt(i, IID_PPV_ARGS(&pShellLinkItem))))
                {
                    sal::systools::COMReference<IPropertyStore> propertyStore(pShellLinkItem,
                                                                              COM_QUERY_THROW);
                    PROPVARIANT propvar;
                    ThrowIfFailed(propertyStore->GetValue(PKEY_Title, &propvar),
                                  "GetValue failed.");
                    item.name = o3tl::toU(PropVariantToStringWithDefault(propvar, L""));

                    ThrowIfFailed(propertyStore->GetValue(PKEY_Link_Arguments, &propvar),
                                  "GetValue failed.");
                    item.arguments = o3tl::toU(PropVariantToStringWithDefault(propvar, L""));
                    PropVariantClear(&propvar);

                    wchar_t itemDesc[MAX_PATH];
                    ThrowIfFailed(pShellLinkItem->GetDescription(
                                      itemDesc, std::extent<decltype(itemDesc)>::value),
                                  "GetDescription failed.");
                    item.description = o3tl::toU(itemDesc);

                    wchar_t path[MAX_PATH];
                    int icon_index;
                    ThrowIfFailed(pShellLinkItem->GetIconLocation(
                                      path, std::extent<decltype(path)>::value, &icon_index),
                                  "GetIconLocation failed.");
                    item.iconPath = o3tl::toU(path);

                    removedItems.emplace_back(item);
                }
            }
        }
    }
    catch (const ComError& e)
    {
        SAL_WARN("shell.jumplist", e.what());
    }

    return containerToSequence(removedItems);
}

// XServiceInfo

OUString SAL_CALL JumpListImpl::getImplementationName()
{
    return "com.sun.star.system.windows.JumpListImpl";
}

sal_Bool SAL_CALL JumpListImpl::supportsService(const OUString& ServiceName)
{
    return cppu::supportsService(this, ServiceName);
}

Sequence<OUString> SAL_CALL JumpListImpl::getSupportedServiceNames()
{
    return { "com.sun.star.system.windows.JumpList" };
}

extern "C" SAL_DLLPUBLIC_EXPORT XInterface*
shell_JumpListExec_get_implementation(XComponentContext* context, Sequence<Any> const&)
{
    return acquire(new JumpListImpl(context));
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */