File: wxpoem.cpp

package info (click to toggle)
wxpython3.0 3.0.2.0%2Bdfsg-8
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 482,632 kB
  • sloc: cpp: 2,127,216; python: 294,089; makefile: 51,946; ansic: 19,033; sh: 3,013; xml: 1,629; perl: 17
file content (1078 lines) | stat: -rw-r--r-- 28,889 bytes parent folder | download | duplicates (10)
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
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
/////////////////////////////////////////////////////////////////////////////
// Name:        wxpoem.cpp
// Purpose:     A small C++ program which displays a random poem on
//              execution. It also allows search for poems containing a
//              string.
//              It requires winpoem.dat and creates winpoem.idx.
//              Original version (WinPoem) written in 1994.
//              This has not been rewritten in a long time so
//              beware, inelegant code!
// Author:      Julian Smart
// Created:     12/12/98
// Copyright:   (c) 1998 Julian Smart
// Licence:     wxWindows licence
/////////////////////////////////////////////////////////////////////////////

// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"

#ifdef __BORLANDC__
#pragma hdrstop
#endif

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

#include "wxpoem.h"

#include "corner1.xpm"
#include "corner2.xpm"
#include "corner3.xpm"
#include "corner4.xpm"
#include "wxpoem.xpm"

#define         BUFFER_SIZE 10000
#define         DEFAULT_POETRY_DAT "wxpoem"
#define         DEFAULT_POETRY_IND "wxpoem"
#define         DEFAULT_CHAR_HEIGHT 18
#define         DEFAULT_FONT "Swiss"
#define         DEFAULT_X_POS 0
#define         DEFAULT_Y_POS 0
#define         BORDER_SIZE 30
#define         THIN_LINE_BORDER 10
#define         THICK_LINE_BORDER 16
#define         THICK_LINE_WIDTH 2
#define         SHADOW_OFFSET 1
#define         X_SIZE 30
#define         Y_SIZE 20

static wxChar   *poem_buffer;                   // Storage for each poem
static wxChar   line[150];                      // Storage for a line
static int      pages[30];                      // For multipage poems -
                                                // store the start of each page
static long     last_poem_start = 0;            // Start of last found poem
static long     last_find = -1;                 // Point in file of last found
                                                // search string
static bool     search_ok = false;              // Search was successful
static bool     same_search = false;            // Searching on same string

static long     poem_index[600];                     // Index of poem starts
static long     nitems = 0;                     // Number of poems
static int      char_height = DEFAULT_CHAR_HEIGHT; // Actual height
static int      index_ptr = -1;                 // Pointer into index
static int      poem_height, poem_width;        // Size of poem
static int      XPos;                           // Startup X position
static int      YPos;                           // Startup Y position
static int      pointSize = 12;                 // Font size

static const wxChar   *index_filename = NULL;            // Index filename
static const wxChar   *data_filename = NULL;             // Data filename
static wxChar   error_buf[300];                 // Error message buffer
static bool     loaded_ok = false;              // Poem loaded ok
static bool     index_ok = false;               // Index loaded ok

static bool     paging = false;                 // Are we paging?
static int      current_page = 0;               // Currently viewed page

// Backing bitmap
wxBitmap        *backingBitmap = NULL;

void            PoetryError(const wxChar *, const wxChar *caption=wxT("wxPoem Error"));
void            PoetryNotify(const wxChar *Msg, const wxChar *caption=wxT("wxPoem"));
void            TryLoadIndex();
bool            LoadPoem(const wxChar *, long);
int             GetIndex();
int             LoadIndex(const wxChar *);
bool            Compile(void);
void            FindMax(int *max_thing, int thing);

#if wxUSE_CLIPBOARD
    #include "wx/dataobj.h"
    #include "wx/clipbrd.h"
#endif

#ifdef __WXWINCE__
    STDAPI_(__int64) CeGetRandomSeed();
#endif

IMPLEMENT_APP(MyApp)

MainWindow *TheMainWindow = NULL;

// Create the fonts
void MainWindow::CreateFonts()
{
    m_normalFont = wxTheFontList->FindOrCreateFont(pointSize, wxSWISS, wxNORMAL, wxNORMAL);
    m_boldFont =   wxTheFontList->FindOrCreateFont(pointSize, wxSWISS, wxNORMAL, wxBOLD);
    m_italicFont = wxTheFontList->FindOrCreateFont(pointSize, wxSWISS, wxITALIC, wxNORMAL);
}

BEGIN_EVENT_TABLE(MainWindow, wxFrame)
    EVT_CLOSE(MainWindow::OnCloseWindow)
    EVT_CHAR(MainWindow::OnChar)
    EVT_MENU(wxID_ANY, MainWindow::OnPopup)
END_EVENT_TABLE()

MainWindow::MainWindow(wxFrame *frame, wxWindowID id, const wxString& title,
     const wxPoint& pos, const wxSize& size, long style):
     wxFrame(frame, id, title, pos, size, style)
{
    m_corners[0] = m_corners[1] = m_corners[2] = m_corners[3] = NULL;

    ReadPreferences();
    CreateFonts();

    SetIcon(wxpoem_xpm);

    m_corners[0] = new wxIcon( corner1_xpm );
    m_corners[1] = new wxIcon( corner2_xpm );
    m_corners[2] = new wxIcon( corner3_xpm );
    m_corners[3] = new wxIcon( corner4_xpm );
}

MainWindow::~MainWindow()
{
    for (int i=0;i<4;i++)
    {
        if(m_corners[i])
        {
            delete m_corners[i];
        }
    }
}

// Read the poetry buffer, either for finding the size
// or for writing to a bitmap (not to the window directly,
// since that displays messily)
// If DrawIt is true, we draw, otherwise we just determine the
// size the window should be.
void MainWindow::ScanBuffer(wxDC *dc, bool DrawIt, int *max_x, int *max_y)
{
    int i = pages[current_page];
    int ch = -1;
    int y = 0;
    int j;
    wxChar *line_ptr;
    int curr_width = 0;
    bool page_break = false;

    int width = 0;
    int height = 0;

    if (DrawIt)
    {
        y = (*max_y - poem_height)/2;
        width = *max_x;
        height = *max_y;
    }

    if (DrawIt && wxColourDisplay())
    {
        dc->SetBrush(*wxLIGHT_GREY_BRUSH);
        dc->SetPen(*wxGREY_PEN);
        dc->DrawRectangle(0, 0, width, height);
        dc->SetBackgroundMode(wxTRANSPARENT);
    }

    // See what ACTUAL char height is
    if(m_normalFont)
        dc->SetFont(*m_normalFont);
    wxCoord xx;
    wxCoord yy;
    dc->GetTextExtent(wxT("X"), &xx, &yy);
    char_height = (int)yy;

    if (current_page == 0)
    {
        m_title = wxEmptyString;
    }
    else if (!m_title.empty())
    {
        dc->SetFont(* m_boldFont);
        dc->GetTextExtent(m_title, &xx, &yy);
        FindMax(&curr_width, (int)xx);

        if (DrawIt)
        {
            int x = (width - xx)/2;
            dc->SetFont(* m_boldFont);

            // Change text to BLACK!
            dc->SetTextForeground(* wxBLACK);
            dc->DrawText(m_title, x, y);
            // Change text to WHITE!
            dc->SetTextForeground(* wxWHITE);
            dc->DrawText(m_title, x-SHADOW_OFFSET, y-SHADOW_OFFSET);
        }
        y += char_height;
        y += char_height;
    }

    while (ch != 0 && !page_break)
    {
        j = 0;
#if defined(__WXMSW__) || defined(__WXMAC__)
        while (((ch = poem_buffer[i]) != 13) && (ch != 0))
#else
        while (((ch = poem_buffer[i]) != 10) && (ch != 0))
#endif
        {
            line[j] = (wxChar)ch;
            j ++;
            i ++;
        }

#if defined(__WXMSW__) || defined(__WXMAC__)
        if (ch == 13)
#else
        if (ch == 10)
#endif
        {
            ch = -1;
            i ++;
#if defined(__WXMSW__) || defined(__WXMAC__)
            // Add another to skip the linefeed
            i ++;
#endif
            // If a single newline on its own, put a space in
            if (j == 0)
            {
                line[j] = ' ';
                j ++;
                line[j] = 0;
            }
        }

        if (j > 0)
        {
            line[j] = 0;
            if (line[0] == '@')
            {
                switch (line[1])
                {
                    case 'P':
                        paging = true;
                        page_break = true;
                        break;

                    case 'T':
                        dc->SetFont(* m_boldFont);
                        line_ptr = line+3;

                        m_title = line_ptr;
                        m_title << wxT(" (cont'd)");

                        dc->GetTextExtent(line_ptr, &xx, &yy);
                        FindMax(&curr_width, (int)xx);

                        if (DrawIt)
                        {
                            int x = (width - xx)/2;
                            dc->SetFont(* m_boldFont);

                            // Change text to BLACK!
                            dc->SetTextForeground(* wxBLACK);
                            dc->DrawText(line_ptr, x, y);

                            // Change text to WHITE!
                            dc->SetTextForeground(* wxWHITE);
                            dc->DrawText(line_ptr, x-SHADOW_OFFSET, y-SHADOW_OFFSET);
                            dc->SetTextForeground(* wxWHITE);
                        }
                        break;

                    case 'A':
                        line_ptr = line+3;
                        dc->SetFont(* m_italicFont);

                        dc->GetTextExtent(line_ptr, &xx, &yy);
                        FindMax(&curr_width, (int)xx);

                        if (DrawIt)
                        {
                            int x = (width - xx)/2;
                            dc->SetTextForeground(* wxBLACK);
                            dc->DrawText(line_ptr, x, y);
                        }
                        break;

                    // Default: just ignore this line
                    default:
                    y -= char_height;
                }
            }
            else
            {
                dc->SetFont(* m_normalFont);

                dc->GetTextExtent(line, &xx, &yy);
                FindMax(&curr_width, (int)xx);

                if (DrawIt)
                {
                    int x = (int)((width - xx)/2.0);
                    dc->SetFont(* m_normalFont);
                    dc->SetTextForeground(* wxBLACK);
                    dc->DrawText(line, x, y);
                }
            }
        }
        y += char_height;
    }

    // Write (cont'd)
    if (page_break)
    {
        const wxChar *cont = wxT("(cont'd)");

        dc->SetFont(* m_normalFont);

        dc->GetTextExtent(cont, &xx, &yy);
        FindMax(&curr_width, (int)xx);
        if (DrawIt)
        {
            int x = (int)((width - xx)/2.0);
            dc->SetFont(* m_normalFont);
            dc->SetTextForeground(* wxBLACK);
            dc->DrawText(cont, x, y);
        }
        y += 2*char_height;
    }

    *max_x = (int)curr_width;
    *max_y = (int)(y-char_height);

    if (page_break)
        pages[current_page+1] = i;
    else
        paging = false;

    if (DrawIt)
    {
        // Draw dark grey thick border
        if (wxColourDisplay())
        {
            dc->SetBrush(*wxGREY_BRUSH);
            dc->SetPen(*wxGREY_PEN);

            // Left side
            dc->DrawRectangle(0, 0, THIN_LINE_BORDER, height);
            // Top side
            dc->DrawRectangle(THIN_LINE_BORDER, 0, width-THIN_LINE_BORDER, THIN_LINE_BORDER);
            // Right side
            dc->DrawRectangle(width-THIN_LINE_BORDER, THIN_LINE_BORDER, width, height-THIN_LINE_BORDER);
            // Bottom side
            dc->DrawRectangle(THIN_LINE_BORDER, height-THIN_LINE_BORDER, width-THIN_LINE_BORDER, height);
        }
        // Draw border
        // Have grey background, plus 3-d border -
        // One black rectangle.
        // Inside this, left and top sides - dark grey. Bottom and right -
        // white.

        // Change pen to black
        dc->SetPen(*wxBLACK_PEN);
        dc->DrawLine(THIN_LINE_BORDER, THIN_LINE_BORDER, width-THIN_LINE_BORDER, THIN_LINE_BORDER);
        dc->DrawLine(width-THIN_LINE_BORDER, THIN_LINE_BORDER, width-THIN_LINE_BORDER, height-THIN_LINE_BORDER);
        dc->DrawLine(width-THIN_LINE_BORDER, height-THIN_LINE_BORDER, THIN_LINE_BORDER, height-THIN_LINE_BORDER);
        dc->DrawLine(THIN_LINE_BORDER, height-THIN_LINE_BORDER, THIN_LINE_BORDER, THIN_LINE_BORDER);

        // Right and bottom white lines - 'grey' (black!) if
        // we're running on a mono display.
        if (wxColourDisplay())
            dc->SetPen(*wxWHITE_PEN);
        else
            dc->SetPen(*wxBLACK_PEN);

        dc->DrawLine(width-THICK_LINE_BORDER, THICK_LINE_BORDER,
                     width-THICK_LINE_BORDER, height-THICK_LINE_BORDER);
        dc->DrawLine(width-THICK_LINE_BORDER, height-THICK_LINE_BORDER,
                     THICK_LINE_BORDER, height-THICK_LINE_BORDER);

        // Left and top grey lines
        dc->SetPen(*wxBLACK_PEN);
        dc->DrawLine(THICK_LINE_BORDER, height-THICK_LINE_BORDER,
                     THICK_LINE_BORDER, THICK_LINE_BORDER);
        dc->DrawLine(THICK_LINE_BORDER, THICK_LINE_BORDER,
                     width-THICK_LINE_BORDER, THICK_LINE_BORDER);

        // Draw icons
        dc->DrawIcon(* m_corners[0], 0, 0);
        dc->DrawIcon(* m_corners[1], int(width-32), 0);

        int y2 = height - 32;
        int x2 = (width-32);
        dc->DrawIcon(* m_corners[2], 0, y2);
        dc->DrawIcon(* m_corners[3], x2, y2);
    }
}

// Get an index (randomly generated) and load the poem
void MainWindow::GetIndexLoadPoem(void)
{
    if (index_ok)
        index_ptr = GetIndex();

    if (index_ptr > -1)
        loaded_ok = LoadPoem(data_filename, -1);
}

// Find the size of the poem and resize the window accordingly
void MainWindow::Resize(void)
{
    wxClientDC dc(canvas);

    // Get the poem size
    ScanBuffer(& dc, false, &poem_width, &poem_height);
    int x = poem_width + (2*BORDER_SIZE);
    int y = poem_height + (2*BORDER_SIZE);

    SetClientSize(x, y);

    // In case client size isn't what we set it to...
    int xx, yy;
    GetClientSize(&xx, &yy);

    wxMemoryDC memDC;
    if (backingBitmap) delete backingBitmap;
    backingBitmap = new wxBitmap(x, yy);
    memDC.SelectObject(* backingBitmap);

    memDC.Clear();
    ScanBuffer(&memDC, true, &xx, &yy);
}

// Which is more?
void FindMax(int *max_thing, int thing)
{
    if (thing > *max_thing)
        *max_thing = thing;
}

// Next page/poem
void MainWindow::NextPage(void)
{
    if (paging)
        current_page ++;
    else
    {
        current_page = 0;
        GetIndexLoadPoem();
    }
    Resize();
}

// Previous page
void MainWindow::PreviousPage(void)
{
    if (current_page > 0)
    {
        current_page --;
        Resize();
    }
}

// Search for a string
void MainWindow::Search(bool ask)
{
    long position;

    if (ask || m_searchString.empty())
    {
        wxString s = wxGetTextFromUser( wxT("Enter search string"), wxT("Search"), m_searchString);
        if (!s.empty())
        {
            s.MakeLower();
            m_searchString = s;
            search_ok = true;
        }
        else
        {
            search_ok = false;
        }
    }
    else
    {
        same_search = true;
        search_ok = true;
    }

    if (!m_searchString.empty() && search_ok)
    {
        position = DoSearch();
        if (position > -1)
        {
            loaded_ok = LoadPoem(data_filename, position);
            Resize();
        }
        else
        {
            last_poem_start = 0;
            PoetryNotify(wxT("Search string not found."));
        }
    }
}

bool MyApp::OnInit()
{
    poem_buffer = new wxChar[BUFFER_SIZE];

    // Seed the random number generator
#ifdef __WXWINCE__
    srand((unsigned) CeGetRandomSeed());
#else
    time_t current_time;

    (void)time(&current_time);
    srand((unsigned int)current_time);
#endif

//    randomize();
    pages[0] = 0;

    TheMainWindow = new MainWindow(NULL,
                                   wxID_ANY,
                                   wxT("wxPoem"),
                                   wxPoint(XPos, YPos),
                                   wxDefaultSize,
                                   wxCAPTION|wxMINIMIZE_BOX|wxSYSTEM_MENU|wxCLOSE_BOX|wxFULL_REPAINT_ON_RESIZE
                                   );

    TheMainWindow->canvas = new MyCanvas(TheMainWindow);

    if (argc > 1)
    {
        index_filename = wxStrcpy(new wxChar[wxStrlen(argv[1]) + 1], argv[1]);
        data_filename = wxStrcpy(new wxChar[wxStrlen(argv[1]) + 1], argv[1]);
    }
    else
    {
        index_filename = wxT(DEFAULT_POETRY_IND);
        data_filename = wxT(DEFAULT_POETRY_DAT);
    }
    TryLoadIndex();

    TheMainWindow->GetIndexLoadPoem();
    TheMainWindow->Resize();
    TheMainWindow->Show(true);

    return true;
}

int MyApp::OnExit()
{
    if (backingBitmap)
        delete backingBitmap;

    delete[] poem_buffer;

    return 0;
}

void MainWindow::OnCloseWindow(wxCloseEvent& WXUNUSED(event))
{
    WritePreferences();
    this->Destroy();
}

void MainWindow::OnChar(wxKeyEvent& event)
{
    canvas->OnChar(event);
}

BEGIN_EVENT_TABLE(MyCanvas, wxWindow)
    EVT_MOUSE_EVENTS(MyCanvas::OnMouseEvent)
    EVT_CHAR(MyCanvas::OnChar)
    EVT_PAINT(MyCanvas::OnPaint)
END_EVENT_TABLE()

// Define a constructor for my canvas
MyCanvas::MyCanvas(wxFrame *frame):
          wxWindow(frame, wxID_ANY)
{
    m_popupMenu = new wxMenu;
    m_popupMenu->Append(POEM_NEXT, wxT("Next poem/page"));
    m_popupMenu->Append(POEM_PREVIOUS, wxT("Previous page"));
    m_popupMenu->AppendSeparator();
    m_popupMenu->Append(POEM_SEARCH, wxT("Search"));
    m_popupMenu->Append(POEM_NEXT_MATCH, wxT("Next match"));
    m_popupMenu->Append(POEM_COPY, wxT("Copy to clipboard"));
    m_popupMenu->Append(POEM_MINIMIZE, wxT("Minimize"));
    m_popupMenu->AppendSeparator();
    m_popupMenu->Append(POEM_BIGGER_TEXT, wxT("Bigger text"));
    m_popupMenu->Append(POEM_SMALLER_TEXT, wxT("Smaller text"));
    m_popupMenu->AppendSeparator();
    m_popupMenu->Append(POEM_ABOUT, wxT("About wxPoem"));
    m_popupMenu->AppendSeparator();
    m_popupMenu->Append(POEM_EXIT, wxT("Exit"));
}

MyCanvas::~MyCanvas()
{
    // Note: this must be done before the main window/canvas are destroyed
    // or we get an error (no parent window for menu item button)
    delete m_popupMenu;
    m_popupMenu = NULL;
}

// Define the repainting behaviour
void MyCanvas::OnPaint(wxPaintEvent& WXUNUSED(event))
{
    wxPaintDC dc(this);

    if (backingBitmap)
    {
        int xx, yy;
        TheMainWindow->GetClientSize(&xx, &yy);

        dc.DrawBitmap(* backingBitmap, 0, 0);
#if 0
        wxMemoryDC memDC;
        memDC.SelectObject(* backingBitmap);
        dc.Blit(0, 0, backingBitmap->GetWidth(), backingBitmap->GetHeight(), &memDC, 0, 0);
#endif
  }
}

void MyCanvas::OnMouseEvent(wxMouseEvent& event)
{
    static int startPosX, startPosY, startFrameX, startFrameY;

    long x, y;
    event.GetPosition(&x, &y);

    if (event.RightDown())
    {
        // Versions from wxWin 1.67 are probably OK
        PopupMenu(m_popupMenu, (int)x, (int)y );
    }
    else if (event.LeftDown())
    {
        this->CaptureMouse();
        int x1 = (int)x;
        int y1 = (int)y;
        ClientToScreen(&x1, &y1);
        startPosX = x1;
        startPosY = y1;
        GetParent()->GetPosition(&startFrameX, &startFrameY);
    }
    else if (event.LeftUp())
    {
        if (GetCapture() == this) this->ReleaseMouse();
    }
    else if (event.Dragging() && event.LeftIsDown())
    {
        int x1 = (int)x;
        int y1 = (int)y;
        ClientToScreen(&x1, &y1);

        int dX = x1 - startPosX;
        int dY = y1 - startPosY;
        GetParent()->Move(startFrameX + dX, startFrameY + dY);
    }
}

// Process characters
void MyCanvas::OnChar(wxKeyEvent& event)
{
    switch (event.GetKeyCode())
    {
        case 'n':
        case 'N':
            // Next match
            TheMainWindow->Search(false);
            break;

        case 's':
        case 'S':
            // New search
            TheMainWindow->Search(true);
            break;

        case WXK_SPACE:
        case WXK_RIGHT:
        case WXK_DOWN:
            // Another poem
            TheMainWindow->NextPage();
            break;

        case WXK_ESCAPE:
            TheMainWindow->Close(true);
        default:
            break;
    }
}

// Load index file
int LoadIndex(const wxChar *file_name)
{
    long data;
    FILE *index_file;

    wxChar buf[100];

    if (file_name == NULL)
        return 0;

    wxSprintf(buf, wxT("%s.idx"), file_name);

    index_file = wxFopen(buf, wxT("r"));
    if (index_file == NULL)
        return 0;

    wxFscanf(index_file, wxT("%ld"), &nitems);

    for (int i = 0; i < nitems; i++)
    {
        wxFscanf(index_file, wxT("%ld"), &data);
        poem_index[i] = data;
    }

    fclose(index_file);

    return 1;
}

// Get index
int GetIndex()
{
    int indexn = (int)(rand() % nitems);

    if ((indexn < 0) || (indexn > nitems))
    { PoetryError(wxT("No such poem!"));
      return -1;
    }
    else
      return indexn;
}

// Read preferences
void MainWindow::ReadPreferences()
{
/* TODO: convert this code to use wxConfig
#if wxUSE_RESOURCES
    wxGetResource(wxT("wxPoem"), wxT("FontSize"), &pointSize);
    wxGetResource(wxT("wxPoem"), wxT("X"), &XPos);
    wxGetResource(wxT("wxPoem"), wxT("Y"), &YPos);
#endif
*/
}

// Write preferences to disk
void MainWindow::WritePreferences()
{
#ifdef __WXMSW__
    TheMainWindow->GetPosition(&XPos, &YPos);
/* TODO: convert this code to use wxConfig
#if wxUSE_RESOURCES
    wxWriteResource(wxT("wxPoem"), wxT("FontSize"), pointSize);
    wxWriteResource(wxT("wxPoem"), wxT("X"), XPos);
    wxWriteResource(wxT("wxPoem"), wxT("Y"), YPos);
#endif
*/
#endif
}

// Load a poem from given file, at given point in file.
// If position is > -1, use this for the position in the
// file, otherwise use index[index_ptr] to find the correct position.
bool LoadPoem(const wxChar *file_name, long position)
{
//    int j = 0;
//    int indexn = 0;
    wxChar buf[100];
    long data;
    FILE *data_file;

    paging = false;
    current_page = 0;

    if (file_name == NULL)
    {
      wxSprintf(error_buf, wxT("Error in Poem loading."));
      PoetryError(error_buf);
      return false;
    }

    wxSprintf(buf, wxT("%s.dat"), file_name);
    data_file = wxFopen(buf, wxT("r"));

    if (data_file == NULL)
    {
      wxSprintf(error_buf, wxT("Data file %s not found."), buf);
      PoetryError(error_buf);
      return false;
    }

    if (position > -1)
        data = position;
    else
        data = poem_index[index_ptr];

    fseek(data_file, data, SEEK_SET);

    int ch = 0;
    int i = 0;
    while ((ch != EOF) && (ch != '#'))
    {
        ch = getc(data_file);
        // Add a linefeed so it will copy to the clipboard ok
        if (ch == 10)
        {
            poem_buffer[i] = 13;
            i++;
        }

        poem_buffer[i] = (wxChar)ch;
        i ++;

        if (i == BUFFER_SIZE)
        {
            wxSprintf(error_buf, wxT("%s"), wxT("Poetry buffer exceeded."));
            PoetryError(error_buf);
            return false;
        }
    }
    fclose(data_file);
    poem_buffer[i-1] = 0;
    return true;
}

// Do the search
long MainWindow::DoSearch(void)
{
    if (m_searchString.empty())
        return false;

    FILE *file;
    size_t i = 0;
    int ch = 0;
    wxChar buf[100];
    long find_start;
    long previous_poem_start;

    bool found = false;
    size_t search_length = m_searchString.length();

    if (same_search)
    {
        find_start = last_find + 1;
        previous_poem_start = last_poem_start;
    }
    else
    {
        find_start = 0;
        last_poem_start = 0;
        previous_poem_start = -1;
    }

    if (data_filename)
        wxSprintf(buf, wxT("%s.dat"), data_filename);

    file = wxFopen(buf, wxT("r"));
    if (! (data_filename && file))
    {
        wxSprintf(error_buf, wxT("Poetry data file %s not found\n"), buf);
        PoetryError(error_buf);
        return false;
    }

    fseek(file, find_start, SEEK_SET);

    while ((ch != EOF) && !found)
    {
        ch = getc(file);
        ch = wxTolower(ch);   // Make lower case

        // Only match if we're looking at a different poem
        // (no point in displaying the same poem again)
        if ((m_searchString[i] == ch) && (last_poem_start != previous_poem_start))
        {
            if (i == 0)
                last_find = ftell(file);
            if (i == search_length-1)
                found = true;
            i ++;
        }
        else
        {
            i = 0;
        }

        if (ch == '#')
        {
            ch = getc(file);
            last_poem_start = ftell(file);
        }
    }
    fclose(file);
    if (ch == EOF)
    {
        last_find = -1;
    }

    if (found)
    {
        return last_poem_start;
    }

    return -1;
}

// Set up poetry filenames, preferences, load the index
// Load index (or compile it if none found)
void TryLoadIndex()
{
    index_ok = (LoadIndex(index_filename) != 0);
    if (!index_ok || (nitems == 0))
    {
        PoetryError(wxT("Index file not found; will compile new one"), wxT("wxPoem"));
        index_ok = Compile();
    }
}

// Error message
void PoetryError(const wxChar *msg, const wxChar *caption)
{
    wxMessageBox(msg, caption, wxOK|wxICON_EXCLAMATION);
}

// Notification (change icon to something appropriate!)
void PoetryNotify(const wxChar *Msg, const wxChar *caption)
{
    wxMessageBox(Msg, caption, wxOK | wxICON_INFORMATION);
}

// Build up and save an index into the poetry data file, for
// rapid random access
bool Compile(void)
{
    FILE *file;
    int j;
    int ch;
    wxChar buf[100];

    if (data_filename)
        wxSprintf(buf, wxT("%s.dat"), data_filename);

    file = wxFopen(buf, wxT("r"));
    if (! (data_filename && file))
    {
        wxSprintf(error_buf, wxT("Poetry data file %s not found\n"), buf);
        PoetryError(error_buf);
        return false;
    }

    nitems = 0;

    // Do first one (?)
    poem_index[nitems] = 0;
    nitems ++;

    // Do rest

    do {
        ch = getc(file);
        if (ch == '#')
        {
            ch = getc(file);
            long data;
            data = ftell(file);
            poem_index[nitems] = data;
            nitems ++;
        }
    } while (ch != EOF);
    fclose(file);

    if (index_filename)
      wxSprintf(buf, wxT("%s.idx"), index_filename);

    file = wxFopen(buf, wxT("w"));
    if (! (data_filename && file))
    {
        wxSprintf(error_buf, wxT("Poetry index file %s cannot be created\n"), buf);
        PoetryError(error_buf);
        return false;
    }

    wxFprintf(file, wxT("%ld\n\n"), nitems);
    for (j = 0; j < nitems; j++)
        wxFprintf(file, wxT("%ld\n"), poem_index[j]);

    fclose(file);
    PoetryNotify(wxT("Poetry index compiled."));
    return true;
}

void MainWindow::OnPopup(wxCommandEvent& event)
{
    switch (event.GetId())
    {
        case POEM_NEXT:
            // Another poem/page
            TheMainWindow->NextPage();
            break;
        case POEM_PREVIOUS:
            // Previous page
            TheMainWindow->PreviousPage();
            break;
        case POEM_SEARCH:
            // Search - with dialog
            TheMainWindow->Search(true);
            break;
        case POEM_NEXT_MATCH:
            // Search - without dialog (next match)
            TheMainWindow->Search(false);
            break;
        case POEM_MINIMIZE:
            TheMainWindow->Iconize(true);
            break;
#if wxUSE_CLIPBOARD
        case POEM_COPY:
            wxTheClipboard->UsePrimarySelection();
            if (wxTheClipboard->Open())
            {
                static wxString s;
                s = poem_buffer;
                s.Replace( wxT("@P"),wxEmptyString);
                s.Replace( wxT("@A "),wxEmptyString);
                s.Replace( wxT("@A"),wxEmptyString);
                s.Replace( wxT("@T "),wxEmptyString);
                s.Replace( wxT("@T"),wxEmptyString);
                wxTextDataObject *data = new wxTextDataObject( s.c_str() );
                if (!wxTheClipboard->SetData( data ))
                    wxMessageBox(wxT("Error while copying to the clipboard."));
            }
            else
            {
                wxMessageBox(wxT("Error opening the clipboard."));
            }
            wxTheClipboard->Close();
            break;
#endif
        case POEM_BIGGER_TEXT:
            pointSize ++;
            CreateFonts();
            TheMainWindow->Resize();
            break;
        case POEM_SMALLER_TEXT:
            if (pointSize > 2)
            {
                pointSize --;
                CreateFonts();
                TheMainWindow->Resize();
            }
            break;
        case POEM_ABOUT:
            (void)wxMessageBox(wxT("wxPoem Version 1.1\nJulian Smart (c) 1995"),
                               wxT("About wxPoem"), wxOK, TheMainWindow);
            break;
        case POEM_EXIT:
            // Exit
            TheMainWindow->Close(true);
            break;
        default:
            break;
    }
}