aboutsummaryrefslogtreecommitdiffstats
path: root/textedit.cpp
blob: 39039f24d73f9caf384f272157db59b6985ad601 (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
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
/*
 *      textedit.cpp
 *
 *      Copyright 2008 gpg4usb-team <[email protected]>
 *
 *      This file is part of gpg4usb.
 *
 *      Gpg4usb is free software: you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation, either version 3 of the License, or
 *      (at your option) any later version.
 *
 *      Gpg4usb is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *
 *      You should have received a copy of the GNU General Public License
 *      along with gpg4usb.  If not, see <http://www.gnu.org/licenses/>
 */

#include "textedit.h"

TextEdit::TextEdit()
{
    countPage = 0;
    tabWidget = new QTabWidget(this);
    tabWidget->setMovable(true);
    tabWidget->setTabsClosable(true);
    tabWidget->setDocumentMode(true);

    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(tabWidget);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(0);
    setLayout(layout);

    connect(tabWidget, SIGNAL(tabCloseRequested(int)), this, SLOT(removeTab(int)));
    newTab();
    setAcceptDrops(false);
}

void TextEdit::newTab()
{
    QString header = tr("untitled") +
                     QString::number(++countPage)+".txt";

    EditorPage *page = new EditorPage();
    tabWidget->addTab(page, header);
    tabWidget->setCurrentIndex(tabWidget->count() - 1);
    page->getTextPage()->setFocus();
    connect(page->getTextPage()->document(), SIGNAL(modificationChanged(bool)), this, SLOT(showModified()));
 }

void TextEdit::newHelpTab(QString title, QString path)
{

    HelpPage *page = new HelpPage(path);
    tabWidget->addTab(page, title);
    tabWidget->setCurrentIndex(tabWidget->count() - 1);

}

void TextEdit::open()
{
    QStringList fileNames = QFileDialog::getOpenFileNames(this, tr("Open file"),
                                                          QDir::currentPath());
    foreach (QString fileName,fileNames){
        if (!fileName.isEmpty()) {
            QFile file(fileName);

            if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
                EditorPage *page = new EditorPage(fileName);

                QTextStream in(&file);
                QApplication::setOverrideCursor(Qt::WaitCursor);
                page->getTextPage()->setPlainText(in.readAll());
                page->setFilePath(fileName);
                QTextDocument *document = page->getTextPage()->document();
                document->setModified(false);

                tabWidget->addTab(page, strippedName(fileName));
                tabWidget->setCurrentIndex(tabWidget->count() - 1);
                QApplication::restoreOverrideCursor();
                page->getTextPage()->setFocus();
                connect(page->getTextPage()->document(), SIGNAL(modificationChanged(bool)), this, SLOT(showModified()));
                //enableAction(true)
                file.close();
            } else {
                QMessageBox::warning(this, tr("Application"),
                                     tr("Cannot read file %1:\n%2.")
                                     .arg(fileName)
                                     .arg(file.errorString()));
            }
        }
    }
}

void TextEdit::save()
{
    if (tabWidget->count() == 0 || curPage() == 0) {
        return;
    }

    QString fileName = curPage()->getFilePath();

    if (fileName.isEmpty()) {
        //QString docname = tabWidget->tabText(tabWidget->currentIndex());
        //docname.remove(0,2);
        saveAs();
    } else {
        saveFile(fileName);
    }
}

bool TextEdit::saveFile(const QString &fileName)
{
    if (fileName.isEmpty()) {
        return false;
    }

    QFile file(fileName);

    if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        EditorPage *page = curPage();

        QTextStream outputStream(&file);
        QApplication::setOverrideCursor(Qt::WaitCursor);
        outputStream << page->getTextPage()->toPlainText();
        QApplication::restoreOverrideCursor();
        QTextDocument *document = page->getTextPage()->document();

        document->setModified(false);

        int curIndex = tabWidget->currentIndex();
        tabWidget->setTabText(curIndex, strippedName(fileName));
        page->setFilePath(fileName);
  //      statusBar()->showMessage(tr("File saved"), 2000);
        file.close();
        return true;
    } else {
        QMessageBox::warning(this, tr("File"),
                             tr("Cannot write file %1:\n%2.")
                             .arg(fileName)
                             .arg(file.errorString()));
        return false;
    }
}


bool TextEdit::saveAs()
{
    if (tabWidget->count() == 0 || curPage() == 0) {
        return true;
    }

    EditorPage *page = curPage();
    QString path;
    if(page->getFilePath() != "") {
        path = page->getFilePath();
    } else {
        path = tabWidget->tabText(tabWidget->currentIndex()).remove(0,2);
    }

    QString fileName = QFileDialog::getSaveFileName(this, tr("Save file "),
                                                    path);
    return saveFile(fileName);
}

void TextEdit::closeTab()
{
    removeTab(tabWidget->currentIndex());
    if (tabWidget->count() != 0) {
        curPage()->getTextPage()->setFocus();
    }
}

void TextEdit::removeTab(int index)
{
    // Do nothing, if no tab is opened
    if (tabWidget->count() == 0) {
        return;
    }

    // get the index of the actual current tab
    int lastIndex = tabWidget->currentIndex();

    // set the focus to argument index
    tabWidget->setCurrentIndex(index);

    if (maybeSaveCurrentTab(true)) {
        tabWidget->removeTab(index);

        if(index >= lastIndex) {
            tabWidget->setCurrentIndex(lastIndex);
        } else {
            tabWidget->setCurrentIndex(lastIndex-1);
        }
    }

    if (tabWidget->count() == 0) {
      //  enableAction(false);
    }
}


 /**
  * Check if current may need to be saved.
  * Call this function before closing the currently active tab-
  *
  * If it returns false, the close event should be aborted.
  */
bool TextEdit::maybeSaveCurrentTab(bool askToSave) {

    EditorPage *page = curPage();
    // if this page is no textedit, there should be nothing to save
    if(page == 0) {
        return true;
    }
    QTextDocument *document = page->getTextPage()->document();

    if (document->isModified()) {
        QMessageBox::StandardButton result = QMessageBox::Cancel;

        // write title of tab to docname and remove the leading *
        QString docname = tabWidget->tabText(tabWidget->currentIndex());
        docname.remove(0,2);

        QString filePath = page->getFilePath();
        if (askToSave) {
            result = QMessageBox::warning(this, tr("Unsaved document"),
                                   tr("<h3>The document \"%1\" has been modified.<br/>Do you want to save your changes?</h3>").arg(docname)+
                                   tr("<b>Note:</b> If you don't save these files, all changes are lost.<br/>"),
                                   QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
        }
        if ((result == QMessageBox::Save) || (!askToSave)) {
            if (filePath == "") {
                //QString docname = tabWidget->tabText(tabWidget->currentIndex());
                //docname.remove(0,2);
                return saveAs();
            } else {
                return saveFile(filePath);
            }
        } else if (result == QMessageBox::Discard) {
            return true;
        } else {
            return false;
        }
    }
    return true;
}

bool TextEdit::maybeSaveAnyTab()
{
    // get a list of all unsaved documents and their tabids
    QHash<int, QString> unsavedDocs = this->unsavedDocuments();

    /*
    * no unsaved documents, so app can be closed
    */
    if (unsavedDocs.size() == 0) {
        return true;
    }
    /*
     * only 1 unsaved document -> set modified tab as current
     * and show normal unsaved doc dialog
     */
    if(unsavedDocs.size() == 1) {
        int modifiedTab = unsavedDocs.keys().at(0);
        tabWidget->setCurrentIndex(modifiedTab);
        return maybeSaveCurrentTab(true);
    }

    /*
     * more than one unsaved documents
     */
    if(unsavedDocs.size() > 1) {
        QHashIterator<int, QString> i (unsavedDocs);

        QuitDialog *dialog;
        dialog=new QuitDialog(this, unsavedDocs);
        int result = dialog->exec();

        // if result is QDialog::Rejected, discard or cancel was clicked
        if (result == QDialog::Rejected){
            // return true, if discard is clicked, so app can be closed
            if (dialog->isDiscarded()){
                return true;
            } else {
                return false;
            }
        } else {
            bool allsaved=true;
            QList <int> tabIdsToSave = dialog->getTabIdsToSave();

            foreach (int tabId, tabIdsToSave) {
                tabWidget->setCurrentIndex(tabId);
                if (! maybeSaveCurrentTab(false)) {
                    allsaved=false;
                }
            }
            if (allsaved) {
                return true;
            } else {
                return false;
            }
        }
    }
    // code should never reach this statement
    return false;
}


QTextEdit* TextEdit::curTextPage()
{
    EditorPage *curTextPage = qobject_cast<EditorPage *>(tabWidget->currentWidget());
    if(curTextPage != 0) {
        return curTextPage->getTextPage();
    } else {
        return 0;
    }
}

QTextBrowser* TextEdit::curHelpPage() {
    HelpPage *curHelpPage = qobject_cast<HelpPage *>(tabWidget->currentWidget());
    if(curHelpPage != 0) {
        return curHelpPage->getBrowser();
    } else {
        return 0;
    }
}

int TextEdit::tabCount()
{
    return tabWidget->count();
}

EditorPage* TextEdit::curPage()
{
    EditorPage *curPage = qobject_cast<EditorPage *>(tabWidget->currentWidget());
    return curPage;
}

void TextEdit::quote()
{
    if (tabWidget->count() == 0 || curTextPage() == 0) {
        return;
    }

    QTextCursor cursor(curTextPage()->document());

    // beginEditBlock and endEditBlock() let operation look like single undo/redo operation
    cursor.beginEditBlock();
    cursor.setPosition(0);
    cursor.insertText("> ");
    while (!cursor.isNull() && !cursor.atEnd()) {
        cursor.movePosition(QTextCursor::EndOfLine);
        cursor.movePosition(QTextCursor::NextCharacter);
        if(!cursor.atEnd()) {
            cursor.insertText("> ");
        }
    }
    cursor.endEditBlock();
}

void TextEdit::fillTextEditWithText(QString text) {
    QTextCursor cursor(curTextPage()->document());
    cursor.beginEditBlock();
    this->curTextPage()->selectAll();
    this->curTextPage()->insertPlainText(text);
    cursor.endEditBlock();
}

void TextEdit::loadFile(const QString &fileName)
{
    QFile file(fileName);
    if (!file.open(QFile::ReadOnly | QFile::Text)) {
        QMessageBox::warning(this, tr("Application"),
                             tr("Cannot read file %1:\n%2.")
                             .arg(fileName)
                             .arg(file.errorString()));
        return;
    }
    QTextStream in(&file);
    QApplication::setOverrideCursor(Qt::WaitCursor);
    curTextPage()->setPlainText(in.readAll());
    QApplication::restoreOverrideCursor();
    curPage()->setFilePath(fileName);
    tabWidget->setTabText(tabWidget->currentIndex(), strippedName(fileName));
    file.close();
   // statusBar()->showMessage(tr("File loaded"), 2000);
}

QString TextEdit::strippedName(const QString &fullFileName)
{
    return QFileInfo(fullFileName).fileName();
}

void TextEdit::print()
{
    if (tabWidget->count() == 0) {
        return;
    }

#ifndef QT_NO_PRINTER
     QTextDocument *document;
    if(curTextPage() == 0) {
        document = curHelpPage()->document();
    } else {
        document = curTextPage()->document();
    }
    QPrinter printer;

    QPrintDialog *dlg = new QPrintDialog(&printer, this);
    if (dlg->exec() != QDialog::Accepted) {
        return;
    }
    document->print(&printer);

    //statusBar()->showMessage(tr("Ready"), 2000);
#endif
}

void TextEdit::showModified() {
    int index=tabWidget->currentIndex();
    QString title= tabWidget->tabText(index);
    // if doc is modified now, add leading * to title,
    // otherwise remove the leading * from the title
    if(curTextPage()->document()->isModified()) {
        tabWidget->setTabText(index, title.prepend("* "));
    } else {
        tabWidget->setTabText(index, title.remove(0,2));
    }
}

void TextEdit::switchTabUp() {
    if (tabWidget->count() > 1) {
        int newindex=(tabWidget->currentIndex()+1)%(tabWidget->count());
        tabWidget->setCurrentIndex(newindex);
    }
}

void TextEdit::switchTabDown() {
    if (tabWidget->count() > 1) {
        int newindex=(tabWidget->currentIndex()-1+tabWidget->count())%tabWidget->count();
        tabWidget->setCurrentIndex(newindex);
    }
}

/*
 *   return a hash of tabindexes and title of unsaved tabs
 */
QHash<int, QString> TextEdit::unsavedDocuments() {
    QHash<int, QString> unsavedDocs;  // this list could be used to implement gedit like "unsaved changed"-dialog

    for(int i=0; i < tabWidget->count(); i++) {
        EditorPage *ep = qobject_cast<EditorPage *> (tabWidget->widget(i));
        if(ep != 0 && ep->getTextPage()->document()->isModified()) {
            QString docname = tabWidget->tabText(i);
            // remove * before name of modified doc
            docname.remove(0,2);
            unsavedDocs.insert(i, docname);
        }
    }
    return unsavedDocs;
}

void TextEdit::cut()
{
    if (tabWidget->count() == 0 || curTextPage() == 0) {
        return;
    }

    curTextPage()->cut();
}

void TextEdit::copy()
{
    if (tabWidget->count() == 0) {
        return;
    }

    if(curTextPage() != 0) {
        curTextPage()->copy();
    } else {
        curHelpPage()->copy();
    }


}

void TextEdit::paste()
{
    if (tabWidget->count() == 0 || curTextPage() == 0) {
        return;
    }

    curTextPage()->paste();
}

void TextEdit::undo()
{
    if (tabWidget->count() == 0 || curTextPage() == 0) {
        return;
    }

    curTextPage()->undo();
}

void TextEdit::redo()
{
    if (tabWidget->count() == 0 || curTextPage() == 0) {
        return;
    }

    curTextPage()->redo();
}

void TextEdit::zoomIn()
{
    if (tabWidget->count() == 0 ) {
        return;
    }

    if(curTextPage() != 0) {
        curTextPage()->zoomIn();
    } else {
        curHelpPage()->zoomIn();
    }

}

void TextEdit::zoomOut()
{
    if (tabWidget->count() == 0 ) {
        return;
    }

    if(curTextPage() != 0) {
        curTextPage()->zoomOut();
    } else {
        curHelpPage()->zoomOut();
    }
}

void TextEdit::selectAll()
{
    if (tabWidget->count() == 0 || curTextPage() == 0) {
        return;
    }

    curTextPage()->selectAll();
}

/*void TextEdit::dragEnterEvent(QDragEnterEvent *event)
{
    if (event->mimeData()->hasFormat("text/plain"))
        qDebug() << "enter textedit drag action";
        event->acceptProposedAction();
}

void TextEdit::dropEvent(QDropEvent* event)
{
    curTextPage()->setPlainText(event->mimeData()->text());

    foreach (QUrl tmp, event->mimeData()->urls())
    {
        qDebug() << tmp;
    }

    //event->acceptProposedAction();
}
*/