summaryrefslogtreecommitdiffstats
path: root/kviewshell/plugins/djvu/djvurenderer.cpp
blob: 2bac17436dc57ce6aa7eb47e8962bbb7df7802e6 (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
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
/***************************************************************************
 *   Copyright (C) 2005 by Stefan Kebekus                                  *
 *   kebekus@kde.org                                                       *
 *                                                                         *
 *   Copyright (C) 2005 by Wilfried Huss                                   *
 *   Wilfried.Huss@gmx.at                                                  *
 *                                                                         *
 *   This program 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 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program 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 this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
 ***************************************************************************/

#include <tdemessagebox.h>
#include <kdebug.h>
#include <tdelocale.h>
#include <tqfileinfo.h>
#include <tqimage.h>
#include <tqpainter.h>
#include <tdeapplication.h>

#include "GBitmap.h"
#include "BSByteStream.h"
#include "IFFByteStream.h"

#include "prefs.h"

#include "documentWidget.h"
#include "djvurenderer.h"
#include "djvumultipage.h"
#include "hyperlink.h"
#include "renderedDocumentPagePixmap.h"
#include "textBox.h"

//#define KF_DEBUG

inline GUTF8String GStringFromTQString(const TQString& x)
{
  GUTF8String retval=(const char*)x.utf8();
  return retval;
}


inline TQString TQStringFromGString(const GUTF8String& x)
{
  TQString retval=TQString::fromUtf8((const char*)x);
  return retval;
}


DjVuRenderer::DjVuRenderer(TQWidget* par)
  : DocumentRenderer(par)
{
#ifdef KF_DEBUG
  kdError() << "DjVuRenderer( parent=" << par << " )" << endl;
#endif

  PPMstream = ByteStream::create();
}



DjVuRenderer::~DjVuRenderer()
{
#ifdef KF_DEBUG
  kdDebug() << "~DjVuRenderer" << endl;
#endif

  // Wait for all access to this documentRenderer to finish
  TQMutexLocker locker( &mutex );
}


void DjVuRenderer::drawPage(double resolution, RenderedDocumentPage* page)
{
#ifdef KF_DEBUG
  kdDebug() << "DjVuRenderer::drawPage(documentPage*) called, page number " << page->getPageNumber() << endl;
#endif

  // Paranoid safety checks
  if (page == 0) {
    kdError() << "DjVuRenderer::drawPage(documentPage*) called with argument == 0" << endl;
    return;
  }
  if (page->getPageNumber() == 0) {
    kdError() << "DjVuRenderer::drawPage(documentPage*) called for a documentPage with page number 0" << endl;
    return;
  }

  // Wait for all access to this documentRenderer to finish
  TQMutexLocker locker( &mutex );

  // more paranoid safety checks
  if (page->getPageNumber() > numPages) {
    kdError() << "DjVuRenderer::drawPage(documentPage*) called for a documentPage with page number " << page->getPageNumber()
	      << " but the current fax file has only " << numPages << " pages." << endl;
    return;
  }

  int pageNumber = page->getPageNumber() - 1;

  GP<DjVuImage> djvuPage = document->get_page(pageNumber, true);
  if (!djvuPage->wait_for_complete_decode())
  {
    kdDebug() << "decoding failed." << endl;
    return;
  }

  if (!pageSizes[pageNumber].isValid())
  {
    int djvuResolution = djvuPage->get_dpi();
    int djvuPageWidth = djvuPage->get_width();
    int djvuPageHeight = djvuPage->get_height();

    Length w, h;
    w.setLength_in_inch(djvuPageWidth / (double)djvuResolution);
    h.setLength_in_inch(djvuPageHeight / (double)djvuResolution);
    pageSizes[pageNumber].setPageSize(w, h);

    SimplePageSize ps = sizeOfPage(page->getPageNumber());

    // If we are not printing we need to resize the pixmap.
    RenderedDocumentPagePixmap* pagePixmap = dynamic_cast<RenderedDocumentPagePixmap*>(page);
    if (pagePixmap)
      pagePixmap->resize(ps.sizeInPixel(resolution));
  }
  
  //kdDebug() << "render page " << pageNumber + 1 << " at size (" << pageWidth << ", " << pageHeight << ")" << endl;
  
  int pageHeight = page->height();
  int pageWidth = page->width();
  
  GRect pageRect(0, 0, pageWidth, pageHeight);


  GP<GPixmap> djvuPixmap;
  if (Prefs::renderMode() == Prefs::EnumRenderMode::Color)
    djvuPixmap = djvuPage->get_pixmap(pageRect, pageRect);
  else if (Prefs::renderMode() == Prefs::EnumRenderMode::Foreground)
    djvuPixmap = djvuPage->get_fg_pixmap(pageRect, pageRect);
  else if (Prefs::renderMode() == Prefs::EnumRenderMode::Background)
    djvuPixmap = djvuPage->get_bg_pixmap(pageRect, pageRect);

  TQPainter* foreGroundPaint = page->getPainter();
  if (foreGroundPaint != 0) 
  {
    if(djvuPixmap && Prefs::renderMode() != Prefs::EnumRenderMode::BlackAndWhite)
    {
      PPMstream->seek(0);
      djvuPixmap->save_ppm(*PPMstream);
      long pixmapsize = PPMstream->tell();
      PPMstream->seek(0);
      uchar* buf = new uchar[pixmapsize];
      long bytesRead = PPMstream->readall(buf, pixmapsize);

      bool ok = pixmap.loadFromData(buf, bytesRead, "PPM");
      if (!ok)
      {
        kdError() << "loading failed" << endl;
        //draw an empty page
        foreGroundPaint->fillRect(0, 0, pageWidth, pageHeight, TQt::white);
      }
      foreGroundPaint->drawPixmap(0, 0, pixmap);
      delete[] buf;

/*      for (int i = 0; i < pageHeight; i++)
      {
        GPixel* pixmapRow = (*djvuPixmap)[i];

        for (int j = 0; j < pageWidth; j++)
        {
          GPixel pixel = pixmapRow[j];
          foreGroundPaint->setPen(TQColor(pixel.r, pixel.g, pixel.b));
          foreGroundPaint->drawPoint(j, pageHeight - i - 1);
        }
      }*/
    }
    else
    {
      GP<GBitmap> djvuBitmap = djvuPage->get_bitmap(pageRect, pageRect);
      if(djvuBitmap)
      {
        PPMstream->seek(0);
        if(djvuBitmap->get_grays() == 2)
          djvuBitmap->save_pbm(*PPMstream);
        else
          djvuBitmap->save_pgm(*PPMstream);

        long pixmapsize = PPMstream->tell();
        PPMstream->seek(0);
        uchar* buf = new uchar[pixmapsize];
        long bytesRead = PPMstream->readall(buf, pixmapsize);

        bool ok = pixmap.loadFromData(buf, bytesRead, "PPM");
        if (!ok)
        {
          kdError() << "loading failed" << endl;
          //draw an empty page
          foreGroundPaint->fillRect(0, 0, pageWidth, pageHeight, TQt::white);
        }
        foreGroundPaint->drawPixmap(0, 0, pixmap);
        delete[] buf;
/*
        for (int i = 0; i < pageHeight; i++)
        {
          unsigned char* bitmapRow = (*djvuBitmap)[i];
          for (int j = 0; j < pageWidth; j++)
          {
            unsigned char pixel = 255-bitmapRow[j];
            foreGroundPaint->setPen(TQColor(pixel, pixel, pixel));
            foreGroundPaint->drawPoint(j, pageHeight - i - 1);
          }
        }*/
      }
      else
      {
        //draw an empty page
        foreGroundPaint->fillRect(0, 0, pageWidth, pageHeight, TQt::white);
      }
    }

    //kdDebug() << "rendering page " << pageNumber + 1 << " at size (" << pageWidth << ", " << pageHeight << ") finished." << endl;
    page->returnPainter(foreGroundPaint);
  }

  GP<DjVuTXT> pageText = getText(pageNumber);

  if (pageText)
  {
    TQSize djvuPageSize(djvuPage->get_width(), djvuPage->get_real_height());
    fillInText(page, pageText, pageText->page_zone, djvuPageSize);
    //kdDebug() << "Text of page " << pageNumber << endl;
    //kdDebug() << (const char*)pageText->textUTF8 << endl;
  }

  getAnnotations(page, djvuPage);

  page->isEmpty = false;
}


bool DjVuRenderer::setFile(const TQString &fname, const KURL &)
{
#ifdef KF_DEBUG
  kdDebug() << "DjVuRenderer::setFile(" << fname << ") called" << endl;
#endif

  // Wait for all access to this documentRenderer to finish
  TQMutexLocker locker( &mutex );

  // If fname is the empty string, then this means: "close".
  if (fname.isEmpty()) {
    kdDebug() << "DjVuRenderer::setFile( ... ) called with empty filename. Closing the file." << endl;
    return true;
  }

  // Paranoid saftey checks: make sure the file actually exists, and
  // that it is a file, not a directory. Otherwise, show an error
  // message and exit..
  TQFileInfo fi(fname);
  TQString   filename = fi.absFilePath();
  if (!fi.exists() || fi.isDir()) {
    KMessageBox::error( parentWidget,
			i18n("<qt><strong>File error.</strong> The specified file '%1' does not exist.</qt>").arg(filename),
			i18n("File Error"));
    // the return value 'false' indicates that this operation was not successful.
    return false;
  }

  // Clear previously loaded document
  clear();

  // Now we assume that the file is fine and load the file.
  G_TRY {
    document = DjVuDocEditor::create_wait(GURL::Filename::UTF8(GStringFromTQString(filename)));
  }
  G_CATCH(ex) {
    ;
  }
  G_ENDCATCH;

  // If the above assumption was false.
  if (!document)
  {
    KMessageBox::error( parentWidget,
      i18n("<qt><strong>File error.</strong> The specified file '%1' could not be loaded.</qt>").arg(filename),
      i18n("File Error"));

    clear();
    kdDebug(1223) << "Loading of document failed." << endl;
    return false;
  }

  bool r = initializeDocument();

  // the return value 'true' indicates that this operation was successful.
  return r;
}

void DjVuRenderer::getAnnotations(RenderedDocumentPage* page, GP<DjVuImage> djvuPage)
{
  GP<ByteStream> annotations = djvuPage->get_anno();
  if (!(annotations && annotations->size()))
    return;

  GP<DjVuANT> ant = DjVuANT::create();

  GP<IFFByteStream> iff = IFFByteStream::create(annotations);

  GUTF8String chkid;

  while (iff->get_chunk(chkid))
  {
    if (chkid == "ANTa")
    {
      ant->merge(*iff->get_bytestream());
    }
    else if (chkid == "ANTz")
    {
      GP<ByteStream> bsiff = BSByteStream::create(iff->get_bytestream());
      ant->merge(*bsiff);
    }
    iff->close_chunk();
  }

  if (!ant->is_empty())
  {
    // Scaling factors for the coordinate conversion.
    // TODO: Refractor this into a function shared with fillInText.
    int pageWidth = page->width();
    int pageHeight = page->height();

    double scaleX = pageWidth / (double)djvuPage->get_width();
    double scaleY = pageHeight / (double)djvuPage->get_height();

    GPList<GMapArea> map = ant->map_areas;

    for (GPosition pos = map; pos; ++pos)
    {
      // Currently we only support rectangular links
      if (!map[pos]->get_shape_type() == GMapArea::RECT)
        continue;

      GRect rect = map[pos]->get_bound_rect();

      TQRect hyperlinkRect((int)(rect.xmin*scaleX+0.5), (int)((djvuPage->get_height()-rect.ymax)*scaleY+0.5),
                          (int)(rect.width()*scaleX +0.5), (int)(rect.height()*scaleY+0.5));

      TQString url((const char*)map[pos]->url);
      TQString target((const char*)map[pos]->target);
      TQString comment((const char*)map[pos]->comment);

      // Create an anchor for this link.
      if (!anchorList.contains(url))
	{
	  // For now we only accept links to pages in the same document.
	  if(url[0] == '#' && target == "_self")
	    {
	      bool conversionOk;
	      PageNumber targetPage = url.remove('#').toInt(&conversionOk);
	      if (conversionOk)
		anchorList[url] = Anchor(targetPage, Length());
	    }
	}
      
      Hyperlink hyperlink(hyperlinkRect.bottom(), hyperlinkRect, url);
      page->hyperLinkList.push_back(hyperlink);
    }
  }
}


bool DjVuRenderer::initializeDocument()
{
  if (document == 0)
    return false;

  if (!document->wait_for_complete_init()) {
    kdDebug() << "Document Initialization failed." << endl;
    return false;
  }
  
  // Set the number of pages page sizes
  numPages = document->get_pages_num();

  pageSizes.resize(numPages);
  Length w,h;

  // Set the page sizes in the pageSizes array. Give feedback for
  // very long documents
  if (numPages > 100)
    emit setStatusBarText(i18n("Loading file. Computing page sizes..."));
  for(TQ_UINT16 i=0; i<numPages; i++) {
    // Keep the GUI updated
    if (i%100 == 0)
      kapp->processEvents();
    
    GP<DjVuFile>  djvuFile = document->get_djvu_file(i);
    int resolution;
    int pageWidth;
    int pageHeight;
    bool ok = getPageInfo(djvuFile, pageWidth, pageHeight, resolution);
    if (!ok)
      kdError() << "Decoding info of page " << i << " failed." << endl;
    else {
      w.setLength_in_inch(pageWidth / (double)resolution);
      h.setLength_in_inch(pageHeight / (double)resolution);
      pageSizes[i].setPageSize(w, h);
    }
  }
  emit setStatusBarText(TQString());
  
  // We will also generate a list of hyperlink-anchors in the document.
  // So declare the existing lists empty.
  anchorList.clear();
  return true;
}


GP<DjVuTXT> DjVuRenderer::getText(PageNumber pageNumber)
{
  GUTF8String chkid;

  const GP<DjVuFile> file = document->get_djvu_file(pageNumber);
  const GP<ByteStream> bs(file->get_text());
  if (bs)
  {
    long int i=0;
    const GP<IFFByteStream> iff(IFFByteStream::create(bs));
    while (iff->get_chunk(chkid))
    {
      i++;
      if (chkid == GUTF8String("TXTa"))
      {
        GP<DjVuTXT> txt = DjVuTXT::create();
        txt->decode(iff->get_bytestream());
        return txt;
      }
      else if (chkid == GUTF8String("TXTz"))
      {
        GP<DjVuTXT> txt = DjVuTXT::create();
        GP<ByteStream> bsiff=BSByteStream::create(iff->get_bytestream());
        txt->decode(bsiff);
        return txt;
      }
      iff->close_chunk();
    }
  }
  return 0;
}

void DjVuRenderer::fillInText(RenderedDocumentPage* page, const GP<DjVuTXT>& text, DjVuTXT::Zone& zone, TQSize& djvuPageSize)
{
  if (zone.children.isempty())
  {
    int pageWidth = page->width();
    int pageHeight = page->height();

    double scaleX = pageWidth / (double)djvuPageSize.width();
    double scaleY = pageHeight / (double)djvuPageSize.height();

    TQString zoneString = TQStringFromGString(text->textUTF8.substr(zone.text_start, zone.text_length));

    //kdDebug() << "zone text: " << zoneString << endl;

    TQRect textRect((int)(zone.rect.xmin*scaleX+0.5), (int)((djvuPageSize.height()-zone.rect.ymax)*scaleY+0.5),
                   (int)(zone.rect.width()*scaleX+0.5), (int)(zone.rect.height()*scaleY+0.5));
    //kdDebug() << "zone rect: " << textRect.x() << ", " << textRect.y() << ", " << textRect.width() << ", " << textRect.height() << endl;
    TextBox textBox(textRect, zoneString);
    page->textBoxList.push_back(textBox);
  }
  else
  {
    for (GPosition pos=zone.children; pos; ++pos)
    {
      fillInText(page, text, zone.children[pos], djvuPageSize);
    }
  }
}

bool DjVuRenderer::getPageInfo(GP<DjVuFile> file, int& width, int& height, int& dpi)
{
  if (!file || !file->is_all_data_present())
    return false;

  const GP<ByteStream> pbs(file->get_djvu_bytestream(false, false));
  const GP<IFFByteStream> iff(IFFByteStream::create(pbs));

  GUTF8String chkid;
  if (iff->get_chunk(chkid))
  {
    if (chkid == "FORM:DJVU")
    {
      while (iff->get_chunk(chkid) && chkid!="INFO")
        iff->close_chunk();
      if (chkid == "INFO")
      {
        GP<ByteStream> gbs = iff->get_bytestream();
        GP<DjVuInfo> info=DjVuInfo::create();
        info->decode(*gbs);
        int rot = ((360-GRect::findangle(info->orientation))/90)%4;

        width = (rot&1) ? info->height : info->width;
        height = (rot&1) ? info->width : info->height;
        dpi = info->dpi;
        return true;
      }
    }
    else if (chkid == "FORM:BM44" || chkid == "FORM:PM44")
    {
      while (iff->get_chunk(chkid) && chkid!="BM44" && chkid!="PM44")
        iff->close_chunk();
      if (chkid=="BM44" || chkid=="PM44")
      {
        GP<ByteStream> gbs = iff->get_bytestream();
        if (gbs->read8() == 0)
        {
          gbs->read8();
          gbs->read8();
          unsigned char xhi = gbs->read8();
          unsigned char xlo = gbs->read8();
          unsigned char yhi = gbs->read8();
          unsigned char ylo = gbs->read8();

          width = (xhi<<8)+xlo;
          height = (yhi<<8)+ylo;
          dpi = 100;
          return true;
        }
      }
    }
  }
  return false;
}

void DjVuRenderer::getText(RenderedDocumentPage* page)
{
  TQMutexLocker locker( &mutex );
  
  int pageNumber = page->getPageNumber() - 1;
  GP<DjVuTXT> pageText = getText(pageNumber);

  if (pageText)
  {
    GP<DjVuFile> djvuFile = document->get_djvu_file(pageNumber);
    int resolution;
    int pageWidth;
    int pageHeight;
    bool ok = getPageInfo(djvuFile, pageWidth, pageHeight, resolution);

    if (ok)
    {
      TQSize djvuPageSize(pageWidth, pageHeight);
      fillInText(page, pageText, pageText->page_zone, djvuPageSize);
    }
  }
}


bool DjVuRenderer::convertToPSFile( DjVuToPS &converter, TQString filename, TQValueList<int> &pageList )
{
  if (document == 0) {
    kdError(1223) << "DjVuRenderer::convertToPSFile(..) called when document was 0" << endl;
    return false;
  }

  TQMutexLocker locker( &mutex );
  
  // Set up progress dialog
  KProgressDialog *pdialog = new KProgressDialog(parentWidget, "Printing-ProgressDialog", i18n("Printing..."), i18n("Preparing pages for printing..."), true);
  pdialog->setButtonText(i18n("Abort"));
  pdialog->showCancelButton(true);
  pdialog->progressBar()->setTotalSteps(pageList.size());
  pdialog->progressBar()->setFormat(TQString());
  
  // Open output file
  GURL outname = GURL::Filename::UTF8(GStringFromTQString(filename));
  GP<ByteStream> obs = ByteStream::create(outname, "w");
  
  TQString pagename;
  TQValueList<int>::ConstIterator it = pageList.begin();
  while (true) {
    pagename += TQString::number(*it);
    ++it;
    if (it == pageList.end())
      break;
    pagename += ",";
  }
  GUTF8String pages = GStringFromTQString(pagename);
  
  converter.set_info_cb(printerInfoCallBack, (void*)pdialog);
  bool iscancelled = false;
  G_TRY {
    converter.print(*obs, (DjVuDocument *)document, pages );	
  }
  G_CATCH(ex) {
    iscancelled = true;
  }
  G_ENDCATCH;
  
  delete pdialog;

  //  This is to keep the GUI updated.
  kapp->processEvents();
  
  obs->flush();
  return !iscancelled;
}


void DjVuRenderer::deletePages(TQ_UINT16 from, TQ_UINT16 to)
{
  // Paranoia security checks
  if (document == 0) {
    kdError(1223) << "DjVuRenderer::deletePages(...) called when no document was loaded" << endl;
    return;
  }
  if ((from > to) || (from == 0) || (from > totalPages()) || (to >  totalPages())) {
    kdError(1223) << "DjVuRenderer::deletePages(...) called with invalid arguments" << endl;
    return;
  }

  TQMutexLocker locker( &mutex );

  KProgressDialog *pdialog = 0;
  if (to-from > 9) {
    pdialog = new KProgressDialog(parentWidget, "Printing-ProgressDialog", i18n("Deleting pages..."), i18n("Please wait while pages are removed..."), true);
    pdialog->showCancelButton(false);
    pdialog->progressBar()->setTotalSteps(to-from+1);
    pdialog->progressBar()->setFormat(TQString());
    pdialog->show();
    kapp->processEvents();
  }
  
  // set the document pointer temporarily to 0, so that no-one tries
  // to render a page while we are deleting pages
  GP<DjVuDocEditor> document_new = document;
  document = 0;

  // Delete pages
  if (pdialog == 0) {
    GList<int> pageList;
    for(TQ_UINT16 i=from; i<= to; i++)
      pageList.append(i-1);
    document_new->remove_pages(pageList); 
  } else {
    for(TQ_UINT16 i=from; i<=to; i++) {
      document_new->remove_page(from-1); 
      pdialog->progressBar()->setProgress(i-from);
      pdialog->progressBar()->setFormat(i18n("deleting page %1").arg(i));
      kapp->processEvents();
    }
    delete pdialog;
  }
  _isModified = true;
  document = document_new;

  initializeDocument();
}


bool DjVuRenderer::save(const TQString &filename)
{
  if (document == 0) {
    kdError() << "DjVuRenderer::save(..) called when document==0" << endl;
    return false;
  }
  
  TQMutexLocker locker( &mutex );
  
  G_TRY {
    document->save_as(GURL::Filename::UTF8(GStringFromTQString(filename)), true);
  }
  G_CATCH(ex) {
    return false;
  }
  G_ENDCATCH;

  document->save_as(GURL::Filename::UTF8(filename.ascii()), true);
  
  if (TQFile::exists(filename) == false)
    return false;
  
  _isModified = false;
  return true;
}


void DjVuRenderer::printerInfoCallBack(int page_num, int page_count, int, DjVuToPS::Stage, void *pd)
{
  if (pd == 0)
    return;
  
  // Update the progress dialog.
  KProgressDialog *pdialog = (KProgressDialog *)pd;
  
  pdialog->progressBar()->setProgress(page_count);
  pdialog->progressBar()->setFormat(i18n("processing page %1").arg(page_num+1));
  pdialog->show();
  
  if (pdialog->wasCancelled())
    G_THROW("STOP");
  
  //  This is to keep the GUI updated.
  kapp->processEvents();
}


#include "djvurenderer.moc"