summaryrefslogtreecommitdiff
path: root/sc/source/ui/docshell/datastream.cxx
blob: 88c2ae40b45c5a5cc5893c4dc4713ee6609d4f48 (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
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
/* -*- 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/.
 */

#include <datastream.hxx>

#include <com/sun/star/frame/XLayoutManager.hpp>
#include <com/sun/star/ui/XUIElement.hpp>
#include <officecfg/Office/Common.hxx>
#include <osl/conditn.hxx>
#include <rtl/strbuf.hxx>
#include <salhelper/thread.hxx>
#include <sfx2/linkmgr.hxx>
#include <sfx2/viewfrm.hxx>
#include <arealink.hxx>
#include <asciiopt.hxx>
#include <datastreamdlg.hxx>
#include <dbfunc.hxx>
#include <docsh.hxx>
#include <documentimport.hxx>
#include <impex.hxx>
#include <rangelst.hxx>
#include <tabvwsh.hxx>
#include <viewdata.hxx>

#include <queue>

namespace datastreams {

class ReaderThread : public salhelper::Thread
{
    SvStream *mpStream;
public:
    bool mbTerminateReading;
    osl::Condition maProduceResume;
    osl::Condition maConsumeResume;
    osl::Mutex maLinesProtector;
    std::queue<LinesList* > maPendingLines;
    std::queue<LinesList* > maUsedLines;

    ReaderThread(SvStream *pData):
        Thread("ReaderThread")
        ,mpStream(pData)
        ,mbTerminateReading(false)
    {
    }

    virtual ~ReaderThread()
    {
        delete mpStream;
        while (!maPendingLines.empty())
        {
            delete maPendingLines.front();
            maPendingLines.pop();
        }
        while (!maUsedLines.empty())
        {
            delete maUsedLines.front();
            maUsedLines.pop();
        }
    }

    void endThread()
    {
        mbTerminateReading = true;
        maProduceResume.set();
        join();
    }

private:
    virtual void execute() SAL_OVERRIDE
    {
        while (!mbTerminateReading)
        {
            LinesList *pLines = 0;
            osl::ResettableMutexGuard aGuard(maLinesProtector);
            if (!maUsedLines.empty())
            {
                pLines = maUsedLines.front();
                maUsedLines.pop();
                aGuard.clear(); // unlock
            }
            else
            {
                aGuard.clear(); // unlock
                pLines = new LinesList(10);
            }
            for (size_t i = 0; i < pLines->size(); ++i)
                mpStream->ReadLine( pLines->at(i) );
            aGuard.reset(); // lock
            while (!mbTerminateReading && maPendingLines.size() >= 8)
            { // pause reading for a bit
                aGuard.clear(); // unlock
                maProduceResume.wait();
                maProduceResume.reset();
                aGuard.reset(); // lock
            }
            maPendingLines.push(pLines);
            maConsumeResume.set();
            if (!mpStream->good())
                mbTerminateReading = true;
        }
    }
};

}

void DataStream::MakeToolbarVisible()
{
    css::uno::Reference< css::frame::XFrame > xFrame =
        ScDocShell::GetViewData()->GetViewShell()->GetViewFrame()->GetFrame().GetFrameInterface();
    if (!xFrame.is())
        return;

    css::uno::Reference< css::beans::XPropertySet > xPropSet(xFrame, css::uno::UNO_QUERY);
    if (!xPropSet.is())
        return;

    css::uno::Reference< css::frame::XLayoutManager > xLayoutManager;
    xPropSet->getPropertyValue("LayoutManager") >>= xLayoutManager;
    if (!xLayoutManager.is())
        return;

    const OUString sResourceURL( "private:resource/toolbar/datastreams" );
    css::uno::Reference< css::ui::XUIElement > xUIElement = xLayoutManager->getElement(sResourceURL);
    if (!xUIElement.is())
    {
        xLayoutManager->createElement( sResourceURL );
        xLayoutManager->showElement( sResourceURL );
    }
}

DataStream* DataStream::Set(ScDocShell *pShell, const OUString& rURL, const OUString& rRange,
        sal_Int32 nLimit, const OUString& rMove, sal_uInt32 nSettings)
{
    // Each DataStream needs a destination area in order to be exported.
    // There can be only one ScAreaLink / DataStream per cell.
    // So - if we don't need range (DataStream with mbValuesInLine == false),
    // just find a free cell for now.
    sfx2::LinkManager* pLinkManager = pShell->GetDocument()->GetLinkManager();
    ScRange aDestArea;
    aDestArea.Parse(rRange, pShell->GetDocument());
    sal_uInt16 nLinkPos = 0;
    while (nLinkPos < pLinkManager->GetLinks().size())
    {
        sfx2::SvBaseLink* pBase = *pLinkManager->GetLinks()[nLinkPos];
        if (rRange.isEmpty())
        {
            if ( (pBase->ISA(ScAreaLink) && dynamic_cast<ScAreaLink*>
                        (&(*pBase))->GetDestArea().aStart == aDestArea.aStart)
                || (pBase->ISA(DataStream) && dynamic_cast<DataStream*>
                        (&(*pBase))->GetRange().aStart == aDestArea.aStart) )
            {
                aDestArea.Move(0, 1, 0);
                nLinkPos = 0;
                continue;
            }
            else
                ++nLinkPos;
        }
        else if ( (pBase->ISA(ScAreaLink) && dynamic_cast<ScAreaLink*>
                    (&(*pBase))->GetDestArea().aStart == aDestArea.aStart)
                || (pBase->ISA(DataStream) && dynamic_cast<DataStream*>
                    (&(*pBase))->GetRange().aStart == aDestArea.aStart) )
        {
            pLinkManager->Remove( pBase );
        }
        else
            ++nLinkPos;
    }

    sfx2::SvBaseLink *pLink = 0;
    pLink = new DataStream( pShell, rURL, rRange, nLimit, rMove, nSettings );
    pLinkManager->InsertFileLink( *pLink, OBJECT_CLIENT_FILE, rURL, NULL, NULL );
    return dynamic_cast<DataStream*>(pLink);
}

DataStream::DataStream(ScDocShell *pShell, const OUString& rURL, const OUString& rRange,
        sal_Int32 nLimit, const OUString& rMove, sal_uInt32 nSettings)
    : mpScDocShell(pShell)
    , mpScDocument(mpScDocShell->GetDocument())
    , meMove(NO_MOVE)
    , mbRunning(false)
    , mpLines(0)
    , mnLinesCount(0)
{
    SetRefreshHandler(LINK( this, DataStream, RefreshHdl ));
    SetRefreshControl(mpScDocument->GetRefreshTimerControlAddress());
    SetTimeout( 1 );
    Decode(rURL, rRange, nLimit, rMove, nSettings);
}

DataStream::~DataStream()
{
    if (mbRunning)
        StopImport();
    if (mxReaderThread.is())
        mxReaderThread->endThread();
}

OString DataStream::ConsumeLine()
{
    if (!mpLines || mnLinesCount >= mpLines->size())
    {
        mnLinesCount = 0;
        if (mxReaderThread->mbTerminateReading)
            return OString();
        osl::ResettableMutexGuard aGuard(mxReaderThread->maLinesProtector);
        if (mpLines)
            mxReaderThread->maUsedLines.push(mpLines);
        while (mxReaderThread->maPendingLines.empty())
        {
            aGuard.clear(); // unlock
            mxReaderThread->maConsumeResume.wait();
            mxReaderThread->maConsumeResume.reset();
            aGuard.reset(); // lock
        }
        mpLines = mxReaderThread->maPendingLines.front();
        mxReaderThread->maPendingLines.pop();
        if (mxReaderThread->maPendingLines.size() <= 4)
            mxReaderThread->maProduceResume.set(); // start producer again
    }
    return mpLines->at(mnLinesCount++);
}

void DataStream::Decode(const OUString& rURL, const OUString& rRange,
        sal_Int32 nLimit, const OUString& rMove, const sal_uInt32 nSettings)
{
    msURL = rURL;
    msRange = rRange;
    mnLimit = nLimit;
    msMove = rMove;
    mnSettings = nSettings;
    mpEndRange.reset( NULL );

    mbValuesInLine = mnSettings & VALUES_IN_LINE;

    if (msMove == "NO_MOVE")
        meMove = NO_MOVE;
    else if (msMove == "RANGE_DOWN")
        meMove = RANGE_DOWN;
    else if (msMove == "MOVE_DOWN")
        meMove = MOVE_DOWN;

    maRange.Parse(msRange);
    maStartRange = maRange;
    sal_Int32 nHeight = maRange.aEnd.Row() - maRange.aStart.Row() + 1;
    nLimit = nHeight * (nLimit / nHeight);
    if (nLimit && maRange.aStart.Row() + nLimit - 1 < MAXROW)
    {
        mpEndRange.reset( new ScRange(maRange) );
        mpEndRange->Move(0, nLimit - nHeight, 0);
    }
}

void DataStream::StartImport()
{
    if (mbRunning)
        return;
    mbIsUndoEnabled = mpScDocument->IsUndoEnabled();
    mpScDocument->EnableUndo(false);
    if (!mxReaderThread.is())
    {
        SvStream *pStream = 0;
        if (mnSettings & SCRIPT_STREAM)
            pStream = new SvScriptStream(msURL);
        else
            pStream = new SvFileStream(msURL, STREAM_READ);
        mxReaderThread = new datastreams::ReaderThread( pStream );
        mxReaderThread->launch();
    }
    mbRunning = true;
    AutoTimer::Start();
}

void DataStream::StopImport()
{
    if (!mbRunning)
        return;
    mbRunning = false;
    AutoTimer::Stop();
    mpScDocument->EnableUndo(mbIsUndoEnabled);
}

void DataStream::MoveData()
{
    switch (meMove)
    {
        case RANGE_DOWN:
            if (maRange.aStart == mpEndRange->aStart)
                meMove = MOVE_UP;
            break;
        case MOVE_UP:
            mpScDocument->DeleteRow(maStartRange);
            mpScDocument->InsertRow(*mpEndRange);
            break;
        case MOVE_DOWN:
            if (mpEndRange.get())
                mpScDocument->DeleteRow(*mpEndRange);
            mpScDocument->InsertRow(maRange);
            break;
        case NO_MOVE:
            break;
    }
}

IMPL_LINK_NOARG(DataStream, RefreshHdl)
{
    ImportData();
    return 0;
}

bool DataStream::ImportData()
{
    MoveData();
    if (mbValuesInLine)
    {
        SCROW nHeight = maRange.aEnd.Row() - maRange.aStart.Row() + 1;
        OStringBuffer aBuf;
        while (nHeight--)
        {
            aBuf.append(ConsumeLine());
            aBuf.append('\n');
        }
        SvMemoryStream aMemoryStream((void *)aBuf.getStr(), aBuf.getLength(), STREAM_READ);
        ScImportExport aImport(mpScDocument, maRange);
        aImport.SetSeparator(',');
        aImport.ImportStream(aMemoryStream, OUString(), FORMAT_STRING);
    }
    else
    {
        ScRangeList aRangeList;
        ScDocumentImport aDocImport(*mpScDocument);
        // read more lines at once but not too much
        for (int i = 0; i < 10; ++i)
        {
            OUString sLine( OStringToOUString(ConsumeLine(), RTL_TEXTENCODING_UTF8) );
            if (sLine.indexOf(',') <= 0)
                continue;

            OUString sAddress( sLine.copy(0, sLine.indexOf(',')) );
            OUString sValue( sLine.copy(sLine.indexOf(',') + 1) );
            ScAddress aAddress;
            aAddress.Parse(sAddress, mpScDocument);
            if (!aAddress.IsValid())
                continue;

            if (sValue == "0" || ( sValue.indexOf(':') == -1 && sValue.toDouble() ))
                aDocImport.setNumericCell(aAddress, sValue.toDouble());
            else
                aDocImport.setStringCell(aAddress, sValue);
            aRangeList.Join(aAddress);
        }
        aDocImport.finalize();
        mpScDocShell->PostPaint( aRangeList, PAINT_GRID );
    }
    // ImportStream calls PostPaint for relevant area,
    // we need to call it explicitly only when moving rows.
    if (meMove == NO_MOVE)
        return mbRunning;

    if (meMove == RANGE_DOWN)
    {
        maRange.Move(0, maRange.aEnd.Row() - maRange.aStart.Row() + 1, 0);
        mpScDocShell->GetViewData()->GetView()->AlignToCursor(
                maRange.aStart.Col(), maRange.aStart.Row(), SC_FOLLOW_JUMP);
    }
    SCROW aEndRow = mpEndRange.get() ? mpEndRange->aEnd.Row() : MAXROW;
    mpScDocShell->PostPaint( ScRange( maStartRange.aStart, ScAddress( maRange.aEnd.Col(),
                    aEndRow, maRange.aStart.Tab()) ), PAINT_GRID );

    return mbRunning;
}

sfx2::SvBaseLink::UpdateResult DataStream::DataChanged(
        const OUString& , const css::uno::Any& )
{
    MakeToolbarVisible();
    StopImport();
    bool bStart = true;
    if (mnSettings & SCRIPT_STREAM && !mxReaderThread.is() &&
        officecfg::Office::Common::Security::Scripting::MacroSecurityLevel::get() >= 1)
    {
        MessageDialog aQBox( NULL, "QueryRunStreamScriptDialog", "modules/scalc/ui/queryrunstreamscriptdialog.ui");
        aQBox.set_primary_text( aQBox.get_primary_text().replaceFirst("%URL", msURL) );
        if (RET_YES != aQBox.Execute())
            bStart = false;
    }
    if (bStart)
        StartImport();
    return SUCCESS;
}

void DataStream::Edit(Window* pWindow, const Link& )
{
    DataStreamDlg aDialog(mpScDocShell, pWindow);
    aDialog.Init(msURL, msRange, mnLimit, msMove, mnSettings);
    if (aDialog.Execute() == RET_OK)
    {
        bool bWasRunning = mbRunning;
        StopImport();
        aDialog.StartStream(this);
        if (bWasRunning)
            StartImport();
    }
}

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